gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
/*
* Copyright 2007-2022 Pavel Ponec
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ujorm.core;
import java.text.Collator;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.ujorm.Key;
import org.ujorm.Ujo;
/**
* A generic comparator for the Ujo objects. A direction is the sorting is controlled by attribute Key.isAscending() .
* @author Pavel Ponec
* @see Key#isAscending()
* @see Key#descending()
*/
final public class UjoComparator <UJO extends Ujo> implements Comparator<UJO> {
@NotNull
final Key[] keys;
final private Locale collatorLocale;
final private int collatorStrength;
@Nullable
private Collator collator;
/** Creates a new instance of UjoComparator. The String are compared as Collator.IDENTICAL by English locale by default.
* @param keys sorting criteria are ordered by importance to down.
* A direction of the sorting is used by a method Key#isAscending().
* @see Key#isAscending()
* @see Key#descending()
*/
public UjoComparator(@NotNull final Key ... keys) {
this(Locale.ENGLISH, Collator.IDENTICAL, keys);
}
/** Creates a new instance of UjoComparator
* @param locale Locale for a String coparation
* @param collatorStrength Cllator Strength for String comparations
* @param keys sorting criteria are ordered by importance to down.
* A direction of the sorting is used by a method Key#isAscending().
* @see Key#isAscending()
* @see Key#descending()
*/
public UjoComparator
( @Nullable final Locale locale
, final int collatorStrength
, @NotNull final Key ... keys) {
this.keys = keys;
this.collatorLocale = locale;
switch (collatorStrength) {
case (Collator.PRIMARY):
case (Collator.SECONDARY):
case (Collator.TERTIARY):
case (Collator.IDENTICAL):
this.collatorStrength = collatorStrength;
break;
default:
// Throw the IllegalArgumentException:
Collator.getInstance(Locale.ENGLISH).setStrength(collatorStrength);
this.collatorStrength = Integer.MIN_VALUE;
}
}
/** Collator for String comparations.
* Default collator have en English locale with the IDENTICAL strength (case sensitive);
*/
@NotNull
public Collator getCollator() {
if (collator==null) {
collator = Collator.getInstance(collatorLocale);
collator.setStrength(collatorStrength);
}
return collator;
}
/** Collator for String comparations */
public void setCollator(@Nullable final Collator collator) {
this.collator = collator;
}
/**
* Compare two Ujo objects.
*
* @param u1 Ujo Object 1
* @param u2 Ujo Object 2
* @return Result of comparation
*/
@SuppressWarnings("unchecked")
@Override
public int compare(@Nullable final UJO u1, @Nullable final UJO u2) {
if (u1==u2 ) { return 0; }
if (u1==null) { return +1; }
if (u2==null) { return -1; }
for (Key key : keys) {
final Comparable c1 = (Comparable) key.of(u1);
final Comparable c2 = (Comparable) key.of(u2);
if (c1==c2 ) { continue; }
if (c1==null) { return +1; }
if (c2==null) { return -1; }
int result;
if (key.isTypeOf(String.class)) {
result = key.isAscending()
? getCollator().compare(c1, c2)
: getCollator().compare(c2, c1)
;
} else {
result = key.isAscending()
? c1.compareTo(c2)
: c2.compareTo(c1)
;
}
if (result != 0) {
return result;
}
}
return 0;
}
/** Sort a list by this Comparator. */
public List<UJO> sort(@NotNull final List<UJO> list) {
Collections.sort(list, this);
return list;
}
/** Sort a list by this Comparator. */
public UJO[] sort(@NotNull final UJO[] array) {
Arrays.sort(array, this);
return array;
}
/** A String reprezentation. */
@Override
public String toString() {
StringBuilder sb = new StringBuilder(32);
for (Key key : keys) {
if (sb.length()>0) {
sb.append(", ");
}
sb.append(key.getName());
sb.append("[");
sb.append(key.isAscending() ? "ASC" : "DESC");
sb.append("]");
}
return sb.toString();
}
/** An equals test */
public final boolean equals(@Nullable final UJO u1, @Nullable final UJO u2) {
return compare(u1, u2) == 0;
}
// ------------ STATIC ------------
/** Creates a new instance of UjoComparator. The String are compared as Collator.IDENTICAL by English locale by default.
* Sample:
* <pre class="pre">
* List<Person> result = UjoComparator.<Person>of(Person.NAME).sort(persons);
* </pre>
* @param keys sorting criteria are ordered by importance to down.
* A direction of the sorting is used by a method Key#isAscending().
* @see Key#isAscending()
* @see Key#descending()
*/
public static <U extends Ujo> UjoComparator<U> of(@NotNull final Key<U,?> ... keys) {
return new UjoComparator<>(keys);
}
/** @see #of(org.ujorm.KeyU[]) */
public static <U extends Ujo> UjoComparator<U> of(@NotNull final Key<U,?> p1) {
return new UjoComparator<>(p1);
}
/** @see #of(org.ujorm.KeyU[]) */
public static <U extends Ujo> UjoComparator<U> of
( @NotNull final Key<U,?> p1
, @NotNull final Key<U,?> p2) {
return new UjoComparator<>(p1, p2);
}
/** @see #of(org.ujorm.KeyU[]) */
public static <U extends Ujo> UjoComparator<? extends U> of
( @NotNull final Key<U,?> p1
, @NotNull final Key<U,?> p2
, @NotNull final Key<U,?> p3) {
return new UjoComparator<>(p1, p2, p3);
}
/** Creates a new instance of UjoComparator
* @param locale Locale for a String comparator
* @param collatorStrength Cllator Strength for String comparations
* @param keys sorting criteria are ordered by importance to down.
* A direction of the sorting is used by a method Key#isAscending().
* @see Key#isAscending()
* @see Key#descending()
*/
public static <UJO extends Ujo> UjoComparator<UJO> of
( @NotNull final Locale locale
, final int collatorStrength
, @NotNull final Key<UJO,?> ... keys) {
return new UjoComparator<>(keys);
}
/** Creates a new instance of UjoComparator. The String are compared as Collator.IDENTICAL by English locale by default.
* Sample:
* <pre class="pre">
* List<Person> result = UjoComparator.<Person>newInstance(Person.NAME).sort(persons);
* </pre>
* @param keys sorting criteria are ordered by importance to down.
* A direction of the sorting is used by a method Key#isAscending().
* @see Key#isAscending()
* @see Key#descending()
* @deprecated Use the {@code of(..)} method instead of
*/
public static <UJO extends Ujo> UjoComparator<UJO> newInstance(Key<UJO,?> ... keys) {
return new UjoComparator<>(keys);
}
/** @see #newInstance(org.ujorm.Key<UJO,?>[])
* @deprecated Use the {@code of(..)} method instead of
*/
public static <UJO extends Ujo> UjoComparator<UJO> newInstance(Key<UJO,?> p1) {
return new UjoComparator<>(p1);
}
/** @see #newInstance(org.ujorm.Key<UJO,?>[])
* @deprecated Use the {@code of(..)} method instead of
*/
public static <UJO extends Ujo> UjoComparator<UJO> newInstance(Key<UJO,?> p1, Key<UJO,?> p2) {
return new UjoComparator<>(p1, p2);
}
/** @see #newInstance(org.ujorm.Key<UJO,?>[])
* @deprecated Use the {@code of(..)} method instead of
*/
public static <UJO extends Ujo> UjoComparator<UJO> newInstance(Key<UJO,?> p1, Key<UJO,?> p2, Key<UJO,?> p3) {
return new UjoComparator<>(p1, p2, p3);
}
/** Creates a new instance of UjoComparator
* @param locale Locale for a String coparation
* @param collatorStrength Cllator Strength for String comparations
* @param keys sorting criteria are ordered by importance to down.
* A direction of the sorting is used by a method Key#isAscending().
* @see Key#isAscending()
* @see Key#descending()
* @deprecated Use the {@code of(..)} method instead of
*/
public static <UJO extends Ujo> UjoComparator<UJO> newInstance(Locale locale, int collatorStrength, final Key<UJO,?> ... keys) {
return new UjoComparator<>(keys);
}
}
| |
/*
* Copyright 2018 Blue Circle Software, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bluecirclesoft.open.jigen.jacksonModeller;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bluecirclesoft.open.jigen.ClassOverrideHandler;
import com.bluecirclesoft.open.jigen.model.JAny;
import com.bluecirclesoft.open.jigen.model.JArray;
import com.bluecirclesoft.open.jigen.model.JBoolean;
import com.bluecirclesoft.open.jigen.model.JEnum;
import com.bluecirclesoft.open.jigen.model.JMap;
import com.bluecirclesoft.open.jigen.model.JNumber;
import com.bluecirclesoft.open.jigen.model.JSpecialization;
import com.bluecirclesoft.open.jigen.model.JString;
import com.bluecirclesoft.open.jigen.model.JType;
import com.bluecirclesoft.open.jigen.model.JTypeVariable;
import com.bluecirclesoft.open.jigen.model.JVoid;
import com.bluecirclesoft.open.jigen.model.JWildcard;
import com.bluecirclesoft.open.jigen.model.Model;
import com.bluecirclesoft.open.jigen.model.PropertyEnumerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonAnyFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonArrayFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonBooleanFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatTypes;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitable;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonIntegerFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonMapFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonNullFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonNumberFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonStringFormatVisitor;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonValueFormat;
/**
* <p>The JacksonTypeModeller coordinates the reading of a set of Java types, producing TypeScript types from them, and collecting the
* resulting TS types into a Model.</p>
* <p>This class uses a breadth-first search to find referenced types. When a type is processed, all the types it references are placed on a
* queue, and the process is repeated until the queue is empty.</p>
* <p>To ease the eventual reading of the model, I wanted to make sure that if a type in the TS model references another type, that it's
* a direct reference, to avoid having to go to a lookup table or something like that. This is necessary, in particular, for circular
* references - one type clearly can't have a reference to another type that hasn't been digested yet. So to solve this, as types are
* read, the modeller stores 'fixups' to join the types properly later. This creates two steps:</p>
* <ol>
* <li>All types are read, but references to other types are stubbed, and fixups are registered for later</li>
* <li>The modeller runs all the fixups, connecting concrete JTypes with other concrete JTypes.</li>
* </ol>
*
* @see Model
*/
public class JacksonTypeModeller implements PropertyEnumerator {
private static class FixupQueueItem implements Comparable<FixupQueueItem> {
private final Type type;
private final int priority;
private final Consumer<JType> fixup;
public FixupQueueItem(Type type, int priority, Consumer<JType> fixup) {
this.type = type;
this.priority = priority;
this.fixup = fixup;
}
@Override
public int compareTo(FixupQueueItem o) {
return Integer.compare(getPriority(), o.getPriority());
}
Consumer<JType> getFixup() {
return fixup;
}
int getPriority() {
return priority;
}
public Type getType() {
return type;
}
}
/**
* First pass of fixups - linking fields to their fully-defined types
*/
public static final int FIELD_FIXUP_PRIORITY = 1;
/**
* Second pass of fixups - reviewing the model after it is fully defined
*/
public static final int MODEL_REVIEW_PRIORITY = 2;
private static final Logger logger = LoggerFactory.getLogger(JacksonTypeModeller.class);
/**
* Types that are intrinsic to TypeScript
*/
private static final Map<Class, Supplier<JType>> FUNDAMENTAL_TYPES = new HashMap<>();
static {
FUNDAMENTAL_TYPES.put(Void.class, JVoid::new);
FUNDAMENTAL_TYPES.put(Void.TYPE, JVoid::new);
FUNDAMENTAL_TYPES.put(Boolean.class, JBoolean::new);
FUNDAMENTAL_TYPES.put(Boolean.TYPE, JBoolean::new);
FUNDAMENTAL_TYPES.put(Byte.class, JNumber::new);
FUNDAMENTAL_TYPES.put(Byte.TYPE, JNumber::new);
FUNDAMENTAL_TYPES.put(Short.class, JNumber::new);
FUNDAMENTAL_TYPES.put(Short.TYPE, JNumber::new);
FUNDAMENTAL_TYPES.put(Integer.class, JNumber::new);
FUNDAMENTAL_TYPES.put(Integer.TYPE, JNumber::new);
FUNDAMENTAL_TYPES.put(Long.class, JNumber::new);
FUNDAMENTAL_TYPES.put(Long.TYPE, JNumber::new);
FUNDAMENTAL_TYPES.put(Float.class, JNumber::new);
FUNDAMENTAL_TYPES.put(Float.TYPE, JNumber::new);
FUNDAMENTAL_TYPES.put(Double.class, JNumber::new);
FUNDAMENTAL_TYPES.put(Double.TYPE, JNumber::new);
FUNDAMENTAL_TYPES.put(BigInteger.class, JNumber::new);
FUNDAMENTAL_TYPES.put(BigDecimal.class, JNumber::new);
FUNDAMENTAL_TYPES.put(String.class, JString::new);
FUNDAMENTAL_TYPES.put(Character.class, JString::new);
FUNDAMENTAL_TYPES.put(Character.TYPE, JString::new);
}
/**
* Queue of pending types to process
*/
private final ArrayDeque<Type> typesToProcess = new ArrayDeque<>();
/**
* List of fixups to run after ingesting.
*/
private final PriorityQueue<FixupQueueItem> typeFixups = new PriorityQueue<>();
private static final ReflectionsCache reflectionsCache = new ReflectionsCache();
private final Reflections subclassFinder;
private final ClassOverrideHandler classOverrides;
private final boolean includeSubclasses;
private final String[] packagesToScan;
private final JEnum.EnumType defaultEnumType;
/**
* Create a modeller.
*/
public JacksonTypeModeller(ClassOverrideHandler classOverrides, JEnum.EnumType defaultEnumType, boolean includeSubclasses,
String[] packagesToScan) {
assert defaultEnumType != null;
assert packagesToScan != null;
assert packagesToScan.length > 0;
this.classOverrides = classOverrides;
this.defaultEnumType = defaultEnumType;
this.includeSubclasses = includeSubclasses;
this.packagesToScan = packagesToScan;
if (includeSubclasses) {
subclassFinder = reflectionsCache.getReflections(packagesToScan);
} else {
subclassFinder = null;
}
// clear list of created types (for debugging)
JType.createdTypes.clear();
}
public static boolean isFundamentalType(Class<?> returnType) {
return FUNDAMENTAL_TYPES.containsKey(returnType);
}
/**
* Add a fixup for a given type
*
* @param type the type
* @param fixup the fixup to apply
* @param priority the priority with which to run the fixup
*/
void addFixup(Type type, Consumer<JType> fixup, int priority) {
typeFixups.add(new FixupQueueItem(type, priority, fixup));
}
/**
* Add a fixup for a given type (field fixup priority)
*
* @param type the type
* @param fixup the fixup to apply
*/
void addFixup(Type type, Consumer<JType> fixup) {
addFixup(type, fixup, FIELD_FIXUP_PRIORITY);
}
/**
* Queue a type for future processing
*
* @param type
*/
void queueType(Type type) {
typesToProcess.add(type);
}
/**
* Read Java types into the model.
*
* @param model the model
* @param types the types to add
* @return a list of TS types added this run
*/
@Override
public List<JType> readTypes(Model model, Type... types) {
// enqueue start types
Collections.addAll(typesToProcess, types);
// drain the queue
while (!typesToProcess.isEmpty()) {
Type type = typesToProcess.pollFirst();
if (model.hasType(type)) {
logger.debug("Type {} already seen", type);
continue;
}
logger.debug("Type {} being added", type);
model.addType(type, handleType(type));
}
// apply fixups
applyFixups(model, typeFixups);
logger.debug("Done");
// double-check that all our types wound up in the model
Collection<JType> interfaces = model.getInterfaces();
for (JType createdType : JType.createdTypes) {
if (!interfaces.contains(createdType)) {
throw new RuntimeException("Type " + createdType + " was created, but it's not in interfaces");
}
}
// find all the TS types created for the type parameters, and return them, in the same order (necessary for #readOneType)
List<JType> result = new ArrayList<>(types.length);
for (Type type : types) {
result.add(model.getType(type));
}
return result;
}
private void applyFixups(Model model, PriorityQueue<FixupQueueItem> typeCleanups) {
while (!typeCleanups.isEmpty()) {
FixupQueueItem fixup = typeCleanups.poll();
if (fixup != null) {
JType jType = model.getType(fixup.getType());
fixup.getFixup().accept(jType);
}
}
}
/**
* Convenience method to process just one type. This may, of course trigger the processing of other types by reference, and they'll
* be added to the model, but the other TS types won't be returned.
*
* @param model the model
* @param type the Java type
* @return the TS type
*/
@Override
public JType readOneType(Model model, Type type) {
return readTypes(model, type).get(0);
}
private JType handleType(Type type) {
logger.debug("Handling {}", type);
if (type instanceof TypeVariable) {
// Case 1: type variable
// Given a type like MyType<T>, the TypeVariable represents T. For a more complex instance like
// MyType<T extends InterfaceA & InterfaceB>, then InterfaceA and InterfaceB will be in the 'intersectionBounds'. This can be
// represented in TypeScript, and the syntax is the same.
logger.debug("is TypeVariable");
TypeVariable variable = (TypeVariable) type;
JTypeVariable jVariable = new JTypeVariable(variable.getName());
// if the bound is only Object, we're going to ignore it
if (variable.getBounds().length != 1 || variable.getBounds()[0] != Object.class) {
for (int i = 0; i < variable.getBounds().length; i++) {
final int finalI = i;
Type bound = variable.getBounds()[i];
jVariable.getIntersectionBounds().add(null);
queueType(bound);
addFixup(bound, jType -> jVariable.getIntersectionBounds().set(finalI, jType));
}
}
return jVariable;
} else if (type instanceof ParameterizedType) {
// Case 2: parametrized type
// This is for the case of a generic type specialization, where the variables have been specified (e.g. List<Integer>)
logger.debug("is ParameterizedType");
ParameterizedType pt = (ParameterizedType) type;
Type base = pt.getRawType();
if (isCollection(base)) {
// Collection<T> -> Array<T>
JArray result = new JArray();
result.setIndexType(new JNumber());
addFixup(pt.getActualTypeArguments()[0], result::setElementType);
queueType(pt.getActualTypeArguments()[0]);
return result;
} else if (isMap(base)) {
// Map<String, T> -> { [key: string]: T }
JMap result = new JMap();
addFixup(pt.getActualTypeArguments()[1], result::setValueType);
queueType(pt.getActualTypeArguments()[1]);
return result;
} else {
// everything else: A<B> -> A<B>
JSpecialization jSpecialization = new JSpecialization();
jSpecialization.setParameters(new JType[pt.getActualTypeArguments().length]);
addFixup(pt.getRawType(), jSpecialization::setBase);
queueType(pt.getRawType());
for (int i = 0; i < pt.getActualTypeArguments().length; i++) {
final int finalI = i;
addFixup(pt.getActualTypeArguments()[i], jType -> jSpecialization.getParameters()[finalI] = jType);
queueType(pt.getActualTypeArguments()[i]);
}
return jSpecialization;
}
} else if (type instanceof WildcardType) {
// Case 3: wildcard type
// This is for the case of a generic type specialization, where the variables have been specified (e.g. List<Integer>)
logger.debug("is WildcardType");
WildcardType pt = (WildcardType) type;
JWildcard jWildcard = new JWildcard();
Type[] upperBounds = pt.getUpperBounds();
for (int i = 0; i < upperBounds.length; i++) {
Type upper = upperBounds[i];
jWildcard.getUpperBounds().add(null);
final int idx = i;
addFixup(upper, (f) -> jWildcard.getUpperBounds().set(idx, f));
queueType(upper);
}
Type[] lowerBounds = pt.getLowerBounds();
for (int i = 0; i < lowerBounds.length; i++) {
Type lower = lowerBounds[i];
jWildcard.getLowerBounds().add(null);
final int idx = i;
addFixup(lower, (f) -> jWildcard.getLowerBounds().set(idx, f));
queueType(lower);
}
return jWildcard;
} else if (type instanceof Class) {
// Case 3: class (non-generic, plain vanilla)
logger.debug("is Class");
Class cl = (Class) type;
if (cl.isArray()) {
// array: A[] -> Array<A>
logger.debug("is array");
JArray result = new JArray();
result.setIndexType(new JNumber());
addFixup(cl.getComponentType(), result::setElementType);
queueType(cl.getComponentType());
return result;
} else {
if (classOverrides.containsKey(cl)) {
// substitute class. If the user created a cycle, sorry.
Class classOverride = classOverrides.get(cl);
return handleType(classOverride);
} else if (FUNDAMENTAL_TYPES.containsKey(type)) {
// built-in type: int -> number, etc
logger.debug("is fundamental type");
return FUNDAMENTAL_TYPES.get(type).get();
} else {
// everything else -> interface
logger.debug("is user-defined class");
if (includeSubclasses) {
enqueueSubclasses((Class) type);
}
return handleUserDefinedClass((Class) type);
}
}
} else {
throw new RuntimeException("Can't handle " + type);
}
}
private void enqueueSubclasses(Class<?> type) {
if (subclassFinder != null) {
if (type != Object.class) {
Set<Class<?>> subtypes = subclassFinder.getSubTypesOf((Class<Object>) type);
for (Class<?> cl : subtypes) {
queueType(cl);
}
}
}
}
/**
* Is this Java type a Map? (will turn into an object)
*
* @param base the type
* @return yes or no
*/
private static boolean isMap(Type base) {
return base instanceof Class && Map.class.isAssignableFrom((Class<?>) base);
}
/**
* Is this Java type a collection? (will turn into an array)
*
* @param base the type
* @return yes or no
*/
private static boolean isCollection(Type base) {
return base instanceof Class && Collection.class.isAssignableFrom((Class<?>) base);
}
private JType handleUserDefinedClass(Class type) {
// Run a Jackson JsonFormatVisitor over our class, let it process all the object properties, and return the resulting JType.
TypeReadingVisitor<?> reader;
try {
ClassReader wrapper = new ClassReader();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.acceptJsonFormatVisitor(type, wrapper);
reader = wrapper.getReader();
} catch (JsonMappingException e) {
throw new RuntimeException(e);
}
if (reader == null) {
return null;
} else {
return reader.getResult();
}
}
/**
* Jackson format visitor which will be invoked over all the properties.
*/
private class ClassReader extends JsonFormatVisitorWrapper.Base {
private TypeReadingVisitor<?> reader;
TypeReadingVisitor<?> getReader() {
return reader;
}
@Override
public JsonArrayFormatVisitor expectArrayFormat(JavaType type) {
return new JsonArrayFormatVisitor.Base() {
@Override
public void itemsFormat(JsonFormatVisitable handler, JavaType elementType) throws JsonMappingException {
super.itemsFormat(handler, elementType);
}
@Override
public void itemsFormat(JsonFormatTypes format) throws JsonMappingException {
super.itemsFormat(format);
}
};
}
@Override
public JsonStringFormatVisitor expectStringFormat(JavaType type) {
reader = JString::new;
return new JsonStringFormatVisitor.Base() {
@Override
public void enumTypes(Set<String> enums) {
reader = () -> {
Class<?> rawClass = type.getRawClass();
return buildEnum((Class<Enum<?>>) rawClass);
};
}
};
}
@Override
public JsonNumberFormatVisitor expectNumberFormat(JavaType type) {
reader = JNumber::new;
return new JsonNumberFormatVisitor() {
@Override
public void numberType(JsonParser.NumberType type) {
throw new RuntimeException("not implemented");
}
@Override
public void format(JsonValueFormat format) {
throw new RuntimeException("not implemented");
}
@Override
public void enumTypes(Set<String> enums) {
throw new RuntimeException("not implemented");
}
};
}
@Override
public JsonIntegerFormatVisitor expectIntegerFormat(JavaType type) {
reader = JNumber::new;
return new JsonIntegerFormatVisitor.Base() {
};
}
@Override
public JsonBooleanFormatVisitor expectBooleanFormat(JavaType type) {
reader = JNumber::new;
return new JsonBooleanFormatVisitor.Base() {
};
}
@Override
public JsonNullFormatVisitor expectNullFormat(JavaType type) {
reader = JNumber::new;
return new JsonNullFormatVisitor.Base() {
};
}
@Override
public JsonAnyFormatVisitor expectAnyFormat(JavaType type) {
reader = JAny::new;
return new JsonAnyFormatVisitor.Base() {
};
}
@Override
public JsonMapFormatVisitor expectMapFormat(JavaType type) {
// We would only have gotten here for a raw map; it's element type is any
JMap map = new JMap(new JAny());
reader = () -> map;
return new JsonMapFormatVisitor.Base() {
};
}
@Override
public JsonObjectFormatVisitor expectObjectFormat(JavaType type) {
JsonObjectReader myReader = new JsonObjectReader(JacksonTypeModeller.this, type.getRawClass());
reader = myReader;
return myReader;
}
}
private JEnum buildEnum(Class<Enum<?>> rawClass) {
JEnum.EnumType enumType = null;
List<JEnum.EnumDeclaration> entries = new ArrayList<>();
Enum<?>[] constants = rawClass.getEnumConstants();
Map<String, Enum<?>> usedValues = new HashMap<>();
for (Enum<?> enumConstant : constants) {
ObjectMapper objectMapper = new ObjectMapper();
try {
String enumConstantValue = objectMapper.writeValueAsString(enumConstant);
// strip quotes
int length = enumConstantValue.length();
if (length > 1 && enumConstantValue.charAt(0) == '"') {
enumConstantValue = enumConstantValue.substring(1, length - 1);
if (enumType != null && enumType != JEnum.EnumType.STRING) {
throw new RuntimeException("Jackson giving both numeric and string values for enum " + rawClass.getName());
}
enumType = JEnum.EnumType.STRING;
} else {
if (enumType != null && enumType != JEnum.EnumType.NUMERIC) {
throw new RuntimeException("Jackson giving both numeric and string values for enum " + rawClass.getName());
}
enumType = JEnum.EnumType.NUMERIC;
}
if (usedValues.containsKey(enumConstantValue)) {
logger.warn("Computed serialized value of {} to be {}, but that value was also used for {} " +
"- keeping first definition only",
new Object[]{enumConstant, enumConstantValue, usedValues.get(enumConstantValue)});
} else {
usedValues.put(enumConstantValue, enumConstant);
}
entries.add(new JEnum.EnumDeclaration(enumConstant.name(), enumConstant.ordinal(), enumConstantValue));
} catch (JsonProcessingException e) {
logger.warn("Couldn not serialize " + enumConstant + ", skipping");
}
}
return new JEnum(rawClass.getName(), enumType == null ? defaultEnumType : enumType, entries);
}
}
| |
/*
* Copyright (C) 2014 Dell, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dell.doradus.common;
import java.io.IOException;
import java.io.Reader;
/**
* JSON parser that uses the SAX-style interface for JSON, aka "SAJ". As constructs are
* recognized, appropriate methods in the {@link SajListener} object passed to
* {@link #parse(SajListener)} are called.
* <p>
* Note that this class supports only the subset of JSON that Doradus uses. As a result,
* there are a few oddities, as described below:
* <ul>
* <li>Arrays within arrays are not supported. That is, <code>foo: [10, [11, 12]]</code>
* will throw an error when the inner array is seen.
* </li>
* <li>All Doradus messages use the general form <code>{"foo": {...stuff...}}</code>. The
* outer braces are silently parsed and ignore. When the sequence <code>"foo": {</code>
* is recognized, {@link SajListener#onStartObject(String)} is called passing "foo" as
* the object name.
* </li>
* <li>When the sequence <code>"foo": [</code> is recognized,
* {@link SajListener#onStartArray(String)} is called passing "foo" as the array name.
* </li>
* <li>When a simple object member value is recognized, e.g., <code>"name": "value"</code>,
* the method {@link SajListener#onValue(String, String)} is called passing "name" and
* "value". If the value is the JSON literal <code>null</code>, an empty string is
* passed as the value. Numbers are also passed as strings, as are the constants
* <code>true</code> and <code>false</code>.
* </li>
* <li>When a simple array value is recognized, e.g., "123" or "xyz", the method
* {@link SajListener#onValue(String, String)} is called passing "value" as the name
* and string form of value using the same rules as in the case above.
* </li>
* <li>When an array value is a "value object" as in the example <code>"foo": [{"bar":
* "bat"}]</code>, the outer curly braces are tossed, after the onArrayStart("foo")
* call, the next call will be onValue("bar", "bar").
* </li>
* <li>Similarly, if an array value is a complex object as in the example <code>"foo":
* [{"bar": {...stuff...}}]</code>, the outer curly braces are stripped. Instead,
* onObjectStart("bar") is called followed by whatever is appropriate based on the
* <code>...stuff...</code> inside the inner curly braces.
* </li>
* <li>{@link SajListener#onEndObject()} and {@link SajListener#onEndArray()} are called
* whenever a matching '}' or ']' is found (except for the ignore-curly-braces cases
* described above).
* </li>
* </ul>
* <p>
* Why Annie? I have a Jack Russel Terrier named Annie, and she is very fast.
*
* @author Randy Guck
*/
public class JSONAnnie {
/**
* The listener interface for {@link JSONAnnie#parse(SajListener)} calls.
*/
public interface SajListener {
/**
* This method is called when the sequence '"name": {' is recognized.
*
* @param name Member name that starts an object declaration.
*/
void onStartObject(String name);
/**
* This method is called when the '}' is recognized that matches a
* {@link #onStartObject(String)} call.
*/
void onEndObject();
/**
* This method is called when the sequence '"name": [' is recognized.
*
* @param name Member name that starts a named array declaration.
*/
void onStartArray(String name);
/**
* This method is called when the ']' is recognized that matches a
* {@link #onStartArray(String)} call.
*/
void onEndArray();
/**
* This method is called when the sequence '"name": "value"' is recognized or when
* a simple unnamed array value is recognized. In the latter case, the name passed
* is "value". When the value is JSON literal <i>null</i>, an empty string is
* passed as the value. Numbers are also passed as strings, and the constants
* <i>true</i> and <i>false</i> are passed as strings as well.
*
* @param name Name of named value of "value" for unnamed array values.
* @param value Value parsed, converted to a String.
*/
void onValue(String name, String value);
} // SajListener
// Constants
private static final int MAX_STACK_DEPTH = 32;
private static final char EOF = (char)-1;
// JSON text input source:
private final JSONInput m_input;
// Stack of nested JSON constructs:
enum Construct {
GHOST, // { } being silently ignore
OBJECT, // { } passed to the listener
ARRAY // [ ] passed to the listener
}
private Construct[] m_stack = new Construct[MAX_STACK_DEPTH];
private int m_stackPos = 0;
// Current parsing state:
enum State {
MEMBER_LIST,
MEMBER,
VALUE,
NEXT,
}
private State state;
///// JSONInput classes
// Abstract class that encapsulates a JSON input source. It provides methods to get the
// next character, get the next non-whitespace character, and push a character back for
// subsequent re-reading. It also provides methods to extract a complete JSON token:
// string, number, or literal constant.
private abstract static class JSONInput {
// Short-term (single method) temporary buffers
final StringBuilder buffer = new StringBuilder();
final StringBuilder digitBuffer = new StringBuilder();
// Return next char to parse or EOF
abstract char nextChar(boolean isEOFAllowed);
// Push back the last character. Only a 1-char pushback is needed.
abstract void pushBack(char ch);
// Return the next non-whitespace character or EOF. Throw is EOF is reached unexpectedly.
char nextNonWSChar(boolean isEOFAllowed) {
char ch = nextChar(isEOFAllowed);
while (ch != EOF && Character.isWhitespace(ch)) {
ch = nextChar(isEOFAllowed);
}
return ch;
} // nextNonWSChar
// Return the quoted string beginning at the given char; error if we don't find one.
String nextString(char ch) {
// Decode escape sequences and return unquoted string value
buffer.setLength(0);
check(ch == '"', "'\"' expected: " + ch);
while (true) {
ch = nextChar(false);
if (ch == '"') {
// Outer closing double quote.
break;
} else if (ch == '\\') {
// Escape sequence.
ch = nextChar(false);
switch (ch) {
case 'u':
// \uDDDD sequence: Expect four hex digits.
digitBuffer.setLength(0);
for (int digits = 0; digits < 4; digits++) {
ch = nextChar(false);
check(Utils.isHexDigit(ch), "Hex digit expected: " + ch);
digitBuffer.append(ch);
}
buffer.append((char)Integer.parseInt(digitBuffer.toString(), 16));
break;
case '\"': buffer.append('\"'); break;
case '\\': buffer.append('\\'); break;
case '/': buffer.append('/'); break;
case 'b': buffer.append('\b'); break;
case 'f': buffer.append('\f'); break;
case 'n': buffer.append('\n'); break;
case 'r': buffer.append('\r'); break;
case 't': buffer.append('\t'); break;
default:
check(false, "Invalid escape sequence: \\" + ch);
}
} else {
// All other chars are allowed as-is, despite JSON spec.
buffer.append(ch);
}
}
return buffer.toString();
} // nextString
// Parse a literal value beginning at the given char; error if we don't find one.
String nextValue(char ch) {
if (ch == '"') {
return nextString(ch);
}
if (ch == '-' || (ch >= '0' && ch <= '9')) {
return nextNumber(ch);
}
if (Character.isLetter(ch)) {
return nextLiteral(ch);
}
check(false, "Unrecognized start of value: " + ch);
return null; // unreachable
} // nextValue
// Parse a number literal. Currently we only recognize integers; not exponents.
String nextNumber(char ch) {
buffer.setLength(0);
// First char only can be a "dash".
if (ch == '-') {
buffer.append(ch);
ch = nextChar(false);
}
// Accumulate leading digits
while (ch >= '0' && ch <= '9') {
buffer.append(ch);
ch = nextChar(false);
}
// Look for fractional part
if (ch == '.') {
buffer.append(ch);
ch = nextChar(false);
int fracDigits = 0;
while (ch >= '0' && ch <= '9') {
fracDigits++;
buffer.append(ch);
ch = nextChar(false);
}
check(fracDigits > 0, "JSON fractional part requires at least one digit: " + buffer);
}
// Look for exponent
if (ch == 'e' || ch == 'E') {
buffer.append(ch);
ch = nextChar(false);
if (ch == '-' || ch == '+') {
buffer.append(ch);
ch = nextChar(false);
}
int expDigits = 0;
while (ch >= '0' && ch <= '9') {
expDigits++;
buffer.append(ch);
ch = nextChar(false);
}
check(expDigits > 0, "JSON exponent part requires at least one digit: " + buffer);
}
// Push back the last non-digit.
pushBack(ch);
// Cannot be "-" only
String value = buffer.toString();
check(!value.equals("-"), "At least one digit must follow '-' in numeric value");
return value;
} // nextNumber
// Parse a keyword constant: false, true, or null. Case-insensitive.
String nextLiteral(char ch) {
buffer.setLength(0);
while (Character.isLetter(ch)) {
buffer.append(ch);
ch = nextChar(false);
}
// Push back the last letter.
pushBack(ch);
String value = buffer.toString();
if (value.equalsIgnoreCase("false")) {
return "false";
}
if (value.equalsIgnoreCase("true")) {
return "true";
}
if (value.equalsIgnoreCase("null")) {
return "";
}
check(false, "Unrecognized literal: " + value);
return null; // not reachable
}
} // class JSONInput
// JSONInput specialization that reads chars from a String.
private static class JSONInputString extends JSONInput {
private int index;
private final String jsonText;
// Wrap the given string.
JSONInputString(String text) {
jsonText = text;
} // constructor
// Return next char to parse or EOF
@Override
char nextChar(boolean isEOFAllowed) {
if (index >= jsonText.length()) {
check(isEOFAllowed, "Unexpected EOF");
return EOF;
}
return jsonText.charAt(index++);
} // nextChar
// Push back 1 char.
@Override
void pushBack(char ch) {
assert index > 0;
index--;
assert jsonText.charAt(index) == ch;
} // pushBack
} // class JSONInputString
// JSONInput specialization that reads chars from a reader.
private static class JSONInputReader extends JSONInput {
final Reader reader;
char pushBack = EOF;
// Wrap the given Reader. Note that we don't close it when we're done.
JSONInputReader(Reader reader) {
this.reader = reader;
} // constructor
// Use the push back char if present, otherwise use the Reader.
@Override
char nextChar(boolean isEOFAllowed) {
char ch;
if (pushBack != EOF) {
ch = pushBack;
pushBack = EOF;
} else {
try {
ch = (char) reader.read();
} catch (IOException e) {
ch = EOF;
}
}
check(ch != EOF || isEOFAllowed, "Unexpected EOF");
return ch;
} // nextChar
// Push back 1 char, which must be read next.
@Override
void pushBack(char ch) {
assert pushBack == EOF : "Only 1 char can be pushed back";
pushBack = ch;
} // pushBack
} // class JSONInputReader
///// Public methods
/**
* Create an object that uses the given text as input when {@link #parse(SajListener)}
* is called.
*
* @param jsonText JSON text string.
*/
public JSONAnnie(String jsonText) {
Utils.require(jsonText != null && jsonText.length() > 0, "JSON text cannot be empty");
m_input = new JSONInputString(jsonText);
} // constructor
/**
* Create an object that uses the given reader as input when {@link #parse(SajListener)}
* is called. Note that we don't close the Reader when we're done with it.
*
* @param reader Open character Reader.
*/
public JSONAnnie(Reader reader) {
m_input = new JSONInputReader(reader);
} // constructor
/**
* Parse the JSON given to the constructor and call the given listener as each construct
* is found. An IllegalArgumentException is thrown if a syntax error or unsupported JSON
* construct is found.
*
* @param listener Callback for SAJ eve.ts
* @throws IllegalArgumentException If there's a syntax error.
*/
public void parse(SajListener listener) throws IllegalArgumentException {
assert listener != null;
// We require the first construct to be an object with no leading whitespace.
m_stackPos = 0;
char ch = m_input.nextChar(false);
check(ch == '{', "First character must be '{': " + ch);
// Mark outer '[' with a "ghost" object.
push(Construct.GHOST);
// Enter the state machine parsing the first member name.
state = State.MEMBER_LIST;
boolean bFinished = false;
String memberName = null;
String value = null;
while (!bFinished) {
switch (state) {
case MEMBER_LIST:
// Expect a quote to start a member or a '}' to denote an empty list.
ch = m_input.nextNonWSChar(false);
if (ch != '}') {
// Should a quote to start a member name.
state = State.MEMBER;
} else {
// Empty object list
if (pop() == Construct.OBJECT) {
listener.onEndObject();
}
if (emptyStack()) {
bFinished = true;
}
state = State.NEXT;
}
break;
case MEMBER:
// Expect an object member: "name": <value>.
memberName = m_input.nextString(ch);
// Colon should follow
ch = m_input.nextNonWSChar(false);
check(ch == ':', "Colon expected: " + ch);
// Member value shoud be next
ch = m_input.nextNonWSChar(false);
if (ch == '{') {
listener.onStartObject(memberName);
push(Construct.OBJECT);
state = State.MEMBER_LIST;
} else if (ch == '[') {
listener.onStartArray(memberName);
push(Construct.ARRAY);
state = State.VALUE;
} else {
// Value must be a literal.
value = m_input.nextValue(ch);
listener.onValue(memberName, value);
// Must be followed by next member or object/array closure.
state = State.NEXT;
}
break;
case VALUE:
// Here, we expect an array value: object or literal.
ch = m_input.nextNonWSChar(false);
if (ch == '{') {
// Push a GHOST so we eat the outer { } pair.
push(Construct.GHOST);
state = State.MEMBER_LIST;
} else if (ch == ']') {
// Empty array.
listener.onEndArray();
pop();
if (emptyStack()) {
bFinished = true;
} else {
state = State.NEXT;
}
} else if (ch == '[') {
// Value is a nested array, which we don't currently support.
check(false, "Nested JSON arrays are not supported");
} else {
// Value must be a literal value. It is implicitly named "value"
value = m_input.nextValue(ch);
listener.onValue("value", value);
// Must be followed by next member or object/array terminator
state = State.NEXT;
}
break;
case NEXT:
// Expect a comma or object/array closure.
ch = m_input.nextNonWSChar(false);
Construct tos = tos();
if (ch == ',') {
if (tos == Construct.OBJECT || tos == Construct.GHOST) {
ch = m_input.nextNonWSChar(false);
state = State.MEMBER;
} else {
state = State.VALUE;
}
} else {
switch (tos) {
case ARRAY:
check(ch == ']', "']' or ',' expected: " + ch);
listener.onEndArray();
break;
case GHOST:
check(ch == '}', "'}' or ',' expected: " + ch);
break;
case OBJECT:
check(ch == '}', "'}' or ',' expected: " + ch);
listener.onEndObject();
break;
}
pop();
if (emptyStack()) {
bFinished = true;
}
// If not finished, stay in NEXT state.
}
break;
default:
assert false: "Missing case for state: " + state;
}
}
// Here, we should be at EOF
ch = m_input.nextNonWSChar(true);
check(ch == EOF, "End of input expected: " + ch);
} // parse
///// Private methods
// Push the given node onto the node stack.
private void push(Construct construct) {
// Make sure we don't blow the stack.
check(m_stackPos < MAX_STACK_DEPTH, "Too many JSON nested levels (maximum=" + MAX_STACK_DEPTH + ")");
m_stack[m_stackPos++] = construct;
} // push
// Return the node currently at top of stack or null if there is none.
private Construct tos() {
assert m_stackPos > 0;
return m_stack[m_stackPos - 1];
} // tos
// Pop the stack by one and return the node removed.
private Construct pop() {
assert m_stackPos > 0;
return m_stack[--m_stackPos];
} // pop
// Return true if the stack is empty.
private boolean emptyStack() {
return m_stackPos == 0;
} // emptyStack
private static void check(boolean condition, String errMsg) {
Utils.require(condition, errMsg);
} // check
} // class JSONAnnie
| |
/*
* Copyright 2013-2014 Richard M. Hightower
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* __________ _____ __ .__
* \______ \ ____ ____ ____ /\ / \ _____ | | _|__| ____ ____
* | | _// _ \ / _ \ / \ \/ / \ / \\__ \ | |/ / |/ \ / ___\
* | | ( <_> | <_> ) | \ /\ / Y \/ __ \| <| | | \/ /_/ >
* |______ /\____/ \____/|___| / \/ \____|__ (____ /__|_ \__|___| /\___ /
* \/ \/ \/ \/ \/ \//_____/
* ____. ___________ _____ ______________.___.
* | |____ ___ _______ \_ _____/ / _ \ / _____/\__ | |
* | \__ \\ \/ /\__ \ | __)_ / /_\ \ \_____ \ / | |
* /\__| |/ __ \\ / / __ \_ | \/ | \/ \ \____ |
* \________(____ /\_/ (____ / /_______ /\____|__ /_______ / / ______|
* \/ \/ \/ \/ \/ \/
*/
package org.boon;
import org.boon.collections.DoubleList;
import org.boon.collections.FloatList;
import org.boon.collections.IntList;
import org.boon.collections.LongList;
import org.boon.core.*;
import org.boon.core.reflection.*;
import org.boon.core.reflection.fields.FieldAccess;
import org.boon.primitive.CharBuf;
import java.lang.reflect.Array;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class Lists {
public static <T> List<T> lazyAdd(List<T> list, T... items) {
list = list == null ? new ArrayList<T>() : list;
for (T item : items) {
list.add(item);
}
return list;
}
public static <T> List<T> lazyAdd(ArrayList<T> list, T... items) {
list = list == null ? new ArrayList<T>() : list;
for (T item : items) {
list.add(item);
}
return list; }
public static <T> List<T> safeLazyAdd(CopyOnWriteArrayList<T> list, T... items) {
list = list == null ? new CopyOnWriteArrayList<T>() : list;
for (T item : items) {
list.add(item);
}
return list;
}
public static <T> List<T> lazyAdd(CopyOnWriteArrayList<T> list, T... items) {
list = list == null ? new CopyOnWriteArrayList<T>() : list;
for (T item : items) {
list.add(item);
}
return list;
}
public static <T> List<T> lazyCreate(List<T> list) {
return list == null ? new ArrayList<T>() : list;
}
public static <T> List<T> lazyCreate(ArrayList<T> list) {
return list == null ? new ArrayList<T>() : list;
}
public static <T> List<T> lazyCreate(CopyOnWriteArrayList<T> list) {
return list == null ? new CopyOnWriteArrayList<T>() : list;
}
public static <T> List<T> safeLazyCreate(CopyOnWriteArrayList<T> list) {
return list == null ? new CopyOnWriteArrayList<T>() : list;
}
public static <T> T fromList( List<Object> list, Class<T> clazz ) {
return MapObjectConversion.fromList( list, clazz );
}
public static <V> List<V> list( Class<V> clazz ) {
return new ArrayList<>();
}
public static <V> List<V> copy( Collection<V> collection ) {
return new ArrayList<>( collection );
}
public static <V> List<V> deepCopy( Collection<V> collection ) {
List<V> list = new ArrayList<>(collection.size());
for (V v : collection) {
list.add( BeanUtils.copy( v ));
}
return list;
}
public static <V> List<V> deepCopyToList( Collection<V> src, List<V> dst) {
for (V v : src) {
dst.add( BeanUtils.copy( v ));
}
return dst;
}
public static <V,T> List<T> deepCopy( Collection<V> src, Class<T> dest ) {
List<T> list = new ArrayList<>(src.size());
for (V v : src) {
list.add( BeanUtils.createFromSrc( v, dest ));
}
return list;
}
/**
* Clones each list item into a new instance with copied fields.
* It is like doing a clone operation.
*
* If the passed list is a LinkedList then the returned list will be a
* LinkedList.
*
* If the passed list is a CopyOnWriteArrayList then the returned list will
* be a CopyOnWriteArrayList list.
*
* All other lists become ArrayList.
*
* @param list list to clone
* @param <V> generics
* @return new list
*/
@Universal
public static <V> List<V> deepCopy( List<V> list ) {
if ( list instanceof LinkedList ) {
return deepCopyToList( list, new LinkedList<V>( ) );
} else if ( list instanceof CopyOnWriteArrayList ) {
return deepCopyToList( list, new CopyOnWriteArrayList<V>( ));
} else {
return deepCopy( (Collection)list);
}
}
public static <V> List<List<V>> lists( Collection<V>... collections ) {
List<List<V>> lists = new ArrayList<>(collections.length);
for (Collection<V> collection : collections) {
lists.add(new ArrayList<>(collection));
}
return lists;
}
public static <V> List<V> list( Iterable<V> iterable ) {
List<V> list = new ArrayList<>();
for ( V o : iterable ) {
list.add( o );
}
return list;
}
public static <V> List<V> list( Collection<V> collection ) {
return new ArrayList<>(collection);
}
public static <V> List<V> linkedList( Iterable<V> iterable ) {
List<V> list = new LinkedList<>();
for ( V o : iterable ) {
list.add( o );
}
return list;
}
public static List<?> toListOrSingletonList( Object item ) {
if ( item == null ) {
return new ArrayList<>();
} else if ( item.getClass().isArray() ) {
final int length = Array.getLength( item );
List<Object> list = new ArrayList<>();
for ( int index = 0; index < length; index++ ) {
list.add( Array.get( item, index ) );
}
return list;
} else if ( item instanceof Collection ) {
return list( ( Collection ) item );
} else if ( item instanceof Iterator ) {
return list( ( Iterator ) item );
} else if ( item instanceof Enumeration ) {
return list( ( Enumeration ) item );
} else if ( item instanceof Iterable ) {
return list( ( Iterable ) item );
} else {
List<Object> list = new ArrayList<>();
list.add( item );
return list;
}
}
public static <PROP> List<PROP> toList( List<?> inputList, Class<PROP> cls, String propertyPath ) {
List<PROP> outputList = new ArrayList<>();
for (Object o : inputList) {
outputList.add((PROP) BeanUtils.idx(o, propertyPath));
}
return outputList;
}
public static IntList toIntList( List<?> inputList, String propertyPath ) {
return IntList.toIntList(inputList, propertyPath);
}
public static FloatList toFloatList( List<?> inputList, String propertyPath ) {
return FloatList.toFloatList(inputList, propertyPath);
}
public static DoubleList toDoubleList( List<?> inputList, String propertyPath ) {
return DoubleList.toDoubleList(inputList, propertyPath);
}
public static LongList toLongList( List<?> inputList, String propertyPath ) {
return LongList.toLongList(inputList, propertyPath);
}
public static List<?> toList( List<?> inputList, String propertyPath ) {
List<Object> outputList = new ArrayList<>();
for (Object o : inputList) {
outputList.add(BeanUtils.idx(o, propertyPath));
}
return outputList;
}
public static List<?> toList( Object item ) {
if ( item!= null && item.getClass().isArray() ) {
final int length = Array.getLength( item );
List<Object> list = new ArrayList<>();
for ( int index = 0; index < length; index++ ) {
list.add( Array.get( item, index ) );
}
return list;
} else if ( item instanceof Collection ) {
return list( ( Collection ) item );
} else if ( item instanceof Iterator ) {
return list( ( Iterator ) item );
} else if ( item instanceof Enumeration ) {
return list( ( Enumeration ) item );
} else if ( item instanceof Iterable ) {
return list( ( Iterable ) item );
} else {
return MapObjectConversion.toList( item );
}
}
public static <V, WRAP> List<WRAP> convert(Class<WRAP> wrapper, Iterable<V> collection ) {
List<WRAP> list = new ArrayList<>( );
for (V v : collection) {
list.add ( Conversions.coerce(wrapper, v) );
}
return list;
}
public static <V, WRAP> List<WRAP> convert(Class<WRAP> wrapper, Collection<V> collection ) {
List<WRAP> list = new ArrayList<>( collection.size() );
for (V v : collection) {
list.add ( Conversions.coerce(wrapper, v) );
}
return list;
}
public static <V, WRAP> List<WRAP> convert(Class<WRAP> wrapper, V[] collection ) {
List<WRAP> list = new ArrayList<>( collection.length );
for (V v : collection) {
list.add ( Conversions.coerce(wrapper, v) );
}
return list;
}
public static <V, WRAP> List<WRAP> wrap(Class<WRAP> wrapper, Iterable<V> collection ) {
List<WRAP> list = new ArrayList<>( );
for (V v : collection) {
WRAP wrap = Reflection.newInstance ( wrapper, v );
list.add ( wrap );
}
return list;
}
public static <V, WRAP> List<WRAP> wrap(Class<WRAP> wrapper, Collection<V> collection ) {
if (collection.size()==0) {
return Collections.EMPTY_LIST;
}
List<WRAP> list = new ArrayList<>( collection.size () );
ClassMeta <WRAP> cls = ClassMeta.classMeta(wrapper);
ConstructorAccess<WRAP> declaredConstructor = cls.declaredConstructor(collection.iterator().next().getClass());
for (V v : collection) {
WRAP wrap = declaredConstructor.create ( v );
list.add ( wrap );
}
return list;
}
public static <V, WRAP> List<WRAP> wrap(Class<WRAP> wrapper, V[] collection ) {
List<WRAP> list = new ArrayList<>( collection.length );
for (V v : collection) {
WRAP wrap = Reflection.newInstance ( wrapper, v );
list.add ( wrap );
}
return list;
}
public static <V> List<V> list( Enumeration<V> enumeration ) {
List<V> list = new ArrayList<>();
while ( enumeration.hasMoreElements() ) {
list.add( enumeration.nextElement() );
}
return list;
}
public static <V> Enumeration<V> enumeration( final List<V> list ) {
final Iterator<V> iter = list.iterator();
return new Enumeration<V>() {
@Override
public boolean hasMoreElements() {
return iter.hasNext();
}
@Override
public V nextElement() {
return iter.next();
}
};
}
public static <V> List<V> list( Iterator<V> iterator ) {
List<V> list = new ArrayList<>();
while ( iterator.hasNext() ) {
list.add( iterator.next() );
}
return list;
}
@SafeVarargs
public static <V> List<V> list( final V... array ) {
if ( array == null ) {
return new ArrayList<>();
}
List<V> list = new ArrayList<>( array.length );
Collections.addAll( list, array );
return list;
}
public static <V> List<V> safeList(Class<V> cls) {
return new CopyOnWriteArrayList<>( );
}
@SafeVarargs
public static <V> List<V> safeList( final V... array ) {
return new CopyOnWriteArrayList<>( array );
}
@SafeVarargs
public static <V> List<V> linkedList( final V... array ) {
if ( array == null ) {
return new LinkedList<>();
}
List<V> list = new LinkedList<>();
Collections.addAll( list, array );
return list;
}
public static <V> List<V> safeList( Collection<V> collection ) {
return new CopyOnWriteArrayList<>( collection );
}
public static <V> List<V> linkedList( Collection<V> collection ) {
return new LinkedList<>( collection );
}
/**
* Universal methods
*/
@Universal
public static int len( List<?> list ) {
return list.size();
}
@Universal
public static int lengthOf( List<?> list ) {
return len (list);
}
public static boolean isEmpty( List<?> list ) {
return list == null || list.size() == 0;
}
@Universal
public static <V> boolean in( V value, List<?> list ) {
return list.contains( value );
}
@Universal
public static <V> void add( List<V> list, V value ) {
list.add( value );
}
@Universal
public static <V> void add( List<V> list, V... values ) {
for (V v : values) {
list.add( v );
}
}
@Universal
public static <T> T atIndex( List<T> list, final int index ) {
return idx(list, index);
}
@Universal
public static <T> T idx( List<T> list, final int index ) {
int i = calculateIndex( list, index );
if ( i > list.size() - 1 ) {
i = list.size() - 1;
}
return list.get( i );
}
public static <T> List idxList( List<T> list, final int index ) {
return (List) idx(list, index);
}
public static <T> Map idxMap( List<T> list, final int index ) {
return (Map) idx(list, index);
}
@Universal
public static <V> void atIndex( List<V> list, int index, V v ) {
idx (list, index, v);
}
@Universal
public static <V> void idx( List<V> list, int index, V v ) {
int i = calculateIndex( list, index );
list.set( i, v );
}
@Universal
public static <V> List<V> sliceOf( List<V> list, int startIndex, int endIndex ) {
return slc(list, startIndex, endIndex);
}
@Universal
public static <V> List<V> slc( List<V> list, int startIndex, int endIndex ) {
int start = calculateIndex( list, startIndex );
int end = calculateIndex( list, endIndex );
return list.subList( start, end );
}
@Universal
public static <V> List<V> sliceOf( List<V> list, int startIndex ) {
return slc(list, startIndex);
}
@Universal
public static <V> List<V> slc( List<V> list, int startIndex ) {
return slc( list, startIndex, list.size() );
}
@Universal
public static <V> List<V> endSliceOf( List<V> list, int endIndex ) {
return slcEnd( list, endIndex );
}
@Universal
public static <V> List<V> slcEnd( List<V> list, int endIndex ) {
return slc( list, 0, endIndex );
}
@Universal
public static <V> List<V> copy( List<V> list ) {
if ( list instanceof LinkedList ) {
return new LinkedList<>( list );
} else if ( list instanceof CopyOnWriteArrayList ) {
return new CopyOnWriteArrayList<>( list );
} else {
return new ArrayList<>( list );
}
}
@Universal
public static <V> List<V> copy( CopyOnWriteArrayList<V> list ) {
return new CopyOnWriteArrayList<>( list );
}
@Universal
public static <V> List<V> copy( ArrayList<V> list ) {
return new ArrayList<>( list );
}
@Universal
public static <V> List<V> copy( LinkedList<V> list ) {
return new LinkedList<>( list );
}
@Universal
public static <V> void insert( List<V> list, int index, V v ) {
int i = calculateIndex( list, index );
list.add( i, v );
}
/* End universal methods. */
private static <T> int calculateIndex( List<T> list, int originalIndex ) {
final int length = list.size();
int index = originalIndex;
/* Adjust for reading from the right as in
-1 reads the 4th element if the length is 5
*/
if ( index < 0 ) {
index = ( length + index );
}
/* Bounds check
if it is still less than 0, then they
have an negative index that is greater than length
*/
if ( index < 0 ) {
index = 0;
}
if ( index > length ) {
index = length;
}
return index;
}
public static <T> List<T> listFromProperty( Class<T> propertyType, String propertyPath, Collection<?> list ) {
List<T> newList = new ArrayList<>( list.size() );
for ( Object item : list ) {
T newItem = ( T ) BeanUtils.idx( item, propertyPath );
newList.add( newItem );
}
return newList;
}
public static <T> List<T> listFromProperty( Class<T> propertyType, String propertyPath, Iterable<?> list ) {
List<T> newList = new ArrayList<>( );
for ( Object item : list ) {
T newItem = ( T ) BeanUtils.idx( item, propertyPath );
newList.add( newItem );
}
return newList;
}
public static List<Map<String, Object>> toListOfMaps( List<?> list ) {
return MapObjectConversion.toListOfMaps( list );
}
public static void setListProperty(List<?> list, String propertyName, Object value) {
for (Object object : list) {
BeanUtils.idx(object, propertyName, value);
}
}
public static List<?> mapBy( Object[] objects, Object instance, String methodName) {
List list = new ArrayList(objects.length);
for (Object o : objects) {
list.add( Invoker.invoke(instance, methodName, o ));
}
return list;
}
public static List<?> mapBy(Object[] objects, Class<?> cls, String methodName) {
List list = new ArrayList(objects.length);
for (Object o : objects) {
list.add( Invoker.invoke(cls,methodName, o ));
}
return list;
}
public static List<?> mapBy(Iterable<?> objects, Class<?> cls, String methodName) {
List list = new ArrayList();
for (Object o : objects) {
list.add( Invoker.invoke(cls, methodName, o ));
}
return list;
}
public static List<?> mapBy(Iterable<?> objects, Object instance, String methodName) {
List list = new ArrayList();
for (Object o : objects) {
list.add( Invoker.invoke(instance, methodName, o ));
}
return list;
}
public static List<?> mapBy(Collection<?> objects, Class<?> cls, String methodName) {
List list = new ArrayList(objects.size());
MethodAccess methodAccess = Invoker.invokeMethodAccess(cls, methodName);
for (Object o : objects) {
list.add( methodAccess.invokeStatic(o));
}
return list;
}
public static List<?> mapBy(Collection<?> objects, Object function) {
MethodAccess methodAccess = Invoker.invokeFunctionMethodAccess(function);
List list = new ArrayList();
for (Object o : objects) {
list.add( methodAccess.invoke(function, o));
}
return list;
}
public static <T> List<T> mapBy(Class<T> cls, Collection<?> objects, Object function) {
return (List<T>) mapBy(objects, function);
}
public static List<?> mapBy(Iterable<?> objects, Object function) {
MethodAccess methodAccess = Invoker.invokeFunctionMethodAccess(function);
List list = new ArrayList();
for (Object o : objects) {
list.add( methodAccess.invoke(function, o));
}
return list;
}
public static List<?> mapBy(Object[] objects, Object function) {
MethodAccess methodAccess = Invoker.invokeFunctionMethodAccess(function);
List list = new ArrayList(objects.length);
for (Object o : objects) {
list.add( methodAccess.invoke(function, o));
}
return list;
}
public static List<?> mapBy(Collection<?> objects, Object object, String methodName) {
MethodAccess methodAccess = Invoker.invokeMethodAccess(object.getClass(), methodName);
List list = new ArrayList(objects.size());
for (Object o : objects) {
list.add( methodAccess.invoke(object, o));
}
return list;
}
public static <V, N> List<N> mapBy( final V[] array, Function<V, N> function ) {
List<N> list = new ArrayList<>( array.length );
for ( V v : array ) {
list.add( function.apply( v ) );
}
return list;
}
public static <V, N> List<N> mapBy( final Collection<V> array, Function<V, N> function ) {
List<N> list = new ArrayList<>( array.size() );
for ( V v : array ) {
list.add( function.apply( v ) );
}
return list;
}
public static <V, N> List<N> mapBy( final Iterable<V> array, Function<V, N> function ) {
List<N> list = new ArrayList<>( );
for ( V v : array ) {
list.add( function.apply( v ) );
}
return list;
}
public static <V, SUM> SUM reduceBy( final Iterable<V> array, Reducer<V, SUM> function ) {
SUM sum = null;
for ( V v : array ) {
sum = function.apply( sum, v ) ;
}
return sum;
}
public static Object reduceBy( final Iterable<?> array, Object object ) {
Object sum = null;
for ( Object v : array ) {
sum = Invoker.invokeReducer(object, sum, v);
}
return sum;
}
public static <T> List<T> filterBy( final Iterable<T> array, Predicate<T> predicate ) {
List<T> list = new ArrayList<>( );
for ( T v : array ) {
if ( predicate.test(v)) {
list.add( v );
}
}
return list;
}
public static <T> List<T> filterBy( final Collection<T> array, Predicate<T> predicate ) {
List<T> list = new ArrayList<>( array.size() );
for ( T v : array ) {
if ( predicate.test(v)) {
list.add( v );
}
}
return list;
}
public static <T> List<T> filterBy( Predicate<T> predicate, final T[] array ) {
List<T> list = new ArrayList<>( array.length );
for ( T v : array ) {
if ( predicate.test(v)) {
list.add( v );
}
}
return list;
}
public static <T> List<T> filterBy( final Iterable<T> array, Object object ) {
List<T> list = new ArrayList<>( );
for ( T v : array ) {
if ( Invoker.invokeBooleanReturn(object, v) ) {
list.add( v );
}
}
return list;
}
public static <T> List<T> filterBy( final Collection<T> array, Object object ) {
List<T> list = new ArrayList<>( array.size() );
for ( T v : array ) {
if ( Invoker.invokeBooleanReturn(object, v) ) {
list.add( v );
}
}
return list;
}
public static <T> List<T> filterBy( final T[] array, Object object ) {
List<T> list = new ArrayList<>( array.length );
for ( T v : array ) {
if ( Invoker.invokeBooleanReturn(object, v) ) {
list.add( v );
}
}
return list;
}
public static <T> List<T> filterBy( final Iterable<T> array, Object object, String methodName ) {
List<T> list = new ArrayList<>( );
for ( T v : array ) {
if ( (boolean) Invoker.invokeEither(object, methodName, v) ) {
list.add( v );
}
}
return list;
}
public static <T> List<T> filterBy( final Collection<T> array, Object object, String methodName ) {
List<T> list = new ArrayList<>( array.size() );
for ( T v : array ) {
if ( (boolean) Invoker.invokeEither(object, methodName, v) ) {
list.add( v );
}
}
return list;
}
public static <T> List<T> filterBy( final T[] array, Object object, String methodName ) {
List<T> list = new ArrayList<>( array.length );
for ( T v : array ) {
if ( (boolean) Invoker.invokeEither(object, methodName, v) ) {
list.add( v );
}
}
return list;
}
public static String toPrettyJson(List list) {
CharBuf buf = CharBuf.createCharBuf();
return buf.prettyPrintCollection(list, false, 0).toString();
}
}
| |
package org.eclipse.jetty.websocket;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.ByteArrayEndPoint;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.Utf8StringBuilder;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* @version $Revision$ $Date$
*/
public class WebSocketMessageD13Test
{
private static Server __server;
private static Connector __connector;
private static TestWebSocket __serverWebSocket;
private static CountDownLatch __latch;
private static AtomicInteger __textCount = new AtomicInteger(0);
@BeforeClass
public static void startServer() throws Exception
{
__server = new Server();
__connector = new SelectChannelConnector();
__server.addConnector(__connector);
WebSocketHandler wsHandler = new WebSocketHandler()
{
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol)
{
__textCount.set(0);
__serverWebSocket = new TestWebSocket();
__serverWebSocket._onConnect=("onConnect".equals(protocol));
__serverWebSocket._echo=("echo".equals(protocol));
__serverWebSocket._aggregate=("aggregate".equals(protocol));
__serverWebSocket._latch=("latch".equals(protocol));
if (__serverWebSocket._latch)
__latch=new CountDownLatch(1);
return __serverWebSocket;
}
};
wsHandler.getWebSocketFactory().setBufferSize(8192);
wsHandler.getWebSocketFactory().setMaxIdleTime(1000);
wsHandler.setHandler(new DefaultHandler());
__server.setHandler(wsHandler);
__server.start();
}
@AfterClass
public static void stopServer() throws Exception
{
__server.stop();
__server.join();
}
@Test
public void testHash()
{
assertEquals("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",WebSocketConnectionD13.hashKey("dGhlIHNhbXBsZSBub25jZQ=="));
}
@Test
public void testServerSendBigStringMessage() throws Exception
{
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: chat, superchat\r\n"+
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
// Make sure the read times out if there are problems with the implementation
socket.setSoTimeout(1000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
// Server sends a big message
StringBuilder message = new StringBuilder();
String text = "0123456789ABCDEF";
for (int i = 0; i < (0x2000) / text.length(); i++)
message.append(text);
String data=message.toString();
__serverWebSocket.connection.sendMessage(data);
assertEquals(WebSocketConnectionD13.OP_TEXT,input.read());
assertEquals(0x7e,input.read());
assertEquals(0x1f,input.read());
assertEquals(0xf6,input.read());
lookFor(data.substring(0,0x1ff6),input);
assertEquals(0x80,input.read());
assertEquals(0x0A,input.read());
lookFor(data.substring(0x1ff6),input);
}
@Test
public void testServerSendOnConnect() throws Exception
{
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: onConnect\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
// Make sure the read times out if there are problems with the implementation
socket.setSoTimeout(1000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
assertEquals(0x81,input.read());
assertEquals(0x0f,input.read());
lookFor("sent on connect",input);
}
@Test
public void testIdentityExtension() throws Exception
{
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: onConnect\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"Sec-WebSocket-Extensions: identity;param=0\r\n"+
"Sec-WebSocket-Extensions: identity;param=1, identity ; param = '2' ; other = ' some = value ' \r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
// Make sure the read times out if there are problems with the implementation
socket.setSoTimeout(1000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("Sec-WebSocket-Extensions: ",input);
lookFor("identity;param=0",input);
skipTo("Sec-WebSocket-Extensions: ",input);
lookFor("identity;param=1",input);
skipTo("Sec-WebSocket-Extensions: ",input);
lookFor("identity;",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
assertEquals(0x81,input.read());
assertEquals(0x0f,input.read());
lookFor("sent on connect",input);
}
@Test
public void testFragmentExtension() throws Exception
{
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: onConnect\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"Sec-WebSocket-Extensions: fragment;maxLength=4;minFragments=7\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
// Make sure the read times out if there are problems with the implementation
socket.setSoTimeout(1000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("Sec-WebSocket-Extensions: ",input);
lookFor("fragment;",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
assertEquals(0x01,input.read());
assertEquals(0x04,input.read());
lookFor("sent",input);
assertEquals(0x00,input.read());
assertEquals(0x04,input.read());
lookFor(" on ",input);
assertEquals(0x00,input.read());
assertEquals(0x04,input.read());
lookFor("conn",input);
assertEquals(0x00,input.read());
assertEquals(0x01,input.read());
lookFor("e",input);
assertEquals(0x00,input.read());
assertEquals(0x01,input.read());
lookFor("c",input);
assertEquals(0x00,input.read());
assertEquals(0x00,input.read());
assertEquals(0x80,input.read());
assertEquals(0x01,input.read());
lookFor("t",input);
}
@Test
public void testDeflateFrameExtension() throws Exception
{
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: echo\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"Sec-WebSocket-Extensions: x-deflate-frame;minLength=64\r\n"+
"Sec-WebSocket-Extensions: fragment;minFragments=2\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
// Make sure the read times out if there are problems with the implementation
socket.setSoTimeout(1000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("Sec-WebSocket-Extensions: ",input);
lookFor("x-deflate-frame;minLength=64",input);
skipTo("Sec-WebSocket-Extensions: ",input);
lookFor("fragment;",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
// Server sends a big message
String text = "0123456789ABCDEF ";
text=text+text+text+text;
text=text+text+text+text;
text=text+text+text+text+'X';
byte[] data=text.getBytes("utf-8");
Deflater deflater = new Deflater();
deflater.setInput(data);
deflater.finish();
byte[] buf=new byte[data.length];
buf[0]=(byte)((byte)0x7e);
buf[1]=(byte)(data.length>>8);
buf[2]=(byte)(data.length&0xff);
int l=deflater.deflate(buf,3,buf.length-3);
assertTrue(deflater.finished());
output.write(0xC1);
output.write((byte)(0x80|(0xff&(l+3))));
output.write(0x00);
output.write(0x00);
output.write(0x00);
output.write(0x00);
output.write(buf,0,l+3);
output.flush();
assertEquals(0x40+WebSocketConnectionD13.OP_TEXT,input.read());
assertEquals(0x20+3,input.read());
assertEquals(0x7e,input.read());
assertEquals(0x02,input.read());
assertEquals(0x20,input.read());
byte[] raw = new byte[32];
assertEquals(32,input.read(raw));
Inflater inflater = new Inflater();
inflater.setInput(raw);
byte[] result = new byte[544];
assertEquals(544,inflater.inflate(result));
assertEquals(TypeUtil.toHexString(data,0,544),TypeUtil.toHexString(result));
assertEquals((byte)0xC0,(byte)input.read());
assertEquals(0x21+3,input.read());
assertEquals(0x7e,input.read());
assertEquals(0x02,input.read());
assertEquals(0x21,input.read());
assertEquals(32,input.read(raw));
inflater.reset();
inflater.setInput(raw);
result = new byte[545];
assertEquals(545,inflater.inflate(result));
assertEquals(TypeUtil.toHexString(data,544,545),TypeUtil.toHexString(result));
}
@Test
public void testServerEcho() throws Exception
{
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: echo\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
output.write(0x84);
output.write(0x8f);
output.write(0xff);
output.write(0xff);
output.write(0xff);
output.write(0xff);
byte[] bytes="this is an echo".getBytes(StringUtil.__ISO_8859_1);
for (int i=0;i<bytes.length;i++)
output.write(bytes[i]^0xff);
output.flush();
// Make sure the read times out if there are problems with the implementation
socket.setSoTimeout(1000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
assertEquals(0x84,input.read());
assertEquals(0x0f,input.read());
lookFor("this is an echo",input);
}
@Test
public void testBlockedConsumer() throws Exception
{
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
byte[] bytes="This is a long message of text that we will send again and again".getBytes(StringUtil.__ISO_8859_1);
byte[] mesg=new byte[bytes.length+6];
mesg[0]=(byte)(0x80+WebSocketConnectionD13.OP_TEXT);
mesg[1]=(byte)(0x80+bytes.length);
mesg[2]=(byte)0xff;
mesg[3]=(byte)0xff;
mesg[4]=(byte)0xff;
mesg[5]=(byte)0xff;
for (int i=0;i<bytes.length;i++)
mesg[6+i]=(byte)(bytes[i]^0xff);
final int count = 100000;
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: latch\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
// Make sure the read times out if there are problems with the implementation
socket.setSoTimeout(60000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
__serverWebSocket.connection.setMaxIdleTime(60000);
// Send and receive 1 message
output.write(mesg);
output.flush();
while(__textCount.get()==0)
Thread.sleep(10);
// unblock the latch in 4s
new Thread()
{
@Override
public void run()
{
try
{
Thread.sleep(4000);
__latch.countDown();
//System.err.println("latched");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}.start();
// Send enough messages to fill receive buffer
long max=0;
long start=System.currentTimeMillis();
for (int i=0;i<count;i++)
{
output.write(mesg);
if (i%100==0)
{
// System.err.println(">>> "+i);
output.flush();
long now=System.currentTimeMillis();
long duration=now-start;
start=now;
if (max<duration)
max=duration;
}
}
Thread.sleep(50);
while(__textCount.get()<count+1)
{
System.err.println(__textCount.get()+"<"+(count+1));
Thread.sleep(10);
}
assertEquals(count+1,__textCount.get()); // all messages
assertTrue(max>2000); // was blocked
}
@Test
public void testBlockedProducer() throws Exception
{
final Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
final int count = 100000;
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: latch\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
// Make sure the read times out if there are problems with the implementation
socket.setSoTimeout(60000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
__serverWebSocket.connection.setMaxIdleTime(60000);
__latch.countDown();
// wait 2s and then consume messages
final AtomicLong totalB=new AtomicLong();
new Thread()
{
@Override
public void run()
{
try
{
Thread.sleep(2000);
byte[] recv = new byte[32*1024];
int len=0;
while (len>=0)
{
totalB.addAndGet(len);
len=socket.getInputStream().read(recv,0,recv.length);
Thread.sleep(10);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}.start();
// Send enough messages to fill receive buffer
long max=0;
long start=System.currentTimeMillis();
String mesg="How Now Brown Cow";
for (int i=0;i<count;i++)
{
__serverWebSocket.connection.sendMessage(mesg);
if (i%100==0)
{
output.flush();
long now=System.currentTimeMillis();
long duration=now-start;
start=now;
if (max<duration)
max=duration;
}
}
while(totalB.get()<(count*(mesg.length()+2)))
Thread.sleep(100);
assertEquals(count*(mesg.length()+2),totalB.get()); // all messages
assertTrue(max>1000); // was blocked
}
@Test
public void testServerPingPong() throws Exception
{
Socket socket = new Socket("localhost", __connector.getLocalPort());
// Make sure the read times out if there are problems with the implementation
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: echo\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
output.write(0x89);
output.write(0x80);
output.write(0xff);
output.write(0xff);
output.write(0xff);
output.write(0xff);
output.flush();
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
socket.setSoTimeout(1000);
assertEquals(0x8A,input.read());
assertEquals(0x00,input.read());
}
@Test
public void testMaxTextSizeFalseFrag() throws Exception
{
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: other\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
socket.setSoTimeout(1000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
__serverWebSocket.getConnection().setMaxTextMessageSize(10*1024);
__serverWebSocket.getConnection().setAllowFrameFragmentation(true);
output.write(0x81);
output.write(0x80|0x7E);
output.write((byte)((16*1024)>>8));
output.write((byte)((16*1024)&0xff));
output.write(0x00);
output.write(0x00);
output.write(0x00);
output.write(0x00);
for (int i=0;i<(16*1024);i++)
output.write('X');
output.flush();
assertEquals(0x80|WebSocketConnectionD13.OP_CLOSE,input.read());
assertEquals(33,input.read());
int code=(0xff&input.read())*0x100+(0xff&input.read());
assertEquals(WebSocketConnectionD13.CLOSE_MESSAGE_TOO_LARGE,code);
lookFor("Text message size > 10240 chars",input);
}
@Test
public void testMaxTextSize() throws Exception
{
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: other\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
socket.setSoTimeout(1000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
__serverWebSocket.getConnection().setMaxTextMessageSize(15);
output.write(0x01);
output.write(0x8a);
output.write(0xff);
output.write(0xff);
output.write(0xff);
output.write(0xff);
byte[] bytes="0123456789".getBytes(StringUtil.__ISO_8859_1);
for (int i=0;i<bytes.length;i++)
output.write(bytes[i]^0xff);
output.flush();
output.write(0x80);
output.write(0x8a);
output.write(0xff);
output.write(0xff);
output.write(0xff);
output.write(0xff);
for (int i=0;i<bytes.length;i++)
output.write(bytes[i]^0xff);
output.flush();
assertEquals(0x80|WebSocketConnectionD13.OP_CLOSE,input.read());
assertEquals(30,input.read());
int code=(0xff&input.read())*0x100+(0xff&input.read());
assertEquals(WebSocketConnectionD13.CLOSE_MESSAGE_TOO_LARGE,code);
lookFor("Text message size > 15 chars",input);
}
@Test
public void testMaxTextSize2() throws Exception
{
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: other\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
socket.setSoTimeout(100000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
__serverWebSocket.getConnection().setMaxTextMessageSize(15);
output.write(0x01);
output.write(0x94);
output.write(0xff);
output.write(0xff);
output.write(0xff);
output.write(0xff);
byte[] bytes="01234567890123456789".getBytes(StringUtil.__ISO_8859_1);
for (int i=0;i<bytes.length;i++)
output.write(bytes[i]^0xff);
output.flush();
assertEquals(0x80|WebSocketConnectionD13.OP_CLOSE,input.read());
assertEquals(30,input.read());
int code=(0xff&input.read())*0x100+(0xff&input.read());
assertEquals(WebSocketConnectionD13.CLOSE_MESSAGE_TOO_LARGE,code);
lookFor("Text message size > 15 chars",input);
}
@Test
public void testBinaryAggregate() throws Exception
{
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: aggregate\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
socket.setSoTimeout(1000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
__serverWebSocket.getConnection().setMaxBinaryMessageSize(1024);
output.write(WebSocketConnectionD13.OP_BINARY);
output.write(0x8a);
output.write(0xff);
output.write(0xff);
output.write(0xff);
output.write(0xff);
byte[] bytes="0123456789".getBytes(StringUtil.__ISO_8859_1);
for (int i=0;i<bytes.length;i++)
output.write(bytes[i]^0xff);
output.flush();
output.write(0x80);
output.write(0x8a);
output.write(0xff);
output.write(0xff);
output.write(0xff);
output.write(0xff);
for (int i=0;i<bytes.length;i++)
output.write(bytes[i]^0xff);
output.flush();
assertEquals(0x80+WebSocketConnectionD13.OP_BINARY,input.read());
assertEquals(20,input.read());
lookFor("01234567890123456789",input);
}
@Test
public void testMaxBinarySize() throws Exception
{
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: other\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
socket.setSoTimeout(100000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
__serverWebSocket.getConnection().setMaxBinaryMessageSize(15);
output.write(0x02);
output.write(0x8a);
output.write(0xff);
output.write(0xff);
output.write(0xff);
output.write(0xff);
byte[] bytes="0123456789".getBytes(StringUtil.__ISO_8859_1);
for (int i=0;i<bytes.length;i++)
output.write(bytes[i]^0xff);
output.flush();
output.write(0x80);
output.write(0x8a);
output.write(0xff);
output.write(0xff);
output.write(0xff);
output.write(0xff);
for (int i=0;i<bytes.length;i++)
output.write(bytes[i]^0xff);
output.flush();
assertEquals(0x80|WebSocketConnectionD13.OP_CLOSE,input.read());
assertEquals(19,input.read());
int code=(0xff&input.read())*0x100+(0xff&input.read());
assertEquals(WebSocketConnectionD13.CLOSE_MESSAGE_TOO_LARGE,code);
lookFor("Message size > 15",input);
}
@Test
public void testCloseIn() throws Exception
{
int[][] tests =
{
{-1,0,-1},
{-1,0,-1},
{1000,2,1000},
{1000,2+4,1000},
{1005,2+23,1002},
{1005,2+23,1002},
{1006,2+23,1002},
{1006,2+23,1002},
{4000,2,4000},
{4000,2+4,4000},
{9000,2+23,1002},
{9000,2+23,1002}
};
String[] mesg =
{
"",
"",
"",
"mesg",
"",
"mesg",
"",
"mesg",
"",
"mesg",
"",
"mesg"
};
String[] resp =
{
"",
"",
"",
"mesg",
"Invalid close code 1005",
"Invalid close code 1005",
"Invalid close code 1006",
"Invalid close code 1006",
"",
"mesg",
"Invalid close code 9000",
"Invalid close code 9000"
};
for (int t=0;t<tests.length;t++)
{
String tst=""+t;
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: chat\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
socket.setSoTimeout(100000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
int code=tests[t][0];
String m=mesg[t];
output.write(0x88);
output.write(0x80 + (code<=0?0:(2+m.length())));
output.write(0x00);
output.write(0x00);
output.write(0x00);
output.write(0x00);
if (code>0)
{
output.write(code/0x100);
output.write(code%0x100);
output.write(m.getBytes());
}
output.flush();
__serverWebSocket.awaitDisconnected(1000);
byte[] buf = new byte[128];
int len = input.read(buf);
assertEquals(tst,2+tests[t][1],len);
assertEquals(tst,(byte)0x88,buf[0]);
if (len>=4)
{
code=(0xff&buf[2])*0x100+(0xff&buf[3]);
assertEquals(tst,tests[t][2],code);
if (len>4)
{
m = new String(buf,4,len-4,"UTF-8");
assertEquals(tst,resp[t],m);
}
}
else
assertEquals(tst,tests[t][2],-1);
len = input.read(buf);
assertEquals(tst,-1,len);
}
}
@Test
public void testCloseOut() throws Exception
{
int[][] tests =
{
{-1,0,-1},
{-1,0,-1},
{0,2,1000},
{0,2+4,1000},
{1000,2,1000},
{1000,2+4,1000},
{1005,0,-1},
{1005,0,-1},
{1006,0,-1},
{1006,0,-1},
{9000,2,9000},
{9000,2+4,9000}
};
String[] mesg =
{
null,
"Not Sent",
null,
"mesg",
null,
"mesg",
null,
"mesg",
null,
"mesg",
null,
"mesg"
};
for (int t=0;t<tests.length;t++)
{
String tst=""+t;
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: chat\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
socket.setSoTimeout(100000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
__serverWebSocket.getConnection().close(tests[t][0],mesg[t]);
byte[] buf = new byte[128];
int len = input.read(buf);
assertEquals(tst,2+tests[t][1],len);
assertEquals(tst,(byte)0x88,buf[0]);
if (len>=4)
{
int code=(0xff&buf[2])*0x100+(0xff&buf[3]);
assertEquals(tst,tests[t][2],code);
if (len>4)
{
String m = new String(buf,4,len-4,"UTF-8");
assertEquals(tst,mesg[t],m);
}
}
else
assertEquals(tst,tests[t][2],-1);
try
{
output.write(0x88);
output.write(0x80);
output.write(0x00);
output.write(0x00);
output.write(0x00);
output.write(0x00);
output.flush();
}
catch(IOException e)
{
System.err.println("socket "+socket);
throw e;
}
len = input.read(buf);
assertEquals(tst,-1,len);
}
}
@Test
public void testNotUTF8() throws Exception
{
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: chat\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
socket.setSoTimeout(100000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
__serverWebSocket.getConnection().setMaxBinaryMessageSize(15);
output.write(0x81);
output.write(0x82);
output.write(0x00);
output.write(0x00);
output.write(0x00);
output.write(0x00);
output.write(0xc3);
output.write(0x28);
output.flush();
assertEquals(0x80|WebSocketConnectionD13.OP_CLOSE,input.read());
assertEquals(15,input.read());
int code=(0xff&input.read())*0x100+(0xff&input.read());
assertEquals(WebSocketConnectionD13.CLOSE_BAD_PAYLOAD,code);
lookFor("Invalid UTF-8",input);
}
@Test
public void testMaxBinarySize2() throws Exception
{
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: other\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
socket.setSoTimeout(100000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
__serverWebSocket.getConnection().setMaxBinaryMessageSize(15);
output.write(0x02);
output.write(0x94);
output.write(0xff);
output.write(0xff);
output.write(0xff);
output.write(0xff);
byte[] bytes="01234567890123456789".getBytes(StringUtil.__ISO_8859_1);
for (int i=0;i<bytes.length;i++)
output.write(bytes[i]^0xff);
output.flush();
assertEquals(0x80|WebSocketConnectionD13.OP_CLOSE,input.read());
assertEquals(19,input.read());
int code=(0xff&input.read())*0x100+(0xff&input.read());
assertEquals(WebSocketConnectionD13.CLOSE_MESSAGE_TOO_LARGE,code);
lookFor("Message size > 15",input);
}
@Test
public void testIdle() throws Exception
{
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: onConnect\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
// Make sure the read times out if there are problems with the implementation
socket.setSoTimeout(10000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
assertEquals(0x81,input.read());
assertEquals(0x0f,input.read());
lookFor("sent on connect",input);
assertEquals((byte)0x88,(byte)input.read());
assertEquals(26,input.read());
assertEquals(1000/0x100,input.read());
assertEquals(1000%0x100,input.read());
lookFor("Idle",input);
// respond to close
output.write(0x88^0xff);
output.write(0x80^0xff);
output.write(0xff);
output.write(0xff);
output.write(0xff);
output.write(0xff);
output.flush();
assertTrue(__serverWebSocket.awaitDisconnected(5000));
try
{
__serverWebSocket.connection.sendMessage("Don't send");
assertTrue(false);
}
catch(IOException e)
{
assertTrue(true);
}
}
@Test
public void testClose() throws Exception
{
Socket socket = new Socket("localhost", __connector.getLocalPort());
OutputStream output = socket.getOutputStream();
output.write(
("GET /chat HTTP/1.1\r\n"+
"Host: server.example.com\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"+
"Sec-WebSocket-Origin: http://example.com\r\n"+
"Sec-WebSocket-Protocol: onConnect\r\n" +
"Sec-WebSocket-Version: "+WebSocketConnectionD13.VERSION+"\r\n"+
"\r\n").getBytes("ISO-8859-1"));
output.flush();
// Make sure the read times out if there are problems with the implementation
socket.setSoTimeout(1000);
InputStream input = socket.getInputStream();
lookFor("HTTP/1.1 101 Switching Protocols\r\n",input);
skipTo("Sec-WebSocket-Accept: ",input);
lookFor("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",input);
skipTo("\r\n\r\n",input);
assertTrue(__serverWebSocket.awaitConnected(1000));
assertNotNull(__serverWebSocket.connection);
assertEquals(0x81,input.read());
assertEquals(0x0f,input.read());
lookFor("sent on connect",input);
socket.close();
assertTrue(__serverWebSocket.awaitDisconnected(500));
try
{
__serverWebSocket.connection.sendMessage("Don't send");
assertTrue(false);
}
catch(IOException e)
{
assertTrue(true);
}
}
@Test
public void testParserAndGenerator() throws Exception
{
String message = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF";
final AtomicReference<String> received = new AtomicReference<String>();
ByteArrayEndPoint endp = new ByteArrayEndPoint(new byte[0],4096);
WebSocketGeneratorD13 gen = new WebSocketGeneratorD13(new WebSocketBuffers(8096),endp,null);
byte[] data = message.getBytes(StringUtil.__UTF8);
gen.addFrame((byte)0x8,(byte)0x4,data,0,data.length);
endp = new ByteArrayEndPoint(endp.getOut().asArray(),4096);
WebSocketParserD13 parser = new WebSocketParserD13(new WebSocketBuffers(8096),endp,new WebSocketParser.FrameHandler()
{
public void onFrame(byte flags, byte opcode, Buffer buffer)
{
received.set(buffer.toString());
}
public void close(int code,String message)
{
}
},false);
parser.parseNext();
assertEquals(message,received.get());
}
@Test
public void testParserAndGeneratorMasked() throws Exception
{
String message = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF";
final AtomicReference<String> received = new AtomicReference<String>();
ByteArrayEndPoint endp = new ByteArrayEndPoint(new byte[0],4096);
MaskGen maskGen = new RandomMaskGen();
WebSocketGeneratorD13 gen = new WebSocketGeneratorD13(new WebSocketBuffers(8096),endp,maskGen);
byte[] data = message.getBytes(StringUtil.__UTF8);
gen.addFrame((byte)0x8,(byte)0x1,data,0,data.length);
endp = new ByteArrayEndPoint(endp.getOut().asArray(),4096);
WebSocketParserD13 parser = new WebSocketParserD13(new WebSocketBuffers(8096),endp,new WebSocketParser.FrameHandler()
{
public void onFrame(byte flags, byte opcode, Buffer buffer)
{
received.set(buffer.toString());
}
public void close(int code,String message)
{
}
},true);
parser.parseNext();
assertEquals(message,received.get());
}
private void lookFor(String string,InputStream in)
throws IOException
{
String orig=string;
Utf8StringBuilder scanned=new Utf8StringBuilder();
try
{
while(true)
{
int b = in.read();
if (b<0)
throw new EOFException();
scanned.append((byte)b);
assertEquals("looking for\""+orig+"\" in '"+scanned+"'",(int)string.charAt(0),b);
if (string.length()==1)
break;
string=string.substring(1);
}
}
catch(IOException e)
{
System.err.println("IOE while looking for \""+orig+"\" in '"+scanned+"'");
throw e;
}
}
private void skipTo(String string,InputStream in)
throws IOException
{
int state=0;
while(true)
{
int b = in.read();
if (b<0)
throw new EOFException();
if (b==string.charAt(state))
{
state++;
if (state==string.length())
break;
}
else
state=0;
}
}
private static class TestWebSocket implements WebSocket.OnFrame, WebSocket.OnBinaryMessage, WebSocket.OnTextMessage
{
protected boolean _latch;
boolean _onConnect=false;
boolean _echo=true;
boolean _aggregate=false;
private final CountDownLatch connected = new CountDownLatch(1);
private final CountDownLatch disconnected = new CountDownLatch(1);
private volatile FrameConnection connection;
public FrameConnection getConnection()
{
return connection;
}
public void onHandshake(FrameConnection connection)
{
this.connection = connection;
}
public void onOpen(Connection connection)
{
if (_onConnect)
{
try
{
connection.sendMessage("sent on connect");
}
catch(IOException e)
{
e.printStackTrace();
}
}
connected.countDown();
}
private boolean awaitConnected(long time) throws InterruptedException
{
return connected.await(time, TimeUnit.MILLISECONDS);
}
private boolean awaitDisconnected(long time) throws InterruptedException
{
return disconnected.await(time, TimeUnit.MILLISECONDS);
}
public void onClose(int code,String message)
{
disconnected.countDown();
}
public boolean onFrame(byte flags, byte opcode, byte[] data, int offset, int length)
{
if (_echo)
{
switch(opcode)
{
case WebSocketConnectionD13.OP_CLOSE:
case WebSocketConnectionD13.OP_PING:
case WebSocketConnectionD13.OP_PONG:
break;
default:
try
{
connection.sendFrame(flags,opcode,data,offset,length);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return false;
}
public void onMessage(byte[] data, int offset, int length)
{
if (_aggregate)
{
try
{
connection.sendMessage(data,offset,length);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public void onMessage(String data)
{
__textCount.incrementAndGet();
if (_latch)
{
try
{
__latch.await();
}
catch(Exception e)
{
e.printStackTrace();
}
}
if (_aggregate)
{
try
{
connection.sendMessage(data);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.apache.shindig.protocol;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shindig.auth.SecurityToken;
import org.apache.shindig.common.servlet.HttpUtil;
import org.apache.shindig.common.util.JsonConversionUtil;
import org.apache.shindig.protocol.multipart.FormDataItem;
import org.apache.shindig.protocol.multipart.MultipartFormParser;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;
/**
* JSON-RPC handler servlet.
*/
public class JsonRpcServlet extends ApiServlet {
public static final Set<String> ALLOWED_CONTENT_TYPES =
new ImmutableSet.Builder<String>().addAll(ContentTypes.ALLOWED_JSON_CONTENT_TYPES)
.addAll(ContentTypes.ALLOWED_MULTIPART_CONTENT_TYPES).build();
/**
* In a multipart request, the form item with field name "request" will contain the
* actual request, per the proposed Opensocial 0.9 specification.
*/
public static final String REQUEST_PARAM = "request";
private MultipartFormParser formParser;
@Inject
void setMultipartFormParser(MultipartFormParser formParser) {
this.formParser = formParser;
}
private String jsonRpcResultField = "result";
private boolean jsonRpcBothFields = false;
@Inject
void setJsonRpcResultField(@Named("shindig.json-rpc.result-field")String jsonRpcResultField) {
this.jsonRpcResultField = jsonRpcResultField;
jsonRpcBothFields = "both".equals(jsonRpcResultField);
}
@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
throws IOException {
setCharacterEncodings(servletRequest, servletResponse);
servletResponse.setContentType(ContentTypes.OUTPUT_JSON_CONTENT_TYPE);
// only GET/POST
String method = servletRequest.getMethod();
if (!("GET".equals(method) || "POST".equals(method))) {
sendError(servletResponse,
new ResponseItem(HttpServletResponse.SC_BAD_REQUEST, "Only POST/GET Allowed"));
return;
}
SecurityToken token = getSecurityToken(servletRequest);
if (token == null) {
sendSecurityError(servletResponse);
return;
}
HttpUtil.setCORSheader(servletResponse, containerConfig.<String>getList(token.getContainer(), "gadgets.parentOrigins"));
try {
String content = null;
String callback = null; // for JSONP
Map<String,FormDataItem> formData = Maps.newHashMap();
// Get content or deal with JSON-RPC GET
if ("POST".equals(method)) {
content = getPostContent(servletRequest, formData);
} else if (HttpUtil.isJSONP(servletRequest)) {
content = servletRequest.getParameter("request");
callback = servletRequest.getParameter("callback");
} else {
// GET request, fromRequest() creates the json objects directly.
JSONObject request = JsonConversionUtil.fromRequest(servletRequest);
if (request != null) {
dispatch(request, formData, servletRequest, servletResponse, token, null);
return;
}
}
if (content == null) {
sendError(servletResponse, new ResponseItem(HttpServletResponse.SC_BAD_REQUEST, "No content specified"));
return;
}
if (isContentJsonBatch(content)) {
JSONArray batch = new JSONArray(content);
dispatchBatch(batch, formData, servletRequest, servletResponse, token, callback);
} else {
JSONObject request = new JSONObject(content);
dispatch(request, formData, servletRequest, servletResponse, token, callback);
}
return;
} catch (JSONException je) {
sendJsonParseError(je, servletResponse);
} catch (IllegalArgumentException e) {
// a bad jsonp request..
sendBadRequest(e, servletResponse);
} catch (ContentTypes.InvalidContentTypeException icte) {
sendBadRequest(icte, servletResponse);
}
}
protected String getPostContent(HttpServletRequest request, Map<String,FormDataItem> formItems)
throws ContentTypes.InvalidContentTypeException, IOException {
String content = null;
ContentTypes.checkContentTypes(ALLOWED_CONTENT_TYPES, request.getContentType());
if (formParser.isMultipartContent(request)) {
for (FormDataItem item : formParser.parse(request)) {
if (item.isFormField() && REQUEST_PARAM.equals(item.getFieldName()) && content == null) {
// As per spec, in case of a multipart/form-data content, there will be one form field
// with field name as "request". It will contain the json request. Any further form
// field or file item will not be parsed out, but will be exposed via getFormItem
// method of RequestItem.
if (!StringUtils.isEmpty(item.getContentType())) {
ContentTypes.checkContentTypes(ContentTypes.ALLOWED_JSON_CONTENT_TYPES, item.getContentType());
}
content = item.getAsString();
} else {
formItems.put(item.getFieldName(), item);
}
}
} else {
content = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
}
return content;
}
protected void dispatchBatch(JSONArray batch, Map<String, FormDataItem> formItems ,
HttpServletRequest servletRequest, HttpServletResponse servletResponse,
SecurityToken token, String callback) throws JSONException, IOException {
// Use linked hash map to preserve order
List<Future<?>> responses = Lists.newArrayListWithCapacity(batch.length());
// Gather all Futures. We do this up front so that
// the first call to get() comes after all futures are created,
// which allows for implementations that batch multiple Futures
// into single requests.
for (int i = 0; i < batch.length(); i++) {
JSONObject batchObj = batch.getJSONObject(i);
responses.add(getHandler(batchObj, servletRequest).execute(formItems, token, jsonConverter));
}
// Resolve each Future into a response.
// TODO: should use shared deadline across each request
List<Object> result = new ArrayList<Object>(batch.length());
for (int i = 0; i < batch.length(); i++) {
JSONObject batchObj = batch.getJSONObject(i);
String key = null;
if (batchObj.has("id")) {
key = batchObj.getString("id");
}
result.add(getJSONResponse(key, getResponseItem(responses.get(i))));
}
// Generate the output
Writer writer = servletResponse.getWriter();
if (callback != null) writer.append(callback).append('(');
jsonConverter.append(writer, result);
if (callback != null) writer.append(");\n");
}
protected void dispatch(JSONObject request, Map<String, FormDataItem> formItems,
HttpServletRequest servletRequest, HttpServletResponse servletResponse,
SecurityToken token, String callback) throws JSONException, IOException {
String key = null;
if (request.has("id")) {
key = request.getString("id");
}
// getRpcHandler never returns null
Future<?> future = getHandler(request, servletRequest).execute(formItems, token, jsonConverter);
// Resolve each Future into a response.
// TODO: should use shared deadline across each request
ResponseItem response = getResponseItem(future);
Object result = getJSONResponse(key, response);
// Generate the output
Writer writer = servletResponse.getWriter();
if (callback != null) writer.append(callback).append('(');
jsonConverter.append(writer, result);
if (callback != null) writer.append(");\n");
}
/**
*
*/
protected void addResult(Map<String,Object> result, Object data) {
if (jsonRpcBothFields) {
result.put("result", data);
result.put("data", data);
}
result.put(jsonRpcResultField, data);
}
/**
* Determine if the content contains a batch request
*
* @param content json content or null
* @return true if content contains is a json array, not a json object or null
*/
private boolean isContentJsonBatch(String content) {
if (content == null) return false;
return ((content.indexOf('[') != -1) && content.indexOf('[') < content.indexOf('{'));
}
/**
* Wrap call to dispatcher to allow for implementation specific overrides
* and servlet-request contextual handling
*/
protected RpcHandler getHandler(JSONObject rpc, HttpServletRequest request) {
return dispatcher.getRpcHandler(rpc);
}
Object getJSONResponse(String key, ResponseItem responseItem) {
Map<String, Object> result = Maps.newHashMap();
if (key != null) {
result.put("id", key);
}
if (responseItem.getErrorCode() < 200 ||
responseItem.getErrorCode() >= 400) {
result.put("error", getErrorJson(responseItem));
} else {
Object response = responseItem.getResponse();
if (response instanceof DataCollection) {
addResult(result, ((DataCollection) response).getEntry());
} else if (response instanceof RestfulCollection) {
Map<String, Object> map = Maps.newHashMap();
RestfulCollection<?> collection = (RestfulCollection<?>) response;
// Return sublist info
if (collection.getTotalResults() != collection.getEntry().size()) {
map.put("startIndex", collection.getStartIndex());
map.put("itemsPerPage", collection.getItemsPerPage());
}
// always put in totalResults
map.put("totalResults", collection.getTotalResults());
if (!collection.isFiltered())
map.put("filtered", collection.isFiltered());
if (!collection.isUpdatedSince())
map.put("updatedSince", collection.isUpdatedSince());
if (!collection.isSorted())
map.put("sorted", collection.isUpdatedSince());
map.put("list", collection.getEntry());
addResult(result, map);
} else {
addResult(result, response);
}
// TODO: put "code" for != 200?
}
return result;
}
/** Map of old-style error titles */
private static final Map<Integer, String> errorTitles = ImmutableMap.<Integer, String> builder()
.put(HttpServletResponse.SC_NOT_IMPLEMENTED, "notImplemented")
.put(HttpServletResponse.SC_UNAUTHORIZED, "unauthorized")
.put(HttpServletResponse.SC_FORBIDDEN, "forbidden")
.put(HttpServletResponse.SC_BAD_REQUEST, "badRequest")
.put(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "internalError")
.put(HttpServletResponse.SC_EXPECTATION_FAILED, "limitExceeded")
.build();
// TODO(doll): Refactor the responseItem so that the fields on it line up with this format.
// Then we can use the general converter to output the response to the client and we won't
// be harcoded to json.
private Object getErrorJson(ResponseItem responseItem) {
Map<String, Object> error = new HashMap<String, Object>(2, 1);
error.put("code", responseItem.getErrorCode());
String message = errorTitles.get(responseItem.getErrorCode());
if (message == null) {
message = responseItem.getErrorMessage();
} else {
if (StringUtils.isNotBlank(responseItem.getErrorMessage())) {
message += ": " + responseItem.getErrorMessage();
}
}
if (StringUtils.isNotBlank(message)) {
error.put("message", message);
}
if (responseItem.getResponse() != null) {
error.put("data", responseItem.getResponse());
}
return error;
}
@Override
protected void sendError(HttpServletResponse servletResponse, ResponseItem responseItem)
throws IOException {
jsonConverter.append(servletResponse.getWriter(), getErrorJson(responseItem));
servletResponse.setStatus(responseItem.getErrorCode());
}
private void sendBadRequest(Throwable t, HttpServletResponse response) throws IOException {
sendError(response, new ResponseItem(HttpServletResponse.SC_BAD_REQUEST,
"Invalid input - " + t.getMessage()));
}
private void sendJsonParseError(JSONException e, HttpServletResponse response) throws IOException {
sendError(response, new ResponseItem(HttpServletResponse.SC_BAD_REQUEST,
"Invalid JSON - " + e.getMessage()));
}
}
| |
/* Generated By:JavaCC: Do not edit this line. ParserTokenManager.java */
/** Token Manager. */
@SuppressWarnings("unused")
class ParserTokenManager implements ParserConstants
{
/** Debug output. */
public static java.io.PrintStream debugStream = System.out;
/** Set debug output. */
public static void setDebugStream(java.io.PrintStream ds) { debugStream = ds; }
static private int jjStopAtPos(int pos, int kind)
{
jjmatchedKind = kind;
jjmatchedPos = pos;
return pos + 1;
}
static private int jjMoveStringLiteralDfa0_0()
{
switch(curChar)
{
case 65:
return jjStopAtPos(0, 1);
case 66:
return jjStopAtPos(0, 2);
case 67:
return jjStopAtPos(0, 3);
case 68:
return jjStopAtPos(0, 4);
default :
return 1;
}
}
static final int[] jjnextStates = {
};
/** Token literal values. */
public static final String[] jjstrLiteralImages = {
"", "\101", "\102", "\103", "\104", };
/** Lexer state names. */
public static final String[] lexStateNames = {
"DEFAULT",
};
static protected SimpleCharStream input_stream;
static private final int[] jjrounds = new int[0];
static private final int[] jjstateSet = new int[2 * 0];
static protected char curChar;
/** Constructor. */
public ParserTokenManager(SimpleCharStream stream){
if (input_stream != null)
throw new TokenMgrError("ERROR: Second call to constructor of static lexer. You must use ReInit() to initialize the static variables.", TokenMgrError.STATIC_LEXER_ERROR);
input_stream = stream;
}
/** Constructor. */
public ParserTokenManager (SimpleCharStream stream, int lexState){
this(stream);
SwitchTo(lexState);
}
/** Reinitialise parser. */
static public void ReInit(SimpleCharStream stream)
{
jjmatchedPos = jjnewStateCnt = 0;
curLexState = defaultLexState;
input_stream = stream;
ReInitRounds();
}
static private void ReInitRounds()
{
int i;
jjround = 0x80000001;
for (i = 0; i-- > 0;)
jjrounds[i] = 0x80000000;
}
/** Reinitialise parser. */
static public void ReInit(SimpleCharStream stream, int lexState)
{
ReInit(stream);
SwitchTo(lexState);
}
/** Switch to specified lex state. */
static public void SwitchTo(int lexState)
{
if (lexState >= 1 || lexState < 0)
throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE);
else
curLexState = lexState;
}
static protected Token jjFillToken()
{
final Token t;
final String curTokenImage;
final int beginLine;
final int endLine;
final int beginColumn;
final int endColumn;
String im = jjstrLiteralImages[jjmatchedKind];
curTokenImage = (im == null) ? input_stream.GetImage() : im;
beginLine = input_stream.getBeginLine();
beginColumn = input_stream.getBeginColumn();
endLine = input_stream.getEndLine();
endColumn = input_stream.getEndColumn();
t = Token.newToken(jjmatchedKind, curTokenImage);
t.beginLine = beginLine;
t.endLine = endLine;
t.beginColumn = beginColumn;
t.endColumn = endColumn;
return t;
}
static int curLexState = 0;
static int defaultLexState = 0;
static int jjnewStateCnt;
static int jjround;
static int jjmatchedPos;
static int jjmatchedKind;
/** Get the next Token. */
public static Token getNextToken()
{
Token matchedToken;
int curPos = 0;
EOFLoop :
for (;;)
{
try
{
curChar = input_stream.BeginToken();
}
catch(java.io.IOException e)
{
jjmatchedKind = 0;
matchedToken = jjFillToken();
return matchedToken;
}
jjmatchedKind = 0x7fffffff;
jjmatchedPos = 0;
curPos = jjMoveStringLiteralDfa0_0();
if (jjmatchedKind != 0x7fffffff)
{
if (jjmatchedPos + 1 < curPos)
input_stream.backup(curPos - jjmatchedPos - 1);
matchedToken = jjFillToken();
return matchedToken;
}
int error_line = input_stream.getEndLine();
int error_column = input_stream.getEndColumn();
String error_after = null;
boolean EOFSeen = false;
try { input_stream.readChar(); input_stream.backup(1); }
catch (java.io.IOException e1) {
EOFSeen = true;
error_after = curPos <= 1 ? "" : input_stream.GetImage();
if (curChar == '\n' || curChar == '\r') {
error_line++;
error_column = 0;
}
else
error_column++;
}
if (!EOFSeen) {
input_stream.backup(1);
error_after = curPos <= 1 ? "" : input_stream.GetImage();
}
throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR);
}
}
static private void jjCheckNAdd(int state)
{
if (jjrounds[state] != jjround)
{
jjstateSet[jjnewStateCnt++] = state;
jjrounds[state] = jjround;
}
}
static private void jjAddStates(int start, int end)
{
do {
jjstateSet[jjnewStateCnt++] = jjnextStates[start];
} while (start++ != end);
}
static private void jjCheckNAddTwoStates(int state1, int state2)
{
jjCheckNAdd(state1);
jjCheckNAdd(state2);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.wicket.application.ComponentInitializationListenerCollection;
import org.apache.wicket.application.ComponentInstantiationListenerCollection;
import org.apache.wicket.application.ComponentOnAfterRenderListenerCollection;
import org.apache.wicket.application.ComponentOnBeforeRenderListenerCollection;
import org.apache.wicket.application.HeaderContributorListenerCollection;
import org.apache.wicket.application.IComponentInitializationListener;
import org.apache.wicket.application.IComponentInstantiationListener;
import org.apache.wicket.core.request.mapper.IMapperContext;
import org.apache.wicket.core.util.lang.PropertyResolver;
import org.apache.wicket.core.util.lang.WicketObjects;
import org.apache.wicket.core.util.resource.ClassPathResourceFinder;
import org.apache.wicket.event.IEvent;
import org.apache.wicket.event.IEventSink;
import org.apache.wicket.javascript.DefaultJavaScriptCompressor;
import org.apache.wicket.markup.MarkupFactory;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.ResourceAggregator;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponseDecorator;
import org.apache.wicket.markup.html.image.resource.DefaultButtonImageResourceFactory;
import org.apache.wicket.markup.parser.filter.EnclosureHandler;
import org.apache.wicket.markup.parser.filter.InlineEnclosureHandler;
import org.apache.wicket.markup.parser.filter.RelativePathPrefixHandler;
import org.apache.wicket.markup.parser.filter.WicketLinkTagHandler;
import org.apache.wicket.markup.parser.filter.WicketMessageTagHandler;
import org.apache.wicket.markup.resolver.FragmentResolver;
import org.apache.wicket.markup.resolver.HtmlHeaderResolver;
import org.apache.wicket.markup.resolver.MarkupInheritanceResolver;
import org.apache.wicket.markup.resolver.WicketContainerResolver;
import org.apache.wicket.markup.resolver.WicketMessageResolver;
import org.apache.wicket.page.DefaultPageManagerContext;
import org.apache.wicket.page.IPageManager;
import org.apache.wicket.page.IPageManagerContext;
import org.apache.wicket.pageStore.IDataStore;
import org.apache.wicket.pageStore.IPageStore;
import org.apache.wicket.protocol.http.IRequestLogger;
import org.apache.wicket.protocol.http.RequestLogger;
import org.apache.wicket.protocol.http.RequestLoggerRequestCycleListener;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.protocol.http.WebSession;
import org.apache.wicket.request.IExceptionMapper;
import org.apache.wicket.request.IRequestHandler;
import org.apache.wicket.request.IRequestMapper;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.cycle.AbstractRequestCycleListener;
import org.apache.wicket.request.cycle.IRequestCycleListener;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.cycle.RequestCycleContext;
import org.apache.wicket.request.cycle.RequestCycleListenerCollection;
import org.apache.wicket.request.mapper.CompoundRequestMapper;
import org.apache.wicket.request.mapper.ICompoundRequestMapper;
import org.apache.wicket.request.resource.ResourceReferenceRegistry;
import org.apache.wicket.response.filter.EmptySrcAttributeCheckFilter;
import org.apache.wicket.session.DefaultPageFactory;
import org.apache.wicket.session.ISessionStore;
import org.apache.wicket.session.ISessionStore.UnboundListener;
import org.apache.wicket.settings.IApplicationSettings;
import org.apache.wicket.settings.IDebugSettings;
import org.apache.wicket.settings.IExceptionSettings;
import org.apache.wicket.settings.IFrameworkSettings;
import org.apache.wicket.settings.IJavaScriptLibrarySettings;
import org.apache.wicket.settings.IMarkupSettings;
import org.apache.wicket.settings.IPageSettings;
import org.apache.wicket.settings.IRequestCycleSettings;
import org.apache.wicket.settings.IRequestLoggerSettings;
import org.apache.wicket.settings.IResourceSettings;
import org.apache.wicket.settings.ISecuritySettings;
import org.apache.wicket.settings.IStoreSettings;
import org.apache.wicket.settings.def.ApplicationSettings;
import org.apache.wicket.settings.def.DebugSettings;
import org.apache.wicket.settings.def.ExceptionSettings;
import org.apache.wicket.settings.def.FrameworkSettings;
import org.apache.wicket.settings.def.JavaScriptLibrarySettings;
import org.apache.wicket.settings.def.MarkupSettings;
import org.apache.wicket.settings.def.PageSettings;
import org.apache.wicket.settings.def.RequestCycleSettings;
import org.apache.wicket.settings.def.RequestLoggerSettings;
import org.apache.wicket.settings.def.ResourceSettings;
import org.apache.wicket.settings.def.SecuritySettings;
import org.apache.wicket.settings.def.StoreSettings;
import org.apache.wicket.util.IProvider;
import org.apache.wicket.util.io.IOUtils;
import org.apache.wicket.util.io.Streams;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.lang.Generics;
import org.apache.wicket.util.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Base class for all Wicket applications. To create a Wicket application, you generally should
* <i>not </i> directly subclass this class. Instead, you will want to subclass some subclass of
* Application, like WebApplication, which is appropriate for the protocol and markup type you are
* working with.
* <p>
* Application has the following interesting features / attributes:
* <ul>
* <li><b>Name </b>- The Application's name, which is the same as its class name.
*
* <li><b>Home Page </b>- The Application's home Page class. Subclasses must override getHomePage()
* to provide this property value.
*
* <li><b>Settings </b>- Application settings are partitioned into sets of related settings using
* interfaces in the org.apache.wicket.settings package. These interfaces are returned by the
* following methods, which should be used to configure framework settings for your application:
* getApplicationSettings(), getDebugSettings(), getExceptionSettings(), getMarkupSettings(),
* getPageSettings(), getRequestCycleSettings(), getSecuritySettings and getSessionSettings(). These
* settings are configured by default through the constructor or internalInit methods. Default the
* application is configured for DEVELOPMENT. You can configure this globally to DEPLOYMENT or
* override specific settings by implementing the init() method.
*
* <li><b>Shared Resources </b>- Resources added to an Application's SharedResources have
* application-wide scope and can be referenced using a logical scope and a name with the
* ResourceReference class. ResourceReferences can then be used by multiple components in the same
* application without additional overhead (beyond the ResourceReference instance held by each
* referee) and will yield a stable URL, permitting efficient browser caching of the resource (even
* if the resource is dynamically generated). Resources shared in this manner may also be localized.
* See {@link org.apache.wicket.request.resource.ResourceReference} for more details.
*
* <li><b>Custom Session Subclasses</b>- In order to install your own {@link Session} subclass you
* must override Application{@link #newSession(Request, Response)}. For subclasses of
* {@link WebApplication} you will want to subclass {@link WebSession}.
*
* </ul>
*
* @see org.apache.wicket.protocol.http.WebApplication
* @author Jonathan Locke
*/
public abstract class Application implements UnboundListener, IEventSink
{
/** Configuration constant for the 2 types */
public static final String CONFIGURATION = "configuration";
/**
* Applications keyed on the {@link #getApplicationKey()} so that they can be retrieved even
* without being in a request/ being set in the thread local (we need that e.g. for when we are
* in a destruction thread).
*/
private static final Map<String, Application> applicationKeyToApplication = Generics.newHashMap(1);
/** Log. */
private static final Logger log = LoggerFactory.getLogger(Application.class);
/** root mapper */
private IRequestMapper rootRequestMapper;
/** The converter locator instance. */
private IConverterLocator converterLocator;
/** list of initializers. */
private final List<IInitializer> initializers = Generics.newArrayList();
/** Application level meta data. */
private MetaDataEntry<?>[] metaData;
/** Name of application subclass. */
private String name;
/** Request logger instance. */
private IRequestLogger requestLogger;
/** The session facade. */
private volatile ISessionStore sessionStore;
/** page renderer provider */
private IPageRendererProvider pageRendererProvider;
/** request cycle provider */
private IRequestCycleProvider requestCycleProvider;
/** exception mapper provider */
private IProvider<IExceptionMapper> exceptionMapperProvider;
/** session store provider */
private IProvider<ISessionStore> sessionStoreProvider;
/**
* The decorator this application uses to decorate any header responses created by Wicket
*/
private IHeaderResponseDecorator headerResponseDecorator;
/**
* Checks if the <code>Application</code> threadlocal is set in this thread
*
* @return true if {@link Application#get()} can return the instance of application, false
* otherwise
*/
public static boolean exists()
{
return ThreadContext.getApplication() != null;
}
/**
* Get Application for current thread.
*
* @return The current thread's Application
*/
public static Application get()
{
Application application = ThreadContext.getApplication();
if (application == null)
{
throw new WicketRuntimeException("There is no application attached to current thread " +
Thread.currentThread().getName());
}
return application;
}
/**
* Gets the Application based on the application key of that application. You typically never
* have to use this method unless you are working on an integration project.
*
* @param applicationKey
* The unique key of the application within a certain context (e.g. a web
* application)
* @return The application or <code>null</code> if application has not been found
*/
public static Application get(final String applicationKey)
{
return applicationKeyToApplication.get(applicationKey);
}
/**
* Gets the keys of the currently registered Wicket applications for this web application. You
* typically never have to use this method unless you are working on an integration project.
*
* @return unmodifiable set with keys that correspond with {@link #getApplicationKey()}. Never
* null, but possibly empty
*/
public static Set<String> getApplicationKeys()
{
return Collections.unmodifiableSet(applicationKeyToApplication.keySet());
}
/**
* Constructor. <strong>Use {@link #init()} for any configuration of your application instead of
* overriding the constructor.</strong>
*/
public Application()
{
// Install default component instantiation listener that uses
// authorization strategy to check component instantiations.
getComponentInstantiationListeners().add(new IComponentInstantiationListener()
{
/**
* @see org.apache.wicket.application.IComponentInstantiationListener#onInstantiation(org.apache.wicket.Component)
*/
@Override
public void onInstantiation(final Component component)
{
final Class<? extends Component> cl = component.getClass();
// If component instantiation is not authorized
if (!Session.get().getAuthorizationStrategy().isInstantiationAuthorized(cl))
{
// then call any unauthorized component instantiation
// listener
getSecuritySettings().getUnauthorizedComponentInstantiationListener()
.onUnauthorizedInstantiation(component);
}
}
});
}
/**
* Configures application settings to good defaults.
*/
public final void configure()
{
// As long as this is public api the development and deployment mode
// should counter act each other for all properties.
switch (getConfigurationType())
{
case DEVELOPMENT : {
getResourceSettings().setResourcePollFrequency(Duration.ONE_SECOND);
getResourceSettings().setJavaScriptCompressor(null);
getResourceSettings().setUseMinifiedResources(false);
getMarkupSettings().setStripWicketTags(false);
getExceptionSettings().setUnexpectedExceptionDisplay(
IExceptionSettings.SHOW_EXCEPTION_PAGE);
getDebugSettings().setComponentUseCheck(true);
getDebugSettings().setAjaxDebugModeEnabled(true);
getDebugSettings().setDevelopmentUtilitiesEnabled(true);
// getDebugSettings().setOutputMarkupContainerClassName(true);
getRequestCycleSettings().addResponseFilter(EmptySrcAttributeCheckFilter.INSTANCE);
break;
}
case DEPLOYMENT : {
getResourceSettings().setResourcePollFrequency(null);
getResourceSettings().setJavaScriptCompressor(new DefaultJavaScriptCompressor());
getMarkupSettings().setStripWicketTags(true);
getExceptionSettings().setUnexpectedExceptionDisplay(
IExceptionSettings.SHOW_INTERNAL_ERROR_PAGE);
getDebugSettings().setComponentUseCheck(false);
getDebugSettings().setAjaxDebugModeEnabled(false);
getDebugSettings().setDevelopmentUtilitiesEnabled(false);
break;
}
}
}
/**
* Gets the unique key of this application within a given context (like a web application). NOT
* INTENDED FOR FRAMEWORK CLIENTS.
*
* @return The unique key of this application
*/
public abstract String getApplicationKey();
/**
* Gets the configuration mode to use for configuring the app, either
* {@link RuntimeConfigurationType#DEVELOPMENT} or {@link RuntimeConfigurationType#DEPLOYMENT}.
* <p>
* The configuration type. Must currently be either DEVELOPMENT or DEPLOYMENT. Currently, if the
* configuration type is DEVELOPMENT, resources are polled for changes, component usage is
* checked, wicket tags are not stripped from output and a detailed exception page is used. If
* the type is DEPLOYMENT, component usage is not checked, wicket tags are stripped from output
* and a non-detailed exception page is used to display errors.
* <p>
* Note that you should not run Wicket in DEVELOPMENT mode on production servers - the various
* debugging checks and resource polling is inefficient and may leak resources, particularly on
* webapp redeploy.
*
* <div style="border-style:solid;">
* <p>
* To change the deployment mode, add the following to your web.xml, inside your <servlet>
* mapping (or <filter> mapping if you're using 1.3.x):
*
* <pre>
* <init-param>
* <param-name>configuration</param-name>
* <param-value>deployment</param-value>
* </init-param>
* </pre>
*
* <p>
* You can alternatively set this as a <context-param> on the whole context.
*
* <p>
* Another option is to set the "wicket.configuration" system property to either "deployment" or
* "development". The value is not case-sensitive.
*
* <p>
* The system property is checked first, allowing you to add a web.xml param for deployment, and
* a command-line override when you want to run in development mode during development.
*
* <p>
* You may also override Application.getConfigurationType() to provide your own custom switch,
* in which case none of the above logic is used. </div>
*
* <p>
* IMPORTANT NOTE
* </p>
* THIS METHOD IS CALLED OFTEN FROM MANY DIFFERENT POINTS IN CODE, INCLUDING DURING THE RENDER
* PROCESS, THEREFORE THE IMPLEMENTATION SHOULD BE FAST - PREFERRABLY USING A FAST-TO-RETRIEVE
* CACHED VALUE
*
* @return configuration
* @since 1.2.3 (function existed as a property getter)
* @since 1.3.0 (abstract, used to configure things)
*/
public abstract RuntimeConfigurationType getConfigurationType();
/**
* Application subclasses must specify a home page class by implementing this abstract method.
*
* @return Home page class for this application
*/
public abstract Class<? extends Page> getHomePage();
/**
* @return The converter locator for this application
*/
public final IConverterLocator getConverterLocator()
{
return converterLocator;
}
/**
* Gets metadata for this application using the given key.
*
* @param <T>
* @param key
* The key for the data
* @return The metadata
* @see MetaDataKey
*/
public final <T> T getMetaData(final MetaDataKey<T> key)
{
return key.get(metaData);
}
/**
* Gets the name of this application.
*
* @return The application name.
*/
public final String getName()
{
return name;
}
/**
* Gets the {@link IRequestLogger}.
*
* @return The RequestLogger
*/
public final IRequestLogger getRequestLogger()
{
if (getRequestLoggerSettings().isRequestLoggerEnabled())
{
if (requestLogger == null)
{
requestLogger = newRequestLogger();
}
}
else
{
requestLogger = null;
}
return requestLogger;
}
/**
* Gets the facade object for working getting/ storing session instances.
*
* @return The session facade
*/
public final ISessionStore getSessionStore()
{
if (sessionStore == null)
{
synchronized (this)
{
if (sessionStore == null)
{
sessionStore = sessionStoreProvider.get();
sessionStore.registerUnboundListener(this);
}
}
}
return sessionStore;
}
/**
* @see org.apache.wicket.session.ISessionStore.UnboundListener#sessionUnbound(java.lang.String)
*/
@Override
public void sessionUnbound(final String sessionId)
{
internalGetPageManager().sessionExpired(sessionId);
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL.
*
* Initializes wicket components.
*/
public final void initializeComponents()
{
// Load any wicket properties files we can find
try
{
// Load properties files used by all libraries
final Iterator<URL> resources = getApplicationSettings().getClassResolver()
.getResources("wicket.properties");
while (resources.hasNext())
{
InputStream in = null;
try
{
final URL url = resources.next();
final Properties properties = new Properties();
in = Streams.readNonCaching(url);
properties.load(in);
load(properties);
}
finally
{
IOUtils.close(in);
}
}
}
catch (IOException e)
{
throw new WicketRuntimeException("Unable to load initializers file", e);
}
// now call any initializers we read
initInitializers();
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL.
*
* @param target
*/
public void logEventTarget(final IRequestHandler target)
{
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL.
*
* @param requestTarget
*/
public void logResponseTarget(final IRequestHandler requestTarget)
{
}
/**
* Creates a new session. Override this method if you want to provide a custom session.
*
* @param request
* The request that will create this session.
* @param response
* The response to initialize, for example with cookies. This is important to use
* cases involving unit testing because those use cases might want to be able to sign
* a user in automatically when the session is created.
*
* @return The session
*
* @since 1.3
*/
public abstract Session newSession(Request request, Response response);
/**
* Sets the metadata for this application using the given key. If the metadata object is not of
* the correct type for the metadata key, an IllegalArgumentException will be thrown. For
* information on creating MetaDataKeys, see {@link MetaDataKey}.
*
* @param <T>
* @param key
* The singleton key for the metadata
* @param object
* The metadata object
* @throws IllegalArgumentException
* @see MetaDataKey
*/
public final synchronized <T> void setMetaData(final MetaDataKey<T> key, final Object object)
{
metaData = key.set(metaData, object);
}
/**
* Construct and add initializer from the provided class name.
*
* @param className
*/
private void addInitializer(final String className)
{
IInitializer initializer = (IInitializer)WicketObjects.newInstance(className);
if (initializer != null)
{
initializers.add(initializer);
}
}
/**
* Iterate initializers list, calling their {@link IInitializer#destroy(Application) destroy}
* methods.
*/
private void destroyInitializers()
{
for (IInitializer initializer : initializers)
{
log.info("[" + getName() + "] destroy: " + initializer);
initializer.destroy(this);
}
}
/**
* Iterate initializers list, calling {@link IInitializer#init(Application)} on any instances
* found in it.
*/
private void initInitializers()
{
for (IInitializer initializer : initializers)
{
log.info("[" + getName() + "] init: " + initializer);
initializer.init(this);
}
}
/**
* @param properties
* Properties map with names of any library initializers in it
*/
private void load(final Properties properties)
{
addInitializer(properties.getProperty("initializer"));
addInitializer(properties.getProperty(getName() + "-initializer"));
}
/**
* Called when wicket servlet is destroyed. Overrides do not have to call super.
*/
protected void onDestroy()
{
}
/**
* Allows for initialization of the application by a subclass. <strong>Use this method for any
* application setup instead of the constructor.</strong>
*/
protected void init()
{
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL IT.
*/
public void internalDestroy()
{
applicationListeners.onBeforeDestroyed(this);
// destroy detach listener
final IDetachListener detachListener = getFrameworkSettings().getDetachListener();
if (detachListener != null)
{
detachListener.onDestroyListener();
}
// Clear caches of Class keys so the classloader can be garbage
// collected (WICKET-625)
PropertyResolver.destroy(this);
MarkupFactory markupFactory = getMarkupSettings().getMarkupFactory();
if (markupFactory.hasMarkupCache())
{
markupFactory.getMarkupCache().shutdown();
}
onDestroy();
destroyInitializers();
internalGetPageManager().destroy();
getSessionStore().destroy();
applicationKeyToApplication.remove(getApplicationKey());
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT OVERRIDE OR CALL.
*
* Internal initialization.
*/
protected void internalInit()
{
settingsAccessible = true;
IPageSettings pageSettings = getPageSettings();
// Install default component resolvers
pageSettings.addComponentResolver(new MarkupInheritanceResolver());
pageSettings.addComponentResolver(new HtmlHeaderResolver());
pageSettings.addComponentResolver(new WicketLinkTagHandler());
pageSettings.addComponentResolver(new WicketMessageResolver());
pageSettings.addComponentResolver(new FragmentResolver());
pageSettings.addComponentResolver(new RelativePathPrefixHandler());
pageSettings.addComponentResolver(new EnclosureHandler());
pageSettings.addComponentResolver(new InlineEnclosureHandler());
pageSettings.addComponentResolver(new WicketMessageTagHandler());
pageSettings.addComponentResolver(new WicketContainerResolver());
getResourceSettings().getResourceFinders().add(new ClassPathResourceFinder(""));
// Install button image resource factory
getResourceSettings().addResourceFactory("buttonFactory",
new DefaultButtonImageResourceFactory());
String applicationKey = getApplicationKey();
applicationKeyToApplication.put(applicationKey, this);
converterLocator = newConverterLocator();
setPageManagerProvider(new DefaultPageManagerProvider(this));
resourceReferenceRegistry = newResourceReferenceRegistry();
sharedResources = newSharedResources(resourceReferenceRegistry);
resourceBundles = newResourceBundles(resourceReferenceRegistry);
// set up default request mapper
setRootRequestMapper(new SystemMapper(this));
pageFactory = newPageFactory();
requestCycleProvider = new DefaultRequestCycleProvider();
exceptionMapperProvider = new DefaultExceptionMapperProvider();
// add a request cycle listener that logs each request for the requestlogger.
getRequestCycleListeners().add(new RequestLoggerRequestCycleListener());
}
/**
* @return the exception mapper provider
*/
public IProvider<IExceptionMapper> getExceptionMapperProvider()
{
return exceptionMapperProvider;
}
/**
*
* @return Session state provider
*/
public final IProvider<ISessionStore> getSessionStoreProvider()
{
return sessionStoreProvider;
}
/**
*
* @param sessionStoreProvider
*/
public final void setSessionStoreProvider(final IProvider<ISessionStore> sessionStoreProvider)
{
this.sessionStoreProvider = sessionStoreProvider;
}
/**
* Creates and returns a new instance of {@link IConverterLocator}.
*
* @return A new {@link IConverterLocator} instance
*/
protected IConverterLocator newConverterLocator()
{
return new ConverterLocator();
}
/**
* creates a new request logger when requests logging is enabled.
*
* @return The new request logger
*
*/
protected IRequestLogger newRequestLogger()
{
return new RequestLogger();
}
/**
* Converts the root mapper to a {@link ICompoundRequestMapper} if necessary and returns the
* converted instance.
*
* @return compound instance of the root mapper
*/
public final ICompoundRequestMapper getRootRequestMapperAsCompound()
{
IRequestMapper root = getRootRequestMapper();
if (!(root instanceof ICompoundRequestMapper))
{
root = new CompoundRequestMapper().add(root);
setRootRequestMapper(root);
}
return (ICompoundRequestMapper)root;
}
/**
* @return The root request mapper
*/
public final IRequestMapper getRootRequestMapper()
{
return rootRequestMapper;
}
/**
* Sets the root request mapper
*
* @param rootRequestMapper
*/
public final void setRootRequestMapper(final IRequestMapper rootRequestMapper)
{
this.rootRequestMapper = rootRequestMapper;
}
/**
* Initialize the application
*/
public final void initApplication()
{
if (name == null)
{
throw new IllegalStateException("setName must be called before initApplication");
}
internalInit();
initializeComponents();
init();
applicationListeners.onAfterInitialized(this);
validateInit();
}
/**
* Gives the Application object a chance to validate if it has been properly initialized
*/
protected void validateInit()
{
if (getPageRendererProvider() == null)
{
throw new IllegalStateException(
"An instance of IPageRendererProvider has not yet been set on this Application. @see Application#setPageRendererProvider");
}
if (getSessionStoreProvider() == null)
{
throw new IllegalStateException(
"An instance of ISessionStoreProvider has not yet been set on this Application. @see Application#setSessionStoreProvider");
}
if (getPageManagerProvider() == null)
{
throw new IllegalStateException(
"An instance of IPageManagerProvider has not yet been set on this Application. @see Application#setPageManagerProvider");
}
}
/**
* Sets application name. This method must be called before any other methods are invoked and
* can only be called once per application instance.
*
* @param name
* unique application name
*/
public final void setName(final String name)
{
Args.notEmpty(name, "name");
if (this.name != null)
{
throw new IllegalStateException("Application name can only be set once.");
}
if (applicationKeyToApplication.get(name) != null)
{
throw new IllegalStateException("Application with name '" + name + "' already exists.'");
}
this.name = name;
applicationKeyToApplication.put(name, this);
}
/**
* Returns the mime type for given filename.
*
* @param fileName
* @return mime type
*/
public String getMimeType(final String fileName)
{
return URLConnection.getFileNameMap().getContentTypeFor(fileName);
}
/** {@inheritDoc} */
@Override
public void onEvent(final IEvent<?> event)
{
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Listeners
//
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** */
private final ComponentOnBeforeRenderListenerCollection componentPreOnBeforeRenderListeners = new ComponentOnBeforeRenderListenerCollection();
/** */
private final ComponentOnBeforeRenderListenerCollection componentPostOnBeforeRenderListeners = new ComponentOnBeforeRenderListenerCollection();
/** */
private final ComponentOnAfterRenderListenerCollection componentOnAfterRenderListeners = new ComponentOnAfterRenderListenerCollection();
/** */
private final RequestCycleListenerCollection requestCycleListeners = new RequestCycleListenerCollection();
private final ApplicationListenerCollection applicationListeners = new ApplicationListenerCollection();
private final SessionListenerCollection sessionListeners = new SessionListenerCollection();
/** list of {@link IComponentInstantiationListener}s. */
private final ComponentInstantiationListenerCollection componentInstantiationListeners = new ComponentInstantiationListenerCollection();
/** list of {@link IComponentInitializationListener}s. */
private final ComponentInitializationListenerCollection componentInitializationListeners = new ComponentInitializationListenerCollection();
/** list of {@link IHeaderContributor}s. */
private final HeaderContributorListenerCollection headerContributorListenerCollection = new HeaderContributorListenerCollection();
private final BehaviorInstantiationListenerCollection behaviorInstantiationListeners = new BehaviorInstantiationListenerCollection();
/**
* @return Gets the application's {@link HeaderContributorListenerCollection}
*/
public final HeaderContributorListenerCollection getHeaderContributorListenerCollection()
{
return headerContributorListenerCollection;
}
/**
* @return collection of initializers
*/
public final List<IInitializer> getInitializers()
{
return Collections.unmodifiableList(initializers);
}
/**
* @return collection of application listeners
*/
public final ApplicationListenerCollection getApplicationListeners()
{
return applicationListeners;
}
/**
* @return collection of session listeners
*/
public final SessionListenerCollection getSessionListeners()
{
return sessionListeners;
}
/**
* @return collection of behavior instantiation listeners
*/
public final BehaviorInstantiationListenerCollection getBehaviorInstantiationListeners()
{
return behaviorInstantiationListeners;
}
/**
* @return Gets the application's ComponentInstantiationListenerCollection
*/
public final ComponentInstantiationListenerCollection getComponentInstantiationListeners()
{
return componentInstantiationListeners;
}
/**
* @return Gets the application's ComponentInitializationListeners
*/
public final ComponentInitializationListenerCollection getComponentInitializationListeners()
{
return componentInitializationListeners;
}
/**
*
* @return ComponentOnBeforeRenderListenerCollection
*/
public final ComponentOnBeforeRenderListenerCollection getComponentPreOnBeforeRenderListeners()
{
return componentPreOnBeforeRenderListeners;
}
/**
*
* @return ComponentOnBeforeRenderListenerCollection
*/
public final ComponentOnBeforeRenderListenerCollection getComponentPostOnBeforeRenderListeners()
{
return componentPostOnBeforeRenderListeners;
}
/**
* @return on after render listeners collection
*/
public final ComponentOnAfterRenderListenerCollection getComponentOnAfterRenderListeners()
{
return componentOnAfterRenderListeners;
}
/**
* @return the unmodifiable request list of {@link IRequestCycleListener}s in this application
*/
public RequestCycleListenerCollection getRequestCycleListeners()
{
return requestCycleListeners;
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Settings
//
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** Application settings */
private IApplicationSettings applicationSettings;
/** JavaScriptLibrary settings */
private IJavaScriptLibrarySettings javaScriptLibrarySettings;
/** Debug Settings */
private IDebugSettings debugSettings;
/** Exception Settings */
private IExceptionSettings exceptionSettings;
/** Framework Settings */
private IFrameworkSettings frameworkSettings;
/** The Markup Settings */
private IMarkupSettings markupSettings;
/** The Page Settings */
private IPageSettings pageSettings;
/** The Request Cycle Settings */
private IRequestCycleSettings requestCycleSettings;
/** The Request Logger Settings */
private IRequestLoggerSettings requestLoggerSettings;
/** The Resource Settings */
private IResourceSettings resourceSettings;
/** The Security Settings */
private ISecuritySettings securitySettings;
/** The settings for {@link IPageStore}, {@link IDataStore} and {@link IPageManager} */
private IStoreSettings storeSettings;
/** can the settings object be set/used. */
private boolean settingsAccessible;
/**
* @return Application's application-wide settings
* @since 1.2
*/
public final IApplicationSettings getApplicationSettings()
{
checkSettingsAvailable();
if (applicationSettings == null)
{
applicationSettings = new ApplicationSettings();
}
return applicationSettings;
}
/**
*
* @param applicationSettings
*/
public final void setApplicationSettings(final IApplicationSettings applicationSettings)
{
this.applicationSettings = applicationSettings;
}
/**
* @return Application's JavaScriptLibrary settings
* @since 6.0
*/
public final IJavaScriptLibrarySettings getJavaScriptLibrarySettings()
{
checkSettingsAvailable();
if (javaScriptLibrarySettings == null)
{
javaScriptLibrarySettings = new JavaScriptLibrarySettings();
}
return javaScriptLibrarySettings;
}
/**
*
* @param javaScriptLibrarySettings
*/
public final void setJavaScriptLibrarySettings(
final IJavaScriptLibrarySettings javaScriptLibrarySettings)
{
this.javaScriptLibrarySettings = javaScriptLibrarySettings;
}
/**
* @return Application's debug related settings
*/
public final IDebugSettings getDebugSettings()
{
checkSettingsAvailable();
if (debugSettings == null)
{
debugSettings = new DebugSettings();
}
return debugSettings;
}
/**
*
* @param debugSettings
*/
public final void setDebugSettings(final IDebugSettings debugSettings)
{
this.debugSettings = debugSettings;
}
/**
* @return Application's exception handling settings
*/
public final IExceptionSettings getExceptionSettings()
{
checkSettingsAvailable();
if (exceptionSettings == null)
{
exceptionSettings = new ExceptionSettings();
}
return exceptionSettings;
}
/**
*
* @param exceptionSettings
*/
public final void setExceptionSettings(final IExceptionSettings exceptionSettings)
{
this.exceptionSettings = exceptionSettings;
}
/**
* @return Wicket framework settings
*/
public final IFrameworkSettings getFrameworkSettings()
{
checkSettingsAvailable();
if (frameworkSettings == null)
{
frameworkSettings = new FrameworkSettings(this);
}
return frameworkSettings;
}
/**
*
* @param frameworkSettings
*/
public final void setFrameworkSettings(final IFrameworkSettings frameworkSettings)
{
this.frameworkSettings = frameworkSettings;
}
/**
* @return Application's page related settings
*/
public final IPageSettings getPageSettings()
{
checkSettingsAvailable();
if (pageSettings == null)
{
pageSettings = new PageSettings();
}
return pageSettings;
}
/**
*
* @param pageSettings
*/
public final void setPageSettings(final IPageSettings pageSettings)
{
this.pageSettings = pageSettings;
}
/**
* @return Application's request cycle related settings
*/
public final IRequestCycleSettings getRequestCycleSettings()
{
checkSettingsAvailable();
if (requestCycleSettings == null)
{
requestCycleSettings = new RequestCycleSettings();
}
return requestCycleSettings;
}
/**
*
* @param requestCycleSettings
*/
public final void setRequestCycleSettings(final IRequestCycleSettings requestCycleSettings)
{
this.requestCycleSettings = requestCycleSettings;
}
/**
* @return Application's markup related settings
*/
public IMarkupSettings getMarkupSettings()
{
checkSettingsAvailable();
if (markupSettings == null)
{
markupSettings = new MarkupSettings();
}
return markupSettings;
}
/**
*
* @param markupSettings
*/
public final void setMarkupSettings(final IMarkupSettings markupSettings)
{
this.markupSettings = markupSettings;
}
/**
* @return Application's request logger related settings
*/
public final IRequestLoggerSettings getRequestLoggerSettings()
{
checkSettingsAvailable();
if (requestLoggerSettings == null)
{
requestLoggerSettings = new RequestLoggerSettings();
}
return requestLoggerSettings;
}
/**
*
* @param requestLoggerSettings
*/
public final void setRequestLoggerSettings(final IRequestLoggerSettings requestLoggerSettings)
{
this.requestLoggerSettings = requestLoggerSettings;
}
/**
* @return Application's resources related settings
*/
public final IResourceSettings getResourceSettings()
{
checkSettingsAvailable();
if (resourceSettings == null)
{
resourceSettings = new ResourceSettings(this);
}
return resourceSettings;
}
/**
*
* @param resourceSettings
*/
public final void setResourceSettings(final IResourceSettings resourceSettings)
{
this.resourceSettings = resourceSettings;
}
/**
* @return Application's security related settings
*/
public final ISecuritySettings getSecuritySettings()
{
checkSettingsAvailable();
if (securitySettings == null)
{
securitySettings = new SecuritySettings();
}
return securitySettings;
}
/**
*
* @param securitySettings
*/
public final void setSecuritySettings(final ISecuritySettings securitySettings)
{
this.securitySettings = securitySettings;
}
/**
* @return Application's stores related settings
*/
public final IStoreSettings getStoreSettings()
{
checkSettingsAvailable();
if (storeSettings == null)
{
storeSettings = new StoreSettings(this);
}
return storeSettings;
}
/**
*
* @param storeSettings
*/
public final void setStoreSettings(final IStoreSettings storeSettings)
{
this.storeSettings = storeSettings;
}
/**
*
*/
private void checkSettingsAvailable()
{
if (!settingsAccessible)
{
throw new WicketRuntimeException(
"Use Application.init() method for configuring your application object");
}
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Page Manager
//
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private volatile IPageManager pageManager;
private IPageManagerProvider pageManagerProvider;
/**
*
* @return PageManagerProvider
*/
public final IPageManagerProvider getPageManagerProvider()
{
return pageManagerProvider;
}
/**
*
* @param provider
*/
public synchronized final void setPageManagerProvider(final IPageManagerProvider provider)
{
pageManagerProvider = provider;
}
/**
* Context for PageManager to interact with rest of Wicket
*/
private final IPageManagerContext pageManagerContext = new DefaultPageManagerContext();
/**
* Returns an unsynchronized version of page manager
*
* @return the page manager
*/
final IPageManager internalGetPageManager()
{
if (pageManager == null)
{
synchronized (this)
{
if (pageManager == null)
{
pageManager = pageManagerProvider.get(getPageManagerContext());
}
}
}
return pageManager;
}
/**
*
* @return the page manager context
*/
protected IPageManagerContext getPageManagerContext()
{
return pageManagerContext;
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Page Rendering
//
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
*
* @return PageRendererProvider
*/
public final IPageRendererProvider getPageRendererProvider()
{
return pageRendererProvider;
}
/**
*
* @param pageRendererProvider
*/
public final void setPageRendererProvider(final IPageRendererProvider pageRendererProvider)
{
Args.notNull(pageRendererProvider, "pageRendererProvider");
this.pageRendererProvider = pageRendererProvider;
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Request Handler encoding
//
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private ResourceReferenceRegistry resourceReferenceRegistry;
private SharedResources sharedResources;
private ResourceBundles resourceBundles;
private IPageFactory pageFactory;
private IMapperContext encoderContext;
/**
* Override to create custom {@link ResourceReferenceRegistry}.
*
* @return new {@link ResourceReferenceRegistry} instance.
*/
protected ResourceReferenceRegistry newResourceReferenceRegistry()
{
return new ResourceReferenceRegistry();
}
/**
* Returns {@link ResourceReferenceRegistry} for this application.
*
* @return ResourceReferenceRegistry
*/
public final ResourceReferenceRegistry getResourceReferenceRegistry()
{
return resourceReferenceRegistry;
}
/**
*
* @param registry
* @return SharedResources
*/
protected SharedResources newSharedResources(final ResourceReferenceRegistry registry)
{
return new SharedResources(registry);
}
/**
*
* @return SharedResources
*/
public SharedResources getSharedResources()
{
return sharedResources;
}
protected ResourceBundles newResourceBundles(final ResourceReferenceRegistry registry)
{
return new ResourceBundles(registry);
}
/**
* @return The registry for resource bundles
*/
public ResourceBundles getResourceBundles()
{
return resourceBundles;
}
/**
* Override to create custom {@link IPageFactory}
*
* @return new {@link IPageFactory} instance.
*/
protected IPageFactory newPageFactory()
{
return new DefaultPageFactory();
}
/**
* Returns {@link IPageFactory} for this application.
*
* @return page factory
*/
public final IPageFactory getPageFactory()
{
return pageFactory;
}
/**
*
* @return mapper context
*/
public final IMapperContext getMapperContext()
{
if (encoderContext == null)
{
encoderContext = newMapperContext();
}
return encoderContext;
}
/**
* Factory method for {@link IMapperContext} implementations. {@link DefaultMapperContext} may
* be a good starting point for custom implementations.
*
* @return new instance of mapper context to be used in the application
*/
protected IMapperContext newMapperContext()
{
return new DefaultMapperContext(this);
}
/**
*
* @param requestCycle
* @return Session
*/
public Session fetchCreateAndSetSession(final RequestCycle requestCycle)
{
Args.notNull(requestCycle, "requestCycle");
Session session = getSessionStore().lookup(requestCycle.getRequest());
if (session == null)
{
session = newSession(requestCycle.getRequest(), requestCycle.getResponse());
ThreadContext.setSession(session);
internalGetPageManager().newSessionCreated();
sessionListeners.onCreated(session);
}
else
{
ThreadContext.setSession(session);
}
return session;
}
/**
*
* @return RequestCycleProvider
*/
public final IRequestCycleProvider getRequestCycleProvider()
{
return requestCycleProvider;
}
/**
*
* @param requestCycleProvider
*/
public final void setRequestCycleProvider(final IRequestCycleProvider requestCycleProvider)
{
this.requestCycleProvider = requestCycleProvider;
}
private static class DefaultExceptionMapperProvider implements IProvider<IExceptionMapper>
{
@Override
public IExceptionMapper get()
{
return new DefaultExceptionMapper();
}
}
/**
*
*/
private static class DefaultRequestCycleProvider implements IRequestCycleProvider
{
@Override
public RequestCycle get(final RequestCycleContext context)
{
return new RequestCycle(context);
}
}
/**
*
* @param request
* @param response
* @return request cycle
*/
public final RequestCycle createRequestCycle(final Request request, final Response response)
{
RequestCycleContext context = new RequestCycleContext(request, response,
getRootRequestMapper(), getExceptionMapperProvider().get());
RequestCycle requestCycle = getRequestCycleProvider().get(context);
requestCycle.getListeners().add(requestCycleListeners);
requestCycle.getListeners().add(new AbstractRequestCycleListener()
{
@Override
public void onDetach(final RequestCycle requestCycle)
{
if (Session.exists())
{
Session.get().getPageManager().commitRequest();
}
}
@Override
public void onEndRequest(RequestCycle cycle)
{
if (Application.exists())
{
IRequestLogger requestLogger = Application.get().getRequestLogger();
if (requestLogger != null)
{
requestLogger.requestTime((System.currentTimeMillis() - cycle.getStartTime()));
}
}
}
});
return requestCycle;
}
/**
* Sets an {@link IHeaderResponseDecorator} that you want your application to use to decorate
* header responses.
*
* @param headerResponseDecorator
* your custom decorator
*/
public final void setHeaderResponseDecorator(
final IHeaderResponseDecorator headerResponseDecorator)
{
this.headerResponseDecorator = headerResponseDecorator;
}
/**
* INTERNAL METHOD - You shouldn't need to call this. This is called every time Wicket creates
* an IHeaderResponse. It gives you the ability to incrementally add features to an
* IHeaderResponse implementation by wrapping it in another implementation.
*
* To decorate an IHeaderResponse in your application, set the {@link IHeaderResponseDecorator}
* on the application.
*
* @see IHeaderResponseDecorator
* @param response
* the response Wicket created
* @return the response Wicket should use in IHeaderContributor traversal
*/
public final IHeaderResponse decorateHeaderResponse(final IHeaderResponse response)
{
final IHeaderResponse aggregatingResponse = new ResourceAggregator(response);
if (headerResponseDecorator == null)
{
return aggregatingResponse;
}
return headerResponseDecorator.decorate(aggregatingResponse);
}
/**
*
* @return true, of app is in Development mode
*/
public final boolean usesDevelopmentConfig()
{
return RuntimeConfigurationType.DEVELOPMENT.equals(getConfigurationType());
}
/**
*
* @return true, of app is in Deployment mode
*/
public final boolean usesDeploymentConfig()
{
return RuntimeConfigurationType.DEPLOYMENT.equals(getConfigurationType());
}
}
| |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chromecast.shell;
import android.net.http.AndroidHttpClient;
import android.util.Log;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.SequenceInputStream;
import java.util.LinkedList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Crash crashdump uploader. Scans the crash dump location provided by CastCrashReporterClient
* for dump files, attempting to upload all crash dumps to the crash server.
*
* Uploading is intended to happen in a background thread, and this method will likely be called
* on startup, looking for crash dumps from previous runs, since Chromium's crash code
* explicitly blocks any post-dump hooks or uploading for Android builds.
*/
public final class CastCrashUploader {
private static final String TAG = "CastCrashUploader";
private static final String CRASH_REPORT_HOST = "clients2.google.com";
private static final String CAST_SHELL_USER_AGENT = android.os.Build.MODEL + "/CastShell";
// Multipart dump filename has format "[random string].dmp[pid]", e.g.
// 20597a65-b822-008e-31f8fc8e-02bb45c0.dmp18169
private static final String DUMP_FILE_REGEX = ".*\\.dmp\\d*";
private final ScheduledExecutorService mExecutorService;
private final String mCrashDumpPath;
private final String mCrashReportUploadUrl;
public CastCrashUploader(String crashDumpPath, boolean uploadCrashToStaging) {
this.mCrashDumpPath = crashDumpPath;
mCrashReportUploadUrl = uploadCrashToStaging
? "http://clients2.google.com/cr/staging_report"
: "http://clients2.google.com/cr/report";
mExecutorService = Executors.newScheduledThreadPool(1);
}
/**
* Sets up a periodic uploader, that checks for new dumps to upload every 20 minutes
*/
public void startPeriodicUpload() {
mExecutorService.scheduleWithFixedDelay(
new Runnable() {
@Override
public void run() {
queueAllCrashDumpUploads(false /* synchronous */, null);
}
},
0, // Do first run immediately
20, // Run once every 20 minutes
TimeUnit.MINUTES);
}
public void uploadCrashDumps(final String logFilePath) {
queueAllCrashDumpUploads(true /* synchronous */, logFilePath);
}
public void removeCrashDumps() {
File crashDumpDirectory = new File(mCrashDumpPath);
for (File potentialDump : crashDumpDirectory.listFiles()) {
if (potentialDump.getName().matches(DUMP_FILE_REGEX)) {
potentialDump.delete();
}
}
}
/**
* Searches for files matching the given regex in the crash dump folder, queueing each
* one for upload.
* @param synchronous Whether or not this function should block on queued uploads
* @param logFile Log file to include, if any
*/
private void queueAllCrashDumpUploads(boolean synchronous, String logFile) {
if (mCrashDumpPath == null) return;
Log.d(TAG, "Checking for crash dumps");
LinkedList<Future> tasks = new LinkedList<Future>();
final AndroidHttpClient httpClient = AndroidHttpClient.newInstance(CAST_SHELL_USER_AGENT);
File crashDumpDirectory = new File(mCrashDumpPath);
for (File potentialDump : crashDumpDirectory.listFiles()) {
String dumpName = potentialDump.getName();
if (dumpName.matches(DUMP_FILE_REGEX)) {
int dumpPid;
try {
dumpPid = Integer.parseInt(
dumpName.substring(dumpName.lastIndexOf(".dmp") + 4));
} catch (NumberFormatException e) {
// Likely resulting from failing to parse an empty string, set value to 0
dumpPid = 0;
}
// Check if the dump we found has pid matching this process, and if so include
// this process's log.
// TODO(kjoswiak): Currently, logs are lost if dump cannot be uploaded right away.
if (dumpPid == android.os.Process.myPid()) {
tasks.add(queueCrashDumpUpload(httpClient, potentialDump, new File(logFile)));
} else {
tasks.add(queueCrashDumpUpload(httpClient, potentialDump, null));
}
}
}
// When finished uploading all of the queued dumps, release httpClient
tasks.add(mExecutorService.submit(new Runnable() {
@Override
public void run() {
httpClient.close();
}
}));
// Wait on tasks, if necessary.
if (synchronous) {
for (Future task : tasks) {
// Wait on task. If thread received interrupt and should stop waiting, return.
if (!waitOnTask(task)) {
return;
}
}
}
}
/**
* Enqueues a background task to upload a single crash dump file.
*/
private Future queueCrashDumpUpload(final AndroidHttpClient httpClient, final File dumpFile,
final File logFile) {
return mExecutorService.submit(new Runnable() {
@Override
public void run() {
Log.d(TAG, "Uploading dump crash log: " + dumpFile.getName());
try {
InputStream uploadCrashDumpStream = new FileInputStream(dumpFile);
InputStream logFileStream = null;
// Dump file is already in multipart MIME format and has a boundary throughout.
// Scrape the first line, remove two dashes, call that the "boundary" and add it
// to the content-type.
FileInputStream dumpFileStream = new FileInputStream(dumpFile);
String dumpFirstLine = getFirstLine(dumpFileStream);
String mimeBoundary = dumpFirstLine.substring(2);
if (logFile != null) {
Log.d(TAG, "Including log file: " + logFile.getName());
StringBuffer logHeader = new StringBuffer();
logHeader.append(dumpFirstLine);
logHeader.append("\n");
logHeader.append(
"Content-Disposition: form-data; name=\"log\"; filename=\"log\"\n");
logHeader.append("Content-Type: text/plain\n\n");
InputStream logHeaderStream =
new ByteArrayInputStream(logHeader.toString().getBytes());
logFileStream = new FileInputStream(logFile);
// Upload: prepend the log file for uploading
uploadCrashDumpStream = new SequenceInputStream(
new SequenceInputStream(logHeaderStream, logFileStream),
uploadCrashDumpStream);
}
InputStreamEntity entity = new InputStreamEntity(uploadCrashDumpStream, -1);
entity.setContentType("multipart/form-data; boundary=" + mimeBoundary);
HttpPost uploadRequest = new HttpPost(mCrashReportUploadUrl);
uploadRequest.setEntity(entity);
HttpResponse response =
httpClient.execute(new HttpHost(CRASH_REPORT_HOST), uploadRequest);
// Expect a report ID as the entire response
String responseLine = getFirstLine(response.getEntity().getContent());
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
Log.d(TAG, "Successfully uploaded as report ID: " + responseLine);
} else {
Log.e(TAG, "Failed response (" + statusCode + "): " + responseLine);
// 400 Bad Request is returned if the dump file is malformed. If requeset
// is not malformed, shortcircuit before clean up to avoid deletion and
// retry later, otherwise pass through and delete malformed file
if (statusCode != HttpStatus.SC_BAD_REQUEST) {
return;
}
}
// Delete the file so we don't re-upload it next time.
uploadCrashDumpStream.close();
dumpFileStream.close();
dumpFile.delete();
if (logFile != null && logFile.exists()) {
logFileStream.close();
logFile.delete();
}
} catch (IOException e) {
Log.e(TAG, "File I/O error trying to upload crash dump", e);
}
}
});
}
/**
* Gets the first line from an input stream, opening and closing readers to do so.
* We're targeting Java 6, so this is still tedious to do.
* @return First line of the input stream.
* @throws IOException
*/
private String getFirstLine(InputStream inputStream) throws IOException {
InputStreamReader streamReader = null;
BufferedReader reader = null;
try {
streamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(streamReader);
return reader.readLine();
} finally {
if (reader != null) {
reader.close();
}
if (streamReader != null) {
streamReader.close();
}
}
}
/**
* Waits until Future is propagated
* @return Whether thread should continue waiting
*/
private boolean waitOnTask(Future task) {
try {
task.get();
return true;
} catch (InterruptedException e) {
// Was interrupted while waiting, tell caller to cancel waiting
return false;
} catch (ExecutionException e) {
// Task execution may have failed, but this is fine as long as it finished
// executing
return true;
}
}
}
| |
package com.akjava.gwt.lib.client.experimental;
import com.akjava.gwt.lib.client.LogUtils;
import com.google.gwt.canvas.dom.client.ImageData;
import com.google.gwt.typedarrays.client.Uint8ArrayNative;
public class ResizeUtils {
private ResizeUtils(){}
//from http://tech-algorithm.com/articles/bilinear-image-scaling/
public static Uint8ArrayNative resizeBilinear(Uint8ArrayNative array, int w, int h, int w2, int h2) {
Uint8ArrayNative result = Uint8ArrayNative.create(w2*h2*4) ;
int a, b, c, d, x, y, index ;
float x_ratio = ((float)(w-1))/w2 ;
float y_ratio = ((float)(h-1))/h2 ;
float x_diff, y_diff, value ;
int offset = 0 ;
for (int i=0;i<h2;i++) {
for (int j=0;j<w2;j++) {
x = (int)(x_ratio * j) ;
y = (int)(y_ratio * i) ;
x_diff = (x_ratio * j) - x ;
y_diff = (y_ratio * i) - y ;
index = (y*w+x) ;
for(int k=0;k<4;k++){
a = array.get((index)*4+k) ;
b =array.get((index+1)*4+k) ;
c = array.get((index+w)*4+k) ;
d = array.get((index+w+1)*4+k) ;
value = (a&0xff)*(1-x_diff)*(1-y_diff) + (b&0xff)*(x_diff)*(1-y_diff) +
(c&0xff)*(y_diff)*(1-x_diff) + (d&0xff)*(x_diff*y_diff);
result.set(offset*4+k,(int) value);
}
offset++;
}
}
return result;
}
/*
* to create data url
private String toDataUrl(Uint8ArrayNative array,int w,int h){
Canvas resizedCanvas=CanvasUtils.createCanvas(w, h);
ImageData data=ImageDataUtils.copySizeOnly(resizedCanvas);//they must have rgba
ResizeUtils.setUint8Array(data, array);
CanvasUtils.copyTo(data, resizedCanvas);
return resizedCanvas.toDataUrl();
}
*/
public static Uint8ArrayNative resizeBilinear(ImageData imageData,int ax,int ay, int w, int h, int w2, int h2) {
Uint8ArrayNative array=ImageDataUtils.getUint8(imageData);
Uint8ArrayNative result = Uint8ArrayNative.create(w2*h2*4) ;
int a, b, c, d, x, y, index ;
float x_ratio = ((float)(w-1))/w2 ;
float y_ratio = ((float)(h-1))/h2 ;
float x_diff, y_diff, value ;
int offset = 0 ;
int iw=imageData.getWidth();
for (int i=0;i<h2;i++) {
for (int j=0;j<w2;j++) {
x = (int)(x_ratio * j) ;
y = (int)(y_ratio * i) ;
x_diff = (x_ratio * j) - x ;
y_diff = (y_ratio * i) - y ;
//index = (y*w+x) ;
index = ((ay+y)*iw+x+ax) ;
for(int k=0;k<4;k++){
a = array.get((index)*4+k) ;
b =array.get((index+1)*4+k) ;
c = array.get((index+iw)*4+k) ;
d = array.get((index+iw+1)*4+k) ;
value = (a&0xff)*(1-x_diff)*(1-y_diff) + (b&0xff)*(x_diff)*(1-y_diff) +
(c&0xff)*(y_diff)*(1-x_diff) + (d&0xff)*(x_diff*y_diff);
result.set(offset*4+k,(int) value);
}
offset++;
}
}
return result;
}
public static Uint8ArrayNative resizeBilinearRedOnly(Uint8ArrayNative array, int w, int h, int w2, int h2) {
Uint8ArrayNative result = Uint8ArrayNative.create(w2*h2*4) ;
int a, b, c, d, x, y, index ;
float x_ratio = ((float)(w-1))/w2 ;
float y_ratio = ((float)(h-1))/h2 ;
float x_diff, y_diff, value ;
int offset = 0 ;
for (int i=0;i<h2;i++) {
for (int j=0;j<w2;j++) {
x = (int)(x_ratio * j) ;
y = (int)(y_ratio * i) ;
x_diff = (x_ratio * j) - x ;
y_diff = (y_ratio * i) - y ;
index = (y*w+x) ;
a = array.get((index)*4) ;
b =array.get((index+1)*4) ;
c = array.get((index+w)*4) ;
d = array.get((index+w+1)*4) ;
value = (a&0xff)*(1-x_diff)*(1-y_diff) + (b&0xff)*(x_diff)*(1-y_diff) +
(c&0xff)*(y_diff)*(1-x_diff) + (d&0xff)*(x_diff*y_diff);
result.set(offset*4,(int) value);
offset++;
}
}
return result;
}
public static Uint8ArrayNative resizeBilinearRedOnly(ImageData imageData,int ax,int ay, int w, int h, int w2, int h2) {
Uint8ArrayNative array=ImageDataUtils.getUint8(imageData);
Uint8ArrayNative result = Uint8ArrayNative.create(w2*h2) ;
int a, b, c, d, x, y, index ;
float x_ratio = ((float)(w-1))/w2 ;
float y_ratio = ((float)(h-1))/h2 ;
float x_diff, y_diff, value ;
int offset = 0 ;
int iw=imageData.getWidth();
for (int i=0;i<h2;i++) {
for (int j=0;j<w2;j++) {
x = (int)(x_ratio * j) ;
y = (int)(y_ratio * i) ;
x_diff = (x_ratio * j) - x ;
y_diff = (y_ratio * i) - y ;
index = ((ay+y)*iw+x+ax) ;
a = array.get((index)*4) ;
b =array.get((index+1)*4) ;
c = array.get((index+iw)*4) ;
d = array.get((index+iw+1)*4) ;
value = (a&0xff)*(1-x_diff)*(1-y_diff) + (b&0xff)*(x_diff)*(1-y_diff) +
(c&0xff)*(y_diff)*(1-x_diff) + (d&0xff)*(x_diff*y_diff);
result.set(offset,(int) value);
offset++;
}
}
return result;
}
/**
*
* @param array must be packed
* @param w
* @param h
* @param w2
* @param h2
* @return
*/
public static Uint8ArrayNative resizeBilinearRedOnlyPacked(Uint8ArrayNative array, int w, int h, int w2, int h2) {
Uint8ArrayNative result = Uint8ArrayNative.create(w2*h2) ;
int a, b, c, d, x, y, index ;
float x_ratio = ((float)(w-1))/w2 ;
float y_ratio = ((float)(h-1))/h2 ;
float x_diff, y_diff, value ;
int offset = 0 ;
for (int i=0;i<h2;i++) {
for (int j=0;j<w2;j++) {
x = (int)(x_ratio * j) ;
y = (int)(y_ratio * i) ;
x_diff = (x_ratio * j) - x ;
y_diff = (y_ratio * i) - y ;
index = (y*w+x) ;
a = array.get((index)) ;
b =array.get((index+1)) ;
c = array.get((index+w)) ;
d = array.get((index+w+1)) ;
value = (a&0xff)*(1-x_diff)*(1-y_diff) + (b&0xff)*(x_diff)*(1-y_diff) +
(c&0xff)*(y_diff)*(1-x_diff) + (d&0xff)*(x_diff*y_diff);
result.set(offset,(int) value);
offset++;
}
}
return result;
}
//http://tech-algorithm.com/articles/nearest-neighbor-image-scaling/
public static Uint8ArrayNative resizePixels(Uint8ArrayNative array,int w1,int h1,int w2,int h2) {
int[] temp = new int[w2*h2*4] ;//rgba
// EDIT: added +1 to account for an early rounding problem
int x_ratio = (int)((w1<<16)/w2) +1;
int y_ratio = (int)((h1<<16)/h2) +1;
//int x_ratio = (int)((w1<<16)/w2) ;
//int y_ratio = (int)((h1<<16)/h2) ;
int x2, y2 ;
for (int i=0;i<h2;i++) {
for (int j=0;j<w2;j++) {
x2 = ((j*x_ratio)>>16) ;
y2 = ((i*y_ratio)>>16) ;
int tempOff=((i*w2)+j)*4;
int arrayOff=((y2*w1)+x2)*4;
for(int k=0;k<4;k++){
temp[tempOff+k] = array.get(arrayOff+k) ;
}
}
}
return Uint8ArrayNative.create(temp);
}
public final static native Uint8ArrayNative getUint8Array(ImageData data) /*-{
return data.data;
}-*/;
public final static void setUint8Array(ImageData data,int[] array){
int w=data.getWidth();
LogUtils.log(array.length+",data="+data.getWidth()+"x"+data.getHeight());
for(int i=0;i<array.length;i+=4){
int x=i%(w*4);
int y=i/(w*4);
data.setRedAt(array[i], x, y);
data.setGreenAt(array[i+1], x, y);
data.setBlueAt(array[i+2], x, y);
data.setAlphaAt(array[i+3], x, y);
//LogUtils.log(x+"x"+y+","+array[i]+"/"+array[i+3]);
}
}
public final static native void setUint8Array(ImageData data,Uint8ArrayNative array) /*-{
data.data.set(array);
}-*/;
}
| |
package cz.zcu.kiv.jop.class_provider;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import cz.zcu.kiv.jop.AbstractContextTest;
import cz.zcu.kiv.jop.annotation.class_provider.ClassLoaderConst;
import cz.zcu.kiv.jop.annotation.class_provider.TargetClassForName;
import cz.zcu.kiv.jop.annotation.class_provider.TargetClassForNameImpl;
import cz.zcu.kiv.jop.ioc.ContextUnitSupport;
import cz.zcu.kiv.jop.ioc.guice.MockModule;
import cz.zcu.kiv.jop.session.ClassLoaderSession;
/**
* Test of class {@link TargetClassForNameProvider}.
*
* @author Mr.FrAnTA
*/
public class TargetClassForNameProviderTest extends AbstractContextTest {
/**
* Preparations before test.
*/
@Override
@Before
public void setUp() {
prepareContext();
}
/**
* Cleanup after test.
*/
@Override
@After
public void tearDown() {
mockery.assertIsSatisfied();
}
/**
* Test of method {@link TargetClassForNameProvider#get} for given null value. Expected
* {@link ClassProviderException}.
*/
@Test(expected = ClassProviderException.class)
public void testGetForNull() throws ClassProviderException {
targetClassForNameProvider.get(null);
}
/**
* Test of method {@link TargetClassForNameProvider#get} for given annotation with null value.
* Expected {@link ClassProviderException}.
*/
@Test(expected = ClassProviderException.class)
public void testGetForNullValue() throws ClassProviderException {
targetClassForNameProvider.get(new TargetClassForNameImpl(null));
}
/**
* Test of method {@link TargetClassForNameProvider#get} for given annotation with empty value.
* Expected {@link ClassProviderException}.
*/
@Test(expected = ClassProviderException.class)
public void testGetForEmptyValue() throws ClassProviderException {
targetClassForNameProvider.get(new TargetClassForNameImpl(""));
}
/**
* Test of method {@link TargetClassForNameProvider#get} for given annotation with blank value.
* Expected {@link ClassProviderException}.
*/
@Test(expected = ClassProviderException.class)
public void testGetForBlankValue() throws ClassProviderException {
targetClassForNameProvider.get(new TargetClassForNameImpl(" "));
}
/**
* Test of method {@link TargetClassForNameProvider#get} for given annotation with null symbolic
* name of class loader. Expected {@link ClassProviderException}.
*/
@Test(expected = ClassProviderException.class)
public void testGetForNullClassLoader() throws ClassProviderException {
targetClassForNameProvider.get(new TargetClassForNameImpl(Integer.class.getName(), true, null));
}
/**
* Test of method {@link TargetClassForNameProvider#get} for given annotation with empty symbolic
* name of class loader. Expected {@link ClassProviderException}.
*/
@Test(expected = ClassProviderException.class)
public void testGetForEmptyClassLoader() throws ClassProviderException {
targetClassForNameProvider.get(new TargetClassForNameImpl(Integer.class.getName(), true, ""));
}
/**
* Test of method {@link TargetClassForNameProvider#get} for given annotation with blank symbolic
* name of class loader. Expected {@link ClassProviderException}.
*/
@Test(expected = ClassProviderException.class)
public void testGetForBlankClassLoader() throws ClassProviderException {
targetClassForNameProvider.get(new TargetClassForNameImpl(Integer.class.getName(), true, " "));
}
/**
* Test of method {@link TargetClassForNameProvider#get} for given annotation with symbolic name
* {@link ClassLoaderConst#CALLER} of class loader.
*/
@Test
public void testGetForCallerClassLoader() throws ClassProviderException {
/*----- Preparation -----*/
TargetClassForName targetClassForName = new TargetClassForNameImpl(Integer.class.getName(), true, ClassLoaderConst.CALLER);
/*----- Execution -----*/
Class<?> clazz = targetClassForNameProvider.get(targetClassForName);
/*----- Verify -----*/
Assert.assertEquals(Integer.class, clazz);
}
/**
* Test of method {@link TargetClassForNameProvider#get} for given annotation with symbolic name
* {@link ClassLoaderConst#CONTEXT} of class loader.
*/
@Test
public void testGetForContextClassLoader() throws ClassProviderException {
/*----- Preparation -----*/
TargetClassForName targetClassForName = new TargetClassForNameImpl(Integer.class.getName(), true, ClassLoaderConst.CONTEXT);
/*----- Execution -----*/
Class<?> clazz = targetClassForNameProvider.get(targetClassForName);
/*----- Verify -----*/
Assert.assertEquals(Integer.class, clazz);
}
/**
* Test of method {@link TargetClassForNameProvider#get} for given annotation with symbolic name
* {@link ClassLoaderConst#SYSTEM} of class loader.
*/
@Test
public void testGetForSystemClassLoader() throws ClassProviderException {
/*----- Preparation -----*/
TargetClassForName targetClassForName = new TargetClassForNameImpl(Integer.class.getName(), true, ClassLoaderConst.SYSTEM);
/*----- Execution -----*/
Class<?> clazz = targetClassForNameProvider.get(targetClassForName);
/*----- Verify -----*/
Assert.assertEquals(Integer.class, clazz);
}
/**
* Test of method {@link TargetClassForNameProvider#get} for given annotation with symbolic name
* of class loader which is stored in session.
*/
@Test
public void testGetForStoredClassLoader() throws ClassProviderException {
/*----- Preparation -----*/
final String name = "NAME";
TargetClassForName targetClassForName = new TargetClassForNameImpl(Integer.class.getName(), true, name);
/*----- Expectations -----*/
mockery.checking(new Expectations() {
{
oneOf(getInstance(ClassLoaderSession.class)).getClassLoader(with(equal(name)));
will(returnValue(Thread.currentThread().getContextClassLoader()));
}
});
/*----- Execution -----*/
Class<?> clazz = targetClassForNameProvider.get(targetClassForName);
/*----- Verify -----*/
Assert.assertEquals(Integer.class, clazz);
}
/**
* Test of method {@link TargetClassForNameProvider#get} for given annotation with symbolic name
* of class loader which is not stored in session.
*/
@Test
public void testGetForNotStoredClassLoader() throws ClassProviderException {
/*----- Preparation -----*/
final String name = "NAME";
TargetClassForName targetClassForName = new TargetClassForNameImpl(Integer.class.getName(), true, name);
/*----- Expectations -----*/
mockery.checking(new Expectations() {
{
oneOf(getInstance(ClassLoaderSession.class)).getClassLoader(with(equal(name)));
will(returnValue(null));
}
});
/*----- Execution -----*/
Class<?> clazz = targetClassForNameProvider.get(targetClassForName);
/*----- Verify -----*/
Assert.assertEquals(Integer.class, clazz);
}
/**
* Test of method {@link TargetClassForNameProvider#get} for non-existing class in given
* annotation with symbolic name {@link ClassLoaderConst#CALLER} of class loader.
*/
@Test(expected = ClassProviderException.class)
public void testGetForNonExistingClass() throws ClassProviderException {
targetClassForNameProvider.get(new TargetClassForNameImpl("java.lang.Foo"));
}
// ------------------------------ context ------------------------------------
/** Tested class generator. */
private TargetClassForNameProvider targetClassForNameProvider;
/**
* {@inheritDoc}
*/
@Override
protected void prepareInstances() {
// prepare testing instance
targetClassForNameProvider = injector.getInstance(TargetClassForNameProvider.class);
}
/**
* {@inheritDoc}
*/
@Override
protected ContextUnitSupport createUnitTestContext() {
// @formatter:off
return new ContextUnitSupport(
new TargetClassForNameProviderModule(mockery)
);
// @formatter:on
}
/**
* Google Guice module for context of this test.
*
* @author Mr.FrAnTA
*/
private class TargetClassForNameProviderModule extends MockModule {
/**
* Constructs module with given mockery.
*
* @param mockery the mockery which will be used for mocking.
*/
public TargetClassForNameProviderModule(Mockery mockery) {
super(mockery);
}
/**
* Configures mocked bindings.
*/
@Override
protected void configure() {
bindMock(ClassLoaderSession.class);
}
}
}
| |
/*
* Copyright (c) 2009, Tony Kohar. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.qi4j.envisage.detail;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.MouseInputAdapter;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumnModel;
import org.qi4j.envisage.event.LinkEvent;
import org.qi4j.envisage.util.TableRow;
import org.qi4j.tools.model.descriptor.LayerDetailDescriptor;
import org.qi4j.tools.model.descriptor.ModuleDetailDescriptor;
import org.qi4j.tools.model.descriptor.ServiceDetailDescriptor;
import org.qi4j.tools.model.util.DescriptorUtilities;
/**
* API would be defined as "All service interfaces which are visible for layer
* or application" and SPI would be defined as "All service dependencies which
* are not satisfied from within the module". And then similar for Layer. This
* way you can select a Module/Layer and immediately see what it produces as
* output and requires as input. This is also very very nice for documentation
* purposes.
*/
/* package */ final class SPIPane
extends DetailPane
{
private static final ResourceBundle BUNDLE = ResourceBundle.getBundle( SPIPane.class.getName() );
private JPanel contentPane;
private JTable spiTable;
private SPITableModel spiTableModel;
private Object linkObject;
private Cursor defaultCursor;
private Cursor linkCursor;
/* package */ SPIPane( DetailModelPane detailModelPane )
{
super( detailModelPane );
this.setLayout( new BorderLayout() );
this.add( contentPane, BorderLayout.CENTER );
spiTableModel = new SPITableModel();
spiTable.setModel( spiTableModel );
spiTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
TableColumnModel columnModel = spiTable.getColumnModel();
columnModel.getColumn( 0 ).setCellRenderer( new DependencyCellRenderer() );
defaultCursor = getCursor();
linkCursor = LinkEvent.LINK_CURSOR;
MouseInputAdapter mouseInputListener = new MouseInputAdapter()
{
@Override
public void mouseMoved( MouseEvent evt )
{
// Column 1 is the Service Column
int col = spiTable.columnAtPoint( evt.getPoint() );
if( col == 0 )
{
setCursor( linkCursor );
}
else
{
if( !getCursor().equals( defaultCursor ) )
{
setCursor( defaultCursor );
}
}
}
@Override
public void mouseClicked( MouseEvent evt )
{
int col = spiTable.columnAtPoint( evt.getPoint() );
if( col != 0 )
{
return;
}
int row = spiTable.rowAtPoint( evt.getPoint() );
if( row < 0 )
{
return;
}
linkObject = spiTable.getValueAt( row, col );
linkActivated();
linkObject = null;
}
};
spiTable.addMouseMotionListener( mouseInputListener );
spiTable.addMouseListener( mouseInputListener );
}
@Override
protected void setDescriptor( Object objectDesciptor )
{
clear();
List<ServiceDetailDescriptor> list = null;
if( objectDesciptor instanceof LayerDetailDescriptor )
{
list = DescriptorUtilities.findLayerSPI( (LayerDetailDescriptor) objectDesciptor );
}
else if( objectDesciptor instanceof ModuleDetailDescriptor )
{
list = DescriptorUtilities.findModule( (ModuleDetailDescriptor) objectDesciptor );
}
if( list != null )
{
spiTableModel.addRow( list );
}
}
private void clear()
{
linkObject = null;
spiTableModel.clear();
}
private void linkActivated()
{
if( linkObject == null )
{
return;
}
LinkEvent linkEvt = new LinkEvent( this, linkObject );
detailModelPane.fireLinkActivated( linkEvt );
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
*/
private void $$$setupUI$$$()
{
contentPane = new JPanel();
contentPane.setLayout( new BorderLayout( 0, 0 ) );
final JScrollPane scrollPane1 = new JScrollPane();
contentPane.add( scrollPane1, BorderLayout.CENTER );
spiTable = new JTable();
scrollPane1.setViewportView( spiTable );
}
public JComponent $$$getRootComponent$$$()
{
return contentPane;
}
private static class SPITableModel
extends AbstractTableModel
{
/**
* the column names for this model
*/
private static final String[] COLUMN_NAMES =
{
BUNDLE.getString( "Dependency.Column" ),
BUNDLE.getString( "Module.Column" ),
BUNDLE.getString( "Layer.Column" )
};
private final ArrayList<TableRow> rows;
private SPITableModel()
{
rows = new ArrayList<>();
}
private void addRow( List<ServiceDetailDescriptor> list )
{
if( list.isEmpty() )
{
return;
}
int i1 = rows.size();
if( i1 > 0 )
{
i1--;
}
int i2 = 0;
for( ServiceDetailDescriptor descriptor : list )
{
TableRow row = new TableRow( COLUMN_NAMES.length );
row.set( 0, descriptor );
row.set( 1, descriptor.module() );
row.set( 2, descriptor.module().layer() );
this.rows.add( row );
i2++;
}
fireTableRowsInserted( i1, i1 + i2 );
}
@Override
public Object getValueAt( int rowIndex, int columnIndex )
{
TableRow row = rows.get( rowIndex );
return row.get( columnIndex );
}
private void clear()
{
rows.clear();
fireTableDataChanged();
}
@Override
public int getColumnCount()
{
return COLUMN_NAMES.length;
}
@Override
public String getColumnName( int col )
{
return COLUMN_NAMES[ col];
}
@Override
public int getRowCount()
{
return rows.size();
}
}
private static class DependencyCellRenderer
extends DefaultTableCellRenderer
{
@Override
public final Component getTableCellRendererComponent( JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column
)
{
if( value != null )
{
value = "<html><a href=\"" + value.toString() + "\">" + value.toString() + "</a></html>";
}
super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column );
return this;
}
}
}
| |
//
// ========================================================================
// Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.io.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SocketChannel;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/**
* Channel End Point.
* <p>Holds the channel and socket for an NIO endpoint.
*
*/
public class ChannelEndPoint implements EndPoint
{
private static final Logger LOG = Log.getLogger(ChannelEndPoint.class);
protected final ByteChannel _channel;
protected final ByteBuffer[] _gather2=new ByteBuffer[2];
protected final Socket _socket;
protected final InetSocketAddress _local;
protected final InetSocketAddress _remote;
protected volatile int _maxIdleTime;
private volatile boolean _ishut;
private volatile boolean _oshut;
public ChannelEndPoint(ByteChannel channel) throws IOException
{
super();
this._channel = channel;
_socket=(channel instanceof SocketChannel)?((SocketChannel)channel).socket():null;
if (_socket!=null)
{
_local=(InetSocketAddress)_socket.getLocalSocketAddress();
_remote=(InetSocketAddress)_socket.getRemoteSocketAddress();
_maxIdleTime=_socket.getSoTimeout();
}
else
{
_local=_remote=null;
}
}
protected ChannelEndPoint(ByteChannel channel, int maxIdleTime) throws IOException
{
this._channel = channel;
_maxIdleTime=maxIdleTime;
_socket=(channel instanceof SocketChannel)?((SocketChannel)channel).socket():null;
if (_socket!=null)
{
_local=(InetSocketAddress)_socket.getLocalSocketAddress();
_remote=(InetSocketAddress)_socket.getRemoteSocketAddress();
_socket.setSoTimeout(_maxIdleTime);
}
else
{
_local=_remote=null;
}
}
public boolean isBlocking()
{
return !(_channel instanceof SelectableChannel) || ((SelectableChannel)_channel).isBlocking();
}
public boolean blockReadable(long millisecs) throws IOException
{
return true;
}
public boolean blockWritable(long millisecs) throws IOException
{
return true;
}
/*
* @see org.eclipse.io.EndPoint#isOpen()
*/
public boolean isOpen()
{
return _channel.isOpen();
}
/** Shutdown the channel Input.
* Cannot be overridden. To override, see {@link #shutdownInput()}
* @throws IOException
*/
protected final void shutdownChannelInput() throws IOException
{
LOG.debug("ishut {}", this);
_ishut = true;
if (_channel.isOpen())
{
if (_socket != null)
{
try
{
if (!_socket.isInputShutdown())
{
_socket.shutdownInput();
}
}
catch (SocketException e)
{
LOG.debug(e.toString());
LOG.ignore(e);
}
finally
{
if (_oshut)
{
close();
}
}
}
}
}
/* (non-Javadoc)
* @see org.eclipse.io.EndPoint#close()
*/
public void shutdownInput() throws IOException
{
shutdownChannelInput();
}
protected final void shutdownChannelOutput() throws IOException
{
LOG.debug("oshut {}",this);
_oshut = true;
if (_channel.isOpen())
{
if (_socket != null)
{
try
{
if (!_socket.isOutputShutdown())
{
_socket.shutdownOutput();
}
}
catch (SocketException e)
{
LOG.debug(e.toString());
LOG.ignore(e);
}
finally
{
if (_ishut)
{
close();
}
}
}
}
}
/* (non-Javadoc)
* @see org.eclipse.io.EndPoint#close()
*/
public void shutdownOutput() throws IOException
{
shutdownChannelOutput();
}
public boolean isOutputShutdown()
{
return _oshut || !_channel.isOpen() || _socket != null && _socket.isOutputShutdown();
}
public boolean isInputShutdown()
{
return _ishut || !_channel.isOpen() || _socket != null && _socket.isInputShutdown();
}
/* (non-Javadoc)
* @see org.eclipse.io.EndPoint#close()
*/
public void close() throws IOException
{
LOG.debug("close {}",this);
_channel.close();
}
/* (non-Javadoc)
* @see org.eclipse.io.EndPoint#fill(org.eclipse.io.Buffer)
*/
public int fill(Buffer buffer) throws IOException
{
if (_ishut)
return -1;
Buffer buf = buffer.buffer();
int len=0;
if (buf instanceof NIOBuffer)
{
final NIOBuffer nbuf = (NIOBuffer)buf;
final ByteBuffer bbuf=nbuf.getByteBuffer();
//noinspection SynchronizationOnLocalVariableOrMethodParameter
try
{
synchronized(bbuf)
{
try
{
bbuf.position(buffer.putIndex());
len=_channel.read(bbuf);
}
finally
{
buffer.setPutIndex(bbuf.position());
bbuf.position(0);
}
}
if (len<0 && isOpen())
{
if (!isInputShutdown())
shutdownInput();
if (isOutputShutdown())
_channel.close();
}
}
catch (IOException x)
{
LOG.debug("Exception while filling", x);
try
{
if (_channel.isOpen())
_channel.close();
}
catch (Exception xx)
{
LOG.ignore(xx);
}
if (len>0)
throw x;
len=-1;
}
}
else
{
throw new IOException("Not Implemented");
}
return len;
}
/* (non-Javadoc)
* @see org.eclipse.io.EndPoint#flush(org.eclipse.io.Buffer)
*/
public int flush(Buffer buffer) throws IOException
{
Buffer buf = buffer.buffer();
int len=0;
if (buf instanceof NIOBuffer)
{
final NIOBuffer nbuf = (NIOBuffer)buf;
final ByteBuffer bbuf=nbuf.getByteBuffer().asReadOnlyBuffer();
try
{
bbuf.position(buffer.getIndex());
bbuf.limit(buffer.putIndex());
len=_channel.write(bbuf);
}
finally
{
if (len>0)
buffer.skip(len);
}
}
else if (buf instanceof RandomAccessFileBuffer)
{
len = ((RandomAccessFileBuffer)buf).writeTo(_channel,buffer.getIndex(),buffer.length());
if (len>0)
buffer.skip(len);
}
else if (buffer.array()!=null)
{
ByteBuffer b = ByteBuffer.wrap(buffer.array(), buffer.getIndex(), buffer.length());
len=_channel.write(b);
if (len>0)
buffer.skip(len);
}
else
{
throw new IOException("Not Implemented");
}
return len;
}
/* (non-Javadoc)
* @see org.eclipse.io.EndPoint#flush(org.eclipse.io.Buffer, org.eclipse.io.Buffer, org.eclipse.io.Buffer)
*/
public int flush(Buffer header, Buffer buffer, Buffer trailer) throws IOException
{
int length=0;
Buffer buf0 = header==null?null:header.buffer();
Buffer buf1 = buffer==null?null:buffer.buffer();
if (_channel instanceof GatheringByteChannel &&
header!=null && header.length()!=0 && buf0 instanceof NIOBuffer &&
buffer!=null && buffer.length()!=0 && buf1 instanceof NIOBuffer)
{
length = gatheringFlush(header,((NIOBuffer)buf0).getByteBuffer(),buffer,((NIOBuffer)buf1).getByteBuffer());
}
else
{
// flush header
if (header!=null && header.length()>0)
length=flush(header);
// flush buffer
if ((header==null || header.length()==0) &&
buffer!=null && buffer.length()>0)
length+=flush(buffer);
// flush trailer
if ((header==null || header.length()==0) &&
(buffer==null || buffer.length()==0) &&
trailer!=null && trailer.length()>0)
length+=flush(trailer);
}
return length;
}
protected int gatheringFlush(Buffer header, ByteBuffer bbuf0, Buffer buffer, ByteBuffer bbuf1) throws IOException
{
int length;
synchronized(this)
{
// Adjust position indexs of buf0 and buf1
bbuf0=bbuf0.asReadOnlyBuffer();
bbuf0.position(header.getIndex());
bbuf0.limit(header.putIndex());
bbuf1=bbuf1.asReadOnlyBuffer();
bbuf1.position(buffer.getIndex());
bbuf1.limit(buffer.putIndex());
_gather2[0]=bbuf0;
_gather2[1]=bbuf1;
// do the gathering write.
length=(int)((GatheringByteChannel)_channel).write(_gather2);
int hl=header.length();
if (length>hl)
{
header.clear();
buffer.skip(length-hl);
}
else if (length>0)
{
header.skip(length);
}
}
return length;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the channel.
*/
public ByteChannel getChannel()
{
return _channel;
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.io.EndPoint#getLocalAddr()
*/
public String getLocalAddr()
{
if (_socket==null)
return null;
if (_local==null || _local.getAddress()==null || _local.getAddress().isAnyLocalAddress())
return StringUtil.ALL_INTERFACES;
return _local.getAddress().getHostAddress();
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.io.EndPoint#getLocalHost()
*/
public String getLocalHost()
{
if (_socket==null)
return null;
if (_local==null || _local.getAddress()==null || _local.getAddress().isAnyLocalAddress())
return StringUtil.ALL_INTERFACES;
return _local.getAddress().getCanonicalHostName();
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.io.EndPoint#getLocalPort()
*/
public int getLocalPort()
{
if (_socket==null)
return 0;
if (_local==null)
return -1;
return _local.getPort();
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.io.EndPoint#getRemoteAddr()
*/
public String getRemoteAddr()
{
if (_socket==null)
return null;
if (_remote==null)
return null;
return _remote.getAddress().getHostAddress();
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.io.EndPoint#getRemoteHost()
*/
public String getRemoteHost()
{
if (_socket==null)
return null;
if (_remote==null)
return null;
return _remote.getAddress().getCanonicalHostName();
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.io.EndPoint#getRemotePort()
*/
public int getRemotePort()
{
if (_socket==null)
return 0;
return _remote==null?-1:_remote.getPort();
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.io.EndPoint#getConnection()
*/
public Object getTransport()
{
return _channel;
}
/* ------------------------------------------------------------ */
public void flush()
throws IOException
{
}
/* ------------------------------------------------------------ */
public int getMaxIdleTime()
{
return _maxIdleTime;
}
/* ------------------------------------------------------------ */
/**
* @see org.eclipse.jetty.io.bio.StreamEndPoint#setMaxIdleTime(int)
*/
public void setMaxIdleTime(int timeMs) throws IOException
{
if (_socket!=null && timeMs!=_maxIdleTime)
_socket.setSoTimeout(timeMs>0?timeMs:0);
_maxIdleTime=timeMs;
}
}
| |
/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
package com.rhomobile.rhodes;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.rhomobile.rhodes.bluetooth.RhoBluetoothManager;
import com.rhomobile.rhodes.extmanager.IRhoExtManager;
import com.rhomobile.rhodes.extmanager.IRhoWebView;
import com.rhomobile.rhodes.extmanager.RhoExtManager;
import com.rhomobile.rhodes.mainview.MainView;
import com.rhomobile.rhodes.mainview.SimpleMainView;
import com.rhomobile.rhodes.mainview.SplashScreen;
import com.rhomobile.rhodes.util.Config;
import com.rhomobile.rhodes.util.Utils;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.widget.FrameLayout;
import android.support.v4.content.PermissionChecker;
import android.support.v4.app.ActivityCompat;
public class RhodesActivity extends BaseActivity implements SplashScreen.SplashScreenListener, ActivityCompat.OnRequestPermissionsResultCallback {
private static final String TAG = RhodesActivity.class.getSimpleName();
private static final boolean DEBUG = false;
public static boolean IS_WINDOWS_KEY = false;
public static boolean isShownSplashScreenFirstTime = false;//Used to display the splash screen only once during launch of an application
public static int MAX_PROGRESS = 10000;
private static RhodesActivity sInstance = null;
private Handler mHandler;
private View mChild;
private int oldHeight;
private FrameLayout.LayoutParams frameLayoutParams;
private int notificationBarHeight = 0;
public static boolean IS_RESIZE_SIP = false;
private FrameLayout mTopLayout;
private SplashScreen mSplashScreen;
private MainView mMainView;
private String lastIntent ="android.intent.action.MAIN";
private RhoMenu mAppMenu;
private long uiThreadId = 0;
public static SharedPreferences pref = null;
public static interface GestureListener {
void onTripleTap();
void onQuadroTap();
};
public static class GestureListenerAdapter implements GestureListener {
public void onTripleTap() {
}
public void onQuadroTap() {
}
};
private static ArrayList<GestureListener> ourGestureListeners = new ArrayList<GestureListener>();
public long getUiThreadId() {
return uiThreadId;
}
private boolean mIsForeground = false;
private boolean mIsInsideStartStop = false;
public boolean isForegroundNow() {
return mIsForeground;
}
public boolean isInsideStartStop() {
return mIsInsideStartStop;
}
//------------------------------------------------------------------------------------------------------------------
// Read SSL settings from config.xml
private ApplicationInfo getAppInfo() {
String pkgName = getPackageName();
try {
ApplicationInfo info = getPackageManager().getApplicationInfo(pkgName, 0);
return info;
} catch (NameNotFoundException e) {
throw new RuntimeException("Internal error: package " + pkgName + " not found: " + e.getMessage());
}
}
private void initConfig(String path) {
InputStream configIs = null;
Config config = new Config();
ApplicationInfo appInfo = getAppInfo();
try {
String externalSharedPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + appInfo.packageName;
Logger.I(TAG, "Config path: " + path);
File configXmlFile = new File(path);
if (configXmlFile.exists()) {
Logger.I(TAG, "Loading Config.xml from " + configXmlFile.getAbsolutePath());
configIs = new FileInputStream(configXmlFile);
config.load(configIs, configXmlFile.getParent());
}
else {
Logger.I(TAG, "Loading Config.xml from resources");
configIs = getResources().openRawResource(RhoExtManager.getResourceId("raw", "config"));
config.load(configIs, externalSharedPath);
}
String isWindowKey = null;
try {
isWindowKey = config.getValue("isWindowsKey");
} catch (Exception e) {
e.printStackTrace();
}
if (isWindowKey != null && isWindowKey.length() > 0){
if(isWindowKey.contains("1")){
IS_WINDOWS_KEY = true;
}
}
String CAFile = config.getValue("CAFile");
if (CAFile != null && CAFile.length() > 0)
RhoConf.setString("CAFile", CAFile);
String CAPath = config.getValue("CAPath");
if (CAPath != null && CAPath.length() > 0)
RhoConf.setString("CAPath", CAPath);
String sVerifyPeer = config.getValue("VerifyPeerCertificate");
if (sVerifyPeer != null && sVerifyPeer.length() > 0)
RhoConf.setBoolean("no_ssl_verify_peer", sVerifyPeer.equals("0"));
String pageZoom=config.getValue("PageZoom");
if(pageZoom !=null && pageZoom.length()>0)
RhoConf.setString("PageZoom", pageZoom);
else
RhoConf.setString("PageZoom", "1.0");
String sFullScreen = null;
try {
sFullScreen = config.getValue("FullScreen");
} catch (Exception e) {
e.printStackTrace();
}
if (sFullScreen != null && sFullScreen.length() > 0){
if(sFullScreen.contains("1")){
RhoConf.setBoolean("full_screen", true);
}else{
RhoConf.setBoolean("full_screen", false);
}
}
} catch (Throwable e) {
Logger.W(TAG, "Error loading RhoElements configuraiton ("+e.getClass().getSimpleName()+"): " + e.getMessage());
//Logger.W(TAG, e);
} finally {
if (configIs != null) {
try {
configIs.close();
} catch (IOException e) {
// just nothing to do
}
}
}
}
private void readRhoElementsConfig() {
String externalSharedPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + getAppInfo().packageName;
String configPath = new File(externalSharedPath, "Config.xml").getAbsolutePath();
initConfig(configPath);
}
//------------------------------------------------------------------------------------------------------------------
private final int RHODES_PERMISSIONS_REQUEST = 1;
private void requestPermissions() {
String pkgName = getPackageName();
try {
PackageInfo info = getPackageManager().getPackageInfo(pkgName, PackageManager.GET_PERMISSIONS);
ArrayList<String> requestedPermissions = new ArrayList<String>();
for ( String p : info.requestedPermissions ) {
int result = PermissionChecker.checkSelfPermission( this, p );
if (result != PackageManager.PERMISSION_GRANTED) {
requestedPermissions.add(p);
}
}
if ( requestedPermissions.size() > 0 ) {
Logger.I(TAG, "Requesting permissions: " + requestedPermissions.toString() );
ActivityCompat.requestPermissions(
this,
requestedPermissions.toArray(new String[0]),
RHODES_PERMISSIONS_REQUEST);
}
} catch (NameNotFoundException e) {
throw new RuntimeException("Internal error: package " + pkgName + " not found: " + e.getMessage());
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
StringBuilder results = new StringBuilder();
for ( int i = 0; i < permissions.length; ++ i ) {
results.append( String.format("%s:%d, ", permissions[i], grantResults[i] ) );
}
Logger.I(
TAG,
String.format(
"onRequestPermissionsResult code: %d, results: %s",
requestCode,
results.toString()
)
);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
Logger.T(TAG, "onCreate");
Thread ct = Thread.currentThread();
//ct.setPriority(Thread.MAX_PRIORITY);
uiThreadId = ct.getId();
sInstance = this;
pref = sInstance.getApplicationContext().getSharedPreferences("RhodesSharedPreference", RhodesActivity.getContext().MODE_PRIVATE);
super.onCreate(savedInstanceState);
if ((RhoConf.isExist("android_title") && !RhoConf.getBool("android_title"))
|| !RhodesService.isTitleEnabled()) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
requestWindowFeature(Window.FEATURE_PROGRESS);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, MAX_PROGRESS);
mHandler = new Handler();
Logger.T(TAG, "Creating default main view");
mTopLayout = new FrameLayout(this);
setContentView(mTopLayout);
SimpleMainView simpleMainView = new SimpleMainView();
setMainView(simpleMainView);
mAppMenu = new RhoMenu();
readRhoElementsConfig();
RhoExtManager.getImplementationInstance().onCreateActivity(this, getIntent());
RhodesApplication.stateChanged(RhodesApplication.UiState.MainActivityCreated);
if (RhoConf.isExist("resize_sip")) {
String resizeSIP = RhoConf.getString("resize_sip");
if (resizeSIP != null && resizeSIP.contains("1")) {
IS_RESIZE_SIP = true;
resizeSIP();
} else {
IS_RESIZE_SIP = false;
}
}
requestPermissions();
}
public MainView switchToSimpleMainView(MainView currentView) {
IRhoWebView rhoWebView = currentView.detachWebView();
SimpleMainView view = new SimpleMainView(rhoWebView);
//rhoWebView.setWebClient(this);
setMainView(view);
return view;
}
public void notifyUiCreated() {
RhodesService r = RhodesService.getInstance();
if ( r != null ) {
RhodesService.callUiCreatedCallback();
}
else {
mHandler.post(new Runnable() {
public void run() {
RhodesService r = RhodesService.getInstance();
if (r == null) {
// If there is no yet running RhodesService instance,
// try to do the same after 100ms
mHandler.postDelayed(this, 100);
return;
}
RhodesService.callUiCreatedCallback();
}
});
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Logger.T(TAG, "onNewIntent");
if(intent !=null && intent.getAction() !=null){
if(((lastIntent.compareTo("android.intent.action.MAIN") == 0) || ! (lastIntent.compareTo("android.intent.action.VIEW") == 0))){
//Use of this If -- generic if to avoid setAction = View for any system related intent. eg:- NFC
if(intent.getAction().compareTo("android.intent.action.MAIN") == 0 && (!(lastIntent.compareTo("com.rho.rhoelements.SHORTCUT_ACTION") == 0)) && (RhoExtManager.getInstance().getWebView().getUrl()!=null/*..Double CLick Crash...*/)){
//This Else for :- If user click on launch the EB through Shortcut and second time launch the EB through the proper
//App that time for handle the Start page , we added this else.
String url = RhoExtManager.getInstance().getWebView().getUrl().toString();
intent.setAction("android.intent.action.VIEW");
intent.setData(Uri.parse(url));
}
}
else if((intent.getAction().compareTo("android.intent.action.MAIN") == 0) && (!(lastIntent.compareTo("com.rho.rhoelements.SHORTCUT_ACTION") == 0)) && (RhoExtManager.getInstance().getWebView().getUrl()!=null/*..Double CLick Crash...*/) ){
//This Else is to handle start page when user call two times on minimize API
//That time last intent will be as VIEW and intent action will be MAIN
String url = RhoExtManager.getInstance().getWebView().getUrl().toString();
intent.setAction("android.intent.action.VIEW");
intent.setData(Uri.parse(url));
}
}else{
//This Else for :- If user Call Restore API that time to maintain the same Page when App resumed back
//Because when user click on restore API that time our intent value is NULL.
String url = RhoExtManager.getInstance().getWebView().getUrl().toString();
intent.setAction("android.intent.action.VIEW");
intent.setData(Uri.parse(url));
}
handleStartParams(intent);
RhoExtManager.getImplementationInstance().onNewIntent(this, intent);
lastIntent = intent.getAction();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Logger.T(TAG, "onActivityResult");
RhoBluetoothManager.onActivityResult(requestCode, resultCode, data);
// com.rhomobile.rhodes.camera.Camera.onActivityResult(requestCode, resultCode, data);
RhoExtManager.getImplementationInstance().onActivityResult(this, requestCode, resultCode, data);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
RhoExtManager.getImplementationInstance().onSaveInstanceState(outState);
}
@Override
public void onStart() {
super.onStart();
Logger.T(TAG, "onStart");
mIsInsideStartStop = true;
RhodesApplication.stateChanged(RhodesApplication.UiState.MainActivityStarted);
RhoExtManager.getImplementationInstance().onStartActivity(this);
}
@Override
public void onResume() {
Logger.T(TAG, "onResume");
if(!isShownSplashScreenFirstTime){
Logger.T(TAG, "Creating splash screen");
mSplashScreen = new SplashScreen(this, mMainView, this);
mMainView = mSplashScreen;
isShownSplashScreenFirstTime = true;
}
mIsForeground = true;
pauseWebViews(false);
super.onResume();
RhodesApplication.stateChanged(RhodesApplication.UiState.MainActivityResumed);
RhoExtManager.getImplementationInstance().onResumeActivity(this);
}
@Override
public void onPause()
{
mIsForeground = false;
pauseWebViews(true);
RhoExtManager.getImplementationInstance().onPauseActivity(this);
super.onPause();
Logger.T(TAG, "onPause");
RhodesApplication.stateChanged(RhodesApplication.UiState.MainActivityPaused);
}
private void pauseWebViews( boolean pause ) {
if ( mMainView != null ) {
IRhoWebView wv = mMainView.getWebView(-1);
if ( wv != null ) {
if ( pause ) {
wv.onPause();
} else {
wv.onResume();
}
} else {
for ( int i = 0; i < mMainView.getTabsCount(); ++i ) {
wv = mMainView.getWebView(i);
if ( wv != null ) {
if ( pause ) {
wv.onPause();
} else {
wv.onResume();
}
}
}
}
}
}
@Override
public void onStop()
{
super.onStop();
Logger.T(TAG, "onStop");
RhoExtManager.getImplementationInstance().onStopActivity(this);
mIsInsideStartStop = false;
}
@Override
public void onDestroy() {
Logger.T(TAG, "onDestroy");
RhoExtManager.getImplementationInstance().onDestroyActivity(this);
RhodesApplication.stateChanged(RhodesApplication.UiState.Undefined);
sInstance = null;
super.onDestroy();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
RhodesService r = RhodesService.getInstance();
if (DEBUG)
Logger.D(TAG, "onKeyDown: r=" + r);
if (r == null)
return false;
// If the RhoConf setting of disable_back_button is set to 1, pretend we did something.
if (RhoConf.isExist("disable_back_button") && RhoConf.getInt("disable_back_button") == 1) {
Logger.D(TAG, "Back button pressed, but back button is disabled in RhoConfig.");
return true;
} else {
MainView v = r.getMainView();
v.goBack();//back(v.activeTab());
return true;
}
}
return super.onKeyDown(keyCode, event);
}
public RhoMenu getMenu() {
return mAppMenu;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
mAppMenu.enumerateMenu(menu);
Logger.T(TAG, "onCreateOptionsMenu");
return mAppMenu.getItemsCount() != 0;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
Logger.T(TAG, "onPrepareOptionsMenu");
mAppMenu.enumerateMenu(menu);
return mAppMenu.getItemsCount() != 0;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return mAppMenu.onMenuItemSelected(item);
}
@Override
public void onSplashScreenGone(SplashScreen splashScreen) {
View splashView = splashScreen.getSplashView();
if (splashView != null) {
ViewGroup parent = (ViewGroup)splashView.getParent();
if (parent != null) {
parent.removeView(splashView);
}
}
if ((mMainView instanceof SplashScreen) && (mMainView == splashScreen)) {
mMainView = splashScreen.getBackendView();
}
}
@Override
public void onSplashScreenNavigateBack() {
moveTaskToBack(true);
}
@Override
protected Dialog onCreateDialog(int id/*, Bundle args*/) {
return RhoExtManager.getImplementationInstance().onCreateDialog(this, id);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
Logger.T(TAG, "onConfigurationChanged");
super.onConfigurationChanged(newConfig);
RhoExtManager.getImplementationInstance().onConfigurationChanged(this, newConfig);
}
@Deprecated
public static RhodesActivity getInstance() {
return sInstance;
}
public static RhodesActivity safeGetInstance() throws NullPointerException {
if(sInstance != null)
return sInstance;
else
throw new NullPointerException("RhodesActivity.sInstance == null");
}
public RhodesService getService() {
return mRhodesService;
}
public void post(Runnable r) {
mHandler.post(r);
}
public void post(Runnable r, long delay) {
mHandler.postDelayed(r, delay);
}
public SplashScreen getSplashScreen() {
return mSplashScreen;
}
public void setMainView(MainView v) {
if (v != null) {
mTopLayout.removeAllViews();
mMainView = v;
mTopLayout.addView(v.getView(), new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
}
}
public MainView getMainView() {
return mMainView;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
super.onServiceConnected(name, service);
Logger.D(TAG, "onServiceConnected: " + name.toShortString());
handleStartParams(getIntent());
}
private void handleStartParams(Intent intent)
{
StringBuilder startParams = new StringBuilder();
boolean firstParam = true;
if (intent.getData() != null) {
String strUri = intent.toUri(0);
if(strUri.length() > 0)
{
Uri uri = Uri.parse(strUri);
String authority = uri.getAuthority();
String path = uri.getPath();
String query = uri.getQuery();
if (authority != null)
startParams.append(authority);
if (path != null)
startParams.append(path);
if (query != null) {
startParams.append('?').append(query);
firstParam = false;
}
}
}
Bundle extras = intent.getExtras();
if (extras != null) {
Set<String> keys = extras.keySet();
for (String key : keys) {
Object value = extras.get(key);
if (firstParam) {
startParams.append("?");
firstParam = false;
} else
startParams.append("&");
startParams.append(key);
if (value != null) {
startParams.append("=");
startParams.append(value.toString());
}
}
}
String paramString = startParams.toString();
Logger.I(TAG, "New start parameters: " + paramString);
if(!RhodesApplication.canStart(paramString))
{
Logger.E(TAG, "This is hidden app and can be started only with security key.");
//Toast.makeText(this,"Invalid security token !",Toast.LENGTH_SHORT).show();
/*
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setCancelable(true);
b.setOnCancelListener( new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
RhodesService.exit();
}
});
AlertDialog securityAlert = b.create();
securityAlert.setMessage(RhodesService.getInvalidSecurityTokenMessage());
securityAlert.setButton("OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface arg0, int arg1) {
RhodesService.exit();
}
});
securityAlert.show();
*/
return;
}
// String urlStart = uri.getPath();
// if (urlStart != null) {
// if ("".compareTo(urlStart) != 0)
// {
// Logger.D(TAG, "PROCESS URL START: " + urlStart);
// RhoConf.setString("start_path", Uri.decode(urlStart));
// }
// }
}
@Override
public boolean dispatchKeyEvent(KeyEvent event)
{
IRhoExtManager extManager = RhoExtManager.getInstance();
if(extManager.onKey(event.getKeyCode(), event))
{
return true;
}
return super.dispatchKeyEvent(event);
}
public static Context getContext() {
RhodesActivity ra = RhodesActivity.getInstance();
if (ra == null)
throw new IllegalStateException("No rhodes activity instance at this moment");
return ra;
}
public static void addGestureListener(GestureListener listener) {
ourGestureListeners.add(listener);
Utils.platformLog(TAG, "$$$ addGestureListener()");
}
public static void onTripleTap() {
Utils.platformLog(TAG, "$$$ onTripleTap()");
Iterator<GestureListener> i = ourGestureListeners.iterator();
while (i.hasNext()) {
i.next().onTripleTap();
}
}
public static void onQuadroTap() {
Utils.platformLog(TAG, "$$$ onQuadroTap()");
Iterator<GestureListener> i = ourGestureListeners.iterator();
while (i.hasNext()) {
i.next().onQuadroTap();
}
}
public static String getDecodeWav(){
String decodeWavPath = null;
decodeWavPath =pref.getString("scandecodewavkey", "");
pref.getString("scandecodewavkey", "");
return decodeWavPath;
}
public static void setDecodeWav(String string){
pref.edit().putString("scandecodewavkey", string).commit();
}
public void resizeSIP() {
FrameLayout mLayout = (FrameLayout) this
.findViewById(android.R.id.content);
if(mLayout != null && mLayout.getChildAt(0) != null) {
mChild = mLayout.getChildAt(0);
mChild.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
resizeChildOfContent();
}
});
frameLayoutParams = (FrameLayout.LayoutParams) mChild.getLayoutParams();
}
}
private void resizeChildOfContent() {
int newHeight = calculateUsedHeight();
if (newHeight != oldHeight && mChild != null && frameLayoutParams != null) {
int sipHeight = mChild.getRootView().getHeight();
int heightDiff = sipHeight - newHeight;
if (heightDiff > (sipHeight / 4)) {
// keyboard probably just became visible
frameLayoutParams.height = sipHeight - heightDiff;
} else {
// keyboard probably just became hidden
frameLayoutParams.height = sipHeight;
}
if( !BaseActivity.getFullScreenMode()){
frameLayoutParams.height = frameLayoutParams.height - notificationBarHeight;
if (heightDiff > (sipHeight / 4)) {
frameLayoutParams.height = frameLayoutParams.height + notificationBarHeight;
}
}
mChild.requestLayout();
oldHeight = newHeight;
}
}
private int calculateUsedHeight() {
Rect r = new Rect();
mChild.getWindowVisibleDisplayFrame(r);
notificationBarHeight = r.top;
return (r.bottom - r.top);
}
}
| |
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uberfire.java.nio.fs.jgit;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.ObjectId;
import org.junit.Ignore;
import org.junit.Test;
import org.uberfire.commons.data.Pair;
import org.uberfire.java.nio.base.FileSystemState;
import org.uberfire.java.nio.base.NotImplementedException;
import org.uberfire.java.nio.base.options.CommentedOption;
import org.uberfire.java.nio.file.DirectoryNotEmptyException;
import org.uberfire.java.nio.file.DirectoryStream;
import org.uberfire.java.nio.file.FileAlreadyExistsException;
import org.uberfire.java.nio.file.FileStore;
import org.uberfire.java.nio.file.FileSystem;
import org.uberfire.java.nio.file.FileSystemAlreadyExistsException;
import org.uberfire.java.nio.file.FileSystemNotFoundException;
import org.uberfire.java.nio.file.NoSuchFileException;
import org.uberfire.java.nio.file.NotDirectoryException;
import org.uberfire.java.nio.file.Path;
import org.uberfire.java.nio.file.StandardWatchEventKind;
import org.uberfire.java.nio.file.WatchEvent;
import org.uberfire.java.nio.file.WatchKey;
import org.uberfire.java.nio.file.WatchService;
import org.uberfire.java.nio.file.attribute.BasicFileAttributeView;
import org.uberfire.java.nio.file.attribute.BasicFileAttributes;
import org.uberfire.java.nio.file.attribute.FileTime;
import org.uberfire.java.nio.fs.jgit.util.JGitUtil;
import org.uberfire.java.nio.fs.jgit.util.JGitUtil.*;
import static org.fest.assertions.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.uberfire.java.nio.file.StandardDeleteOption.*;
import static org.uberfire.java.nio.fs.jgit.util.JGitUtil.*;
public class JGitFileSystemProviderTest extends AbstractTestInfra {
private int gitDaemonPort;
@Override
public Map<String, String> getGitPreferences() {
Map<String, String> gitPrefs = super.getGitPreferences();
gitPrefs.put( "org.uberfire.nio.git.daemon.enabled", "true" );
gitDaemonPort = findFreePort();
gitPrefs.put( "org.uberfire.nio.git.daemon.port", String.valueOf( gitDaemonPort ) );
return gitPrefs;
}
@Test
@Ignore
public void testDaemob() throws InterruptedException {
final URI newRepo = URI.create( "git://repo-name" );
final Map<String, ?> env = new HashMap<String, Object>() {{
put( "init", Boolean.TRUE );
}};
FileSystem fs = provider.newFileSystem( newRepo, env );
WatchService ws = null;
ws = fs.newWatchService();
final Path path = fs.getRootDirectories().iterator().next();
path.register( ws, StandardWatchEventKind.ENTRY_CREATE, StandardWatchEventKind.ENTRY_MODIFY, StandardWatchEventKind.ENTRY_DELETE, StandardWatchEventKind.ENTRY_RENAME );
final WatchKey k = ws.take();
final List<WatchEvent<?>> events = k.pollEvents();
for ( WatchEvent object : events ) {
if ( object.kind() == StandardWatchEventKind.ENTRY_MODIFY ) {
System.out.println( "Modify: " + object.context().toString() );
}
if ( object.kind() == StandardWatchEventKind.ENTRY_RENAME ) {
System.out.println( "Rename: " + object.context().toString() );
}
if ( object.kind() == StandardWatchEventKind.ENTRY_DELETE ) {
System.out.println( "Delete: " + object.context().toString() );
}
if ( object.kind() == StandardWatchEventKind.ENTRY_CREATE ) {
System.out.println( "Created: " + object.context().toString() );
}
}
}
@Test
public void testNewFileSystem() {
final URI newRepo = URI.create( "git://repo-name" );
final FileSystem fs = provider.newFileSystem( newRepo, EMPTY_ENV );
assertThat( fs ).isNotNull();
final DirectoryStream<Path> stream = provider.newDirectoryStream( provider.getPath( newRepo ), null );
assertThat( stream ).isNotNull().hasSize( 0 );
try {
provider.newFileSystem( newRepo, EMPTY_ENV );
failBecauseExceptionWasNotThrown( FileSystemAlreadyExistsException.class );
} catch ( final Exception ignored ) {
}
provider.newFileSystem( URI.create( "git://repo-name2" ), EMPTY_ENV );
}
@Test
public void testNewFileSystemInited() {
final URI newRepo = URI.create( "git://init-repo-name" );
final Map<String, ?> env = new HashMap<String, Object>() {{
put( "init", Boolean.TRUE );
}};
final FileSystem fs = provider.newFileSystem( newRepo, env );
assertThat( fs ).isNotNull();
final DirectoryStream<Path> stream = provider.newDirectoryStream( provider.getPath( newRepo ), null );
assertThat( stream ).isNotNull().hasSize( 1 );
}
@Test
public void testInvalidURINewFileSystem() {
final URI newRepo = URI.create( "git:///repo-name" );
try {
provider.newFileSystem( newRepo, EMPTY_ENV );
failBecauseExceptionWasNotThrown( IllegalArgumentException.class );
} catch ( final IllegalArgumentException ex ) {
assertThat( ex.getMessage() ).isEqualTo( "Parameter named 'uri' is invalid, missing host repository!" );
}
}
@Test
public void testNewFileSystemClone() throws IOException {
final URI originRepo = URI.create( "git://my-simple-test-origin-name" );
final JGitFileSystem origin = (JGitFileSystem) provider.newFileSystem( originRepo, new HashMap<String, Object>() {{
put( "listMode", "ALL" );
}} );
commit( origin.gitRepo(), "master", "user1", "user1@example.com", "commitx", null, null, false, new HashMap<String, File>() {{
put( "file.txt", tempFile( "temp" ) );
}} );
final URI newRepo = URI.create( "git://my-repo-name" );
final Map<String, Object> env = new HashMap<String, Object>() {{
put( JGitFileSystemProvider.GIT_ENV_KEY_DEFAULT_REMOTE_NAME, "git://localhost:" + gitDaemonPort + "/my-simple-test-origin-name" );
put( "listMode", "ALL" );
}};
final FileSystem fs = provider.newFileSystem( newRepo, env );
assertThat( fs ).isNotNull();
assertThat( fs.getRootDirectories() ).hasSize( 2 );
assertThat( fs.getPath( "file.txt" ).toFile() ).isNotNull().exists();
commit( origin.gitRepo(), "master", "user1", "user1@example.com", "commitx", null, null, false, new HashMap<String, File>() {{
put( "fileXXXXX.txt", tempFile( "temp" ) );
}} );
provider.getFileSystem( URI.create( "git://my-repo-name?sync=git://localhost:" + gitDaemonPort + "/my-simple-test-origin-name&force" ) );
assertThat( fs ).isNotNull();
assertThat( fs.getRootDirectories() ).hasSize( 3 );
for ( final Path root : fs.getRootDirectories() ) {
if ( root.toAbsolutePath().toUri().toString().contains( "upstream" ) ) {
assertThat( provider.newDirectoryStream( root, null ) ).isNotEmpty().hasSize( 2 );
} else if ( root.toAbsolutePath().toUri().toString().contains( "origin" ) ) {
assertThat( provider.newDirectoryStream( root, null ) ).isNotEmpty().hasSize( 1 );
} else {
assertThat( provider.newDirectoryStream( root, null ) ).isNotEmpty().hasSize( 2 );
}
}
commit( origin.gitRepo(), "master", "user1", "user1@example.com", "commitx", null, null, false, new HashMap<String, File>() {{
put( "fileYYYY.txt", tempFile( "tempYYYY" ) );
}} );
provider.getFileSystem( URI.create( "git://my-repo-name?sync=git://localhost:" + gitDaemonPort + "/my-simple-test-origin-name&force" ) );
assertThat( fs.getRootDirectories() ).hasSize( 3 );
for ( final Path root : fs.getRootDirectories() ) {
if ( root.toAbsolutePath().toUri().toString().contains( "upstream" ) ) {
assertThat( provider.newDirectoryStream( root, null ) ).isNotEmpty().hasSize( 3 );
} else if ( root.toAbsolutePath().toUri().toString().contains( "origin" ) ) {
assertThat( provider.newDirectoryStream( root, null ) ).isNotEmpty().hasSize( 1 );
} else {
assertThat( provider.newDirectoryStream( root, null ) ).isNotEmpty().hasSize( 3 );
}
}
}
@Test
public void testNewFileSystemCloneAndPush() throws IOException {
final URI originRepo = URI.create( "git://my-simple-test-origin-repo" );
final JGitFileSystem origin = (JGitFileSystem) provider.newFileSystem( originRepo, new HashMap<String, Object>() {{
put( "listMode", "ALL" );
}} );
commit( origin.gitRepo(), "master", "user1", "user1@example.com", "commitx", null, null, false, new HashMap<String, File>() {{
put( "file.txt", tempFile( "temp" ) );
}} );
final URI newRepo = URI.create( "git://my-repo" );
final Map<String, Object> env = new HashMap<String, Object>() {{
put( JGitFileSystemProvider.GIT_ENV_KEY_DEFAULT_REMOTE_NAME, "git://localhost:" + gitDaemonPort + "/my-simple-test-origin-repo" );
put( "listMode", "ALL" );
}};
final FileSystem fs = provider.newFileSystem( newRepo, env );
assertThat( fs ).isNotNull();
assertThat( fs.getRootDirectories() ).hasSize( 2 );
assertThat( fs.getPath( "file.txt" ).toFile() ).isNotNull().exists();
commit( ( (JGitFileSystem) fs ).gitRepo(), "master", "user1", "user1@example.com", "commitx", null, null, false, new HashMap<String, File>() {{
put( "fileXXXXX.txt", tempFile( "temp" ) );
}} );
final URI newRepo2 = URI.create( "git://my-repo2" );
final Map<String, Object> env2 = new HashMap<String, Object>() {{
put( JGitFileSystemProvider.GIT_ENV_KEY_DEFAULT_REMOTE_NAME, "git://localhost:" + gitDaemonPort + "/my-simple-test-origin-repo" );
put( "listMode", "ALL" );
}};
final FileSystem fs2 = provider.newFileSystem( newRepo2, env2 );
commit( origin.gitRepo(), "user-branch", "user1", "user1@example.com", "commitx", null, null, false, new HashMap<String, File>() {{
put( "file1UserBranch.txt", tempFile( "tempX" ) );
}} );
provider.getFileSystem( URI.create( "git://my-repo2?sync=git://localhost:" + gitDaemonPort + "/my-simple-test-origin-repo&force" ) );
assertThat( fs2.getRootDirectories() ).hasSize( 5 );
final List<String> rootURIs1 = new ArrayList<String>() {{
add( "git://master@my-repo2/" );
add( "git://user-branch@my-repo2/" );
add( "git://origin/master@my-repo2/" );
add( "git://upstream/master@my-repo2/" );
add( "git://upstream/user-branch@my-repo2/" );
}};
final List<String> rootURIs2 = new ArrayList<String>() {{
add( "git://master@my-repo2/" );
add( "git://user-branch@my-repo2/" );
add( "git://user-branch-2@my-repo2/" );
add( "git://origin/master@my-repo2/" );
add( "git://upstream/master@my-repo2/" );
add( "git://upstream/user-branch@my-repo2/" );
add( "git://upstream/user-branch-2@my-repo2/" );
}};
final Set<String> rootURIs = new HashSet<String>();
for ( final Path root : fs2.getRootDirectories() ) {
rootURIs.add( root.toUri().toString() );
}
rootURIs.removeAll( rootURIs1 );
assertThat( rootURIs ).isEmpty();
commit( origin.gitRepo(), "user-branch-2", "user1", "user1@example.com", "commitx", null, null, false, new HashMap<String, File>() {{
put( "file2UserBranch.txt", tempFile( "tempX" ) );
}} );
provider.getFileSystem( URI.create( "git://my-repo2?sync=git://localhost:" + gitDaemonPort + "/my-simple-test-origin-repo&force" ) );
assertThat( fs2.getRootDirectories() ).hasSize( 7 );
for ( final Path root : fs2.getRootDirectories() ) {
rootURIs.add( root.toUri().toString() );
}
rootURIs.removeAll( rootURIs2 );
assertThat( rootURIs ).isEmpty();
}
@Test
public void testNewFileSystemCloneAndRescan() throws IOException {
final URI originRepo = URI.create( "git://my-simple-test-origin-name" );
final JGitFileSystem origin = (JGitFileSystem) provider.newFileSystem( originRepo, new HashMap<String, Object>() {{
put( "listMode", "ALL" );
}} );
commit( origin.gitRepo(), "master", "user1", "user1@example.com", "commitx", null, null, false, new HashMap<String, File>() {{
put( "file.txt", tempFile( "temp" ) );
}} );
final URI newRepo = URI.create( "git://my-repo-name" );
final Map<String, Object> env = new HashMap<String, Object>() {{
put( JGitFileSystemProvider.GIT_ENV_KEY_DEFAULT_REMOTE_NAME, "git://localhost:" + gitDaemonPort + "/my-simple-test-origin-name" );
}};
final FileSystem fs = provider.newFileSystem( newRepo, env );
assertThat( fs ).isNotNull();
assertThat( fs.getRootDirectories() ).hasSize( 1 );
provider.rescanForExistingRepositories();
final FileSystem fs2 = provider.getFileSystem( newRepo );
assertThat( fs2 ).isNotNull();
assertThat( fs2.getRootDirectories() ).hasSize( 1 );
}
@Test
public void testGetFileSystem() {
final URI newRepo = URI.create( "git://new-repo-name" );
final FileSystem fs = provider.newFileSystem( newRepo, EMPTY_ENV );
assertThat( fs ).isNotNull();
assertThat( provider.getFileSystem( newRepo ) ).isEqualTo( fs );
assertThat( provider.getFileSystem( URI.create( "git://master@new-repo-name" ) ) ).isEqualTo( fs );
assertThat( provider.getFileSystem( URI.create( "git://branch@new-repo-name" ) ) ).isEqualTo( fs );
assertThat( provider.getFileSystem( URI.create( "git://branch@new-repo-name?fetch" ) ) ).isEqualTo( fs );
}
@Test
public void testInvalidURIGetFileSystem() {
final URI newRepo = URI.create( "git:///new-repo-name" );
try {
provider.getFileSystem( newRepo );
failBecauseExceptionWasNotThrown( IllegalArgumentException.class );
} catch ( final IllegalArgumentException ex ) {
assertThat( ex.getMessage() ).isEqualTo( "Parameter named 'uri' is invalid, missing host repository!" );
}
}
@Test
public void testGetPath() {
final URI newRepo = URI.create( "git://new-get-repo-name" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final Path path = provider.getPath( URI.create( "git://master@new-get-repo-name/home" ) );
assertThat( path ).isNotNull();
assertThat( path.getRoot().toString() ).isEqualTo( "/" );
assertThat( path.getRoot().toRealPath().toUri().toString() ).isEqualTo( "git://master@new-get-repo-name/" );
assertThat( path.toString() ).isEqualTo( "/home" );
final Path pathRelative = provider.getPath( URI.create( "git://master@new-get-repo-name/:home" ) );
assertThat( pathRelative ).isNotNull();
assertThat( pathRelative.toRealPath().toUri().toString() ).isEqualTo( "git://master@new-get-repo-name/:home" );
assertThat( pathRelative.getRoot().toString() ).isEqualTo( "" );
assertThat( pathRelative.toString() ).isEqualTo( "home" );
}
@Test
public void testInvalidURIGetPath() {
final URI uri = URI.create( "git:///master@new-get-repo-name/home" );
try {
provider.getPath( uri );
failBecauseExceptionWasNotThrown( IllegalArgumentException.class );
} catch ( final IllegalArgumentException ex ) {
assertThat( ex.getMessage() ).isEqualTo( "Parameter named 'uri' is invalid, missing host repository!" );
}
}
@Test
public void testGetComplexPath() {
final URI newRepo = URI.create( "git://new-complex-get-repo-name" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final Path path = provider.getPath( URI.create( "git://origin/master@new-complex-get-repo-name/home" ) );
assertThat( path ).isNotNull();
assertThat( path.getRoot().toString() ).isEqualTo( "/" );
assertThat( path.toString() ).isEqualTo( "/home" );
final Path pathRelative = provider.getPath( URI.create( "git://origin/master@new-complex-get-repo-name/:home" ) );
assertThat( pathRelative ).isNotNull();
assertThat( pathRelative.getRoot().toString() ).isEqualTo( "" );
assertThat( pathRelative.toString() ).isEqualTo( "home" );
}
@Test
public void testInputStream() throws IOException {
final File parentFolder = createTempDirectory();
final File gitFolder = new File( parentFolder, "mytest.git" );
final Git origin = JGitUtil.newRepository( gitFolder, true );
commit( origin, "master", "user", "user@example.com", "commit message", null, null, false, new HashMap<String, File>() {{
put( "myfile.txt", tempFile( "temp\n.origin\n.content" ) );
}} );
final URI newRepo = URI.create( "git://inputstream-test-repo" );
final Map<String, Object> env = new HashMap<String, Object>() {{
put( JGitFileSystemProvider.GIT_ENV_KEY_DEFAULT_REMOTE_NAME, origin.getRepository().getDirectory().toString() );
}};
final FileSystem fs = provider.newFileSystem( newRepo, env );
assertThat( fs ).isNotNull();
final Path path = provider.getPath( URI.create( "git://origin/master@inputstream-test-repo/myfile.txt" ) );
final InputStream inputStream = provider.newInputStream( path );
assertThat( inputStream ).isNotNull();
final String content = new Scanner( inputStream ).useDelimiter( "\\A" ).next();
inputStream.close();
assertThat( content ).isNotNull().isEqualTo( "temp\n.origin\n.content" );
}
@Test
public void testInputStream2() throws IOException {
final File parentFolder = createTempDirectory();
final File gitFolder = new File( parentFolder, "mytest.git" );
final Git origin = JGitUtil.newRepository( gitFolder, true );
commit( origin, "master", "user", "user@example.com", "commit message", null, null, false, new HashMap<String, File>() {{
put( "path/to/file/myfile.txt", tempFile( "temp\n.origin\n.content" ) );
}} );
final URI newRepo = URI.create( "git://xinputstream-test-repo" );
final Map<String, Object> env = new HashMap<String, Object>() {{
put( JGitFileSystemProvider.GIT_ENV_KEY_DEFAULT_REMOTE_NAME, origin.getRepository().getDirectory().toString() );
}};
final FileSystem fs = provider.newFileSystem( newRepo, env );
assertThat( fs ).isNotNull();
final Path path = provider.getPath( URI.create( "git://origin/master@xinputstream-test-repo/path/to/file/myfile.txt" ) );
final InputStream inputStream = provider.newInputStream( path );
assertThat( inputStream ).isNotNull();
final String content = new Scanner( inputStream ).useDelimiter( "\\A" ).next();
inputStream.close();
assertThat( content ).isNotNull().isEqualTo( "temp\n.origin\n.content" );
}
@Test(expected = NoSuchFileException.class)
public void testInputStream3() throws IOException {
final File parentFolder = createTempDirectory();
final File gitFolder = new File( parentFolder, "mytest.git" );
final Git origin = JGitUtil.newRepository( gitFolder, true );
commit( origin, "master", "user", "user@example.com", "commit message", null, null, false, new HashMap<String, File>() {{
put( "path/to/file/myfile.txt", tempFile( "temp\n.origin\n.content" ) );
}} );
final URI newRepo = URI.create( "git://xxinputstream-test-repo" );
final Map<String, Object> env = new HashMap<String, Object>() {{
put( JGitFileSystemProvider.GIT_ENV_KEY_DEFAULT_REMOTE_NAME, origin.getRepository().getDirectory().toString() );
}};
final FileSystem fs = provider.newFileSystem( newRepo, env );
assertThat( fs ).isNotNull();
final Path path = provider.getPath( URI.create( "git://origin/master@xxinputstream-test-repo/path/to" ) );
provider.newInputStream( path );
}
@Test(expected = NoSuchFileException.class)
public void testInputStreamNoSuchFile() throws IOException {
final File parentFolder = createTempDirectory();
final File gitFolder = new File( parentFolder, "mytest.git" );
final Git origin = JGitUtil.newRepository( gitFolder, true );
commit( origin, "master", "user1", "user1@example.com", "commitx", null, null, false, new HashMap<String, File>() {{
put( "file.txt", tempFile( "temp.origin.content.2" ) );
}} );
final URI newRepo = URI.create( "git://inputstream-not-exists-test-repo" );
final Map<String, Object> env = new HashMap<String, Object>() {{
put( JGitFileSystemProvider.GIT_ENV_KEY_DEFAULT_REMOTE_NAME, origin.getRepository().getDirectory().toString() );
}};
final FileSystem fs = provider.newFileSystem( newRepo, env );
assertThat( fs ).isNotNull();
final Path path = provider.getPath( URI.create( "git://origin/master@inputstream-not-exists-test-repo/temp.txt" ) );
provider.newInputStream( path );
}
@Test
public void testNewOutputStream() throws Exception {
final File parentFolder = createTempDirectory();
final File gitFolder = new File( parentFolder, "mytest.git" );
final Git origin = JGitUtil.newRepository( gitFolder, true );
commit( origin, "master", "user", "user@example.com", "commit message", null, null, false, new HashMap<String, File>() {{
put( "myfile.txt", tempFile( "temp\n.origin\n.content" ) );
}} );
commit( origin, "user_branch", "user", "user@example.com", "commit message", null, null, false, new HashMap<String, File>() {{
put( "path/to/some/file/myfile.txt", tempFile( "some\n.content\nhere" ) );
}} );
final URI newRepo = URI.create( "git://outstream-test-repo" );
final Map<String, Object> env = new HashMap<String, Object>() {{
put( JGitFileSystemProvider.GIT_ENV_KEY_DEFAULT_REMOTE_NAME, origin.getRepository().getDirectory().toString() );
}};
final FileSystem fs = provider.newFileSystem( newRepo, env );
assertThat( fs ).isNotNull();
final Path path = provider.getPath( URI.create( "git://user_branch@outstream-test-repo/some/path/myfile.txt" ) );
final OutputStream outStream = provider.newOutputStream( path );
assertThat( outStream ).isNotNull();
outStream.write( "my cool content".getBytes() );
outStream.close();
final InputStream inStream = provider.newInputStream( path );
final String content = new Scanner( inStream ).useDelimiter( "\\A" ).next();
inStream.close();
assertThat( content ).isNotNull().isEqualTo( "my cool content" );
try {
provider.newOutputStream( provider.getPath( URI.create( "git://user_branch@outstream-test-repo/some/path/" ) ) );
failBecauseExceptionWasNotThrown( org.uberfire.java.nio.IOException.class );
} catch ( Exception ignored ) {
}
}
@Test
public void testNewOutputStreamWithJGitOp() throws Exception {
final File parentFolder = createTempDirectory();
final File gitFolder = new File( parentFolder, "mytest.git" );
final Git origin = JGitUtil.newRepository( gitFolder, true );
commit( origin, "master", "user", "user@example.com", "commit message", null, null, false, new HashMap<String, File>() {{
put( "myfile.txt", tempFile( "temp\n.origin\n.content" ) );
}} );
commit( origin, "user_branch", "user", "user@example.com", "commit message", null, null, false, new HashMap<String, File>() {{
put( "path/to/some/file/myfile.txt", tempFile( "some\n.content\nhere" ) );
}} );
final URI newRepo = URI.create( "git://outstreamwithop-test-repo" );
final Map<String, Object> env = new HashMap<String, Object>() {{
put( JGitFileSystemProvider.GIT_ENV_KEY_DEFAULT_REMOTE_NAME, origin.getRepository().getDirectory().toString() );
}};
final FileSystem fs = provider.newFileSystem( newRepo, env );
assertThat( fs ).isNotNull();
final SimpleDateFormat formatter = new SimpleDateFormat( "dd/MM/yyyy" );
final CommentedOption op = new CommentedOption( "User Tester", "user.tester@example.com", "omg, is it the end?", formatter.parse( "31/12/2012" ) );
final Path path = provider.getPath( URI.create( "git://user_branch@outstreamwithop-test-repo/some/path/myfile.txt" ) );
final OutputStream outStream = provider.newOutputStream( path, op );
assertThat( outStream ).isNotNull();
outStream.write( "my cool content".getBytes() );
outStream.close();
final InputStream inStream = provider.newInputStream( path );
final String content = new Scanner( inStream ).useDelimiter( "\\A" ).next();
inStream.close();
assertThat( content ).isNotNull().isEqualTo( "my cool content" );
}
@Test(expected = FileSystemNotFoundException.class)
public void testGetPathFileSystemNotExisting() {
provider.getPath( URI.create( "git://master@not-exists-get-repo-name/home" ) );
}
@Test(expected = FileSystemNotFoundException.class)
public void testGetFileSystemNotExisting() {
final URI newRepo = URI.create( "git://not-new-repo-name" );
provider.getFileSystem( newRepo );
}
@Test
public void testDelete() throws IOException {
final URI newRepo = URI.create( "git://delete1-test-repo" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final Path path = provider.getPath( URI.create( "git://user_branch@delete1-test-repo/path/to/myfile.txt" ) );
final OutputStream outStream = provider.newOutputStream( path );
assertThat( outStream ).isNotNull();
outStream.write( "my cool content".getBytes() );
outStream.close();
provider.newInputStream( path ).close();
try {
provider.delete( provider.getPath( URI.create( "git://user_branch@delete1-test-repo/non_existent_path" ) ) );
failBecauseExceptionWasNotThrown( NoSuchFileException.class );
} catch ( NoSuchFileException ignored ) {
}
try {
provider.delete( provider.getPath( URI.create( "git://user_branch@delete1-test-repo/path/to/" ) ) );
failBecauseExceptionWasNotThrown( DirectoryNotEmptyException.class );
} catch ( DirectoryNotEmptyException ignored ) {
}
provider.delete( path );
try {
provider.newFileSystem( newRepo, EMPTY_ENV );
failBecauseExceptionWasNotThrown( FileSystemAlreadyExistsException.class );
} catch ( FileSystemAlreadyExistsException ignored ) {
}
final Path fsPath = path.getFileSystem().getPath( null );
provider.delete( fsPath );
assertThat( fsPath.getFileSystem().isOpen() ).isEqualTo( false );
final URI newRepo2 = URI.create( "git://delete1-test-repo" );
provider.newFileSystem( newRepo2, EMPTY_ENV );
}
@Test
public void testDeleteBranch() throws IOException {
final URI newRepo = URI.create( "git://delete-branch-test-repo" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final Path path = provider.getPath( URI.create( "git://user_branch@delete-branch-test-repo/path/to/myfile.txt" ) );
final OutputStream outStream = provider.newOutputStream( path );
assertThat( outStream ).isNotNull();
outStream.write( "my cool content".getBytes() );
outStream.close();
provider.newInputStream( path ).close();
provider.delete( provider.getPath( URI.create( "git://user_branch@delete-branch-test-repo" ) ) );
try {
provider.delete( provider.getPath( URI.create( "git://user_branch@delete-branch-test-repo" ) ) );
failBecauseExceptionWasNotThrown( NoSuchFileException.class );
} catch ( NoSuchFileException ignored ) {
}
try {
provider.delete( provider.getPath( URI.create( "git://some_user_branch@delete-branch-test-repo" ) ) );
failBecauseExceptionWasNotThrown( NoSuchFileException.class );
} catch ( NoSuchFileException ignored ) {
}
}
@Test
public void testDeleteIfExists() throws IOException {
final URI newRepo = URI.create( "git://deleteifexists1-test-repo" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final Path path = provider.getPath( URI.create( "git://user_branch@deleteifexists1-test-repo/path/to/myfile.txt" ) );
final OutputStream outStream = provider.newOutputStream( path );
assertThat( outStream ).isNotNull();
outStream.write( "my cool content".getBytes() );
outStream.close();
provider.newInputStream( path ).close();
assertThat( provider.deleteIfExists( provider.getPath( URI.create( "git://user_branch@deleteifexists1-test-repo/non_existent_path" ) ) ) ).isFalse();
try {
provider.deleteIfExists( provider.getPath( URI.create( "git://user_branch@deleteifexists1-test-repo/path/to/" ) ) );
failBecauseExceptionWasNotThrown( DirectoryNotEmptyException.class );
} catch ( DirectoryNotEmptyException ignored ) {
}
assertThat( provider.deleteIfExists( path ) ).isTrue();
}
@Test
public void testDeleteBranchIfExists() throws IOException {
final URI newRepo = URI.create( "git://deletebranchifexists1-test-repo" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final Path path = provider.getPath( URI.create( "git://user_branch@deletebranchifexists1-test-repo/path/to/myfile.txt" ) );
final OutputStream outStream = provider.newOutputStream( path );
assertThat( outStream ).isNotNull();
outStream.write( "my cool content".getBytes() );
outStream.close();
provider.newInputStream( path ).close();
assertThat( provider.deleteIfExists( provider.getPath( URI.create( "git://user_branch@deletebranchifexists1-test-repo" ) ) ) ).isTrue();
assertThat( provider.deleteIfExists( provider.getPath( URI.create( "git://not_user_branch@deletebranchifexists1-test-repo" ) ) ) ).isFalse();
assertThat( provider.deleteIfExists( provider.getPath( URI.create( "git://user_branch@deletebranchifexists1-test-repo" ) ) ) ).isFalse();
}
@Test
public void testIsHidden() throws IOException {
final URI newRepo = URI.create( "git://ishidden-test-repo" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final Path path = provider.getPath( URI.create( "git://user_branch@ishidden-test-repo/path/to/.myfile.txt" ) );
final OutputStream outStream = provider.newOutputStream( path );
assertThat( outStream ).isNotNull();
outStream.write( "my cool content".getBytes() );
outStream.close();
final Path path2 = provider.getPath( URI.create( "git://user_branch@ishidden-test-repo/path/to/myfile.txt" ) );
final OutputStream outStream2 = provider.newOutputStream( path2 );
assertThat( outStream2 ).isNotNull();
outStream2.write( "my cool content".getBytes() );
outStream2.close();
assertThat( provider.isHidden( provider.getPath( URI.create( "git://user_branch@ishidden-test-repo/path/to/.myfile.txt" ) ) ) ).isTrue();
assertThat( provider.isHidden( provider.getPath( URI.create( "git://user_branch@ishidden-test-repo/path/to/myfile.txt" ) ) ) ).isFalse();
assertThat( provider.isHidden( provider.getPath( URI.create( "git://user_branch@ishidden-test-repo/path/to/non_existent/.myfile.txt" ) ) ) ).isTrue();
assertThat( provider.isHidden( provider.getPath( URI.create( "git://user_branch@ishidden-test-repo/path/to/non_existent/myfile.txt" ) ) ) ).isFalse();
assertThat( provider.isHidden( provider.getPath( URI.create( "git://user_branch@ishidden-test-repo/" ) ) ) ).isFalse();
assertThat( provider.isHidden( provider.getPath( URI.create( "git://user_branch@ishidden-test-repo/some" ) ) ) ).isFalse();
}
@Test
public void testIsSameFile() throws IOException {
final URI newRepo = URI.create( "git://issamefile-test-repo" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final Path path = provider.getPath( URI.create( "git://master@issamefile-test-repo/path/to/myfile1.txt" ) );
final OutputStream outStream = provider.newOutputStream( path );
outStream.write( "my cool content".getBytes() );
outStream.close();
final Path path2 = provider.getPath( URI.create( "git://user_branch@issamefile-test-repo/path/to/myfile2.txt" ) );
final OutputStream outStream2 = provider.newOutputStream( path2 );
outStream2.write( "my cool content".getBytes() );
outStream2.close();
final Path path3 = provider.getPath( URI.create( "git://user_branch@issamefile-test-repo/path/to/myfile3.txt" ) );
final OutputStream outStream3 = provider.newOutputStream( path3 );
outStream3.write( "my cool content".getBytes() );
outStream3.close();
assertThat( provider.isSameFile( path, path2 ) ).isTrue();
assertThat( provider.isSameFile( path, path3 ) ).isTrue();
}
@Test
public void testCreateDirectory() throws Exception {
final URI newRepo = URI.create( "git://xcreatedir-test-repo" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final JGitPathImpl path = (JGitPathImpl) provider.getPath( URI.create( "git://master@xcreatedir-test-repo/some/path/to/" ) );
final Pair<PathType, ObjectId> result = JGitUtil.checkPath( path.getFileSystem().gitRepo(), path.getRefTree(), path.getPath() );
assertThat( result.getK1() ).isEqualTo( PathType.NOT_FOUND );
provider.createDirectory( path );
final Pair<PathType, ObjectId> resultAfter = JGitUtil.checkPath( path.getFileSystem().gitRepo(), path.getRefTree(), path.getPath() );
assertThat( resultAfter.getK1() ).isEqualTo( PathType.DIRECTORY );
try {
provider.createDirectory( path );
failBecauseExceptionWasNotThrown( FileAlreadyExistsException.class );
} catch ( FileAlreadyExistsException ignored ) {
}
}
@Test
public void testCheckAccess() throws Exception {
final URI newRepo = URI.create( "git://checkaccess-test-repo" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final Path path = provider.getPath( URI.create( "git://master@checkaccess-test-repo/path/to/myfile1.txt" ) );
final OutputStream outStream = provider.newOutputStream( path );
outStream.write( "my cool content".getBytes() );
outStream.close();
provider.checkAccess( path );
final Path path_to_dir = provider.getPath( URI.create( "git://master@checkaccess-test-repo/path/to" ) );
provider.checkAccess( path_to_dir );
final Path path_not_exists = provider.getPath( URI.create( "git://master@checkaccess-test-repo/path/to/some.txt" ) );
try {
provider.checkAccess( path_not_exists );
failBecauseExceptionWasNotThrown( NoSuchFileException.class );
} catch ( NoSuchFileException ignored ) {
}
}
@Test
public void testGetFileStore() throws Exception {
final URI newRepo = URI.create( "git://filestore-test-repo" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final Path path = provider.getPath( URI.create( "git://master@filestore-test-repo/path/to/myfile1.txt" ) );
final OutputStream outStream = provider.newOutputStream( path );
outStream.write( "my cool content".getBytes() );
outStream.close();
final FileStore fileStore = provider.getFileStore( path );
assertThat( fileStore ).isNotNull();
assertThat( fileStore.getAttribute( "readOnly" ) ).isEqualTo( Boolean.FALSE );
}
@Test
public void testNewDirectoryStream() throws IOException {
final URI newRepo = URI.create( "git://dirstream-test-repo" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final Path path = provider.getPath( URI.create( "git://master@dirstream-test-repo/myfile1.txt" ) );
final OutputStream outStream = provider.newOutputStream( path );
outStream.write( "my cool content".getBytes() );
outStream.close();
final Path path2 = provider.getPath( URI.create( "git://user_branch@dirstream-test-repo/other/path/myfile2.txt" ) );
final OutputStream outStream2 = provider.newOutputStream( path2 );
outStream2.write( "my cool content".getBytes() );
outStream2.close();
final Path path3 = provider.getPath( URI.create( "git://user_branch@dirstream-test-repo/myfile3.txt" ) );
final OutputStream outStream3 = provider.newOutputStream( path3 );
outStream3.write( "my cool content".getBytes() );
outStream3.close();
final DirectoryStream<Path> stream1 = provider.newDirectoryStream( provider.getPath( URI.create( "git://user_branch@dirstream-test-repo/" ) ), null );
assertThat( stream1 ).isNotNull().hasSize( 2 ).contains( path3, provider.getPath( URI.create( "git://user_branch@dirstream-test-repo/other" ) ) );
final DirectoryStream<Path> stream2 = provider.newDirectoryStream( provider.getPath( URI.create( "git://user_branch@dirstream-test-repo/other" ) ), null );
assertThat( stream2 ).isNotNull().hasSize( 1 ).contains( provider.getPath( URI.create( "git://user_branch@dirstream-test-repo/other/path" ) ) );
final DirectoryStream<Path> stream3 = provider.newDirectoryStream( provider.getPath( URI.create( "git://user_branch@dirstream-test-repo/other/path" ) ), null );
assertThat( stream3 ).isNotNull().hasSize( 1 ).contains( path2 );
final DirectoryStream<Path> stream4 = provider.newDirectoryStream( provider.getPath( URI.create( "git://master@dirstream-test-repo/" ) ), null );
assertThat( stream4 ).isNotNull().hasSize( 1 ).contains( path );
try {
provider.newDirectoryStream( path, null );
failBecauseExceptionWasNotThrown( NotDirectoryException.class );
} catch ( NotDirectoryException ignored ) {
}
final Path crazyPath = provider.getPath( URI.create( "git://master@dirstream-test-repo/crazy/path/here" ) );
try {
provider.newDirectoryStream( crazyPath, null );
failBecauseExceptionWasNotThrown( NotDirectoryException.class );
} catch ( NotDirectoryException ignored ) {
}
provider.createDirectory( crazyPath );
assertThat( provider.newDirectoryStream( crazyPath, null ) ).isNotNull().hasSize( 1 );
}
@Test
public void testDeleteNonEmptyDirectory() throws IOException {
final URI newRepo = URI.create( "git://delete-non-empty-test-repo" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final Path dir = provider.getPath( URI.create( "git://master@delete-non-empty-test-repo/other/path" ) );
final Path _root = provider.getPath( URI.create( "git://master@delete-non-empty-test-repo/myfile1.txt" ) );
final OutputStream outRootStream = provider.newOutputStream( _root );
outRootStream.write( "my cool content".getBytes() );
outRootStream.close();
final Path path = provider.getPath( URI.create( "git://master@delete-non-empty-test-repo/other/path/myfile1.txt" ) );
final OutputStream outStream = provider.newOutputStream( path );
outStream.write( "my cool content".getBytes() );
outStream.close();
final Path path2 = provider.getPath( URI.create( "git://master@delete-non-empty-test-repo/other/path/myfile2.txt" ) );
final OutputStream outStream2 = provider.newOutputStream( path2 );
outStream2.write( "my cool content".getBytes() );
outStream2.close();
final Path path3 = provider.getPath( URI.create( "git://master@delete-non-empty-test-repo/other/path/myfile3.txt" ) );
final OutputStream outStream3 = provider.newOutputStream( path3 );
outStream3.write( "my cool content".getBytes() );
outStream3.close();
final Path dir1 = provider.getPath( URI.create( "git://master@delete-non-empty-test-repo/other/path/dir" ) );
provider.createDirectory( dir1 );
final DirectoryStream<Path> stream3 = provider.newDirectoryStream( dir, null );
assertThat( stream3 ).isNotNull().hasSize( 4 );
try {
provider.delete( dir );
fail( "dir not empty" );
} catch ( final DirectoryNotEmptyException ignore ) {
}
try {
final CommentedOption op = new CommentedOption( "User Tester", "user.tester@example.com", "omg, erase dir!" );
provider.delete( dir, NON_EMPTY_DIRECTORIES, op );
} catch ( final DirectoryNotEmptyException ignore ) {
fail( "dir should be deleted!" );
}
assertThat( provider.exists( dir ) ).isEqualTo( false );
}
@Test
public void testFilteredNewDirectoryStream() throws IOException {
final URI newRepo = URI.create( "git://filter-dirstream-test-repo" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final Path path = provider.getPath( URI.create( "git://master@filter-dirstream-test-repo/myfile1.txt" ) );
final OutputStream outStream = provider.newOutputStream( path );
outStream.write( "my cool content".getBytes() );
outStream.close();
final Path path2 = provider.getPath( URI.create( "git://user_branch@filter-dirstream-test-repo/other/path/myfile2.txt" ) );
final OutputStream outStream2 = provider.newOutputStream( path2 );
outStream2.write( "my cool content".getBytes() );
outStream2.close();
final Path path3 = provider.getPath( URI.create( "git://user_branch@filter-dirstream-test-repo/myfile3.txt" ) );
final OutputStream outStream3 = provider.newOutputStream( path3 );
outStream3.write( "my cool content".getBytes() );
outStream3.close();
final Path path4 = provider.getPath( URI.create( "git://user_branch@filter-dirstream-test-repo/myfile4.xxx" ) );
final OutputStream outStream4 = provider.newOutputStream( path4 );
outStream4.write( "my cool content".getBytes() );
outStream4.close();
final DirectoryStream<Path> stream1 = provider.newDirectoryStream( provider.getPath( URI.create( "git://user_branch@filter-dirstream-test-repo/" ) ), new DirectoryStream.Filter<Path>() {
@Override
public boolean accept( final Path entry ) throws org.uberfire.java.nio.IOException {
return entry.toString().endsWith( ".xxx" );
}
} );
assertThat( stream1 ).isNotNull().hasSize( 1 ).contains( path4 );
final DirectoryStream<Path> stream2 = provider.newDirectoryStream( provider.getPath( URI.create( "git://master@filter-dirstream-test-repo/" ) ), new DirectoryStream.Filter<Path>() {
@Override
public boolean accept( final Path entry ) throws org.uberfire.java.nio.IOException {
return false;
}
} );
assertThat( stream2 ).isNotNull().hasSize( 0 );
}
@Test
public void testGetFileAttributeView() throws IOException {
final URI newRepo = URI.create( "git://getfileattriview-test-repo" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final Path path = provider.getPath( URI.create( "git://master@getfileattriview-test-repo/myfile1.txt" ) );
final OutputStream outStream = provider.newOutputStream( path );
outStream.write( "my cool content".getBytes() );
outStream.close();
final Path path2 = provider.getPath( URI.create( "git://user_branch@getfileattriview-test-repo/other/path/myfile2.txt" ) );
final OutputStream outStream2 = provider.newOutputStream( path2 );
outStream2.write( "my cool content".getBytes() );
outStream2.close();
final Path path3 = provider.getPath( URI.create( "git://user_branch@getfileattriview-test-repo/myfile3.txt" ) );
final OutputStream outStream3 = provider.newOutputStream( path3 );
outStream3.write( "my cool content".getBytes() );
outStream3.close();
final JGitVersionAttributeView attrs = provider.getFileAttributeView( path3, JGitVersionAttributeView.class );
assertThat( attrs.readAttributes().history().records().size() ).isEqualTo( 1 );
assertThat( attrs.readAttributes().history().records().get( 0 ).uri() ).isNotNull();
assertThat( attrs.readAttributes().isDirectory() ).isFalse();
assertThat( attrs.readAttributes().isRegularFile() ).isTrue();
assertThat( attrs.readAttributes().creationTime() ).isNotNull();
assertThat( attrs.readAttributes().lastModifiedTime() ).isNotNull();
assertThat( attrs.readAttributes().size() ).isEqualTo( 15L );
try {
provider.getFileAttributeView( provider.getPath( URI.create( "git://user_branch@getfileattriview-test-repo/not_exists.txt" ) ), BasicFileAttributeView.class );
failBecauseExceptionWasNotThrown( NoSuchFileException.class );
} catch ( Exception ignored ) {
}
assertThat( provider.getFileAttributeView( path3, MyInvalidFileAttributeView.class ) ).isNull();
final Path rootPath = provider.getPath( URI.create( "git://user_branch@getfileattriview-test-repo/" ) );
final BasicFileAttributeView attrsRoot = provider.getFileAttributeView( rootPath, BasicFileAttributeView.class );
assertThat( attrsRoot.readAttributes().isDirectory() ).isTrue();
assertThat( attrsRoot.readAttributes().isRegularFile() ).isFalse();
assertThat( attrsRoot.readAttributes().creationTime() ).isNotNull();
assertThat( attrsRoot.readAttributes().lastModifiedTime() ).isNotNull();
assertThat( attrsRoot.readAttributes().size() ).isEqualTo( -1L );
}
@Test
public void testReadAttributes() throws IOException {
final URI newRepo = URI.create( "git://readattrs-test-repo" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final Path path = provider.getPath( URI.create( "git://master@readattrs-test-repo/myfile1.txt" ) );
final OutputStream outStream = provider.newOutputStream( path );
outStream.write( "my cool content".getBytes() );
outStream.close();
final Path path2 = provider.getPath( URI.create( "git://user_branch@readattrs-test-repo/other/path/myfile2.txt" ) );
final OutputStream outStream2 = provider.newOutputStream( path2 );
outStream2.write( "my cool content".getBytes() );
outStream2.close();
final Path path3 = provider.getPath( URI.create( "git://user_branch@readattrs-test-repo/myfile3.txt" ) );
final OutputStream outStream3 = provider.newOutputStream( path3 );
outStream3.write( "my cool content".getBytes() );
outStream3.close();
final BasicFileAttributes attrs = provider.readAttributes( path3, BasicFileAttributes.class );
assertThat( attrs.isDirectory() ).isFalse();
assertThat( attrs.isRegularFile() ).isTrue();
assertThat( attrs.creationTime() ).isNotNull();
assertThat( attrs.lastModifiedTime() ).isNotNull();
assertThat( attrs.size() ).isEqualTo( 15L );
try {
provider.readAttributes( provider.getPath( URI.create( "git://user_branch@readattrs-test-repo/not_exists.txt" ) ), BasicFileAttributes.class );
failBecauseExceptionWasNotThrown( NoSuchFileException.class );
} catch ( NoSuchFileException ignored ) {
}
assertThat( provider.readAttributes( path3, MyAttrs.class ) ).isNull();
final Path rootPath = provider.getPath( URI.create( "git://user_branch@readattrs-test-repo/" ) );
final BasicFileAttributes attrsRoot = provider.readAttributes( rootPath, BasicFileAttributes.class );
assertThat( attrsRoot.isDirectory() ).isTrue();
assertThat( attrsRoot.isRegularFile() ).isFalse();
assertThat( attrsRoot.creationTime() ).isNotNull();
assertThat( attrsRoot.lastModifiedTime() ).isNotNull();
assertThat( attrsRoot.size() ).isEqualTo( -1L );
}
@Test
public void testReadAttributesMap() throws IOException {
final URI newRepo = URI.create( "git://readattrsmap-test-repo" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final Path path = provider.getPath( URI.create( "git://master@readattrsmap-test-repo/myfile1.txt" ) );
final OutputStream outStream = provider.newOutputStream( path );
outStream.write( "my cool content".getBytes() );
outStream.close();
final Path path2 = provider.getPath( URI.create( "git://user_branch@readattrsmap-test-repo/other/path/myfile2.txt" ) );
final OutputStream outStream2 = provider.newOutputStream( path2 );
outStream2.write( "my cool content".getBytes() );
outStream2.close();
final Path path3 = provider.getPath( URI.create( "git://user_branch@readattrsmap-test-repo/myfile3.txt" ) );
final OutputStream outStream3 = provider.newOutputStream( path3 );
outStream3.write( "my cool content".getBytes() );
outStream3.close();
assertThat( provider.readAttributes( path, "*" ) ).isNotNull().hasSize( 9 );
assertThat( provider.readAttributes( path, "basic:*" ) ).isNotNull().hasSize( 9 );
assertThat( provider.readAttributes( path, "basic:isRegularFile" ) ).isNotNull().hasSize( 1 );
assertThat( provider.readAttributes( path, "basic:isRegularFile,isDirectory" ) ).isNotNull().hasSize( 2 );
assertThat( provider.readAttributes( path, "basic:isRegularFile,isDirectory,someThing" ) ).isNotNull().hasSize( 2 );
assertThat( provider.readAttributes( path, "basic:someThing" ) ).isNotNull().hasSize( 0 );
assertThat( provider.readAttributes( path, "version:version" ) ).isNotNull().hasSize( 1 );
assertThat( provider.readAttributes( path, "isRegularFile" ) ).isNotNull().hasSize( 1 );
assertThat( provider.readAttributes( path, "isRegularFile,isDirectory" ) ).isNotNull().hasSize( 2 );
assertThat( provider.readAttributes( path, "isRegularFile,isDirectory,someThing" ) ).isNotNull().hasSize( 2 );
assertThat( provider.readAttributes( path, "someThing" ) ).isNotNull().hasSize( 0 );
try {
provider.readAttributes( path, ":someThing" );
failBecauseExceptionWasNotThrown( IllegalArgumentException.class );
} catch ( IllegalArgumentException ignored ) {
}
try {
provider.readAttributes( path, "advanced:isRegularFile" );
failBecauseExceptionWasNotThrown( UnsupportedOperationException.class );
} catch ( UnsupportedOperationException ignored ) {
}
final Path rootPath = provider.getPath( URI.create( "git://user_branch@readattrsmap-test-repo/" ) );
assertThat( provider.readAttributes( rootPath, "*" ) ).isNotNull().hasSize( 9 );
assertThat( provider.readAttributes( rootPath, "basic:*" ) ).isNotNull().hasSize( 9 );
assertThat( provider.readAttributes( rootPath, "basic:isRegularFile" ) ).isNotNull().hasSize( 1 );
assertThat( provider.readAttributes( rootPath, "basic:isRegularFile,isDirectory" ) ).isNotNull().hasSize( 2 );
assertThat( provider.readAttributes( rootPath, "basic:isRegularFile,isDirectory,someThing" ) ).isNotNull().hasSize( 2 );
assertThat( provider.readAttributes( rootPath, "basic:someThing" ) ).isNotNull().hasSize( 0 );
assertThat( provider.readAttributes( rootPath, "isRegularFile" ) ).isNotNull().hasSize( 1 );
assertThat( provider.readAttributes( rootPath, "isRegularFile,isDirectory" ) ).isNotNull().hasSize( 2 );
assertThat( provider.readAttributes( rootPath, "isRegularFile,isDirectory,someThing" ) ).isNotNull().hasSize( 2 );
assertThat( provider.readAttributes( rootPath, "someThing" ) ).isNotNull().hasSize( 0 );
try {
provider.readAttributes( rootPath, ":someThing" );
failBecauseExceptionWasNotThrown( IllegalArgumentException.class );
} catch ( IllegalArgumentException ignored ) {
}
try {
provider.readAttributes( rootPath, "advanced:isRegularFile" );
failBecauseExceptionWasNotThrown( UnsupportedOperationException.class );
} catch ( UnsupportedOperationException ignored ) {
}
try {
provider.readAttributes( provider.getPath( URI.create( "git://user_branch@readattrsmap-test-repo/not_exists.txt" ) ), BasicFileAttributes.class );
failBecauseExceptionWasNotThrown( NoSuchFileException.class );
} catch ( NoSuchFileException ignored ) {
}
}
@Test
public void testSetAttribute() throws IOException {
final URI newRepo = URI.create( "git://setattr-test-repo" );
provider.newFileSystem( newRepo, EMPTY_ENV );
final Path path = provider.getPath( URI.create( "git://master@setattr-test-repo/myfile1.txt" ) );
final OutputStream outStream = provider.newOutputStream( path );
outStream.write( "my cool content".getBytes() );
outStream.close();
final Path path2 = provider.getPath( URI.create( "git://user_branch@setattr-test-repo/other/path/myfile2.txt" ) );
final OutputStream outStream2 = provider.newOutputStream( path2 );
outStream2.write( "my cool content".getBytes() );
outStream2.close();
final Path path3 = provider.getPath( URI.create( "git://user_branch@setattr-test-repo/myfile3.txt" ) );
final OutputStream outStream3 = provider.newOutputStream( path3 );
outStream3.write( "my cool content".getBytes() );
outStream3.close();
try {
provider.setAttribute( path3, "basic:isRegularFile", true );
failBecauseExceptionWasNotThrown( NotImplementedException.class );
} catch ( NotImplementedException ignored ) {
}
try {
provider.setAttribute( path3, "isRegularFile", true );
failBecauseExceptionWasNotThrown( NotImplementedException.class );
} catch ( NotImplementedException ignored ) {
}
try {
provider.setAttribute( path3, "notExisits", true );
failBecauseExceptionWasNotThrown( IllegalStateException.class );
} catch ( IllegalStateException ignored ) {
}
try {
provider.setAttribute( path3, "advanced:notExisits", true );
failBecauseExceptionWasNotThrown( UnsupportedOperationException.class );
} catch ( UnsupportedOperationException ignored ) {
}
try {
provider.setAttribute( path3, ":isRegularFile", true );
failBecauseExceptionWasNotThrown( IllegalArgumentException.class );
} catch ( IllegalArgumentException ignored ) {
}
}
private static class MyInvalidFileAttributeView implements BasicFileAttributeView {
@Override
public BasicFileAttributes readAttributes() throws org.uberfire.java.nio.IOException {
return null;
}
@Override
public void setTimes( FileTime lastModifiedTime,
FileTime lastAccessTime,
FileTime createTime ) throws org.uberfire.java.nio.IOException {
}
@Override
public String name() {
return null;
}
}
@Test
public void checkProperAmend() throws Exception {
final URI newRepo = URI.create( "git://outstream-test-repo" );
final FileSystem fs = provider.newFileSystem( newRepo, new HashMap<String, Object>() {{
put( JGitFileSystemProvider.GIT_ENV_KEY_INIT, "true" );
}} );
assertThat( fs ).isNotNull();
for ( int z = 0; z < 5; z++ ) {
final Path _path = provider.getPath( URI.create( "git://user_branch@outstream-test-repo/some/path/myfile.txt" ) );
provider.setAttribute( _path, FileSystemState.FILE_SYSTEM_STATE_ATTR, FileSystemState.BATCH );
{
final Path path = provider.getPath( URI.create( "git://user_branch@outstream-test-repo/some/path/myfile.txt" ) );
final OutputStream outStream = provider.newOutputStream( path );
assertThat( outStream ).isNotNull();
outStream.write( ( "my cool content" + z ).getBytes() );
outStream.close();
}
{
final Path path2 = provider.getPath( URI.create( "git://error_branch@outstream-test-repo/some/path/myfile.txt" ) );
final OutputStream outStream2 = provider.newOutputStream( path2 );
assertThat( outStream2 ).isNotNull();
outStream2.write( ( "bad content" + z ).getBytes() );
outStream2.close();
}
provider.setAttribute( _path, FileSystemState.FILE_SYSTEM_STATE_ATTR, FileSystemState.NORMAL );
}
final Path path = provider.getPath( URI.create( "git://error_branch@outstream-test-repo/some/path/myfile.txt" ) );
final JGitVersionAttributeView attrs = provider.getFileAttributeView( path.getRoot(), JGitVersionAttributeView.class );
assertThat( attrs.readAttributes().history().records().size() ).isEqualTo( 5 );
}
@Test
public void checkBatchError() throws Exception {
final URI newRepo = URI.create( "git://outstream-test-repo" );
final FileSystem fs = provider.newFileSystem( newRepo, new HashMap<String, Object>() {{
put( JGitFileSystemProvider.GIT_ENV_KEY_INIT, "true" );
}} );
provider = spy( provider );
doThrow( new RuntimeException() ).
when( provider ).
notifyDiffs( any( JGitFileSystem.class ),
any( String.class ),
any( String.class ),
any( String.class ),
any( String.class ),
any( ObjectId.class ),
any( ObjectId.class ) );
assertThat( fs ).isNotNull();
final Path path = provider.getPath( URI.create( "git://user_branch@outstream-test-repo/some/path/myfile.txt" ) );
provider.setAttribute( path, FileSystemState.FILE_SYSTEM_STATE_ATTR, FileSystemState.BATCH );
final OutputStream outStream = provider.newOutputStream( path );
assertThat( outStream ).isNotNull();
outStream.write( ( "my cool content" ).getBytes() );
outStream.close();
try {
provider.setAttribute( path, FileSystemState.FILE_SYSTEM_STATE_ATTR, FileSystemState.NORMAL );
} catch ( Exception ex ) {
fail( "Batch can't fail!", ex );
}
}
private static interface MyAttrs extends BasicFileAttributes {
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.core.protocol.core;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import java.util.List;
import java.util.Objects;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.ActiveMQExceptionType;
import org.apache.activemq.artemis.api.core.ActiveMQIOErrorException;
import org.apache.activemq.artemis.api.core.ActiveMQInternalErrorException;
import org.apache.activemq.artemis.api.core.ActiveMQQueueMaxConsumerLimitReached;
import org.apache.activemq.artemis.api.core.ICoreMessage;
import org.apache.activemq.artemis.api.core.Message;
import org.apache.activemq.artemis.api.core.QueueConfiguration;
import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.core.exception.ActiveMQXAException;
import org.apache.activemq.artemis.core.io.IOCallback;
import org.apache.activemq.artemis.core.persistence.StorageManager;
import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ActiveMQExceptionMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ActiveMQExceptionMessage_V2;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CreateAddressMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CreateQueueMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CreateQueueMessage_V2;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CreateSharedQueueMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CreateSharedQueueMessage_V2;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.NullResponseMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.NullResponseMessage_V2;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.RollbackMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionAcknowledgeMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionAddMetaDataMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionAddMetaDataMessageV2;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionBindingQueryMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionBindingQueryResponseMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionBindingQueryResponseMessage_V2;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionBindingQueryResponseMessage_V3;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionBindingQueryResponseMessage_V4;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionConsumerCloseMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionConsumerFlowCreditMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionCreateConsumerMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionDeleteQueueMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionExpireMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionForceConsumerDelivery;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionIndividualAcknowledgeMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionQueueQueryMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionQueueQueryResponseMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionQueueQueryResponseMessage_V2;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionQueueQueryResponseMessage_V3;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionRequestProducerCreditsMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionSendContinuationMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionSendLargeMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionSendMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionUniqueAddMetaDataMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionXAAfterFailedMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionXACommitMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionXAEndMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionXAForgetMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionXAGetInDoubtXidsResponseMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionXAGetTimeoutResponseMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionXAJoinMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionXAPrepareMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionXAResponseMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionXAResponseMessage_V2;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionXAResumeMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionXARollbackMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionXASetTimeoutMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionXASetTimeoutResponseMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionXAStartMessage;
import org.apache.activemq.artemis.core.remoting.CloseListener;
import org.apache.activemq.artemis.core.remoting.FailureListener;
import org.apache.activemq.artemis.core.server.ActiveMQMessageBundle;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServerLogger;
import org.apache.activemq.artemis.core.server.BindingQueryResult;
import org.apache.activemq.artemis.core.server.LargeServerMessage;
import org.apache.activemq.artemis.core.server.QueueQueryResult;
import org.apache.activemq.artemis.core.server.ServerSession;
import org.apache.activemq.artemis.logs.AuditLogger;
import org.apache.activemq.artemis.spi.core.protocol.EmbedMessageUtil;
import org.apache.activemq.artemis.spi.core.remoting.Connection;
import org.apache.activemq.artemis.utils.pools.MpscPool;
import org.apache.activemq.artemis.utils.pools.Pool;
import org.apache.activemq.artemis.utils.SimpleFuture;
import org.apache.activemq.artemis.utils.SimpleFutureImpl;
import org.apache.activemq.artemis.utils.actors.Actor;
import org.apache.activemq.artemis.utils.actors.ArtemisExecutor;
import org.jboss.logging.Logger;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.CREATE_ADDRESS;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.CREATE_QUEUE;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.CREATE_QUEUE_V2;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.CREATE_SHARED_QUEUE;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.CREATE_SHARED_QUEUE_V2;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.DELETE_QUEUE;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_ACKNOWLEDGE;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_BINDINGQUERY;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_CLOSE;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_COMMIT;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_CONSUMER_CLOSE;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_CREATECONSUMER;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_EXPIRED;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_FLOWTOKEN;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_FORCE_CONSUMER_DELIVERY;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_INDIVIDUAL_ACKNOWLEDGE;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_PRODUCER_REQUEST_CREDITS;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_QUEUEQUERY;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_ROLLBACK;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_SEND;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_SEND_CONTINUATION;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_SEND_LARGE;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_START;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_STOP;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_XA_COMMIT;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_XA_END;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_XA_FAILED;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_XA_FORGET;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_XA_GET_TIMEOUT;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_XA_INDOUBT_XIDS;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_XA_JOIN;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_XA_PREPARE;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_XA_RESUME;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_XA_ROLLBACK;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_XA_SET_TIMEOUT;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_XA_START;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_XA_SUSPEND;
public class ServerSessionPacketHandler implements ChannelHandler {
private static final int MAX_CACHED_NULL_RESPONSES = 32;
private static final Logger logger = Logger.getLogger(ServerSessionPacketHandler.class);
private final ServerSession session;
private final StorageManager storageManager;
private final Channel channel;
private volatile CoreRemotingConnection remotingConnection;
private final Actor<Packet> packetActor;
private final ArtemisExecutor callExecutor;
// The current currentLargeMessage being processed
private volatile LargeServerMessage currentLargeMessage;
private final boolean direct;
private final Object largeMessageLock = new Object();
private final Pool<NullResponseMessage> poolNullResponse;
private final Pool<NullResponseMessage_V2> poolNullResponseV2;
public ServerSessionPacketHandler(final ActiveMQServer server,
final ServerSession session,
final Channel channel) {
this.session = session;
session.addCloseable((boolean failed) -> clearLargeMessage());
this.storageManager = server.getStorageManager();
this.channel = channel;
this.remotingConnection = channel.getConnection();
Connection conn = remotingConnection.getTransportConnection();
this.callExecutor = server.getExecutorFactory().getExecutor();
// In an optimized way packetActor should use the threadPool as the parent executor
// directly from server.getThreadPool();
// However due to how transferConnection is handled we need to
// use the same executor
this.packetActor = new Actor<>(callExecutor, this::onMessagePacket);
this.direct = conn.isDirectDeliver();
// no confirmation window size means no resend cache hence NullResponsePackets
// won't get cached on it because need confirmation
poolNullResponse = new MpscPool<>(this.channel.getConfirmationWindowSize() == -1 ? MAX_CACHED_NULL_RESPONSES : 0, NullResponseMessage::reset, () -> new NullResponseMessage());
poolNullResponseV2 = new MpscPool<>(this.channel.getConfirmationWindowSize() == -1 ? MAX_CACHED_NULL_RESPONSES : 0, NullResponseMessage_V2::reset, () -> new NullResponseMessage_V2());
}
private void clearLargeMessage() {
synchronized (largeMessageLock) {
if (currentLargeMessage != null) {
try {
currentLargeMessage.deleteFile();
} catch (Throwable error) {
ActiveMQServerLogger.LOGGER.errorDeletingLargeMessageFile(error);
} finally {
currentLargeMessage = null;
}
}
}
}
public ServerSession getSession() {
return session;
}
public long getID() {
return channel.getID();
}
public void connectionFailed(final ActiveMQException exception, boolean failedOver) {
ActiveMQServerLogger.LOGGER.clientConnectionFailed(session.getName());
closeExecutors();
try {
session.close(true);
} catch (Exception e) {
ActiveMQServerLogger.LOGGER.errorClosingSession(e);
}
ActiveMQServerLogger.LOGGER.clearingUpSession(session.getName());
}
public void closeExecutors() {
packetActor.shutdown();
callExecutor.shutdown();
}
public void close() {
closeExecutors();
channel.flushConfirmations();
try {
session.close(false);
} catch (Exception e) {
ActiveMQServerLogger.LOGGER.errorClosingSession(e);
}
}
public Channel getChannel() {
return channel;
}
@Override
public void handlePacket(final Packet packet) {
// This method will call onMessagePacket through an actor
packetActor.act(packet);
}
private void onMessagePacket(final Packet packet) {
if (logger.isTraceEnabled()) {
logger.trace("ServerSessionPacketHandler::handlePacket," + packet);
}
if (AuditLogger.isAnyLoggingEnabled()) {
AuditLogger.setRemoteAddress(remotingConnection.getRemoteAddress());
AuditLogger.setCurrentCaller(remotingConnection.getAuditSubject());
}
final byte type = packet.getType();
switch (type) {
case SESS_SEND: {
onSessionSend(packet);
break;
}
case SESS_ACKNOWLEDGE: {
onSessionAcknowledge(packet);
break;
}
case SESS_PRODUCER_REQUEST_CREDITS: {
onSessionRequestProducerCredits(packet);
break;
}
case SESS_FLOWTOKEN: {
onSessionConsumerFlowCredit(packet);
break;
}
default:
// separating a method for everything else as JIT was faster this way
slowPacketHandler(packet);
break;
}
}
// This is being separated from onMessagePacket as JIT was more efficient with a small method for the
// hot executions.
private void slowPacketHandler(final Packet packet) {
final byte type = packet.getType();
storageManager.setContext(session.getSessionContext());
Packet response = null;
boolean flush = false;
boolean closeChannel = false;
boolean requiresResponse = false;
try {
try {
switch (type) {
case SESS_SEND_LARGE: {
SessionSendLargeMessage message = (SessionSendLargeMessage) packet;
sendLarge(message.getLargeMessage());
break;
}
case SESS_SEND_CONTINUATION: {
SessionSendContinuationMessage message = (SessionSendContinuationMessage) packet;
requiresResponse = message.isRequiresResponse();
sendContinuations(message.getPacketSize(), message.getMessageBodySize(), message.getBody(), message.isContinues());
if (requiresResponse) {
response = createNullResponseMessage(packet);
}
break;
}
case SESS_CREATECONSUMER: {
SessionCreateConsumerMessage request = (SessionCreateConsumerMessage) packet;
requiresResponse = request.isRequiresResponse();
session.createConsumer(request.getID(), request.getQueueName(), request.getFilterString(), request.getPriority(), request.isBrowseOnly(), true, null);
if (requiresResponse) {
// We send back queue information on the queue as a response- this allows the queue to
// be automatically recreated on failover
QueueQueryResult queueQueryResult = session.executeQueueQuery(request.getQueueName());
if (channel.supports(PacketImpl.SESS_QUEUEQUERY_RESP_V3)) {
response = new SessionQueueQueryResponseMessage_V3(queueQueryResult);
} else if (channel.supports(PacketImpl.SESS_QUEUEQUERY_RESP_V2)) {
response = new SessionQueueQueryResponseMessage_V2(queueQueryResult);
} else {
response = new SessionQueueQueryResponseMessage(queueQueryResult);
}
}
break;
}
case CREATE_ADDRESS: {
CreateAddressMessage request = (CreateAddressMessage) packet;
requiresResponse = request.isRequiresResponse();
session.createAddress(request.getAddress(), request.getRoutingTypes(), request.isAutoCreated());
if (requiresResponse) {
response = createNullResponseMessage(packet);
}
break;
}
case CREATE_QUEUE: {
CreateQueueMessage request = (CreateQueueMessage) packet;
requiresResponse = request.isRequiresResponse();
session.createQueue(new QueueConfiguration(request.getQueueName())
.setAddress(request.getAddress())
.setRoutingType(getRoutingTypeFromAddress(request.getAddress()))
.setFilterString(request.getFilterString())
.setTemporary(request.isTemporary())
.setDurable(request.isDurable()));
if (requiresResponse) {
response = createNullResponseMessage(packet);
}
break;
}
case CREATE_QUEUE_V2: {
CreateQueueMessage_V2 request = (CreateQueueMessage_V2) packet;
requiresResponse = request.isRequiresResponse();
session.createQueue(request.toQueueConfiguration());
if (requiresResponse) {
response = createNullResponseMessage(packet);
}
break;
}
case CREATE_SHARED_QUEUE: {
CreateSharedQueueMessage request = (CreateSharedQueueMessage) packet;
requiresResponse = request.isRequiresResponse();
QueueQueryResult result = session.executeQueueQuery(request.getQueueName());
if (!(result.isExists() && Objects.equals(result.getAddress(), request.getAddress()) && Objects.equals(result.getFilterString(), request.getFilterString()))) {
session.createSharedQueue(new QueueConfiguration(request.getQueueName())
.setAddress(request.getAddress())
.setFilterString(request.getFilterString())
.setDurable(request.isDurable()));
}
if (requiresResponse) {
response = createNullResponseMessage(packet);
}
break;
}
case CREATE_SHARED_QUEUE_V2: {
CreateSharedQueueMessage_V2 request = (CreateSharedQueueMessage_V2) packet;
requiresResponse = request.isRequiresResponse();
QueueQueryResult result = session.executeQueueQuery(request.getQueueName());
if (!(result.isExists() && Objects.equals(result.getAddress(), request.getAddress()) && Objects.equals(result.getFilterString(), request.getFilterString()))) {
session.createSharedQueue(request.toQueueConfiguration());
}
if (requiresResponse) {
response = createNullResponseMessage(packet);
}
break;
}
case DELETE_QUEUE: {
requiresResponse = true;
SessionDeleteQueueMessage request = (SessionDeleteQueueMessage) packet;
session.deleteQueue(request.getQueueName());
response = createNullResponseMessage(packet);
break;
}
case SESS_QUEUEQUERY: {
requiresResponse = true;
SessionQueueQueryMessage request = (SessionQueueQueryMessage) packet;
QueueQueryResult result = session.executeQueueQuery(request.getQueueName());
if (result.isExists() && remotingConnection.getChannelVersion() < PacketImpl.ADDRESSING_CHANGE_VERSION) {
result.setAddress(SessionQueueQueryMessage.getOldPrefixedAddress(result.getAddress(), result.getRoutingType()));
}
if (channel.supports(PacketImpl.SESS_QUEUEQUERY_RESP_V3)) {
response = new SessionQueueQueryResponseMessage_V3(result);
} else if (channel.supports(PacketImpl.SESS_QUEUEQUERY_RESP_V2)) {
response = new SessionQueueQueryResponseMessage_V2(result);
} else {
response = new SessionQueueQueryResponseMessage(result);
}
break;
}
case SESS_BINDINGQUERY: {
requiresResponse = true;
SessionBindingQueryMessage request = (SessionBindingQueryMessage) packet;
final int clientVersion = remotingConnection.getChannelVersion();
BindingQueryResult result = session.executeBindingQuery(request.getAddress());
/* if the session is JMS and it's from an older client then we need to add the old prefix to the queue
* names otherwise the older client won't realize the queue exists and will try to create it and receive
* an error
*/
if (result.isExists() && clientVersion < PacketImpl.ADDRESSING_CHANGE_VERSION && session.getMetaData(ClientSession.JMS_SESSION_IDENTIFIER_PROPERTY) != null) {
final List<SimpleString> queueNames = result.getQueueNames();
if (!queueNames.isEmpty()) {
final List<SimpleString> convertedQueueNames = request.convertQueueNames(clientVersion, queueNames);
if (convertedQueueNames != queueNames) {
result = new BindingQueryResult(result.isExists(), result.getAddressInfo(), convertedQueueNames, result.isAutoCreateQueues(), result.isAutoCreateAddresses(), result.isDefaultPurgeOnNoConsumers(), result.getDefaultMaxConsumers(), result.isDefaultExclusive(), result.isDefaultLastValue(), result.getDefaultLastValueKey(), result.isDefaultNonDestructive(), result.getDefaultConsumersBeforeDispatch(), result.getDefaultDelayBeforeDispatch());
}
}
}
if (channel.supports(PacketImpl.SESS_BINDINGQUERY_RESP_V4)) {
response = new SessionBindingQueryResponseMessage_V4(result.isExists(), result.getQueueNames(), result.isAutoCreateQueues(), result.isAutoCreateAddresses(), result.isDefaultPurgeOnNoConsumers(), result.getDefaultMaxConsumers(), result.isDefaultExclusive(), result.isDefaultLastValue(), result.getDefaultLastValueKey(), result.isDefaultNonDestructive(), result.getDefaultConsumersBeforeDispatch(), result.getDefaultDelayBeforeDispatch());
} else if (channel.supports(PacketImpl.SESS_BINDINGQUERY_RESP_V3)) {
response = new SessionBindingQueryResponseMessage_V3(result.isExists(), result.getQueueNames(), result.isAutoCreateQueues(), result.isAutoCreateAddresses());
} else if (channel.supports(PacketImpl.SESS_BINDINGQUERY_RESP_V2)) {
response = new SessionBindingQueryResponseMessage_V2(result.isExists(), result.getQueueNames(), result.isAutoCreateQueues());
} else {
response = new SessionBindingQueryResponseMessage(result.isExists(), result.getQueueNames());
}
break;
}
case SESS_EXPIRED: {
SessionExpireMessage message = (SessionExpireMessage) packet;
session.expire(message.getConsumerID(), message.getMessageID());
break;
}
case SESS_COMMIT: {
requiresResponse = true;
session.commit();
response = createNullResponseMessage(packet);
break;
}
case SESS_ROLLBACK: {
requiresResponse = true;
session.rollback(((RollbackMessage) packet).isConsiderLastMessageAsDelivered());
response = createNullResponseMessage(packet);
break;
}
case SESS_XA_COMMIT: {
requiresResponse = true;
SessionXACommitMessage message = (SessionXACommitMessage) packet;
session.xaCommit(message.getXid(), message.isOnePhase());
response = createSessionXAResponseMessage(packet);
break;
}
case SESS_XA_END: {
requiresResponse = true;
SessionXAEndMessage message = (SessionXAEndMessage) packet;
session.xaEnd(message.getXid());
response = createSessionXAResponseMessage(packet);
break;
}
case SESS_XA_FORGET: {
requiresResponse = true;
SessionXAForgetMessage message = (SessionXAForgetMessage) packet;
session.xaForget(message.getXid());
response = createSessionXAResponseMessage(packet);
break;
}
case SESS_XA_JOIN: {
requiresResponse = true;
SessionXAJoinMessage message = (SessionXAJoinMessage) packet;
session.xaJoin(message.getXid());
response = createSessionXAResponseMessage(packet);
break;
}
case SESS_XA_RESUME: {
requiresResponse = true;
SessionXAResumeMessage message = (SessionXAResumeMessage) packet;
session.xaResume(message.getXid());
response = createSessionXAResponseMessage(packet);
break;
}
case SESS_XA_ROLLBACK: {
requiresResponse = true;
SessionXARollbackMessage message = (SessionXARollbackMessage) packet;
session.xaRollback(message.getXid());
response = createSessionXAResponseMessage(packet);
break;
}
case SESS_XA_START: {
requiresResponse = true;
SessionXAStartMessage message = (SessionXAStartMessage) packet;
session.xaStart(message.getXid());
response = createSessionXAResponseMessage(packet);
break;
}
case SESS_XA_FAILED: {
requiresResponse = true;
SessionXAAfterFailedMessage message = (SessionXAAfterFailedMessage) packet;
session.xaFailed(message.getXid());
// no response on this case
break;
}
case SESS_XA_SUSPEND: {
requiresResponse = true;
session.xaSuspend();
response = createSessionXAResponseMessage(packet);
break;
}
case SESS_XA_PREPARE: {
requiresResponse = true;
SessionXAPrepareMessage message = (SessionXAPrepareMessage) packet;
session.xaPrepare(message.getXid());
response = createSessionXAResponseMessage(packet);
break;
}
case SESS_XA_INDOUBT_XIDS: {
requiresResponse = true;
List<Xid> xids = session.xaGetInDoubtXids();
response = new SessionXAGetInDoubtXidsResponseMessage(xids);
break;
}
case SESS_XA_GET_TIMEOUT: {
requiresResponse = true;
int timeout = session.xaGetTimeout();
response = new SessionXAGetTimeoutResponseMessage(timeout);
break;
}
case SESS_XA_SET_TIMEOUT: {
requiresResponse = true;
SessionXASetTimeoutMessage message = (SessionXASetTimeoutMessage) packet;
session.xaSetTimeout(message.getTimeoutSeconds());
response = new SessionXASetTimeoutResponseMessage(true);
break;
}
case SESS_START: {
session.start();
break;
}
case SESS_STOP: {
requiresResponse = true;
session.stop();
response = createNullResponseMessage(packet);
break;
}
case SESS_CLOSE: {
requiresResponse = true;
session.close(false);
// removeConnectionListeners();
response = createNullResponseMessage(packet);
flush = true;
closeChannel = true;
break;
}
case SESS_INDIVIDUAL_ACKNOWLEDGE: {
SessionIndividualAcknowledgeMessage message = (SessionIndividualAcknowledgeMessage) packet;
requiresResponse = message.isRequiresResponse();
session.individualAcknowledge(message.getConsumerID(), message.getMessageID());
if (requiresResponse) {
response = createNullResponseMessage(packet);
}
break;
}
case SESS_CONSUMER_CLOSE: {
requiresResponse = true;
SessionConsumerCloseMessage message = (SessionConsumerCloseMessage) packet;
session.closeConsumer(message.getConsumerID());
response = createNullResponseMessage(packet);
break;
}
case SESS_FORCE_CONSUMER_DELIVERY: {
SessionForceConsumerDelivery message = (SessionForceConsumerDelivery) packet;
session.forceConsumerDelivery(message.getConsumerID(), message.getSequence());
break;
}
case PacketImpl.SESS_ADD_METADATA: {
response = createNullResponseMessage(packet);
SessionAddMetaDataMessage message = (SessionAddMetaDataMessage) packet;
session.addMetaData(message.getKey(), message.getData());
break;
}
case PacketImpl.SESS_ADD_METADATA2: {
requiresResponse = true;
SessionAddMetaDataMessageV2 message = (SessionAddMetaDataMessageV2) packet;
if (message.isRequiresConfirmations()) {
response = createNullResponseMessage(packet);
}
session.addMetaData(message.getKey(), message.getData());
break;
}
case PacketImpl.SESS_UNIQUE_ADD_METADATA: {
requiresResponse = true;
SessionUniqueAddMetaDataMessage message = (SessionUniqueAddMetaDataMessage) packet;
if (session.addUniqueMetaData(message.getKey(), message.getData())) {
response = createNullResponseMessage(packet);
} else {
response = new ActiveMQExceptionMessage(ActiveMQMessageBundle.BUNDLE.duplicateMetadata(message.getKey(), message.getData()));
}
break;
}
}
} catch (ActiveMQIOErrorException e) {
response = onActiveMQIOErrorExceptionWhileHandlePacket(packet, e, requiresResponse, response, this.session);
} catch (ActiveMQXAException e) {
response = onActiveMQXAExceptionWhileHandlePacket(packet, e, requiresResponse, response);
} catch (ActiveMQQueueMaxConsumerLimitReached e) {
response = onActiveMQQueueMaxConsumerLimitReachedWhileHandlePacket(packet, e, requiresResponse, response);
} catch (ActiveMQException e) {
response = onActiveMQExceptionWhileHandlePacket(packet, e, requiresResponse, response);
} catch (Throwable t) {
response = onCatchThrowableWhileHandlePacket(packet, t, requiresResponse, response, this.session);
}
sendResponse(packet, response, flush, closeChannel);
} finally {
storageManager.clearContext();
}
}
private RoutingType getRoutingTypeFromAddress(SimpleString address) {
if (address.startsWith(PacketImpl.OLD_QUEUE_PREFIX) || address.startsWith(PacketImpl.OLD_TEMP_QUEUE_PREFIX)) {
return RoutingType.ANYCAST;
}
return RoutingType.MULTICAST;
}
private boolean requireNullResponseMessage_V1(Packet packet) {
return !packet.isResponseAsync() || channel.getConnection().isVersionBeforeAsyncResponseChange();
}
private NullResponseMessage createNullResponseMessage_V1(Packet packet) {
assert requireNullResponseMessage_V1(packet);
return poolNullResponse.borrow();
}
private NullResponseMessage_V2 createNullResponseMessage_V2(Packet packet) {
assert !requireNullResponseMessage_V1(packet);
NullResponseMessage_V2 response;
response = poolNullResponseV2.borrow();
// this should be already set by the channel too, but let's do it just in case
response.setCorrelationID(packet.getCorrelationID());
return response;
}
private Packet createNullResponseMessage(Packet packet) {
if (requireNullResponseMessage_V1(packet)) {
return createNullResponseMessage_V1(packet);
}
return createNullResponseMessage_V2(packet);
}
private Packet createSessionXAResponseMessage(Packet packet) {
Packet response;
if (packet.isResponseAsync()) {
response = new SessionXAResponseMessage_V2(packet.getCorrelationID(), false, XAResource.XA_OK, null);
} else {
response = new SessionXAResponseMessage(false, XAResource.XA_OK, null);
}
return response;
}
private void releaseResponse(Packet packet) {
if (poolNullResponse == null || poolNullResponseV2 == null) {
return;
}
if (packet instanceof NullResponseMessage) {
poolNullResponse.release((NullResponseMessage) packet);
return;
}
if (packet instanceof NullResponseMessage_V2) {
poolNullResponseV2.release((NullResponseMessage_V2) packet);
}
}
private void onSessionAcknowledge(Packet packet) {
this.storageManager.setContext(session.getSessionContext());
try {
Packet response = null;
boolean requiresResponse = false;
try {
final SessionAcknowledgeMessage message = (SessionAcknowledgeMessage) packet;
requiresResponse = message.isRequiresResponse();
this.session.acknowledge(message.getConsumerID(), message.getMessageID());
if (requiresResponse) {
response = createNullResponseMessage(packet);
}
} catch (ActiveMQIOErrorException e) {
response = onActiveMQIOErrorExceptionWhileHandlePacket(packet, e, requiresResponse, response, this.session);
} catch (ActiveMQXAException e) {
response = onActiveMQXAExceptionWhileHandlePacket(packet, e, requiresResponse, response);
} catch (ActiveMQQueueMaxConsumerLimitReached e) {
response = onActiveMQQueueMaxConsumerLimitReachedWhileHandlePacket(packet, e, requiresResponse, response);
} catch (ActiveMQException e) {
response = onActiveMQExceptionWhileHandlePacket(packet, e, requiresResponse, response);
} catch (Throwable t) {
response = onCatchThrowableWhileHandlePacket(packet, t, requiresResponse, response, this.session);
}
sendResponse(packet, response, false, false);
} finally {
this.storageManager.clearContext();
}
}
private void onSessionSend(Packet packet) {
this.storageManager.setContext(session.getSessionContext());
try {
Packet response = null;
boolean requiresResponse = false;
try {
final SessionSendMessage message = (SessionSendMessage) packet;
requiresResponse = message.isRequiresResponse();
this.session.send(EmbedMessageUtil.extractEmbedded(message.getMessage(), storageManager), this.direct);
if (requiresResponse) {
response = createNullResponseMessage(packet);
}
} catch (ActiveMQIOErrorException e) {
response = onActiveMQIOErrorExceptionWhileHandlePacket(packet, e, requiresResponse, response, this.session);
} catch (ActiveMQXAException e) {
response = onActiveMQXAExceptionWhileHandlePacket(packet, e, requiresResponse, response);
} catch (ActiveMQQueueMaxConsumerLimitReached e) {
response = onActiveMQQueueMaxConsumerLimitReachedWhileHandlePacket(packet, e, requiresResponse, response);
} catch (ActiveMQException e) {
response = onActiveMQExceptionWhileHandlePacket(packet, e, requiresResponse, response);
} catch (Throwable t) {
response = onCatchThrowableWhileHandlePacket(packet, t, requiresResponse, response, this.session);
}
sendResponse(packet, response, false, false);
} finally {
this.storageManager.clearContext();
}
}
private void onSessionRequestProducerCredits(Packet packet) {
this.storageManager.setContext(session.getSessionContext());
try {
Packet response = null;
boolean requiresResponse = false;
try {
SessionRequestProducerCreditsMessage message = (SessionRequestProducerCreditsMessage) packet;
session.requestProducerCredits(message.getAddress(), message.getCredits());
} catch (ActiveMQIOErrorException e) {
response = onActiveMQIOErrorExceptionWhileHandlePacket(packet, e, requiresResponse, response, this.session);
} catch (ActiveMQXAException e) {
response = onActiveMQXAExceptionWhileHandlePacket(packet, e, requiresResponse, response);
} catch (ActiveMQQueueMaxConsumerLimitReached e) {
response = onActiveMQQueueMaxConsumerLimitReachedWhileHandlePacket(packet, e, requiresResponse, response);
} catch (ActiveMQException e) {
response = onActiveMQExceptionWhileHandlePacket(packet, e, requiresResponse, response);
} catch (Throwable t) {
response = onCatchThrowableWhileHandlePacket(packet, t, requiresResponse, response, this.session);
}
sendResponse(packet, response, false, false);
} finally {
this.storageManager.clearContext();
}
}
private void onSessionConsumerFlowCredit(Packet packet) {
this.storageManager.setContext(session.getSessionContext());
try {
Packet response = null;
boolean requiresResponse = false;
try {
SessionConsumerFlowCreditMessage message = (SessionConsumerFlowCreditMessage) packet;
session.receiveConsumerCredits(message.getConsumerID(), message.getCredits());
} catch (ActiveMQIOErrorException e) {
response = onActiveMQIOErrorExceptionWhileHandlePacket(packet, e, requiresResponse, response, this.session);
} catch (ActiveMQXAException e) {
response = onActiveMQXAExceptionWhileHandlePacket(packet, e, requiresResponse, response);
} catch (ActiveMQQueueMaxConsumerLimitReached e) {
response = onActiveMQQueueMaxConsumerLimitReachedWhileHandlePacket(packet, e, requiresResponse, response);
} catch (ActiveMQException e) {
response = onActiveMQExceptionWhileHandlePacket(packet, e, requiresResponse, response);
} catch (Throwable t) {
response = onCatchThrowableWhileHandlePacket(packet, t, requiresResponse, response, this.session);
}
sendResponse(packet, response, false, false);
} finally {
this.storageManager.clearContext();
}
}
private static Packet onActiveMQIOErrorExceptionWhileHandlePacket(Packet packet,
ActiveMQIOErrorException e,
boolean requiresResponse,
Packet response,
ServerSession session) {
session.markTXFailed(e);
if (requiresResponse) {
logger.debug("Sending exception to client", e);
response = convertToExceptionPacket(packet, e);
} else {
ActiveMQServerLogger.LOGGER.caughtException(e);
}
return response;
}
private static Packet onActiveMQXAExceptionWhileHandlePacket(Packet packet,
ActiveMQXAException e,
boolean requiresResponse,
Packet response) {
if (requiresResponse) {
logger.debug("Sending exception to client", e);
if (packet.isResponseAsync()) {
response = new SessionXAResponseMessage_V2(packet.getCorrelationID(), true, e.errorCode, e.getMessage());
} else {
response = new SessionXAResponseMessage(true, e.errorCode, e.getMessage());
}
} else {
ActiveMQServerLogger.LOGGER.caughtXaException(e);
}
return response;
}
private static Packet onActiveMQQueueMaxConsumerLimitReachedWhileHandlePacket(Packet packet,
ActiveMQQueueMaxConsumerLimitReached e,
boolean requiresResponse,
Packet response) {
if (requiresResponse) {
logger.debug("Sending exception to client", e);
response = convertToExceptionPacket(packet, e);
} else {
ActiveMQServerLogger.LOGGER.caughtException(e);
}
return response;
}
private static Packet convertToExceptionPacket(Packet packet, ActiveMQException e) {
Packet response;
if (packet.isResponseAsync()) {
response = new ActiveMQExceptionMessage_V2(packet.getCorrelationID(), e);
} else {
response = new ActiveMQExceptionMessage(e);
}
return response;
}
private static Packet onActiveMQExceptionWhileHandlePacket(Packet packet,
ActiveMQException e,
boolean requiresResponse,
Packet response) {
if (requiresResponse) {
logger.debug("Sending exception to client", e);
response = convertToExceptionPacket(packet, e);
} else {
if (e.getType() == ActiveMQExceptionType.QUEUE_EXISTS) {
logger.debug("Caught exception", e);
} else {
ActiveMQServerLogger.LOGGER.caughtException(e);
}
}
return response;
}
private static Packet onCatchThrowableWhileHandlePacket(Packet packet,
Throwable t,
boolean requiresResponse,
Packet response,
ServerSession session) {
session.markTXFailed(t);
if (requiresResponse) {
ActiveMQServerLogger.LOGGER.sendingUnexpectedExceptionToClient(t);
ActiveMQException activeMQInternalErrorException = new ActiveMQInternalErrorException();
activeMQInternalErrorException.initCause(t);
response = convertToExceptionPacket(packet, activeMQInternalErrorException);
} else {
ActiveMQServerLogger.LOGGER.caughtException(t);
}
return response;
}
private void sendResponse(final Packet confirmPacket,
final Packet response,
final boolean flush,
final boolean closeChannel) {
if (logger.isTraceEnabled()) {
logger.trace("ServerSessionPacketHandler::scheduling response::" + response);
}
storageManager.afterCompleteOperations(new IOCallback() {
@Override
public void onError(final int errorCode, final String errorMessage) {
ActiveMQServerLogger.LOGGER.errorProcessingIOCallback(errorCode, errorMessage);
Packet exceptionPacket = convertToExceptionPacket(confirmPacket, ActiveMQExceptionType.createException(errorCode, errorMessage));
doConfirmAndResponse(confirmPacket, exceptionPacket, flush, closeChannel);
if (logger.isTraceEnabled()) {
logger.trace("ServerSessionPacketHandler::exception response sent::" + exceptionPacket);
}
}
@Override
public void done() {
if (logger.isTraceEnabled()) {
logger.trace("ServerSessionPacketHandler::regular response sent::" + response);
}
doConfirmAndResponse(confirmPacket, response, flush, closeChannel);
}
});
}
private void doConfirmAndResponse(final Packet confirmPacket,
final Packet response,
final boolean flush,
final boolean closeChannel) {
// don't confirm if the response is an exception
if (confirmPacket != null && (response == null || (response != null && response.getType() != PacketImpl.EXCEPTION))) {
channel.confirm(confirmPacket);
if (flush) {
channel.flushConfirmations();
}
}
if (response != null) {
try {
channel.send(response);
} finally {
releaseResponse(response);
}
}
if (closeChannel) {
channel.close();
}
}
public void closeListeners() {
List<CloseListener> listeners = remotingConnection.removeCloseListeners();
for (CloseListener closeListener : listeners) {
closeListener.connectionClosed();
if (closeListener instanceof FailureListener) {
remotingConnection.removeFailureListener((FailureListener) closeListener);
}
}
}
public int transferConnection(final CoreRemotingConnection newConnection, final int lastReceivedCommandID) {
SimpleFuture<Integer> future = new SimpleFutureImpl<>();
callExecutor.execute(() -> {
int value = internaltransferConnection(newConnection, lastReceivedCommandID);
future.set(value);
});
try {
return future.get().intValue();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
private int internaltransferConnection(final CoreRemotingConnection newConnection, final int lastReceivedCommandID) {
// We need to disable delivery on all the consumers while the transfer is occurring- otherwise packets might get
// delivered
// after the channel has transferred but *before* packets have been replayed - this will give the client the wrong
// sequence of packets.
// It is not sufficient to just stop the session, since right after stopping the session, another session start
// might be executed
// before we have transferred the connection, leaving it in a started state
session.setTransferring(true);
// Note. We do not destroy the replicating connection here. In the case the live server has really crashed
// then the connection will get cleaned up anyway when the server ping timeout kicks in.
// In the case the live server is really still up, i.e. a split brain situation (or in tests), then closing
// the replicating connection will cause the outstanding responses to be be replayed on the live server,
// if these reach the client who then subsequently fails over, on reconnection to backup, it will have
// received responses that the backup did not know about.
channel.transferConnection(newConnection);
newConnection.syncIDGeneratorSequence(remotingConnection.getIDGeneratorSequence());
session.transferConnection(newConnection);
Connection oldTransportConnection = remotingConnection.getTransportConnection();
remotingConnection = newConnection;
int serverLastReceivedCommandID = channel.getLastConfirmedCommandID();
channel.replayCommands(lastReceivedCommandID);
channel.setTransferring(false);
session.setTransferring(false);
// We do this because the old connection could be out of credits on netty
// this will force anything to resume after the reattach through the ReadyListener callbacks
oldTransportConnection.fireReady(true);
return serverLastReceivedCommandID;
}
// Large Message is part of the core protocol, we have these functions here as part of Packet handler
private void sendLarge(final Message message) throws Exception {
// need to create the LargeMessage before continue
long id = storageManager.generateID();
LargeServerMessage largeMsg = storageManager.createLargeMessage(id, message);
if (logger.isTraceEnabled()) {
logger.trace("sendLarge::" + largeMsg);
}
if (currentLargeMessage != null) {
ActiveMQServerLogger.LOGGER.replacingIncompleteLargeMessage(currentLargeMessage.getMessageID());
}
currentLargeMessage = largeMsg;
}
private void sendContinuations(final int packetSize,
final long messageBodySize,
final byte[] body,
final boolean continues) throws Exception {
synchronized (largeMessageLock) {
if (currentLargeMessage == null) {
throw ActiveMQMessageBundle.BUNDLE.largeMessageNotInitialised();
}
// Immediately release the credits for the continuations- these don't contribute to the in-memory size
// of the message
currentLargeMessage.addBytes(body);
if (!continues) {
currentLargeMessage.releaseResources(true, true);
if (messageBodySize >= 0) {
currentLargeMessage.toMessage().putLongProperty(Message.HDR_LARGE_BODY_SIZE, messageBodySize);
}
LargeServerMessage message = currentLargeMessage;
currentLargeMessage.setStorageManager(storageManager);
currentLargeMessage = null;
session.doSend(session.getCurrentTransaction(), EmbedMessageUtil.extractEmbedded((ICoreMessage)message.toMessage(), storageManager), null, false, false);
}
}
}
}
| |
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.redshift.model;
import java.io.Serializable;
/**
* <p>
* Describes the status of changes to HSM settings.
* </p>
*/
public class HsmStatus implements Serializable, Cloneable {
/**
* <p>
* Specifies the name of the HSM client certificate the Amazon Redshift
* cluster uses to retrieve the data encryption keys stored in an HSM.
* </p>
*/
private String hsmClientCertificateIdentifier;
/**
* <p>
* Specifies the name of the HSM configuration that contains the information
* the Amazon Redshift cluster can use to retrieve and store keys in an HSM.
* </p>
*/
private String hsmConfigurationIdentifier;
/**
* <p>
* Reports whether the Amazon Redshift cluster has finished applying any HSM
* settings changes specified in a modify cluster command.
* </p>
* <p>
* Values: active, applying
* </p>
*/
private String status;
/**
* <p>
* Specifies the name of the HSM client certificate the Amazon Redshift
* cluster uses to retrieve the data encryption keys stored in an HSM.
* </p>
*
* @param hsmClientCertificateIdentifier
* Specifies the name of the HSM client certificate the Amazon
* Redshift cluster uses to retrieve the data encryption keys stored
* in an HSM.
*/
public void setHsmClientCertificateIdentifier(
String hsmClientCertificateIdentifier) {
this.hsmClientCertificateIdentifier = hsmClientCertificateIdentifier;
}
/**
* <p>
* Specifies the name of the HSM client certificate the Amazon Redshift
* cluster uses to retrieve the data encryption keys stored in an HSM.
* </p>
*
* @return Specifies the name of the HSM client certificate the Amazon
* Redshift cluster uses to retrieve the data encryption keys stored
* in an HSM.
*/
public String getHsmClientCertificateIdentifier() {
return this.hsmClientCertificateIdentifier;
}
/**
* <p>
* Specifies the name of the HSM client certificate the Amazon Redshift
* cluster uses to retrieve the data encryption keys stored in an HSM.
* </p>
*
* @param hsmClientCertificateIdentifier
* Specifies the name of the HSM client certificate the Amazon
* Redshift cluster uses to retrieve the data encryption keys stored
* in an HSM.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public HsmStatus withHsmClientCertificateIdentifier(
String hsmClientCertificateIdentifier) {
setHsmClientCertificateIdentifier(hsmClientCertificateIdentifier);
return this;
}
/**
* <p>
* Specifies the name of the HSM configuration that contains the information
* the Amazon Redshift cluster can use to retrieve and store keys in an HSM.
* </p>
*
* @param hsmConfigurationIdentifier
* Specifies the name of the HSM configuration that contains the
* information the Amazon Redshift cluster can use to retrieve and
* store keys in an HSM.
*/
public void setHsmConfigurationIdentifier(String hsmConfigurationIdentifier) {
this.hsmConfigurationIdentifier = hsmConfigurationIdentifier;
}
/**
* <p>
* Specifies the name of the HSM configuration that contains the information
* the Amazon Redshift cluster can use to retrieve and store keys in an HSM.
* </p>
*
* @return Specifies the name of the HSM configuration that contains the
* information the Amazon Redshift cluster can use to retrieve and
* store keys in an HSM.
*/
public String getHsmConfigurationIdentifier() {
return this.hsmConfigurationIdentifier;
}
/**
* <p>
* Specifies the name of the HSM configuration that contains the information
* the Amazon Redshift cluster can use to retrieve and store keys in an HSM.
* </p>
*
* @param hsmConfigurationIdentifier
* Specifies the name of the HSM configuration that contains the
* information the Amazon Redshift cluster can use to retrieve and
* store keys in an HSM.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public HsmStatus withHsmConfigurationIdentifier(
String hsmConfigurationIdentifier) {
setHsmConfigurationIdentifier(hsmConfigurationIdentifier);
return this;
}
/**
* <p>
* Reports whether the Amazon Redshift cluster has finished applying any HSM
* settings changes specified in a modify cluster command.
* </p>
* <p>
* Values: active, applying
* </p>
*
* @param status
* Reports whether the Amazon Redshift cluster has finished applying
* any HSM settings changes specified in a modify cluster
* command.</p>
* <p>
* Values: active, applying
*/
public void setStatus(String status) {
this.status = status;
}
/**
* <p>
* Reports whether the Amazon Redshift cluster has finished applying any HSM
* settings changes specified in a modify cluster command.
* </p>
* <p>
* Values: active, applying
* </p>
*
* @return Reports whether the Amazon Redshift cluster has finished applying
* any HSM settings changes specified in a modify cluster
* command.</p>
* <p>
* Values: active, applying
*/
public String getStatus() {
return this.status;
}
/**
* <p>
* Reports whether the Amazon Redshift cluster has finished applying any HSM
* settings changes specified in a modify cluster command.
* </p>
* <p>
* Values: active, applying
* </p>
*
* @param status
* Reports whether the Amazon Redshift cluster has finished applying
* any HSM settings changes specified in a modify cluster
* command.</p>
* <p>
* Values: active, applying
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public HsmStatus withStatus(String status) {
setStatus(status);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getHsmClientCertificateIdentifier() != null)
sb.append("HsmClientCertificateIdentifier: "
+ getHsmClientCertificateIdentifier() + ",");
if (getHsmConfigurationIdentifier() != null)
sb.append("HsmConfigurationIdentifier: "
+ getHsmConfigurationIdentifier() + ",");
if (getStatus() != null)
sb.append("Status: " + getStatus());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof HsmStatus == false)
return false;
HsmStatus other = (HsmStatus) obj;
if (other.getHsmClientCertificateIdentifier() == null
^ this.getHsmClientCertificateIdentifier() == null)
return false;
if (other.getHsmClientCertificateIdentifier() != null
&& other.getHsmClientCertificateIdentifier().equals(
this.getHsmClientCertificateIdentifier()) == false)
return false;
if (other.getHsmConfigurationIdentifier() == null
^ this.getHsmConfigurationIdentifier() == null)
return false;
if (other.getHsmConfigurationIdentifier() != null
&& other.getHsmConfigurationIdentifier().equals(
this.getHsmConfigurationIdentifier()) == false)
return false;
if (other.getStatus() == null ^ this.getStatus() == null)
return false;
if (other.getStatus() != null
&& other.getStatus().equals(this.getStatus()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime
* hashCode
+ ((getHsmClientCertificateIdentifier() == null) ? 0
: getHsmClientCertificateIdentifier().hashCode());
hashCode = prime
* hashCode
+ ((getHsmConfigurationIdentifier() == null) ? 0
: getHsmConfigurationIdentifier().hashCode());
hashCode = prime * hashCode
+ ((getStatus() == null) ? 0 : getStatus().hashCode());
return hashCode;
}
@Override
public HsmStatus clone() {
try {
return (HsmStatus) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
}
| |
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonValue;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
"name",
"type",
"aggregate",
"timeUnit",
"bin",
"scale",
"legend",
"value",
"sort"
})
public class Size {
@JsonProperty("name")
private String name;
@JsonProperty("type")
private Size.Type type;
@JsonProperty("aggregate")
private Size.Aggregate aggregate;
@JsonProperty("timeUnit")
private Size.TimeUnit timeUnit;
@JsonProperty("bin")
private Bin____ bin = null;
@JsonProperty("scale")
private Scale__ scale;
/**
* Properties of a legend.
*
*/
@JsonProperty("legend")
private Legend legend;
/**
* Size of marks.
*
*/
@JsonProperty("value")
private Integer value = 30;
@JsonProperty("sort")
private List<Sort____> sort = new ArrayList<Sort____>();
/**
*
* @return
* The name
*/
@JsonProperty("name")
public String getName() {
return name;
}
/**
*
* @param name
* The name
*/
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
public Size withName(String name) {
this.name = name;
return this;
}
/**
*
* @return
* The type
*/
@JsonProperty("type")
public Size.Type getType() {
return type;
}
/**
*
* @param type
* The type
*/
@JsonProperty("type")
public void setType(Size.Type type) {
this.type = type;
}
public Size withType(Size.Type type) {
this.type = type;
return this;
}
/**
*
* @return
* The aggregate
*/
@JsonProperty("aggregate")
public Size.Aggregate getAggregate() {
return aggregate;
}
/**
*
* @param aggregate
* The aggregate
*/
@JsonProperty("aggregate")
public void setAggregate(Size.Aggregate aggregate) {
this.aggregate = aggregate;
}
public Size withAggregate(Size.Aggregate aggregate) {
this.aggregate = aggregate;
return this;
}
/**
*
* @return
* The timeUnit
*/
@JsonProperty("timeUnit")
public Size.TimeUnit getTimeUnit() {
return timeUnit;
}
/**
*
* @param timeUnit
* The timeUnit
*/
@JsonProperty("timeUnit")
public void setTimeUnit(Size.TimeUnit timeUnit) {
this.timeUnit = timeUnit;
}
public Size withTimeUnit(Size.TimeUnit timeUnit) {
this.timeUnit = timeUnit;
return this;
}
/**
*
* @return
* The bin
*/
@JsonProperty("bin")
public Bin____ getBin() {
return bin;
}
/**
*
* @param bin
* The bin
*/
@JsonProperty("bin")
public void setBin(Bin____ bin) {
this.bin = bin;
}
public Size withBin(Bin____ bin) {
this.bin = bin;
return this;
}
/**
*
* @return
* The scale
*/
@JsonProperty("scale")
public Scale__ getScale() {
return scale;
}
/**
*
* @param scale
* The scale
*/
@JsonProperty("scale")
public void setScale(Scale__ scale) {
this.scale = scale;
}
public Size withScale(Scale__ scale) {
this.scale = scale;
return this;
}
/**
* Properties of a legend.
*
* @return
* The legend
*/
@JsonProperty("legend")
public Legend getLegend() {
return legend;
}
/**
* Properties of a legend.
*
* @param legend
* The legend
*/
@JsonProperty("legend")
public void setLegend(Legend legend) {
this.legend = legend;
}
public Size withLegend(Legend legend) {
this.legend = legend;
return this;
}
/**
* Size of marks.
*
* @return
* The value
*/
@JsonProperty("value")
public Integer getValue() {
return value;
}
/**
* Size of marks.
*
* @param value
* The value
*/
@JsonProperty("value")
public void setValue(Integer value) {
this.value = value;
}
public Size withValue(Integer value) {
this.value = value;
return this;
}
/**
*
* @return
* The sort
*/
@JsonProperty("sort")
public List<Sort____> getSort() {
return sort;
}
/**
*
* @param sort
* The sort
*/
@JsonProperty("sort")
public void setSort(List<Sort____> sort) {
this.sort = sort;
}
public Size withSort(List<Sort____> sort) {
this.sort = sort;
return this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(name).append(type).append(aggregate).append(timeUnit).append(bin).append(scale).append(legend).append(value).append(sort).toHashCode();
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Size) == false) {
return false;
}
Size rhs = ((Size) other);
return new EqualsBuilder().append(name, rhs.name).append(type, rhs.type).append(aggregate, rhs.aggregate).append(timeUnit, rhs.timeUnit).append(bin, rhs.bin).append(scale, rhs.scale).append(legend, rhs.legend).append(value, rhs.value).append(sort, rhs.sort).isEquals();
}
@Generated("org.jsonschema2pojo")
public static enum Aggregate {
AVG("avg"),
SUM("sum"),
MEDIAN("median"),
MIN("min"),
MAX("max"),
COUNT("count");
private final String value;
private static Map<String, Size.Aggregate> constants = new HashMap<String, Size.Aggregate>();
static {
for (Size.Aggregate c: values()) {
constants.put(c.value, c);
}
}
private Aggregate(String value) {
this.value = value;
}
@JsonValue
@Override
public String toString() {
return this.value;
}
@JsonCreator
public static Size.Aggregate fromValue(String value) {
Size.Aggregate constant = constants.get(value);
if (constant == null) {
throw new IllegalArgumentException(value);
} else {
return constant;
}
}
}
@Generated("org.jsonschema2pojo")
public static enum TimeUnit {
YEAR("year"),
MONTH("month"),
DAY("day"),
DATE("date"),
HOURS("hours"),
MINUTES("minutes"),
SECONDS("seconds");
private final String value;
private static Map<String, Size.TimeUnit> constants = new HashMap<String, Size.TimeUnit>();
static {
for (Size.TimeUnit c: values()) {
constants.put(c.value, c);
}
}
private TimeUnit(String value) {
this.value = value;
}
@JsonValue
@Override
public String toString() {
return this.value;
}
@JsonCreator
public static Size.TimeUnit fromValue(String value) {
Size.TimeUnit constant = constants.get(value);
if (constant == null) {
throw new IllegalArgumentException(value);
} else {
return constant;
}
}
}
@Generated("org.jsonschema2pojo")
public static enum Type {
N("N"),
O("O"),
Q("Q"),
T("T");
private final String value;
private static Map<String, Size.Type> constants = new HashMap<String, Size.Type>();
static {
for (Size.Type c: values()) {
constants.put(c.value, c);
}
}
private Type(String value) {
this.value = value;
}
@JsonValue
@Override
public String toString() {
return this.value;
}
@JsonCreator
public static Size.Type fromValue(String value) {
Size.Type constant = constants.get(value);
if (constant == null) {
throw new IllegalArgumentException(value);
} else {
return constant;
}
}
}
}
| |
/*
* Copyright (C) 2016 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package OptimizationTests.TrivialLoopEvaluator.RemTests;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static final int maxIter=999;
public static void main(String[] args) {
Main main = new Main();
Class<Main> cls = Main.class;
Method[] mets = cls.getDeclaredMethods();
Arrays.sort(mets, new Comparator<Method>() {
@Override
public int compare(Method arg0, Method arg1) {
return arg0.getName().compareTo(arg1.getName());
}
});
for (Method met:mets){
if (met.getName().equalsIgnoreCase("main"))
continue;
try {
System.out.println("Test "+met.getName()+" result: "+met.invoke(main));
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
public int testInt1(){
int i=1;
int res=123456;
int res1=1;
for (;i<5;i++){
res1+=res%i;
}
return res1;
}
public int testInt2(){
int i=1;
int res=123456;
int res1=1;
int tmp=-10;
for (;i<50;i++){
res%=i;
tmp--;
res1=res%tmp;
}
return res1;
}
public int testInt3(){
int i=1;
int res=123456778;
int res1=1;
int tmp=1;
for (i=0;i<maxIter;i++){
res1+=res%tmp;
tmp++;
}
return res1;
}
public int testInt4(){
int i=1;
int res=1234567;
int res1=10000;
int tmp=-10;
for (i=tmp;i<res;i++){
res1+=res%tmp;
}
return res1;
}
public long testLong1(){
long i=1;
long res=123456;
long res1=0;
for (;i<5;i++){
res1+=res%i;
}
return res1;
}
public long testLong2(){
long i=1;
long res=123456;
long res1=0;
long tmp=10;
for (;i<50;i++){
res1+=res%i;
tmp++;
res+=tmp;
}
return res1;
}
public long testLong3(){
long i=1;
long res=123455;
long res1=0;
long tmp=10;
for (i=0;i<maxIter;i++){
res1+=res%tmp;
tmp++;
}
return res1;
}
public long testLong4(){
long i=1;
long res=1234456;
long res1=10000;
long tmp=-10;
for (i=tmp;i<res;i++){
res1+=res%tmp;
}
return res1;
}
public byte testByte1(){
byte i=127;
byte res=12;
byte res1=1;
for (;i<5;i++){
res1+=res%i;
}
return res1;
}
public byte testByte2(){
byte i=1;
byte res=126;
byte res1=1;
byte tmp=-10;
for (;i<50;i++){
res%=i;
tmp--;
res1=(byte) (res%tmp);
}
return res1;
}
public byte testByte3(){
byte i=1;
byte res=123;
byte res1=1;
byte tmp=1;
for (i=Byte.MIN_VALUE/100;i<Byte.MAX_VALUE/100;i++){
res1+=res%tmp;
tmp++;
}
return res1;
}
public byte testByte4(){
byte i=1;
byte res=123;
byte res1=100;
byte tmp=-10;
for (i=tmp;i<res;i++){
res1+=res%tmp;
}
return res1;
}
public short testShort1(){
short i=1;
short res=1236;
short res1=0;
for (;i<5;i++){
res1+=res%i;
}
return res1;
}
public short testShort2(){
short i=1;
short res=1236;
short res1=0;
short tmp=10;
for (;i<50;i++){
res1+=res%i;
tmp++;
res+=tmp;
}
return res1;
}
public short testShort3(){
short i=1;
short res=1235;
short res1=0;
short tmp=10;
for (i=0/100;i<maxIter/100;i++){
res1+=res%tmp;
tmp++;
}
return res1;
}
public short testShort4(){
short i=1;
short res=12356;
short res1=10000;
short tmp=-10;
for (i=tmp;i<res;i++){
res1+=res%tmp;
}
return res1;
}
public int testFloat1(){
int i=1;
float res=1234567.0f;
float res1=0.0f;
for (;i<5;i++){
res1+=res%i;
}
return Float.floatToIntBits(res1);
}
public int testFloat2(){
int i=1;
float res=1234456.0f;
float res1=0.0f;
float tmp=10.0f;
for (;i<50;i++){
res1+=res%i;
tmp++;
res+=tmp;
}
return Float.floatToIntBits(res1);
}
public int testFloat3(){
int i=1;
float res=1234456.0f;
float res1=0.0f;
float tmp=10.0f;
for (i=00;i<maxIter;i++){
res1+=res%tmp;
tmp++;
}
return Float.floatToIntBits(res1);
}
public int testFloat4(){
int i=1;
float res=12345567.0f;
float res1=10000.0f;
float tmp=-10.0f;
for (i=(int)tmp;i<res;i++){
res1+=res%tmp;
}
return Float.floatToIntBits(res1);
}
public long testDouble1(){
int i=1;
double res=123434576.0;
double res1=0.0;
for (;i<5;i++){
res1+=res%i;
}
return Double.doubleToLongBits(res1);
}
public long testDouble2(){
int i=1;
double res=1234356.0;
double res1=0.0;
double tmp=-10.0;
for (;i<50;i++){
res1+=res%i;
tmp--;
res+=tmp;
}
return Double.doubleToLongBits(res1);
}
public long testDouble3(){
int i=1;
double res=1234456.0;
double res1=0.0;
double tmp=-10.0;
for (i=00;i<maxIter;i++){
res1+=res%tmp;
tmp--;
}
return Double.doubleToLongBits(res1);
}
public long testDouble4(){
int i=1;
double res=11233456.0;
double res1=10000.0;
double tmp=-10.0;
for (i=(int)tmp;i<res;i++){
res1+=res%tmp;
}
return Double.doubleToLongBits(res1);
}
public int testInt5(){
int i=1;
int res=123456;
int tmp=1132322;
for (;i<5;i++){
res%=tmp;
tmp++;
}
return res;
}
public int testInt6(){
int i=1;
int res=12;
int tmp=1122220;
for (;i<50;i++){
res%=tmp;
tmp--;
}
return res;
}
public int testInt7(){
int i=1;
int res=123456778;
int tmp=1123121231;
for (i=0;i<maxIter;i++){
res%=tmp;
tmp++;
}
return res;
}
public int testInt8(){
int i=1;
int res=1234567;
int tmp=10242342;
for (i=tmp;i<res;i++){
res%=tmp++;
}
return res;
}
public long testLong5(){
long i=1;
long res=123456;
long res1=1111110;
for (;i<5;i++){
res%=res1++;
}
return res;
}
public long testLong6(){
long i=1;
long res=123456;
long tmp=1012333;
for (;i<50;i++){
res%=tmp;
tmp++;
}
return res;
}
public long testLong7(){
long i=1;
long res=123455;
long tmp=1034232;
for (i=0;i<maxIter;i++){
res%=tmp;
tmp++;
}
return res;
}
public long testLong8(){
long i=1;
long res=1234456;
long tmp=1123423420;
for (i=tmp;i<res;i++){
res%=tmp++;
}
return res;
}
public byte testByte5(){
byte i=1;
byte res=100;
byte res1=127;
for (;i<5;i++){
res%=res1--;
}
return res;
}
public byte testByte6(){
byte i=1;
byte res=60;
byte res1=127;
for (;i<50;i++){
res%=res1--;
}
return res;
}
public byte testByte7(){
byte i=1;
byte res=1;
byte res1=127;
for (i=Byte.MIN_VALUE;i<Byte.MAX_VALUE;i++){
res%=res1+=128;
}
return res;
}
public byte testByte8(){
byte i=1;
byte res=1;
byte res1=127;
for (i=res;i<res;i++){
res1%=res1;
}
return res;
}
public short testShort5(){
short i=1;
short res=1236;
short res1=12312;
for (;i<5;i++){
res%=res1--;
}
return res;
}
public short testShort6(){
short i=1;
short res=1236;
short res1=12123;
for (;i<50;i++){
res%=res1--;
}
return res;
}
public short testShort7(){
short i=1;
short res=123;
short res1=12311;
for (i=0/100;i<maxIter/100;i++){
res%=res1--;
}
return res;
}
public short testShort8(){
short i=1;
short res=1236;
short res1=10000;
for (;i<res;i++){
res%=res1--;
}
return res;
}
public int testFloat5(){
int i=1;
float res=12347.0f;
float res1=1231110.0f;
for (;i<5;i++){
res%=res1--;
}
return Float.floatToIntBits(res);
}
public int testFloat6(){
int i=1;
float res=1234456.0f;
float res1=123121231212312.0f;
for (;i<50;i++){
res%=res1--;
}
return Float.floatToIntBits(res);
}
public int testFloat7(){
int i=1;
float res=1234456.0f;
float res1=0.0f;
for (i=00;i<maxIter;i++){
res%=res1--;
}
return Float.floatToIntBits(res);
}
public int testFloat8(){
int i=1;
float res=12345567.0f;
float res1=1000123120.0f;
float tmp=-10;
for (i=(int)tmp;i<res;i++){
res%=res1--;
}
return Float.floatToIntBits(res);
}
public long testDouble5(){
int i=1;
double res=123434576.0;
double res1=12311111230.0;
for (;i<5;i++){
res%=res1--;
}
return Double.doubleToLongBits(res);
}
public long testDouble6(){
int i=1;
double res=1234356.0;
double res1=356678545.0;
for (;i<50;i++){
res%=res1--;
}
return Double.doubleToLongBits(res);
}
public long testDouble7(){
int i=1;
double res=1234456.0;
double res1=12312110.0;
for (i=00;i<maxIter;i++){
res%=res1--;
}
return Double.doubleToLongBits(res);
}
public long testDouble8(){
int i=1;
double res=11233456.0;
double res1=10000.0;
for (;i<res;i++){
res%=res1--;
}
return Double.doubleToLongBits(res);
}
}
| |
/**
* Copyright (C) 2016 Hurence (support@hurence.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hurence.logisland.service.hbase;
import com.hurence.logisland.classloading.PluginProxy;
import com.hurence.logisland.component.InitializationException;
import com.hurence.logisland.controller.ControllerServiceInitializationContext;
import com.hurence.logisland.service.hbase.put.PutColumn;
import com.hurence.logisland.service.hbase.put.PutRecord;
import com.hurence.logisland.service.hbase.scan.Column;
import com.hurence.logisland.service.hbase.scan.ResultCell;
import com.hurence.logisland.service.hbase.scan.ResultHandler;
import com.hurence.logisland.service.hbase.security.KerberosProperties;
import com.hurence.logisland.util.runner.TestRunner;
import com.hurence.logisland.util.runner.TestRunners;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.Filter;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.*;
public class TestHBase_1_1_2_ClientService {
private KerberosProperties kerberosPropsWithFile;
private KerberosProperties kerberosPropsWithoutFile;
@Before
public void setup() {
// needed for calls to UserGroupInformation.setConfiguration() to work when passing in
// config with Kerberos authentication enabled
System.setProperty("java.security.krb5.realm", "logisland.com");
System.setProperty("java.security.krb5.kdc", "logisland.kdc");
kerberosPropsWithFile = new KerberosProperties(new File("src/test/resources/krb5.conf"));
kerberosPropsWithoutFile = new KerberosProperties(null);
}
@Test
public void testCustomValidate() throws InitializationException, IOException {
final TestRunner runner = TestRunners.newTestRunner(new TestProcessor());
final String tableName = "logisland";
final Table table = Mockito.mock(Table.class);
when(table.getName()).thenReturn(TableName.valueOf(tableName));
// no conf file or zk properties so should be invalid
final MockHBaseClientService service = new MockHBaseClientService(table);
runner.addControllerService("hbaseClientService", service);
runner.assertNotValid(service);
// conf file with no zk properties should be valid
runner.setProperty(service, HBase_1_1_2_ClientService.HADOOP_CONF_FILES, "src/test/resources/hbase-site.xml");
runner.enableControllerService(service);
runner.assertValid(service);
runner.disableControllerService(service);
// only quorum and no conf file should be invalid
runner.addControllerService("hbaseClientService", service);
runner.setProperty(service, HBase_1_1_2_ClientService.ZOOKEEPER_QUORUM, "localhost");
runner.assertNotValid(service);
// quorum and port, no znode, no conf file, should be invalid
runner.addControllerService("hbaseClientService", service);
runner.setProperty(service, HBase_1_1_2_ClientService.ZOOKEEPER_QUORUM, "localhost");
runner.setProperty(service, HBase_1_1_2_ClientService.ZOOKEEPER_CLIENT_PORT, "2181");
runner.assertNotValid(service);
// quorum, port, and znode, no conf file, should be valid
runner.addControllerService("hbaseClientService", service);
runner.setProperty(service, HBase_1_1_2_ClientService.ZOOKEEPER_QUORUM, "localhost");
runner.setProperty(service, HBase_1_1_2_ClientService.ZOOKEEPER_CLIENT_PORT, "2181");
runner.setProperty(service, HBase_1_1_2_ClientService.ZOOKEEPER_ZNODE_PARENT, "/hbase");
runner.enableControllerService(service);
runner.assertValid(service);
runner.disableControllerService(service);
// quorum and port with conf file should be valid
runner.addControllerService("hbaseClientService", service);
runner.setProperty(service, HBase_1_1_2_ClientService.HADOOP_CONF_FILES, "src/test/resources/hbase-site.xml");
runner.setProperty(service, HBase_1_1_2_ClientService.ZOOKEEPER_QUORUM, "localhost");
runner.setProperty(service, HBase_1_1_2_ClientService.ZOOKEEPER_CLIENT_PORT, "2181");
runner.enableControllerService(service);
runner.assertValid(service);
runner.disableControllerService(service);
// Kerberos - principal with non-set keytab and only hbase-site-security - valid because we need core-site-security to turn on security
runner.addControllerService("hbaseClientService", service);
runner.setProperty(service, HBase_1_1_2_ClientService.HADOOP_CONF_FILES, "src/test/resources/hbase-site-security.xml");
runner.setProperty(service, kerberosPropsWithFile.getKerberosPrincipal(), "test@REALM");
runner.setProperty(service, "logisland.kerberos.krb5.file", "src/test/resources/krb5.conf");
runner.enableControllerService(service);
runner.assertValid(service);
// Kerberos - principal with non-set keytab and both config files
runner.disableControllerService(service);
runner.setProperty(service, HBase_1_1_2_ClientService.HADOOP_CONF_FILES,
"src/test/resources/hbase-site-security.xml, src/test/resources/core-site-security.xml");
runner.assertNotValid(service);
// Kerberos - add valid options
runner.setProperty(service, kerberosPropsWithFile.getKerberosKeytab(), "src/test/resources/fake.keytab");
runner.setProperty(service, kerberosPropsWithFile.getKerberosPrincipal(), "test@REALM");
runner.enableControllerService(service);
runner.assertValid(service);
// Kerberos - add invalid non-existent keytab file
runner.disableControllerService(service);
runner.setProperty(service, kerberosPropsWithFile.getKerberosKeytab(), "src/test/resources/missing.keytab");
runner.assertNotValid(service);
// Kerberos - add invalid principal
runner.setProperty(service, kerberosPropsWithFile.getKerberosKeytab(), "src/test/resources/fake.keytab");
runner.setProperty(service, kerberosPropsWithFile.getKerberosPrincipal(), "");
runner.assertNotValid(service);
// Kerberos - valid props but the KerberosProperties has a null Kerberos config file so be invalid
runner.addControllerService("hbaseClientService", service);
runner.setProperty(service, HBase_1_1_2_ClientService.HADOOP_CONF_FILES,
"src/test/resources/hbase-site-security.xml, src/test/resources/core-site-security.xml");
runner.setProperty(service, kerberosPropsWithoutFile.getKerberosKeytab(), "src/test/resources/fake.keytab");
runner.setProperty(service, kerberosPropsWithoutFile.getKerberosPrincipal(), "test@REALM");
runner.assertNotValid(service);
}
@Test
public void testSinglePut() throws InitializationException, IOException {
final String tableName = "logisland";
final String row = "row1";
final String columnFamily = "family1";
final String columnQualifier = "qualifier1";
final String content = "content1";
final Collection<PutColumn> columns = Collections.singletonList(new PutColumn(columnFamily.getBytes(StandardCharsets.UTF_8), columnQualifier.getBytes(StandardCharsets.UTF_8),
content.getBytes(StandardCharsets.UTF_8)));
final PutRecord putFlowFile = new PutRecord(tableName, row.getBytes(StandardCharsets.UTF_8), columns, null);
final TestRunner runner = TestRunners.newTestRunner(new TestProcessor());
// Mock an HBase Table so we can verify the put operations later
final Table table = Mockito.mock(Table.class);
when(table.getName()).thenReturn(TableName.valueOf(tableName));
// create the controller service and link it to the test processor
final HBaseClientService service = configureHBaseClientService(runner, table);
runner.assertValid(service);
// try to put a single cell
final HBaseClientService hBaseClientService = PluginProxy.unwrap(runner.getProcessContext().getPropertyValue(TestProcessor.HBASE_CLIENT_SERVICE)
.asControllerService());
hBaseClientService.put(tableName, Arrays.asList(putFlowFile));
// verify only one call to put was made
ArgumentCaptor<List> capture = ArgumentCaptor.forClass(List.class);
verify(table, times(1)).put(capture.capture());
// verify only one put was in the list of puts
final List<Put> puts = capture.getValue();
assertEquals(1, puts.size());
verifyPut(row, columnFamily, columnQualifier, content, puts.get(0));
}
@Test
public void testMultiplePutsSameRow() throws IOException, InitializationException {
final String tableName = "logisland";
final String row = "row1";
final String columnFamily = "family1";
final String columnQualifier = "qualifier1";
final String content1 = "content1";
final String content2 = "content2";
final Collection<PutColumn> columns1 = Collections.singletonList(new PutColumn(columnFamily.getBytes(StandardCharsets.UTF_8),
columnQualifier.getBytes(StandardCharsets.UTF_8),
content1.getBytes(StandardCharsets.UTF_8)));
final PutRecord putFlowFile1 = new PutRecord(tableName, row.getBytes(StandardCharsets.UTF_8), columns1, null);
final Collection<PutColumn> columns2 = Collections.singletonList(new PutColumn(columnFamily.getBytes(StandardCharsets.UTF_8),
columnQualifier.getBytes(StandardCharsets.UTF_8),
content2.getBytes(StandardCharsets.UTF_8)));
final PutRecord putFlowFile2 = new PutRecord(tableName, row.getBytes(StandardCharsets.UTF_8), columns2, null);
final TestRunner runner = TestRunners.newTestRunner(new TestProcessor());
// Mock an HBase Table so we can verify the put operations later
final Table table = Mockito.mock(Table.class);
when(table.getName()).thenReturn(TableName.valueOf(tableName));
// create the controller service and link it to the test processor
final HBaseClientService service = configureHBaseClientService(runner, table);
runner.assertValid(service);
// try to put a multiple cells for the same row
final HBaseClientService hBaseClientService = PluginProxy.unwrap(
runner.getProcessContext().getPropertyValue(TestProcessor.HBASE_CLIENT_SERVICE)
.asControllerService());
hBaseClientService.put(tableName, Arrays.asList(putFlowFile1, putFlowFile2));
// verify put was only called once
ArgumentCaptor<List> capture = ArgumentCaptor.forClass(List.class);
verify(table, times(1)).put(capture.capture());
// verify there was only one put in the list of puts
final List<Put> puts = capture.getValue();
assertEquals(1, puts.size());
// verify two cells were added to this one put operation
final NavigableMap<byte[], List<Cell>> familyCells = puts.get(0).getFamilyCellMap();
Map.Entry<byte[], List<Cell>> entry = familyCells.firstEntry();
assertEquals(2, entry.getValue().size());
}
@Test
public void testMultiplePutsDifferentRow() throws IOException, InitializationException {
final String tableName = "logisland";
final String row1 = "row1";
final String row2 = "row2";
final String columnFamily = "family1";
final String columnQualifier = "qualifier1";
final String content1 = "content1";
final String content2 = "content2";
final Collection<PutColumn> columns1 = Collections.singletonList(new PutColumn(columnFamily.getBytes(StandardCharsets.UTF_8),
columnQualifier.getBytes(StandardCharsets.UTF_8),
content1.getBytes(StandardCharsets.UTF_8)));
final PutRecord putFlowFile1 = new PutRecord(tableName, row1.getBytes(StandardCharsets.UTF_8), columns1, null);
final Collection<PutColumn> columns2 = Collections.singletonList(new PutColumn(columnFamily.getBytes(StandardCharsets.UTF_8),
columnQualifier.getBytes(StandardCharsets.UTF_8),
content2.getBytes(StandardCharsets.UTF_8)));
final PutRecord putFlowFile2 = new PutRecord(tableName, row2.getBytes(StandardCharsets.UTF_8), columns2, null);
final TestRunner runner = TestRunners.newTestRunner(new TestProcessor());
// Mock an HBase Table so we can verify the put operations later
final Table table = Mockito.mock(Table.class);
when(table.getName()).thenReturn(TableName.valueOf(tableName));
// create the controller service and link it to the test processor
final HBaseClientService service = configureHBaseClientService(runner, table);
runner.assertValid(service);
// try to put a multiple cells with different rows
final HBaseClientService hBaseClientService = PluginProxy.unwrap(runner.getProcessContext().getPropertyValue(TestProcessor.HBASE_CLIENT_SERVICE)
.asControllerService());
hBaseClientService.put(tableName, Arrays.asList(putFlowFile1, putFlowFile2));
// verify put was only called once
ArgumentCaptor<List> capture = ArgumentCaptor.forClass(List.class);
verify(table, times(1)).put(capture.capture());
// verify there were two puts in the list
final List<Put> puts = capture.getValue();
assertEquals(2, puts.size());
}
@Test
public void testScan() throws InitializationException, IOException {
final String tableName = "logisland";
final TestRunner runner = TestRunners.newTestRunner(new TestProcessor());
// Mock an HBase Table so we can verify the put operations later
final Table table = Mockito.mock(Table.class);
when(table.getName()).thenReturn(TableName.valueOf(tableName));
// create the controller service and link it to the test processor
final MockHBaseClientService service = configureHBaseClientService(runner, table);
runner.assertValid(service);
// stage some results in the mock service...
final long now = System.currentTimeMillis();
final Map<String, String> cells = new HashMap<>();
cells.put("greeting", "hello");
cells.put("name", "logisland");
service.addResult("row0", cells, now - 2);
service.addResult("row1", cells, now - 1);
service.addResult("row2", cells, now - 1);
service.addResult("row3", cells, now);
// perform a scan and verify the four rows were returned
final CollectingResultHandler handler = new CollectingResultHandler();
final HBaseClientService hBaseClientService = PluginProxy.unwrap(runner.getProcessContext().getPropertyValue(TestProcessor.HBASE_CLIENT_SERVICE)
.asControllerService());
hBaseClientService.scan(tableName, new ArrayList<Column>(), null, now, handler);
assertEquals(4, handler.results.size());
// get row0 using the row id and verify it has 2 cells
final ResultCell[] results = handler.results.get("row0");
assertNotNull(results);
assertEquals(2, results.length);
verifyResultCell(results[0], "logisland", "greeting", "hello");
verifyResultCell(results[1], "logisland", "name", "logisland");
}
@Test
public void testScanWithValidFilter() throws InitializationException, IOException {
final String tableName = "logisland";
final TestRunner runner = TestRunners.newTestRunner(new TestProcessor());
// Mock an HBase Table so we can verify the put operations later
final Table table = Mockito.mock(Table.class);
when(table.getName()).thenReturn(TableName.valueOf(tableName));
// create the controller service and link it to the test processor
final MockHBaseClientService service = configureHBaseClientService(runner, table);
runner.assertValid(service);
// perform a scan and verify the four rows were returned
final CollectingResultHandler handler = new CollectingResultHandler();
final HBaseClientService hBaseClientService = PluginProxy.unwrap(runner.getProcessContext().getPropertyValue(TestProcessor.HBASE_CLIENT_SERVICE)
.asControllerService());
// make sure we parse the filter expression without throwing an exception
final String filter = "PrefixFilter ('Row') AND PageFilter (1) AND FirstKeyOnlyFilter ()";
hBaseClientService.scan(tableName, new ArrayList<Column>(), filter, System.currentTimeMillis(), handler);
}
@Test(expected = IllegalArgumentException.class)
public void testScanWithInvalidFilter() throws InitializationException, IOException {
final String tableName = "logisland";
final TestRunner runner = TestRunners.newTestRunner(new TestProcessor());
// Mock an HBase Table so we can verify the put operations later
final Table table = Mockito.mock(Table.class);
when(table.getName()).thenReturn(TableName.valueOf(tableName));
// create the controller service and link it to the test processor
final MockHBaseClientService service = configureHBaseClientService(runner, table);
runner.assertValid(service);
// perform a scan and verify the four rows were returned
final CollectingResultHandler handler = new CollectingResultHandler();
final HBaseClientService hBaseClientService = PluginProxy.unwrap(
runner.getProcessContext().getPropertyValue(TestProcessor.HBASE_CLIENT_SERVICE)
.asControllerService());
// this should throw IllegalArgumentException
final String filter = "this is not a filter";
hBaseClientService.scan(tableName, new ArrayList<Column>(), filter, System.currentTimeMillis(), handler);
}
private MockHBaseClientService configureHBaseClientService(final TestRunner runner, final Table table) throws InitializationException {
final MockHBaseClientService service = new MockHBaseClientService(table);
runner.addControllerService("hbaseClient", service);
runner.setProperty(service, HBase_1_1_2_ClientService.HADOOP_CONF_FILES, "src/test/resources/hbase-site.xml");
runner.enableControllerService(service);
runner.setProperty(TestProcessor.HBASE_CLIENT_SERVICE, "hbaseClient");
return service;
}
private void verifyResultCell(final ResultCell result, final String cf, final String cq, final String val) {
final String colFamily = new String(result.getFamilyArray(), result.getFamilyOffset(), result.getFamilyLength());
assertEquals(cf, colFamily);
final String colQualifier = new String(result.getQualifierArray(), result.getQualifierOffset(), result.getQualifierLength());
assertEquals(cq, colQualifier);
final String value = new String(result.getValueArray(), result.getValueOffset(), result.getValueLength());
assertEquals(val, value);
}
private void verifyPut(String row, String columnFamily, String columnQualifier, String content, Put put) {
assertEquals(row, new String(put.getRow()));
NavigableMap<byte[], List<Cell>> familyCells = put.getFamilyCellMap();
assertEquals(1, familyCells.size());
Map.Entry<byte[], List<Cell>> entry = familyCells.firstEntry();
assertEquals(columnFamily, new String(entry.getKey()));
assertEquals(1, entry.getValue().size());
Cell cell = entry.getValue().get(0);
assertEquals(columnQualifier, new String(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength()));
assertEquals(content, new String(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
}
// Override methods to create a mock service that can return staged data
private class MockHBaseClientService extends HBase_1_1_2_ClientService {
private Table table;
private List<Result> results = new ArrayList<>();
public MockHBaseClientService(final Table table) {
this.table = table;
}
public void addResult(final String rowKey, final Map<String, String> cells, final long timestamp) {
final byte[] rowArray = rowKey.getBytes(StandardCharsets.UTF_8);
final Cell[] cellArray = new Cell[cells.size()];
int i = 0;
for (final Map.Entry<String, String> cellEntry : cells.entrySet()) {
final Cell cell = Mockito.mock(Cell.class);
when(cell.getRowArray()).thenReturn(rowArray);
when(cell.getRowOffset()).thenReturn(0);
when(cell.getRowLength()).thenReturn((short) rowArray.length);
final String cellValue = cellEntry.getValue();
final byte[] valueArray = cellValue.getBytes(StandardCharsets.UTF_8);
when(cell.getValueArray()).thenReturn(valueArray);
when(cell.getValueOffset()).thenReturn(0);
when(cell.getValueLength()).thenReturn(valueArray.length);
final byte[] familyArray = "logisland".getBytes(StandardCharsets.UTF_8);
when(cell.getFamilyArray()).thenReturn(familyArray);
when(cell.getFamilyOffset()).thenReturn(0);
when(cell.getFamilyLength()).thenReturn((byte) familyArray.length);
final String qualifier = cellEntry.getKey();
final byte[] qualifierArray = qualifier.getBytes(StandardCharsets.UTF_8);
when(cell.getQualifierArray()).thenReturn(qualifierArray);
when(cell.getQualifierOffset()).thenReturn(0);
when(cell.getQualifierLength()).thenReturn(qualifierArray.length);
when(cell.getTimestamp()).thenReturn(timestamp);
cellArray[i++] = cell;
}
final Result result = Mockito.mock(Result.class);
when(result.getRow()).thenReturn(rowArray);
when(result.rawCells()).thenReturn(cellArray);
results.add(result);
}
@Override
protected ResultScanner getResults(Table table, Collection<Column> columns, Filter filter, long minTime) throws IOException {
final ResultScanner scanner = Mockito.mock(ResultScanner.class);
Mockito.when(scanner.iterator()).thenReturn(results.iterator());
return scanner;
}
@Override
protected Connection createConnection(ControllerServiceInitializationContext context) throws IOException {
Connection connection = Mockito.mock(Connection.class);
Mockito.when(connection.getTable(table.getName())).thenReturn(table);
return connection;
}
}
// handler that saves results for verification
private static final class CollectingResultHandler implements ResultHandler {
Map<String, ResultCell[]> results = new LinkedHashMap<>();
@Override
public void handle(byte[] row, ResultCell[] resultCells) {
final String rowStr = new String(row, StandardCharsets.UTF_8);
results.put(rowStr, resultCells);
}
}
}
| |
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.percentlayout.widget;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import android.os.Build;
import android.support.test.filters.SmallTest;
import android.view.View;
import androidx.core.view.ViewCompat;
import androidx.percentlayout.test.R;
import org.junit.Before;
import org.junit.Test;
/**
* The arrangement of child views in the layout class in the default LTR (left-to-right) direction
* is as follows:
*
* +---------------------------------------------+
* | |
* | TTTTTTTTTTTTTTTTTTTTT |
* | |
* | S |
* | S CCCCCCCCCCCCCCCCCC |
* | S CCCCCCCCCCCCCCCCCC |
* | S CCCCCCCCCCCCCCCCCC E |
* | S CCCCCCCCCCCCCCCCCC E |
* | S CCCCCCCCCCCCCCCCCC E |
* | CCCCCCCCCCCCCCCCCC E |
* | CCCCCCCCCCCCCCCCCC E |
* | E |
* | |
* | BBBBBBBBBBBBBBBBBBBBB |
* | |
* +---------------------------------------------+
*
* The arrangement of child views in the layout class in the RTL (right-to-left) direction
* is as follows:
*
* +---------------------------------------------+
* | |
* | TTTTTTTTTTTTTTTTTTTTT |
* | |
* | S |
* | CCCCCCCCCCCCCCCCCC S |
* | CCCCCCCCCCCCCCCCCC S |
* | E CCCCCCCCCCCCCCCCCC S |
* | E CCCCCCCCCCCCCCCCCC S |
* | E CCCCCCCCCCCCCCCCCC S |
* | E CCCCCCCCCCCCCCCCCC |
* | E CCCCCCCCCCCCCCCCCC |
* | E |
* | |
* | BBBBBBBBBBBBBBBBBBBBB |
* | |
* +---------------------------------------------+
*
* Child views are exercising the following percent-based constraints supported by
* <code>PercentRelativeLayout</code>:
*
* <ul>
* <li>Top child (marked with T) - width, aspect ratio, top margin, start margin.</li>
* <li>Start child (marked with S) - height, aspect ratio, top margin, start margin.</li>
* <li>Bottom child (marked with B) - width, aspect ratio, bottom margin, end margin.</li>
* <li>Right child (marked with E) - height, aspect ratio, bottom margin, end margin.</li>
* <li>Center child (marked with C) - margin (all sides) from the other four children.</li>
* </ul>
*
* Under LTR direction (pre-v17 devices and v17+ with default direction of en-US locale) we are
* testing the same assertions as <code>PercentRelativeTest</code>. Under RTL direction (on v17+
* devices with Espresso-powered direction switch) we are testing the reverse assertions along the
* X axis for all child views.
*
* Note that due to a bug in the core {@link RelativeLayout} (base class of
* {@link PercentRelativeLayout}) in how it treats end margin of child views on v17 devices, we are
* skipping all tests in this class for v17 devices. This is in line with the overall contract
* of percent-based layouts provided by the support library - we do not work around / fix bugs in
* the core classes, but rather just provide a translation layer between percentage-based values
* and pixel-based ones.
*/
@SmallTest
public class PercentRelativeRtlTest extends BaseInstrumentationTestCase<TestRelativeRtlActivity> {
private PercentRelativeLayout mPercentRelativeLayout;
private int mContainerWidth;
private int mContainerHeight;
public PercentRelativeRtlTest() {
super(TestRelativeRtlActivity.class);
}
@Before
public void setUp() throws Exception {
final TestRelativeRtlActivity activity = mActivityTestRule.getActivity();
mPercentRelativeLayout = (PercentRelativeLayout) activity.findViewById(R.id.container);
mContainerWidth = mPercentRelativeLayout.getWidth();
mContainerHeight = mPercentRelativeLayout.getHeight();
}
private void switchToRtl() {
// Force the container to RTL mode
onView(withId(R.id.container)).perform(
LayoutDirectionActions.setLayoutDirection(ViewCompat.LAYOUT_DIRECTION_RTL));
// Force a full measure + layout pass on the container
mPercentRelativeLayout.measure(
View.MeasureSpec.makeMeasureSpec(mContainerWidth, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(mContainerHeight, View.MeasureSpec.EXACTLY));
mPercentRelativeLayout.layout(mPercentRelativeLayout.getLeft(),
mPercentRelativeLayout.getTop(), mPercentRelativeLayout.getRight(),
mPercentRelativeLayout.getBottom());
}
@Test
public void testTopChild() {
if (Build.VERSION.SDK_INT == 17) {
return;
}
final View childToTest = mPercentRelativeLayout.findViewById(R.id.child_top);
if (Build.VERSION.SDK_INT >= 17) {
switchToRtl();
final int childRight = childToTest.getRight();
assertFuzzyEquals("Child start margin as 20% of the container",
0.2f * mContainerWidth, mContainerWidth - childRight);
} else {
final int childLeft = childToTest.getLeft();
assertFuzzyEquals("Child start margin as 20% of the container",
0.2f * mContainerWidth, childLeft);
}
final int childTop = childToTest.getTop();
assertFuzzyEquals("Child top margin as 5% of the container",
0.05f * mContainerHeight, childTop);
final int childWidth = childToTest.getWidth();
final int childHeight = childToTest.getHeight();
assertFuzzyEquals("Child width as 50% of the container",
0.5f * mContainerWidth, childWidth);
assertFuzzyEquals("Child aspect ratio of 2000%",
0.05f * childWidth, childHeight);
}
@Test
public void testStartChild() {
if (Build.VERSION.SDK_INT == 17) {
return;
}
final View childToTest = mPercentRelativeLayout.findViewById(R.id.child_start);
if (Build.VERSION.SDK_INT >= 17) {
switchToRtl();
final int childRight = childToTest.getRight();
assertFuzzyEquals("Child start margin as 5% of the container",
0.05f * mContainerWidth, mContainerWidth - childRight);
} else {
final int childLeft = childToTest.getLeft();
assertFuzzyEquals("Child start margin as 5% of the container",
0.05f * mContainerWidth, childLeft);
}
final int childWidth = childToTest.getWidth();
final int childHeight = childToTest.getHeight();
assertFuzzyEquals("Child height as 50% of the container",
0.5f * mContainerHeight, childHeight);
assertFuzzyEquals("Child aspect ratio of 5%",
0.05f * childHeight, childWidth);
final int childTop = childToTest.getTop();
assertFuzzyEquals("Child top margin as 20% of the container",
0.2f * mContainerHeight, childTop);
}
@Test
public void testBottomChild() {
if (Build.VERSION.SDK_INT == 17) {
return;
}
final View childToTest = mPercentRelativeLayout.findViewById(R.id.child_bottom);
if (Build.VERSION.SDK_INT >= 17) {
switchToRtl();
final int childLeft = childToTest.getLeft();
assertFuzzyEquals("Child end margin as 20% of the container",
0.2f * mContainerWidth, childLeft);
} else {
final int childRight = childToTest.getRight();
assertFuzzyEquals("Child end margin as 20% of the container",
0.2f * mContainerWidth, mContainerWidth - childRight);
}
final int childWidth = childToTest.getWidth();
final int childHeight = childToTest.getHeight();
assertFuzzyEquals("Child width as 40% of the container",
0.4f * mContainerWidth, childWidth);
assertFuzzyEquals("Child aspect ratio of 2000%",
0.05f * childWidth, childHeight);
final int childBottom = childToTest.getBottom();
assertFuzzyEquals("Child bottom margin as 5% of the container",
0.05f * mContainerHeight, mContainerHeight - childBottom);
}
@Test
public void testEndChild() {
if (Build.VERSION.SDK_INT == 17) {
return;
}
final View childToTest = mPercentRelativeLayout.findViewById(R.id.child_end);
if (Build.VERSION.SDK_INT >= 17) {
switchToRtl();
final int childLeft = childToTest.getLeft();
assertFuzzyEquals("Child end margin as 5% of the container",
0.05f * mContainerWidth, childLeft);
} else {
final int childRight = childToTest.getRight();
assertFuzzyEquals("Child end margin as 5% of the container",
0.05f * mContainerWidth, mContainerWidth - childRight);
}
final int childWidth = childToTest.getWidth();
final int childHeight = childToTest.getHeight();
assertFuzzyEquals("Child height as 50% of the container",
0.4f * mContainerHeight, childHeight);
assertFuzzyEquals("Child aspect ratio of 5%",
0.05f * childHeight, childWidth);
final int childBottom = childToTest.getBottom();
assertFuzzyEquals("Child bottom margin as 20% of the container",
0.2f * mContainerHeight, mContainerHeight - childBottom);
}
@Test
public void testCenterChild() {
if (Build.VERSION.SDK_INT == 17) {
return;
}
final View childToTest = mPercentRelativeLayout.findViewById(R.id.child_center);
boolean supportsRtl = Build.VERSION.SDK_INT >= 17;
if (supportsRtl) {
switchToRtl();
}
final int childLeft = childToTest.getLeft();
final int childTop = childToTest.getTop();
final int childRight = childToTest.getRight();
final int childBottom = childToTest.getBottom();
final View leftChild = supportsRtl
? mPercentRelativeLayout.findViewById(R.id.child_end)
: mPercentRelativeLayout.findViewById(R.id.child_start);
assertFuzzyEquals("Child left margin as 10% of the container",
leftChild.getRight() + 0.1f * mContainerWidth, childLeft);
final View topChild = mPercentRelativeLayout.findViewById(R.id.child_top);
assertFuzzyEquals("Child top margin as 10% of the container",
topChild.getBottom() + 0.1f * mContainerHeight, childTop);
final View rightChild = supportsRtl
? mPercentRelativeLayout.findViewById(R.id.child_start)
: mPercentRelativeLayout.findViewById(R.id.child_end);
assertFuzzyEquals("Child right margin as 10% of the container",
rightChild.getLeft() - 0.1f * mContainerWidth, childRight);
final View bottomChild = mPercentRelativeLayout.findViewById(R.id.child_bottom);
assertFuzzyEquals("Child bottom margin as 10% of the container",
bottomChild.getTop() - 0.1f * mContainerHeight, childBottom);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.mbeans;
import java.util.Set;
import javax.management.DynamicMBean;
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.Group;
import org.apache.catalina.Loader;
import org.apache.catalina.Role;
import org.apache.catalina.Server;
import org.apache.catalina.User;
import org.apache.catalina.UserDatabase;
import org.apache.catalina.util.ContextName;
import org.apache.tomcat.util.descriptor.web.ContextEnvironment;
import org.apache.tomcat.util.descriptor.web.ContextResource;
import org.apache.tomcat.util.descriptor.web.ContextResourceLink;
import org.apache.tomcat.util.modeler.ManagedBean;
import org.apache.tomcat.util.modeler.Registry;
/**
* Public utility methods in support of the server side MBeans implementation.
*
* @author Craig R. McClanahan
* @author Amy Roh
*/
public class MBeanUtils {
// ------------------------------------------------------- Static Variables
/**
* The set of exceptions to the normal rules used by
* <code>createManagedBean()</code>. The first element of each pair
* is a class name, and the second element is the managed bean name.
*/
private static final String exceptions[][] = {
{ "org.apache.catalina.users.MemoryGroup",
"Group" },
{ "org.apache.catalina.users.MemoryRole",
"Role" },
{ "org.apache.catalina.users.MemoryUser",
"User" },
};
/**
* The configuration information registry for our managed beans.
*/
private static Registry registry = createRegistry();
/**
* The <code>MBeanServer</code> for this application.
*/
private static MBeanServer mserver = createServer();
// --------------------------------------------------------- Static Methods
/**
* Create and return the name of the <code>ManagedBean</code> that
* corresponds to this Catalina component.
*
* @param component The component for which to create a name
*/
static String createManagedName(Object component) {
// Deal with exceptions to the standard rule
String className = component.getClass().getName();
for (int i = 0; i < exceptions.length; i++) {
if (className.equals(exceptions[i][0])) {
return (exceptions[i][1]);
}
}
// Perform the standard transformation
int period = className.lastIndexOf('.');
if (period >= 0)
className = className.substring(period + 1);
return (className);
}
/**
* Create, register, and return an MBean for this
* <code>ContextEnvironment</code> object.
*
* @param environment The ContextEnvironment to be managed
* @return a new MBean
* @exception Exception if an MBean cannot be created or registered
*/
public static DynamicMBean createMBean(ContextEnvironment environment)
throws Exception {
String mname = createManagedName(environment);
ManagedBean managed = registry.findManagedBean(mname);
if (managed == null) {
Exception e = new Exception("ManagedBean is not found with "+mname);
throw new MBeanException(e);
}
String domain = managed.getDomain();
if (domain == null)
domain = mserver.getDefaultDomain();
DynamicMBean mbean = managed.createMBean(environment);
ObjectName oname = createObjectName(domain, environment);
if( mserver.isRegistered( oname )) {
mserver.unregisterMBean(oname);
}
mserver.registerMBean(mbean, oname);
return (mbean);
}
/**
* Create, register, and return an MBean for this
* <code>ContextResource</code> object.
*
* @param resource The ContextResource to be managed
* @return a new MBean
* @exception Exception if an MBean cannot be created or registered
*/
public static DynamicMBean createMBean(ContextResource resource)
throws Exception {
String mname = createManagedName(resource);
ManagedBean managed = registry.findManagedBean(mname);
if (managed == null) {
Exception e = new Exception("ManagedBean is not found with "+mname);
throw new MBeanException(e);
}
String domain = managed.getDomain();
if (domain == null)
domain = mserver.getDefaultDomain();
DynamicMBean mbean = managed.createMBean(resource);
ObjectName oname = createObjectName(domain, resource);
if( mserver.isRegistered( oname )) {
mserver.unregisterMBean(oname);
}
mserver.registerMBean(mbean, oname);
return (mbean);
}
/**
* Create, register, and return an MBean for this
* <code>ContextResourceLink</code> object.
*
* @param resourceLink The ContextResourceLink to be managed
* @return a new MBean
* @exception Exception if an MBean cannot be created or registered
*/
public static DynamicMBean createMBean(ContextResourceLink resourceLink)
throws Exception {
String mname = createManagedName(resourceLink);
ManagedBean managed = registry.findManagedBean(mname);
if (managed == null) {
Exception e = new Exception("ManagedBean is not found with "+mname);
throw new MBeanException(e);
}
String domain = managed.getDomain();
if (domain == null)
domain = mserver.getDefaultDomain();
DynamicMBean mbean = managed.createMBean(resourceLink);
ObjectName oname = createObjectName(domain, resourceLink);
if( mserver.isRegistered( oname )) {
mserver.unregisterMBean(oname);
}
mserver.registerMBean(mbean, oname);
return (mbean);
}
/**
* Create, register, and return an MBean for this
* <code>Group</code> object.
*
* @param group The Group to be managed
* @return a new MBean
* @exception Exception if an MBean cannot be created or registered
*/
static DynamicMBean createMBean(Group group)
throws Exception {
String mname = createManagedName(group);
ManagedBean managed = registry.findManagedBean(mname);
if (managed == null) {
Exception e = new Exception("ManagedBean is not found with "+mname);
throw new MBeanException(e);
}
String domain = managed.getDomain();
if (domain == null)
domain = mserver.getDefaultDomain();
DynamicMBean mbean = managed.createMBean(group);
ObjectName oname = createObjectName(domain, group);
if( mserver.isRegistered( oname )) {
mserver.unregisterMBean(oname);
}
mserver.registerMBean(mbean, oname);
return (mbean);
}
/**
* Create, register, and return an MBean for this
* <code>Role</code> object.
*
* @param role The Role to be managed
* @return a new MBean
* @exception Exception if an MBean cannot be created or registered
*/
static DynamicMBean createMBean(Role role)
throws Exception {
String mname = createManagedName(role);
ManagedBean managed = registry.findManagedBean(mname);
if (managed == null) {
Exception e = new Exception("ManagedBean is not found with "+mname);
throw new MBeanException(e);
}
String domain = managed.getDomain();
if (domain == null)
domain = mserver.getDefaultDomain();
DynamicMBean mbean = managed.createMBean(role);
ObjectName oname = createObjectName(domain, role);
if( mserver.isRegistered( oname )) {
mserver.unregisterMBean(oname);
}
mserver.registerMBean(mbean, oname);
return (mbean);
}
/**
* Create, register, and return an MBean for this
* <code>User</code> object.
*
* @param user The User to be managed
* @return a new MBean
* @exception Exception if an MBean cannot be created or registered
*/
static DynamicMBean createMBean(User user)
throws Exception {
String mname = createManagedName(user);
ManagedBean managed = registry.findManagedBean(mname);
if (managed == null) {
Exception e = new Exception("ManagedBean is not found with "+mname);
throw new MBeanException(e);
}
String domain = managed.getDomain();
if (domain == null)
domain = mserver.getDefaultDomain();
DynamicMBean mbean = managed.createMBean(user);
ObjectName oname = createObjectName(domain, user);
if( mserver.isRegistered( oname )) {
mserver.unregisterMBean(oname);
}
mserver.registerMBean(mbean, oname);
return (mbean);
}
/**
* Create, register, and return an MBean for this
* <code>UserDatabase</code> object.
*
* @param userDatabase The UserDatabase to be managed
* @return a new MBean
* @exception Exception if an MBean cannot be created or registered
*/
static DynamicMBean createMBean(UserDatabase userDatabase)
throws Exception {
String mname = createManagedName(userDatabase);
ManagedBean managed = registry.findManagedBean(mname);
if (managed == null) {
Exception e = new Exception("ManagedBean is not found with "+mname);
throw new MBeanException(e);
}
String domain = managed.getDomain();
if (domain == null)
domain = mserver.getDefaultDomain();
DynamicMBean mbean = managed.createMBean(userDatabase);
ObjectName oname = createObjectName(domain, userDatabase);
if( mserver.isRegistered( oname )) {
mserver.unregisterMBean(oname);
}
mserver.registerMBean(mbean, oname);
return (mbean);
}
/**
* Create an <code>ObjectName</code> for this
* <code>Service</code> object.
*
* @param domain Domain in which this name is to be created
* @param environment The ContextEnvironment to be named
* @return a new object name
* @exception MalformedObjectNameException if a name cannot be created
*/
public static ObjectName createObjectName(String domain,
ContextEnvironment environment)
throws MalformedObjectNameException {
ObjectName name = null;
Object container =
environment.getNamingResources().getContainer();
if (container instanceof Server) {
name = new ObjectName(domain + ":type=Environment" +
",resourcetype=Global,name=" + environment.getName());
} else if (container instanceof Context) {
Context context = ((Context)container);
ContextName cn = new ContextName(context.getName(), false);
Container host = context.getParent();
name = new ObjectName(domain + ":type=Environment" +
",resourcetype=Context,host=" + host.getName() +
",context=" + cn.getDisplayName() +
",name=" + environment.getName());
}
return (name);
}
/**
* Create an <code>ObjectName</code> for this
* <code>ContextResource</code> object.
*
* @param domain Domain in which this name is to be created
* @param resource The ContextResource to be named
* @return a new object name
* @exception MalformedObjectNameException if a name cannot be created
*/
public static ObjectName createObjectName(String domain,
ContextResource resource)
throws MalformedObjectNameException {
ObjectName name = null;
String quotedResourceName = ObjectName.quote(resource.getName());
Object container =
resource.getNamingResources().getContainer();
if (container instanceof Server) {
name = new ObjectName(domain + ":type=Resource" +
",resourcetype=Global,class=" + resource.getType() +
",name=" + quotedResourceName);
} else if (container instanceof Context) {
Context context = ((Context)container);
ContextName cn = new ContextName(context.getName(), false);
Container host = context.getParent();
name = new ObjectName(domain + ":type=Resource" +
",resourcetype=Context,host=" + host.getName() +
",context=" + cn.getDisplayName() +
",class=" + resource.getType() +
",name=" + quotedResourceName);
}
return (name);
}
/**
* Create an <code>ObjectName</code> for this
* <code>ContextResourceLink</code> object.
*
* @param domain Domain in which this name is to be created
* @param resourceLink The ContextResourceLink to be named
* @return a new object name
* @exception MalformedObjectNameException if a name cannot be created
*/
public static ObjectName createObjectName(String domain,
ContextResourceLink resourceLink)
throws MalformedObjectNameException {
ObjectName name = null;
String quotedResourceLinkName
= ObjectName.quote(resourceLink.getName());
Object container =
resourceLink.getNamingResources().getContainer();
if (container instanceof Server) {
name = new ObjectName(domain + ":type=ResourceLink" +
",resourcetype=Global" +
",name=" + quotedResourceLinkName);
} else if (container instanceof Context) {
Context context = ((Context)container);
ContextName cn = new ContextName(context.getName(), false);
Container host = context.getParent();
name = new ObjectName(domain + ":type=ResourceLink" +
",resourcetype=Context,host=" + host.getName() +
",context=" + cn.getDisplayName() +
",name=" + quotedResourceLinkName);
}
return (name);
}
/**
* Create an <code>ObjectName</code> for this
* <code>Group</code> object.
*
* @param domain Domain in which this name is to be created
* @param group The Group to be named
* @return a new object name
* @exception MalformedObjectNameException if a name cannot be created
*/
static ObjectName createObjectName(String domain,
Group group)
throws MalformedObjectNameException {
ObjectName name = null;
name = new ObjectName(domain + ":type=Group,groupname=" +
ObjectName.quote(group.getGroupname()) +
",database=" + group.getUserDatabase().getId());
return (name);
}
/**
* Create an <code>ObjectName</code> for this
* <code>Loader</code> object.
*
* @param domain Domain in which this name is to be created
* @param loader The Loader to be named
* @return a new object name
* @exception MalformedObjectNameException if a name cannot be created
*/
static ObjectName createObjectName(String domain, Loader loader)
throws MalformedObjectNameException {
ObjectName name = null;
Context context = loader.getContext();
ContextName cn = new ContextName(context.getName(), false);
Container host = context.getParent();
name = new ObjectName(domain + ":type=Loader,host=" + host.getName() +
",context=" + cn.getDisplayName());
return name;
}
/**
* Create an <code>ObjectName</code> for this
* <code>Role</code> object.
*
* @param domain Domain in which this name is to be created
* @param role The Role to be named
* @return a new object name
* @exception MalformedObjectNameException if a name cannot be created
*/
static ObjectName createObjectName(String domain, Role role)
throws MalformedObjectNameException {
ObjectName name = new ObjectName(domain + ":type=Role,rolename=" +
ObjectName.quote(role.getRolename()) +
",database=" + role.getUserDatabase().getId());
return name;
}
/**
* Create an <code>ObjectName</code> for this
* <code>User</code> object.
*
* @param domain Domain in which this name is to be created
* @param user The User to be named
* @return a new object name
* @exception MalformedObjectNameException if a name cannot be created
*/
static ObjectName createObjectName(String domain, User user)
throws MalformedObjectNameException {
ObjectName name = new ObjectName(domain + ":type=User,username=" +
ObjectName.quote(user.getUsername()) +
",database=" + user.getUserDatabase().getId());
return name;
}
/**
* Create an <code>ObjectName</code> for this
* <code>UserDatabase</code> object.
*
* @param domain Domain in which this name is to be created
* @param userDatabase The UserDatabase to be named
* @return a new object name
* @exception MalformedObjectNameException if a name cannot be created
*/
static ObjectName createObjectName(String domain,
UserDatabase userDatabase)
throws MalformedObjectNameException {
ObjectName name = null;
name = new ObjectName(domain + ":type=UserDatabase,database=" +
userDatabase.getId());
return (name);
}
/**
* Create and configure (if necessary) and return the registry of
* managed object descriptions.
* @return the singleton registry
*/
public static synchronized Registry createRegistry() {
if (registry == null) {
registry = Registry.getRegistry(null, null);
ClassLoader cl = MBeanUtils.class.getClassLoader();
registry.loadDescriptors("org.apache.catalina.mbeans", cl);
registry.loadDescriptors("org.apache.catalina.authenticator", cl);
registry.loadDescriptors("org.apache.catalina.core", cl);
registry.loadDescriptors("org.apache.catalina", cl);
registry.loadDescriptors("org.apache.catalina.deploy", cl);
registry.loadDescriptors("org.apache.catalina.loader", cl);
registry.loadDescriptors("org.apache.catalina.realm", cl);
registry.loadDescriptors("org.apache.catalina.session", cl);
registry.loadDescriptors("org.apache.catalina.startup", cl);
registry.loadDescriptors("org.apache.catalina.users", cl);
registry.loadDescriptors("org.apache.catalina.ha", cl);
registry.loadDescriptors("org.apache.catalina.connector", cl);
registry.loadDescriptors("org.apache.catalina.valves", cl);
registry.loadDescriptors("org.apache.catalina.storeconfig", cl);
registry.loadDescriptors("org.apache.tomcat.util.descriptor.web", cl);
}
return (registry);
}
/**
* Create and configure (if necessary) and return the
* <code>MBeanServer</code> with which we will be
* registering our <code>DynamicMBean</code> implementations.
* @return the singleton MBean server
*/
public static synchronized MBeanServer createServer() {
if (mserver == null) {
mserver = Registry.getRegistry(null, null).getMBeanServer();
}
return (mserver);
}
/**
* Deregister the MBean for this
* <code>ContextEnvironment</code> object.
*
* @param environment The ContextEnvironment to be managed
*
* @exception Exception if an MBean cannot be deregistered
*/
public static void destroyMBean(ContextEnvironment environment)
throws Exception {
String mname = createManagedName(environment);
ManagedBean managed = registry.findManagedBean(mname);
if (managed == null) {
return;
}
String domain = managed.getDomain();
if (domain == null)
domain = mserver.getDefaultDomain();
ObjectName oname = createObjectName(domain, environment);
if( mserver.isRegistered(oname) )
mserver.unregisterMBean(oname);
}
/**
* Deregister the MBean for this
* <code>ContextResource</code> object.
*
* @param resource The ContextResource to be managed
*
* @exception Exception if an MBean cannot be deregistered
*/
public static void destroyMBean(ContextResource resource)
throws Exception {
// If this is a user database resource need to destroy groups, roles,
// users and UserDatabase mbean
if ("org.apache.catalina.UserDatabase".equals(resource.getType())) {
destroyMBeanUserDatabase(resource.getName());
}
String mname = createManagedName(resource);
ManagedBean managed = registry.findManagedBean(mname);
if (managed == null) {
return;
}
String domain = managed.getDomain();
if (domain == null)
domain = mserver.getDefaultDomain();
ObjectName oname = createObjectName(domain, resource);
if( mserver.isRegistered(oname ))
mserver.unregisterMBean(oname);
}
/**
* Deregister the MBean for this
* <code>ContextResourceLink</code> object.
*
* @param resourceLink The ContextResourceLink to be managed
*
* @exception Exception if an MBean cannot be deregistered
*/
public static void destroyMBean(ContextResourceLink resourceLink)
throws Exception {
String mname = createManagedName(resourceLink);
ManagedBean managed = registry.findManagedBean(mname);
if (managed == null) {
return;
}
String domain = managed.getDomain();
if (domain == null)
domain = mserver.getDefaultDomain();
ObjectName oname = createObjectName(domain, resourceLink);
if( mserver.isRegistered(oname) )
mserver.unregisterMBean(oname);
}
/**
* Deregister the MBean for this
* <code>Group</code> object.
*
* @param group The Group to be managed
*
* @exception Exception if an MBean cannot be deregistered
*/
static void destroyMBean(Group group)
throws Exception {
String mname = createManagedName(group);
ManagedBean managed = registry.findManagedBean(mname);
if (managed == null) {
return;
}
String domain = managed.getDomain();
if (domain == null)
domain = mserver.getDefaultDomain();
ObjectName oname = createObjectName(domain, group);
if( mserver.isRegistered(oname) )
mserver.unregisterMBean(oname);
}
/**
* Deregister the MBean for this
* <code>Role</code> object.
*
* @param role The Role to be managed
*
* @exception Exception if an MBean cannot be deregistered
*/
static void destroyMBean(Role role)
throws Exception {
String mname = createManagedName(role);
ManagedBean managed = registry.findManagedBean(mname);
if (managed == null) {
return;
}
String domain = managed.getDomain();
if (domain == null)
domain = mserver.getDefaultDomain();
ObjectName oname = createObjectName(domain, role);
if( mserver.isRegistered(oname) )
mserver.unregisterMBean(oname);
}
/**
* Deregister the MBean for this
* <code>User</code> object.
*
* @param user The User to be managed
*
* @exception Exception if an MBean cannot be deregistered
*/
static void destroyMBean(User user)
throws Exception {
String mname = createManagedName(user);
ManagedBean managed = registry.findManagedBean(mname);
if (managed == null) {
return;
}
String domain = managed.getDomain();
if (domain == null)
domain = mserver.getDefaultDomain();
ObjectName oname = createObjectName(domain, user);
if( mserver.isRegistered(oname) )
mserver.unregisterMBean(oname);
}
/**
* Deregister the MBean for the
* <code>UserDatabase</code> object with this name.
*
* @param userDatabase The UserDatabase to be managed
*
* @exception Exception if an MBean cannot be deregistered
*/
static void destroyMBeanUserDatabase(String userDatabase)
throws Exception {
ObjectName query = null;
Set<ObjectName> results = null;
// Groups
query = new ObjectName(
"Users:type=Group,database=" + userDatabase + ",*");
results = mserver.queryNames(query, null);
for(ObjectName result : results) {
mserver.unregisterMBean(result);
}
// Roles
query = new ObjectName(
"Users:type=Role,database=" + userDatabase + ",*");
results = mserver.queryNames(query, null);
for(ObjectName result : results) {
mserver.unregisterMBean(result);
}
// Users
query = new ObjectName(
"Users:type=User,database=" + userDatabase + ",*");
results = mserver.queryNames(query, null);
for(ObjectName result : results) {
mserver.unregisterMBean(result);
}
// The database itself
ObjectName db = new ObjectName(
"Users:type=UserDatabase,database=" + userDatabase);
if( mserver.isRegistered(db) ) {
mserver.unregisterMBean(db);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.spring;
import java.util.Map;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletContext;
import org.apache.wicket.protocol.http.IWebApplicationFactory;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.protocol.http.WicketFilter;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;
/**
* Implementation of IWebApplicationFactory that pulls the WebApplication object out of spring
* application context.
*
* Configuration example:
*
* <pre>
* <filter>
* <filter-name>MyApplication</filter-name>
* <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
* <init-param>
* <param-name>applicationFactoryClassName</param-name>
* <param-value>org.apache.wicket.spring.SpringWebApplicationFactory</param-value>
* </init-param>
* </filter>
* </pre>
*
* <code>applicationBean</code> init parameter can be used if there are multiple WebApplications
* defined on the spring application context.
*
* Example:
*
* <pre>
* <filter>
* <filter-name>MyApplication</filter-name>
* <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
* <init-param>
* <param-name>applicationFactoryClassName</param-name>
* <param-value>org.apache.wicket.spring.SpringWebApplicationFactory</param-value>
* </init-param>
* <init-param>
* <param-name>applicationBean</param-name>
* <param-value>phonebookApplication</param-value>
* </init-param>
* </filter>
* </pre>
*
* <p>
* This factory is also capable of creating a {@link WebApplication}-specific application context
* (path to which is specified via the {@code contextConfigLocation} filter param) and chaining it
* to the global one
* </p>
*
* <pre>
* <filter>
* <filter-name>MyApplication</filter-name>
* <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
* <init-param>
* <param-name>applicationFactoryClassName</param-name>
* <param-value>org.apache.wicket.spring.SpringWebApplicationFactory</param-value>
* </init-param>
* <init-param>
* <param-name>contextConfigLocation</param-name>
* <param-value>classpath:com/myapplication/customers-app/context.xml</param-value>
* </init-param>
* </filter>
* </pre>
*
* @author Igor Vaynberg (ivaynberg)
* @author Janne Hietamäki (jannehietamaki)
*
*/
public class SpringWebApplicationFactory implements IWebApplicationFactory
{
/** web application context created for this filter, if any */
private ConfigurableWebApplicationContext webApplicationContext;
/**
* Returns location of context config that will be used to create a {@link WebApplication}
* -specific application context.
*
* @param filter
* @return location of context config
*/
protected final String getContextConfigLocation(final WicketFilter filter)
{
String contextConfigLocation;
final FilterConfig filterConfig = filter.getFilterConfig();
contextConfigLocation = filterConfig.getInitParameter("contextConfigLocation");
if (contextConfigLocation == null)
{
final ServletContext servletContext = filterConfig.getServletContext();
contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
}
return contextConfigLocation;
}
/**
* Factory method used to create a new instance of the web application context, by default an
* instance of {@link XmlWebApplicationContext} will be created.
*
* @return application context instance
*/
protected ConfigurableWebApplicationContext newApplicationContext()
{
return new XmlWebApplicationContext();
}
@Override
public WebApplication createApplication(final WicketFilter filter)
{
ServletContext servletContext = filter.getFilterConfig().getServletContext();
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
if (getContextConfigLocation(filter) != null)
{
applicationContext = createWebApplicationContext(applicationContext, filter);
}
String beanName = filter.getFilterConfig().getInitParameter("applicationBean");
return createApplication(applicationContext, beanName);
}
private WebApplication createApplication(final ApplicationContext applicationContext,
final String beanName)
{
WebApplication application;
if (beanName != null)
{
application = (WebApplication)applicationContext.getBean(beanName);
if (application == null)
{
throw new IllegalArgumentException(
"Unable to find WebApplication bean with name [" + beanName + "]");
}
}
else
{
Map<?, ?> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext,
WebApplication.class, false, false);
if (beans.size() == 0)
{
throw new IllegalStateException("bean of type [" + WebApplication.class.getName() +
"] not found");
}
if (beans.size() > 1)
{
throw new IllegalStateException("More than one bean of type [" +
WebApplication.class.getName() + "] found, must have only one");
}
application = (WebApplication)beans.values().iterator().next();
}
// make the application context default for SpringComponentInjectors
SpringComponentInjector.setDefaultContext(application, applicationContext);
return application;
}
/**
* Creates and initializes a new {@link WebApplicationContext}, with the given context as the
* parent. Based on the logic in Spring's FrameworkServlet#createWebApplicationContext()
*
* @param parent
* parent application context
* @param filter
* wicket filter
* @return instance of web application context
* @throws BeansException
*/
protected final ConfigurableWebApplicationContext createWebApplicationContext(
final WebApplicationContext parent, final WicketFilter filter) throws BeansException
{
webApplicationContext = newApplicationContext();
webApplicationContext.setParent(parent);
webApplicationContext.setServletContext(filter.getFilterConfig().getServletContext());
webApplicationContext.setConfigLocation(getContextConfigLocation(filter));
postProcessWebApplicationContext(webApplicationContext, filter);
webApplicationContext.refresh();
return webApplicationContext;
}
/**
* This is a hook for potential subclasses to perform additional processing on the context.
* Based on the logic in Spring's FrameworkServlet#postProcessWebApplicationContext()
*
* @param wac
* additional application context
* @param filter
* wicket filter
*/
protected void postProcessWebApplicationContext(final ConfigurableWebApplicationContext wac,
final WicketFilter filter)
{
// noop
}
@Override
public void destroy(final WicketFilter filter)
{
if (webApplicationContext != null)
{
webApplicationContext.close();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jasper.compiler;
import java.io.ByteArrayInputStream;
import java.io.CharArrayWriter;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ListIterator;
import javax.servlet.jsp.tagext.PageData;
import org.apache.jasper.JasperException;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.AttributesImpl;
/**
* An implementation of <tt>javax.servlet.jsp.tagext.PageData</tt> which
* builds the XML view of a given page.
*
* The XML view is built in two passes:
*
* During the first pass, the FirstPassVisitor collects the attributes of the
* top-level jsp:root and those of the jsp:root elements of any included
* pages, and adds them to the jsp:root element of the XML view.
* In addition, any taglib directives are converted into xmlns: attributes and
* added to the jsp:root element of the XML view.
* This pass ignores any nodes other than JspRoot and TaglibDirective.
*
* During the second pass, the SecondPassVisitor produces the XML view, using
* the combined jsp:root attributes determined in the first pass and any
* remaining pages nodes (this pass ignores any JspRoot and TaglibDirective
* nodes).
*
* @author Jan Luehe
*/
class PageDataImpl extends PageData implements TagConstants {
private static final String JSP_VERSION = "2.0";
private static final String CDATA_START_SECTION = "<![CDATA[\n";
private static final String CDATA_END_SECTION = "]]>\n";
private static final Charset CHARSET_UTF8 = Charset.forName("UTF-8");
// string buffer used to build XML view
private StringBuilder buf;
/**
* Constructor.
*
* @param page the page nodes from which to generate the XML view
*/
public PageDataImpl(Node.Nodes page, Compiler compiler)
throws JasperException {
// First pass
FirstPassVisitor firstPass = new FirstPassVisitor(page.getRoot(),
compiler.getPageInfo());
page.visit(firstPass);
// Second pass
buf = new StringBuilder();
SecondPassVisitor secondPass
= new SecondPassVisitor(page.getRoot(), buf, compiler,
firstPass.getJspIdPrefix());
page.visit(secondPass);
}
/**
* Returns the input stream of the XML view.
*
* @return the input stream of the XML view
*/
@Override
public InputStream getInputStream() {
return new ByteArrayInputStream(buf.toString().getBytes(CHARSET_UTF8));
}
/*
* First-pass Visitor for JspRoot nodes (representing jsp:root elements)
* and TablibDirective nodes, ignoring any other nodes.
*
* The purpose of this Visitor is to collect the attributes of the
* top-level jsp:root and those of the jsp:root elements of any included
* pages, and add them to the jsp:root element of the XML view.
* In addition, this Visitor converts any taglib directives into xmlns:
* attributes and adds them to the jsp:root element of the XML view.
*/
static class FirstPassVisitor
extends Node.Visitor implements TagConstants {
private Node.Root root;
private AttributesImpl rootAttrs;
private PageInfo pageInfo;
// Prefix for the 'id' attribute
private String jspIdPrefix;
/*
* Constructor
*/
public FirstPassVisitor(Node.Root root, PageInfo pageInfo) {
this.root = root;
this.pageInfo = pageInfo;
this.rootAttrs = new AttributesImpl();
this.rootAttrs.addAttribute("", "", "version", "CDATA",
JSP_VERSION);
this.jspIdPrefix = "jsp";
}
@Override
public void visit(Node.Root n) throws JasperException {
visitBody(n);
if (n == root) {
/*
* Top-level page.
*
* Add
* xmlns:jsp="http://java.sun.com/JSP/Page"
* attribute only if not already present.
*/
if (!JSP_URI.equals(rootAttrs.getValue("xmlns:jsp"))) {
rootAttrs.addAttribute("", "", "xmlns:jsp", "CDATA",
JSP_URI);
}
if (pageInfo.isJspPrefixHijacked()) {
/*
* 'jsp' prefix has been hijacked, that is, bound to a
* namespace other than the JSP namespace. This means that
* when adding an 'id' attribute to each element, we can't
* use the 'jsp' prefix. Therefore, create a new prefix
* (one that is unique across the translation unit) for use
* by the 'id' attribute, and bind it to the JSP namespace
*/
jspIdPrefix += "jsp";
while (pageInfo.containsPrefix(jspIdPrefix)) {
jspIdPrefix += "jsp";
}
rootAttrs.addAttribute("", "", "xmlns:" + jspIdPrefix,
"CDATA", JSP_URI);
}
root.setAttributes(rootAttrs);
}
}
@Override
public void visit(Node.JspRoot n) throws JasperException {
addAttributes(n.getTaglibAttributes());
addAttributes(n.getNonTaglibXmlnsAttributes());
addAttributes(n.getAttributes());
visitBody(n);
}
/*
* Converts taglib directive into "xmlns:..." attribute of jsp:root
* element.
*/
@Override
public void visit(Node.TaglibDirective n) throws JasperException {
Attributes attrs = n.getAttributes();
if (attrs != null) {
String qName = "xmlns:" + attrs.getValue("prefix");
/*
* According to javadocs of org.xml.sax.helpers.AttributesImpl,
* the addAttribute method does not check to see if the
* specified attribute is already contained in the list: This
* is the application's responsibility!
*/
if (rootAttrs.getIndex(qName) == -1) {
String location = attrs.getValue("uri");
if (location != null) {
if (location.startsWith("/")) {
location = URN_JSPTLD + location;
}
rootAttrs.addAttribute("", "", qName, "CDATA",
location);
} else {
location = attrs.getValue("tagdir");
rootAttrs.addAttribute("", "", qName, "CDATA",
URN_JSPTAGDIR + location);
}
}
}
}
public String getJspIdPrefix() {
return jspIdPrefix;
}
private void addAttributes(Attributes attrs) {
if (attrs != null) {
int len = attrs.getLength();
for (int i=0; i<len; i++) {
String qName = attrs.getQName(i);
if ("version".equals(qName)) {
continue;
}
// Bugzilla 35252: http://bz.apache.org/bugzilla/show_bug.cgi?id=35252
if(rootAttrs.getIndex(qName) == -1) {
rootAttrs.addAttribute(attrs.getURI(i),
attrs.getLocalName(i),
qName,
attrs.getType(i),
attrs.getValue(i));
}
}
}
}
}
/*
* Second-pass Visitor responsible for producing XML view and assigning
* each element a unique jsp:id attribute.
*/
static class SecondPassVisitor extends Node.Visitor
implements TagConstants {
private Node.Root root;
private StringBuilder buf;
private Compiler compiler;
private String jspIdPrefix;
private boolean resetDefaultNS = false;
// Current value of jsp:id attribute
private int jspId;
/*
* Constructor
*/
public SecondPassVisitor(Node.Root root, StringBuilder buf,
Compiler compiler, String jspIdPrefix) {
this.root = root;
this.buf = buf;
this.compiler = compiler;
this.jspIdPrefix = jspIdPrefix;
}
/*
* Visits root node.
*/
@Override
public void visit(Node.Root n) throws JasperException {
if (n == this.root) {
// top-level page
appendXmlProlog();
appendTag(n);
} else {
boolean resetDefaultNSSave = resetDefaultNS;
if (n.isXmlSyntax()) {
resetDefaultNS = true;
}
visitBody(n);
resetDefaultNS = resetDefaultNSSave;
}
}
/*
* Visits jsp:root element of JSP page in XML syntax.
*
* Any nested jsp:root elements (from pages included via an
* include directive) are ignored.
*/
@Override
public void visit(Node.JspRoot n) throws JasperException {
visitBody(n);
}
@Override
public void visit(Node.PageDirective n) throws JasperException {
appendPageDirective(n);
}
@Override
public void visit(Node.IncludeDirective n) throws JasperException {
// expand in place
visitBody(n);
}
@Override
public void visit(Node.Comment n) throws JasperException {
// Comments are ignored in XML view
}
@Override
public void visit(Node.Declaration n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.Expression n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.Scriptlet n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.JspElement n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.ELExpression n) throws JasperException {
if (!n.getRoot().isXmlSyntax()) {
buf.append("<").append(JSP_TEXT_ACTION);
buf.append(" ");
buf.append(jspIdPrefix);
buf.append(":id=\"");
buf.append(jspId++).append("\">");
}
buf.append("${");
buf.append(JspUtil.escapeXml(n.getText()));
buf.append("}");
if (!n.getRoot().isXmlSyntax()) {
buf.append(JSP_TEXT_ACTION_END);
}
buf.append("\n");
}
@Override
public void visit(Node.IncludeAction n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.ForwardAction n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.GetProperty n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.SetProperty n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.ParamAction n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.ParamsAction n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.FallBackAction n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.UseBean n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.PlugIn n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.NamedAttribute n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.JspBody n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.CustomTag n) throws JasperException {
boolean resetDefaultNSSave = resetDefaultNS;
appendTag(n, resetDefaultNS);
resetDefaultNS = resetDefaultNSSave;
}
@Override
public void visit(Node.UninterpretedTag n) throws JasperException {
boolean resetDefaultNSSave = resetDefaultNS;
appendTag(n, resetDefaultNS);
resetDefaultNS = resetDefaultNSSave;
}
@Override
public void visit(Node.JspText n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.DoBodyAction n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.InvokeAction n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.TagDirective n) throws JasperException {
appendTagDirective(n);
}
@Override
public void visit(Node.AttributeDirective n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.VariableDirective n) throws JasperException {
appendTag(n);
}
@Override
public void visit(Node.TemplateText n) throws JasperException {
/*
* If the template text came from a JSP page written in JSP syntax,
* create a jsp:text element for it (JSP 5.3.2).
*/
appendText(n.getText(), !n.getRoot().isXmlSyntax());
}
/*
* Appends the given tag, including its body, to the XML view.
*/
private void appendTag(Node n) throws JasperException {
appendTag(n, false);
}
/*
* Appends the given tag, including its body, to the XML view,
* and optionally reset default namespace to "", if none specified.
*/
private void appendTag(Node n, boolean addDefaultNS)
throws JasperException {
Node.Nodes body = n.getBody();
String text = n.getText();
buf.append("<").append(n.getQName());
buf.append("\n");
printAttributes(n, addDefaultNS);
buf.append(" ").append(jspIdPrefix).append(":id").append("=\"");
buf.append(jspId++).append("\"\n");
if (ROOT_ACTION.equals(n.getLocalName()) || body != null
|| text != null) {
buf.append(">\n");
if (ROOT_ACTION.equals(n.getLocalName())) {
if (compiler.getCompilationContext().isTagFile()) {
appendTagDirective();
} else {
appendPageDirective();
}
}
if (body != null) {
body.visit(this);
} else {
appendText(text, false);
}
buf.append("</" + n.getQName() + ">\n");
} else {
buf.append("/>\n");
}
}
/*
* Appends the page directive with the given attributes to the XML
* view.
*
* Since the import attribute of the page directive is the only page
* attribute that is allowed to appear multiple times within the same
* document, and since XML allows only single-value attributes,
* the values of multiple import attributes must be combined into one,
* separated by comma.
*
* If the given page directive contains just 'contentType' and/or
* 'pageEncoding' attributes, we ignore it, as we've already appended
* a page directive containing just these two attributes.
*/
private void appendPageDirective(Node.PageDirective n) {
boolean append = false;
Attributes attrs = n.getAttributes();
int len = (attrs == null) ? 0 : attrs.getLength();
for (int i=0; i<len; i++) {
@SuppressWarnings("null") // If attrs==null, len == 0
String attrName = attrs.getQName(i);
if (!"pageEncoding".equals(attrName)
&& !"contentType".equals(attrName)) {
append = true;
break;
}
}
if (!append) {
return;
}
buf.append("<").append(n.getQName());
buf.append("\n");
// append jsp:id
buf.append(" ").append(jspIdPrefix).append(":id").append("=\"");
buf.append(jspId++).append("\"\n");
// append remaining attributes
for (int i=0; i<len; i++) {
@SuppressWarnings("null") // If attrs==null, len == 0
String attrName = attrs.getQName(i);
if ("import".equals(attrName) || "contentType".equals(attrName)
|| "pageEncoding".equals(attrName)) {
/*
* Page directive's 'import' attribute is considered
* further down, and its 'pageEncoding' and 'contentType'
* attributes are ignored, since we've already appended
* a new page directive containing just these two
* attributes
*/
continue;
}
String value = attrs.getValue(i);
buf.append(" ").append(attrName).append("=\"");
buf.append(JspUtil.getExprInXml(value)).append("\"\n");
}
if (n.getImports().size() > 0) {
// Concatenate names of imported classes/packages
boolean first = true;
ListIterator<String> iter = n.getImports().listIterator();
while (iter.hasNext()) {
if (first) {
first = false;
buf.append(" import=\"");
} else {
buf.append(",");
}
buf.append(JspUtil.getExprInXml(iter.next()));
}
buf.append("\"\n");
}
buf.append("/>\n");
}
/*
* Appends a page directive with 'pageEncoding' and 'contentType'
* attributes.
*
* The value of the 'pageEncoding' attribute is hard-coded
* to UTF-8, whereas the value of the 'contentType' attribute, which
* is identical to what the container will pass to
* ServletResponse.setContentType(), is derived from the pageInfo.
*/
private void appendPageDirective() {
buf.append("<").append(JSP_PAGE_DIRECTIVE_ACTION);
buf.append("\n");
// append jsp:id
buf.append(" ").append(jspIdPrefix).append(":id").append("=\"");
buf.append(jspId++).append("\"\n");
buf.append(" ").append("pageEncoding").append("=\"UTF-8\"\n");
buf.append(" ").append("contentType").append("=\"");
buf.append(compiler.getPageInfo().getContentType()).append("\"\n");
buf.append("/>\n");
}
/*
* Appends the tag directive with the given attributes to the XML
* view.
*
* If the given tag directive contains just a 'pageEncoding'
* attributes, we ignore it, as we've already appended
* a tag directive containing just this attributes.
*/
private void appendTagDirective(Node.TagDirective n)
throws JasperException {
boolean append = false;
Attributes attrs = n.getAttributes();
int len = (attrs == null) ? 0 : attrs.getLength();
for (int i=0; i<len; i++) {
@SuppressWarnings("null") // If attrs==null, len == 0
String attrName = attrs.getQName(i);
if (!"pageEncoding".equals(attrName)) {
append = true;
break;
}
}
if (!append) {
return;
}
appendTag(n);
}
/*
* Appends a tag directive containing a single 'pageEncoding'
* attribute whose value is hard-coded to UTF-8.
*/
private void appendTagDirective() {
buf.append("<").append(JSP_TAG_DIRECTIVE_ACTION);
buf.append("\n");
// append jsp:id
buf.append(" ").append(jspIdPrefix).append(":id").append("=\"");
buf.append(jspId++).append("\"\n");
buf.append(" ").append("pageEncoding").append("=\"UTF-8\"\n");
buf.append("/>\n");
}
private void appendText(String text, boolean createJspTextElement) {
if (createJspTextElement) {
buf.append("<").append(JSP_TEXT_ACTION);
buf.append("\n");
// append jsp:id
buf.append(" ").append(jspIdPrefix).append(":id").append("=\"");
buf.append(jspId++).append("\"\n");
buf.append(">\n");
appendCDATA(text);
buf.append(JSP_TEXT_ACTION_END);
buf.append("\n");
} else {
appendCDATA(text);
}
}
/*
* Appends the given text as a CDATA section to the XML view, unless
* the text has already been marked as CDATA.
*/
private void appendCDATA(String text) {
buf.append(CDATA_START_SECTION);
buf.append(escapeCDATA(text));
buf.append(CDATA_END_SECTION);
}
/*
* Escapes any occurrences of "]]>" (by replacing them with "]]>")
* within the given text, so it can be included in a CDATA section.
*/
private String escapeCDATA(String text) {
if( text==null ) return "";
int len = text.length();
CharArrayWriter result = new CharArrayWriter(len);
for (int i=0; i<len; i++) {
if (((i+2) < len)
&& (text.charAt(i) == ']')
&& (text.charAt(i+1) == ']')
&& (text.charAt(i+2) == '>')) {
// match found
result.write(']');
result.write(']');
result.write('&');
result.write('g');
result.write('t');
result.write(';');
i += 2;
} else {
result.write(text.charAt(i));
}
}
return result.toString();
}
/*
* Appends the attributes of the given Node to the XML view.
*/
private void printAttributes(Node n, boolean addDefaultNS) {
/*
* Append "xmlns" attributes that represent tag libraries
*/
Attributes attrs = n.getTaglibAttributes();
int len = (attrs == null) ? 0 : attrs.getLength();
for (int i=0; i<len; i++) {
@SuppressWarnings("null") // If attrs==null, len == 0
String name = attrs.getQName(i);
String value = attrs.getValue(i);
buf.append(" ").append(name).append("=\"").append(value).append("\"\n");
}
/*
* Append "xmlns" attributes that do not represent tag libraries
*/
attrs = n.getNonTaglibXmlnsAttributes();
len = (attrs == null) ? 0 : attrs.getLength();
boolean defaultNSSeen = false;
for (int i=0; i<len; i++) {
@SuppressWarnings("null") // If attrs==null, len == 0
String name = attrs.getQName(i);
String value = attrs.getValue(i);
buf.append(" ").append(name).append("=\"").append(value).append("\"\n");
defaultNSSeen |= "xmlns".equals(name);
}
if (addDefaultNS && !defaultNSSeen) {
buf.append(" xmlns=\"\"\n");
}
resetDefaultNS = false;
/*
* Append all other attributes
*/
attrs = n.getAttributes();
len = (attrs == null) ? 0 : attrs.getLength();
for (int i=0; i<len; i++) {
@SuppressWarnings("null") // If attrs==null, len == 0
String name = attrs.getQName(i);
String value = attrs.getValue(i);
buf.append(" ").append(name).append("=\"");
buf.append(JspUtil.getExprInXml(value)).append("\"\n");
}
}
/*
* Appends XML prolog with encoding declaration.
*/
private void appendXmlProlog() {
buf.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
}
}
}
| |
/**
* Copyright 2007-2016, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaazing.gateway.server.impl;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
public final class VersionUtils {
public static String PRODUCT_TITLE;
public static String PRODUCT_VERSION;
public static String PRODUCT_EDITION;
public static String PRODUCT_DEPENDENCIES;
private VersionUtils() {
}
public static String getGatewayProductTitle() {
getGatewayProductInfo();
return PRODUCT_TITLE;
}
public static String getGatewayProductVersion() {
getGatewayProductInfo();
return PRODUCT_VERSION;
}
public static String getGatewayProductVersionMajor() {
String v = getGatewayProductVersion();
if (v == null) {
return null;
}
int dotPos = v.indexOf(".");
return dotPos < 0 ? v : v.substring(0, dotPos);
}
public static String getGatewayProductVersionMinor() {
String v = getGatewayProductVersion();
if (v == null || v.length() == 0) {
return null;
}
int dotPos = v.indexOf(".");
if (dotPos < 0) {
return v + ".0";
}
dotPos = v.indexOf(".", dotPos + 1); // 2nd dot
return dotPos < 0 ? v : v.substring(0, dotPos);
}
public static String getGatewayProductVersionPatch() {
String v = getGatewayProductVersion();
// Non SNAPSHOT versions will be 3 digits in value.
// develop-SNAPSHOT will always be considered the lowest version
// available
if ("develop-SNAPSHOT".equals(v)) {
return "0.0.0";
}
if (v == null || v.length() == 0) {
return null;
}
int dotPos = v.indexOf(".");
if (dotPos < 0) {
return v + ".0.0";
}
dotPos = v.indexOf(".", dotPos + 1); // 2nd dot
if (dotPos < 0) {
return v + ".0";
}
dotPos = v.indexOf(".", dotPos + 1); // 3rd dot
return dotPos < 0 ? v : v.substring(0, dotPos);
}
public static String getGatewayProductVersionBuild() {
String v = getGatewayProductVersion();
if (v == null || v.length() == 0) {
return null;
}
int dotPos = v.indexOf(".");
if (dotPos < 0) {
return v + ".0.0.0";
}
dotPos = v.indexOf(".", dotPos + 1); // 2nd dot
if (dotPos < 0) {
return v + ".0.0";
}
dotPos = v.indexOf(".", dotPos + 1); // 3rd dot
if (dotPos < 0) {
return v + ".0";
}
// we know there is no 4th dot
return v;
}
public static String getGatewayProductEdition() {
getGatewayProductInfo();
return PRODUCT_EDITION;
}
public static String getGatewayProductDependencies() {
getGatewayProductInfo();
return PRODUCT_DEPENDENCIES;
}
/**
* Find the product information from the server JAR MANIFEST files and store it
* in static variables here for later retrieval.
*
*/
private static void getGatewayProductInfo() {
// TODO: Now that we've switched the products to include
// an "assembly.version" JAR, this routine could be greatly
// simplified. Removals and dependencies should no longer be needed.
if (PRODUCT_TITLE != null) {
// We've already run through this before, so do nothing.
return;
}
boolean foundJar = false;
String[] pathEntries = System.getProperty("java.class.path").split(System.getProperty("path.separator"));
HashMap<String, Attributes> products = new HashMap<>(7);
HashSet<String> removals = new HashSet<>(7);
for (String pathEntry : pathEntries) {
if (pathEntry.contains("gateway.server")) {
try {
JarFile jar = new JarFile(pathEntry);
Manifest mf = jar.getManifest();
Attributes attrs = mf.getMainAttributes();
if (attrs != null) {
String title = attrs.getValue("Implementation-Title");
String version = attrs.getValue("Implementation-Version");
String product = attrs.getValue("Kaazing-Product");
String dependencies = attrs.getValue("Kaazing-Dependencies");
if (product != null && title != null && version != null) {
foundJar = true;
// Store the list of products found, but remove any products
// marked as dependencies (i.e. products on which the current
// product depends. We want to find the product that nothing
// else depends on.
products.put(product != null ? product : title, attrs);
if (dependencies != null) {
String[] deps = dependencies.split(",");
Collections.addAll(removals, deps);
}
}
}
}
catch (IOException e) {
// ignore
}
}
}
// remove any products that depend on other products
for (String removal : removals) {
products.remove(removal);
}
if (!foundJar || products.size() == 0) {
// If running in IDE, there will be no manifest information.
// Therefore default title to "Kaazing WebSocket Gateway (Development)"
// and default the others to null.
PRODUCT_TITLE = "Kaazing WebSocket Gateway (Development)";
PRODUCT_VERSION = null;
PRODUCT_EDITION = null;
PRODUCT_DEPENDENCIES = null;
} else {
// The remaining values in 'products' are the real top-level product names.
// NOTE: Per discussion with Brian in 3.3, this should be only a single value,
// so we're going to extract our values from that.
Attributes attrs = products.values().iterator().next();
PRODUCT_TITLE = attrs.getValue("Implementation-Title");
PRODUCT_VERSION = attrs.getValue("Implementation-Version");
PRODUCT_EDITION = attrs.getValue("Kaazing-Product");
PRODUCT_DEPENDENCIES = attrs.getValue("Kaazing-Dependencies");
}
}
}
| |
//
// ========================================================================
// Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.jndi.java;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import org.eclipse.jetty.jndi.ContextFactory;
import org.eclipse.jetty.jndi.NamingContext;
import org.eclipse.jetty.jndi.NamingUtil;
import org.eclipse.jetty.util.log.Logger;
/** javaRootURLContext
* <p>This is the root of the java: url namespace
*
* <p><h4>Notes</h4>
* <p>Thanks to Rickard Oberg for the idea of binding an ObjectFactory at "comp".
*
* <p><h4>Usage</h4>
* <pre>
*/
/*
* </pre>
*
* @see
*
*
* @version 1.0
*/
public class javaRootURLContext implements Context
{
private static Logger __log = NamingUtil.__log;
public static final String URL_PREFIX = "java:";
protected Hashtable _env;
protected static NamingContext __nameRoot;
protected static NameParser __javaNameParser;
static
{
try
{
__javaNameParser = new javaNameParser();
__nameRoot = new NamingContext(null,null,null,__javaNameParser);
StringRefAddr parserAddr = new StringRefAddr("parser", __javaNameParser.getClass().getName());
Reference ref = new Reference ("javax.naming.Context",
parserAddr,
ContextFactory.class.getName(),
(String)null);
//bind special object factory at comp
__nameRoot.bind ("comp", ref);
}
catch (Exception e)
{
__log.warn(e);
}
}
/*------------------------------------------------*/
/**
* Creates a new <code>javaRootURLContext</code> instance.
*
* @param env a <code>Hashtable</code> value
*/
public javaRootURLContext(Hashtable env)
{
_env = env;
}
public Object lookup(Name name)
throws NamingException
{
return getRoot().lookup(stripProtocol(name));
}
public Object lookup(String name)
throws NamingException
{
return getRoot().lookup(stripProtocol(name));
}
public void bind(Name name, Object obj)
throws NamingException
{
getRoot().bind(stripProtocol(name), obj);
}
public void bind(String name, Object obj)
throws NamingException
{
getRoot().bind(stripProtocol(name), obj);
}
public void unbind (String name)
throws NamingException
{
getRoot().unbind(stripProtocol(name));
}
public void unbind (Name name)
throws NamingException
{
getRoot().unbind(stripProtocol(name));
}
public void rename (String oldStr, String newStr)
throws NamingException
{
getRoot().rename (stripProtocol(oldStr), stripProtocol(newStr));
}
public void rename (Name oldName, Name newName)
throws NamingException
{
getRoot().rename (stripProtocol(oldName), stripProtocol(newName));
}
public void rebind (Name name, Object obj)
throws NamingException
{
getRoot().rebind(stripProtocol(name), obj);
}
public void rebind (String name, Object obj)
throws NamingException
{
getRoot().rebind(stripProtocol(name), obj);
}
public Object lookupLink (Name name)
throws NamingException
{
return getRoot().lookupLink(stripProtocol(name));
}
public Object lookupLink (String name)
throws NamingException
{
return getRoot().lookupLink(stripProtocol(name));
}
public Context createSubcontext (Name name)
throws NamingException
{
return getRoot().createSubcontext(stripProtocol(name));
}
public Context createSubcontext (String name)
throws NamingException
{
return getRoot().createSubcontext(stripProtocol(name));
}
public void destroySubcontext (Name name)
throws NamingException
{
getRoot().destroySubcontext(stripProtocol(name));
}
public void destroySubcontext (String name)
throws NamingException
{
getRoot().destroySubcontext(stripProtocol(name));
}
public NamingEnumeration list(Name name)
throws NamingException
{
return getRoot().list(stripProtocol(name));
}
public NamingEnumeration list(String name)
throws NamingException
{
return getRoot().list(stripProtocol(name));
}
public NamingEnumeration listBindings(Name name)
throws NamingException
{
return getRoot().listBindings(stripProtocol(name));
}
public NamingEnumeration listBindings(String name)
throws NamingException
{
return getRoot().listBindings(stripProtocol(name));
}
public Name composeName (Name name,
Name prefix)
throws NamingException
{
return getRoot().composeName(name, prefix);
}
public String composeName (String name,
String prefix)
throws NamingException
{
return getRoot().composeName(name, prefix);
}
public void close ()
throws NamingException
{
}
public String getNameInNamespace ()
throws NamingException
{
return URL_PREFIX;
}
public NameParser getNameParser (Name name)
throws NamingException
{
return __javaNameParser;
}
public NameParser getNameParser (String name)
throws NamingException
{
return __javaNameParser;
}
public Object addToEnvironment(String propName,
Object propVal)
throws NamingException
{
return _env.put (propName,propVal);
}
public Object removeFromEnvironment(String propName)
throws NamingException
{
return _env.remove (propName);
}
public Hashtable getEnvironment ()
{
return _env;
}
public static NamingContext getRoot ()
{
return __nameRoot;
}
protected Name stripProtocol (Name name)
throws NamingException
{
if ((name != null) && (name.size() > 0))
{
String head = name.get(0);
if(__log.isDebugEnabled())__log.debug("Head element of name is: "+head);
if (head.startsWith(URL_PREFIX))
{
head = head.substring (URL_PREFIX.length());
name.remove(0);
if (head.length() > 0)
name.add(0, head);
if(__log.isDebugEnabled())__log.debug("name modified to "+name.toString());
}
}
return name;
}
protected String stripProtocol (String name)
{
String newName = name;
if ((name != null) && (!name.equals("")))
{
if (name.startsWith(URL_PREFIX))
newName = name.substring(URL_PREFIX.length());
}
return newName;
}
}
| |
/* Copyright (c) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.spreadsheet.gui;
import com.google.gdata.client.spreadsheet.FeedURLFactory;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.data.spreadsheet.WorksheetEntry;
import com.google.gdata.data.spreadsheet.WorksheetFeed;
import com.google.gdata.util.ServiceException;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
/**
* Window for selecting a spreadsheet.
*
* This is a little bit of a complicated class, but the main GData
* parts to know are:
*
* - populateSpreadsheetList just makes a few calls in order to
* get a list of spreadsheets
* - populateWorksheetList will get a list of worksheets within
* that spreadsheet
*
*
*/
public class ChooseSpreadsheetFrame extends JFrame {
/** The Google Spreadsheets GData service. */
private SpreadsheetService service;
private FeedURLFactory factory;
private List<SpreadsheetEntry> spreadsheetEntries;
private JList spreadsheetListBox;
private List<WorksheetEntry> worksheetEntries;
private JList worksheetListBox;
private JTextField ajaxLinkField;
private JTextField worksheetsFeedUrlField;
private JTextField cellsFeedUrlField;
private JTextField listFeedUrlField;
private JButton viewWorksheetsButton;
private JButton submitCellsButton;
private JButton submitListButton;
/** Starts the selection off with a spreadsheet feed helper. */
public ChooseSpreadsheetFrame(SpreadsheetService spreadsheetService) {
service = spreadsheetService;
factory = FeedURLFactory.getDefault();
initializeGui();
}
/**
* Gets the list of spreadsheets, and fills the list box.
*/
private void populateSpreadsheetList() {
if (retrieveSpreadsheetList()) {
fillSpreadsheetListBox();
}
}
/**
* Asks Google Spreadsheets for a list of all the spreadsheets
* the user has access to.
* @return true if successful
*/
private boolean retrieveSpreadsheetList() {
SpreadsheetFeed feed;
try {
feed = service.getFeed(
factory.getSpreadsheetsFeedUrl(), SpreadsheetFeed.class);
} catch (IOException e) {
SpreadsheetApiDemo.showErrorBox(e);
return false;
} catch (ServiceException e) {
SpreadsheetApiDemo.showErrorBox(e);
return false;
}
this.spreadsheetEntries = feed.getEntries();
return true;
}
/**
* Fills up the list-box of spreadsheets with the already-computed entries.
*/
private void fillSpreadsheetListBox() {
String[] stringsForListbox = new String[spreadsheetEntries.size()];
for (int i = 0; i < spreadsheetEntries.size(); i++) {
SpreadsheetEntry entry = spreadsheetEntries.get(i);
// Title of Spreadsheet (author, updated 2006-6-20 7:30PM)
stringsForListbox[i] =
entry.getTitle().getPlainText()
+ " (" + entry.getAuthors().get(0).getEmail()
+ ", updated " + entry.getUpdated().toUiString()
+ ")";
}
spreadsheetListBox.setListData(stringsForListbox);
}
/**
* Gets the list of worksheets in the specified spreadsheet,
* and fills the list box.
* @param spreadsheet the selected spreadsheet
*/
private void populateWorksheetList(SpreadsheetEntry spreadsheet) {
if (retrieveWorksheetList(spreadsheet)) {
fillWorksheetListBox(spreadsheet.getTitle().getPlainText());
}
}
/**
* Gets the list of worksheets from Google Spreadsheets.
* @param spreadsheet the spreadsheet to get a list of worksheets for
* @return true if successful
*/
private boolean retrieveWorksheetList(SpreadsheetEntry spreadsheet) {
WorksheetFeed feed;
try {
feed = service.getFeed(
spreadsheet.getWorksheetFeedUrl(), WorksheetFeed.class);
} catch (IOException e) {
SpreadsheetApiDemo.showErrorBox(e);
return false;
} catch (ServiceException e) {
SpreadsheetApiDemo.showErrorBox(e);
return false;
}
this.worksheetEntries = feed.getEntries();
return true;
}
/**
* Fills up the list-box of worksheets with the already computed entries.
*/
private void fillWorksheetListBox(String spreadsheetTitle) {
String[] stringsForListbox = new String[worksheetEntries.size()];
for (int i = 0; i < worksheetEntries.size(); i++) {
WorksheetEntry entry = worksheetEntries.get(i);
// Title Of Worksheet (T)
stringsForListbox[i] = entry.getTitle().getPlainText()
+ " (in " + spreadsheetTitle + ")";
}
worksheetListBox.setListData(stringsForListbox);
}
/**
* Handles when a user presses the "View Worksheets" button.
*
*/
private void handleViewWorksheetsButton() {
int selected = spreadsheetListBox.getSelectedIndex();
if (spreadsheetEntries != null && selected >= 0) {
populateWorksheetList(spreadsheetEntries.get(selected));
}
}
/**
* Handles when a user presses a "View Cells Demo" button.
*/
private void handleSubmitCellsButton() {
int selected = worksheetListBox.getSelectedIndex();
if (worksheetEntries != null && selected >= 0) {
CellBasedSpreadsheetPanel.createWindow(
service, worksheetEntries.get(selected).getCellFeedUrl());
}
}
/**
* Handles when a user presses a "View List Demo" button.
*/
private void handleSubmitListButton() {
int selected = worksheetListBox.getSelectedIndex();
if (worksheetEntries != null && selected >= 0) {
ListBasedSpreadsheetPanel.createWindow(service,
worksheetEntries.get(selected).getListFeedUrl());
}
}
/**
* Shows the feed URL's as you select spreadsheets.
*/
private void handleSpreadsheetSelection() {
int selected = spreadsheetListBox.getSelectedIndex();
if (spreadsheetEntries != null && selected >= 0) {
SpreadsheetEntry entry = spreadsheetEntries.get(selected);
ajaxLinkField.setText(
entry.getHtmlLink().getHref());
worksheetsFeedUrlField.setText(
entry.getWorksheetFeedUrl().toExternalForm());
}
}
/**
* Shows the feed URL's as you select worksheets within a spreadsheets.
*/
private void handleWorksheetSelection() {
int selected = worksheetListBox.getSelectedIndex();
if (worksheetEntries != null && selected >= 0) {
WorksheetEntry entry = worksheetEntries.get(selected);
cellsFeedUrlField.setText(entry.getCellFeedUrl().toExternalForm());
listFeedUrlField.setText(entry.getListFeedUrl().toExternalForm());
}
}
// ---- GUI code from here on down ----------------------------------------
private void initializeGui() {
setTitle("Choose your Spreadsheet");
Container panel = getContentPane();
panel.setLayout(new GridLayout(2, 1));
// Top part - choose a spreadsheet
JPanel spreadsheetPanel = new JPanel();
spreadsheetPanel.setLayout(new BorderLayout());
spreadsheetListBox = new JList();
spreadsheetPanel.add(new JScrollPane(spreadsheetListBox),
BorderLayout.CENTER);
spreadsheetListBox.addListSelectionListener(new ActionHandler());
Container topButtonsPanel = new JPanel();
topButtonsPanel.setLayout(new GridLayout(3, 1));
viewWorksheetsButton = new JButton("View Worksheets");
viewWorksheetsButton.addActionListener(new ActionHandler());
topButtonsPanel.add(viewWorksheetsButton);
panel.add(spreadsheetPanel);
ajaxLinkField = new JTextField();
ajaxLinkField.setEditable(false);
topButtonsPanel.add(ajaxLinkField);
worksheetsFeedUrlField = new JTextField();
worksheetsFeedUrlField.setEditable(false);
topButtonsPanel.add(worksheetsFeedUrlField);
spreadsheetPanel.add(topButtonsPanel, BorderLayout.SOUTH);
panel.add(spreadsheetPanel);
// Bottom part - choose a worksheet
JPanel worksheetPanel = new JPanel();
worksheetPanel.setLayout(new BorderLayout());
worksheetListBox = new JList(
new String[] { "[Please click 'View Worksheets' for a list.]" });
worksheetPanel.add(new JScrollPane(worksheetListBox), BorderLayout.CENTER);
worksheetListBox.addListSelectionListener(new ActionHandler());
Container bottomButtonsPanel = new JPanel();
bottomButtonsPanel.setLayout(new GridLayout(4, 1));
submitCellsButton = new JButton("Cells Demo");
submitCellsButton.addActionListener(new ActionHandler());
bottomButtonsPanel.add(submitCellsButton);
cellsFeedUrlField = new JTextField();
cellsFeedUrlField.setEditable(false);
bottomButtonsPanel.add(cellsFeedUrlField);
submitListButton = new JButton("List Demo");
submitListButton.addActionListener(new ActionHandler());
bottomButtonsPanel.add(submitListButton);
listFeedUrlField = new JTextField();
listFeedUrlField.setEditable(false);
bottomButtonsPanel.add(listFeedUrlField);
worksheetPanel.add(bottomButtonsPanel, BorderLayout.SOUTH);
panel.add(worksheetPanel);
populateSpreadsheetList();
pack();
setSize(700, 600);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class ActionHandler
implements ActionListener, ListSelectionListener {
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == viewWorksheetsButton) {
handleViewWorksheetsButton();
} else if (ae.getSource() == submitCellsButton) {
handleSubmitCellsButton();
} else if (ae.getSource() == submitListButton) {
handleSubmitListButton();
}
}
public void valueChanged(ListSelectionEvent e) {
if (e.getSource() == spreadsheetListBox) {
handleSpreadsheetSelection();
} else if (e.getSource() == worksheetListBox) {
handleWorksheetSelection();
}
}
}
}
| |
/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.android;
import com.facebook.buck.android.AndroidPackageableCollection.ResourceDetails;
import com.facebook.buck.jvm.java.HasJavaClassHashes;
import com.facebook.buck.jvm.java.JavaNativeLinkable;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.coercer.BuildConfigFields;
import com.facebook.buck.util.HumanReadableException;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.hash.HashCode;
import java.util.Map;
import java.util.Set;
public class AndroidPackageableCollector {
private final AndroidPackageableCollection.Builder collectionBuilder =
AndroidPackageableCollection.builder();
private final ResourceDetails.Builder resourceDetailsBuilder = ResourceDetails.builder();
private final ImmutableList.Builder<BuildTarget> resourcesWithNonEmptyResDir =
ImmutableList.builder();
private final ImmutableList.Builder<BuildTarget> resourcesWithAssets = ImmutableList.builder();
private final ImmutableList.Builder<SourcePath> resourceDirectories = ImmutableList.builder();
// Map is used instead of ImmutableMap.Builder for its containsKey() method.
private final Map<String, BuildConfigFields> buildConfigs = Maps.newHashMap();
private final ImmutableSet.Builder<HasJavaClassHashes> javaClassHashesProviders =
ImmutableSet.builder();
private final BuildTarget collectionRoot;
private final ImmutableSet<BuildTarget> buildTargetsToExcludeFromDex;
private final ImmutableSet<BuildTarget> resourcesToExclude;
@VisibleForTesting
AndroidPackageableCollector(BuildTarget collectionRoot) {
this(collectionRoot, ImmutableSet.<BuildTarget>of(), ImmutableSet.<BuildTarget>of());
}
/**
* @param resourcesToExclude Only relevant to {@link AndroidInstrumentationApk} which needs to
* remove resources that are already included in the
* {@link AndroidInstrumentationApkDescription.Arg#apk}
*/
public AndroidPackageableCollector(
BuildTarget collectionRoot,
ImmutableSet<BuildTarget> buildTargetsToExcludeFromDex,
ImmutableSet<BuildTarget> resourcesToExclude) {
this.collectionRoot = collectionRoot;
this.buildTargetsToExcludeFromDex = buildTargetsToExcludeFromDex;
this.resourcesToExclude = resourcesToExclude;
}
public void addPackageables(Iterable<AndroidPackageable> packageables) {
Set<AndroidPackageable> explored = Sets.newHashSet();
for (AndroidPackageable packageable : packageables) {
postOrderTraverse(packageable, explored);
}
}
private void postOrderTraverse(
AndroidPackageable packageable,
Set<AndroidPackageable> explored) {
if (explored.contains(packageable)) {
return;
}
explored.add(packageable);
for (AndroidPackageable dep : packageable.getRequiredPackageables()) {
postOrderTraverse(dep, explored);
}
packageable.addToCollector(this);
}
/**
* Returns all {@link BuildRule}s of the given rules that are {@link AndroidPackageable}.
* Helper for implementations of AndroidPackageable that just want to return all of their
* packagable dependencies.
*/
public static Iterable<AndroidPackageable> getPackageableRules(Iterable<BuildRule> rules) {
return FluentIterable.from(rules)
.filter(AndroidPackageable.class)
.toList();
}
public AndroidPackageableCollector addStringWhitelistedResourceDirectory(
BuildTarget owner,
SourcePath resourceDir) {
if (resourcesToExclude.contains(owner)) {
return this;
}
resourceDetailsBuilder.addWhitelistedStringDirectories(resourceDir);
doAddResourceDirectory(owner, resourceDir);
return this;
}
public AndroidPackageableCollector addResourceDirectory(
BuildTarget owner,
SourcePath resourceDir) {
if (resourcesToExclude.contains(owner)) {
return this;
}
doAddResourceDirectory(owner, resourceDir);
return this;
}
private void doAddResourceDirectory(BuildTarget owner, SourcePath resourceDir) {
resourcesWithNonEmptyResDir.add(owner);
resourceDirectories.add(resourceDir);
}
public AndroidPackageableCollector addNativeLibsDirectory(
BuildTarget owner,
SourcePath nativeLibDir) {
collectionBuilder.addNativeLibsTargets(owner);
collectionBuilder.addNativeLibsDirectories(nativeLibDir);
return this;
}
public AndroidPackageableCollector addNativeLinkable(JavaNativeLinkable nativeLinkable) {
collectionBuilder.addNativeLinkables(nativeLinkable);
return this;
}
public AndroidPackageableCollector addNativeLinkableAsset(JavaNativeLinkable nativeLinkable) {
collectionBuilder.addNativeLinkablesAssets(nativeLinkable);
return this;
}
public AndroidPackageableCollector addNativeLibAssetsDirectory(
BuildTarget owner,
SourcePath assetsDir) {
// We need to build the native target in order to have the assets available still.
collectionBuilder.addNativeLibsTargets(owner);
collectionBuilder.addNativeLibAssetsDirectories(assetsDir);
return this;
}
public AndroidPackageableCollector addAssetsDirectory(
BuildTarget owner,
SourcePath assetsDirectory) {
if (resourcesToExclude.contains(owner)) {
return this;
}
resourcesWithAssets.add(owner);
collectionBuilder.addAssetsDirectories(assetsDirectory);
return this;
}
public AndroidPackageableCollector addProguardConfig(
BuildTarget owner,
SourcePath proguardConfig) {
if (!buildTargetsToExcludeFromDex.contains(owner)) {
collectionBuilder.addProguardConfigs(proguardConfig);
}
return this;
}
public AndroidPackageableCollector addClasspathEntry(
HasJavaClassHashes hasJavaClassHashes,
SourcePath classpathEntry) {
if (buildTargetsToExcludeFromDex.contains(hasJavaClassHashes.getBuildTarget())) {
collectionBuilder.addNoDxClasspathEntries(classpathEntry);
} else {
collectionBuilder.addClasspathEntriesToDex(classpathEntry);
javaClassHashesProviders.add(hasJavaClassHashes);
}
return this;
}
public AndroidPackageableCollector addPathToThirdPartyJar(
BuildTarget owner,
SourcePath pathToThirdPartyJar) {
if (buildTargetsToExcludeFromDex.contains(owner)) {
collectionBuilder.addNoDxClasspathEntries(pathToThirdPartyJar);
} else {
collectionBuilder.addPathsToThirdPartyJars(pathToThirdPartyJar);
}
return this;
}
public void addBuildConfig(String javaPackage, BuildConfigFields constants) {
if (buildConfigs.containsKey(javaPackage)) {
throw new HumanReadableException(
"Multiple android_build_config() rules with the same package %s in the " +
"transitive deps of %s.",
javaPackage,
collectionRoot);
}
buildConfigs.put(javaPackage, constants);
}
public AndroidPackageableCollection build() {
collectionBuilder.setBuildConfigs(ImmutableMap.copyOf(buildConfigs));
final ImmutableSet<HasJavaClassHashes> javaClassProviders = javaClassHashesProviders.build();
collectionBuilder.addAllJavaLibrariesToDex(
FluentIterable.from(javaClassProviders).transform(BuildTarget.TO_TARGET).toSet());
collectionBuilder.setClassNamesToHashesSupplier(Suppliers.memoize(
new Supplier<Map<String, HashCode>>() {
@Override
public Map<String, HashCode> get() {
ImmutableMap.Builder<String, HashCode> builder = ImmutableMap.builder();
for (HasJavaClassHashes hasJavaClassHashes : javaClassProviders) {
builder.putAll(hasJavaClassHashes.getClassNamesToHashes());
}
return builder.build();
}
}));
ImmutableSet<BuildTarget> resources = ImmutableSet.copyOf(resourcesWithNonEmptyResDir.build());
for (BuildTarget buildTarget : resourcesWithAssets.build()) {
if (!resources.contains(buildTarget)) {
resourceDetailsBuilder.addResourcesWithEmptyResButNonEmptyAssetsDir(buildTarget);
}
}
// Reverse the resource directories/targets collections because we perform a post-order
// traversal of the action graph, and we need to return these collections topologically
// sorted.
resourceDetailsBuilder.setResourceDirectories(resourceDirectories.build().reverse());
resourceDetailsBuilder.setResourcesWithNonEmptyResDir(
resourcesWithNonEmptyResDir.build().reverse());
collectionBuilder.setResourceDetails(resourceDetailsBuilder.build());
return collectionBuilder.build();
}
}
| |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
public class SmartListTest {
@Test
public void testEmpty() {
assertThat(new SmartList<Integer>()).isEmpty();
}
@Test
public void testOneElement() {
List<Integer> l = new SmartList<>();
l.add(1);
assertThat(l).hasSize(1);
assertThat(l.get(0)).isEqualTo(1);
assertThat(l.indexOf(1)).isEqualTo(0);
assertThat(l.indexOf(2)).isEqualTo(-1);
assertThat(l.contains(1)).isTrue();
assertThat(l.contains(2)).isFalse();
}
@Test
public void testTwoElement() {
List<Integer> l = new SmartList<>();
l.add(1);
l.add(2);
assertThat(l).hasSize(2);
assertThat(l.get(0)).isEqualTo(1);
assertThat(l.get(1)).isEqualTo(2);
assertThat(l.indexOf(1)).isEqualTo(0);
assertThat(l.indexOf(2)).isEqualTo(1);
assertThat(l.contains(1)).isTrue();
assertThat(l.contains(2)).isTrue();
assertThat(l.indexOf(42)).isEqualTo(-1);
assertThat(l.contains(42)).isFalse();
}
@Test
public void testThreeElement() {
List<Integer> l = new SmartList<>();
l.add(1);
l.add(2);
l.add(3);
assertThat(l).hasSize(3);
assertThat(l.get(0)).isEqualTo(1);
assertThat(l.get(1)).isEqualTo(2);
assertThat(l.get(2)).isEqualTo(3);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testFourElement() {
SmartList<Integer> l = new SmartList<>();
int modCount = 0;
assertThat(l.getModificationCount()).isEqualTo(modCount);
l.add(1);
assertThat(l.getModificationCount()).isEqualTo(++modCount);
l.add(2);
assertThat(l.getModificationCount()).isEqualTo(++modCount);
l.add(3);
assertThat(l.getModificationCount()).isEqualTo(++modCount);
l.add(4);
assertThat(l.getModificationCount()).isEqualTo(++modCount);
assertThat(l).hasSize(4);
assertThat(l.get(0)).isEqualTo(1);
assertThat(l.get(1)).isEqualTo(2);
assertThat(l.get(2)).isEqualTo(3);
assertThat(l.get(3)).isEqualTo(4);
assertThat(l.getModificationCount()).isEqualTo(modCount);
l.remove(2);
assertThat(l).hasSize(3);
assertThat(l.getModificationCount()).isEqualTo(++modCount);
assertThat(l.toString()).isEqualTo("[1, 2, 4]");
l.set(2, 3);
assertThat(l).hasSize(3);
assertThat(l.getModificationCount()).isEqualTo(modCount);
assertThat(l.toString()).isEqualTo("[1, 2, 3]");
l.clear();
assertThat(l).isEmpty();
assertThat(l.getModificationCount()).isEqualTo(++modCount);
assertThat(l.toString()).isEqualTo("[]");
l.set(1, 3);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testFourElement2() {
SmartList<Integer> l = new SmartList<>();
int modCount = 0;
l.clear();
assertThat(l).isEmpty();
assertThat(l.getModificationCount()).isEqualTo(++modCount);
assertThat(l.toString()).isEqualTo("[]");
Iterator<Integer> iterator = l.iterator();
assertThat(iterator).isSameAs(Collections.emptyIterator());
assertThat(iterator.hasNext()).isFalse();
l.add(-2);
iterator = l.iterator();
assertThat(iterator).isNotSameAs(Collections.emptyIterator());
assertThat(iterator.hasNext()).isTrue();
assertThat(iterator.next()).isEqualTo(-2);
assertThat(iterator.hasNext()).isFalse();
l.get(1);
}
@SuppressWarnings("CollectionAddedToSelf")
@Test(expected = ConcurrentModificationException.class)
public void testFourElement3() {
SmartList<Integer> l = new SmartList<>();
l.clear();
l.add(-2);
l.addAll(l);
assertThat(l).hasSize(2);
assertThat(l.toString()).isEqualTo("[-2, -2]");
l.addAll(l);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testAddIndexedNegativeIndex() {
new SmartList<Integer>().add(-1, 1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testAddIndexedWrongIndex() {
new SmartList<>(1).add(3, 1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testAddIndexedEmptyWrongIndex() {
new SmartList<Integer>().add(1, 1);
}
@Test
public void testAddIndexedEmpty() {
SmartList<Integer> l = new SmartList<>();
int modCount = 0;
l.add(0, 1);
assertThat(l.getModificationCount()).isEqualTo(++modCount);
assertThat(l).hasSize(1);
assertThat(l.get(0)).isEqualTo(1);
}
@Test
public void testAddIndexedOneElement() {
SmartList<Integer> l = new SmartList<>(0);
assertThat(l).hasSize(1);
int modCount = l.getModificationCount();
l.add(0, 42);
assertThat(l.getModificationCount()).isEqualTo(++modCount);
assertThat(l).hasSize(2);
assertThat(l.get(0)).isEqualTo(42);
assertThat(l.get(1)).isEqualTo(0);
}
@Test
public void testAddIndexedOverOneElement() {
SmartList<Integer> l = new SmartList<>(0);
assertThat(l).hasSize(1);
int modCount = l.getModificationCount();
l.add(1, 42);
assertThat(l.getModificationCount()).isEqualTo(++modCount);
assertThat(l).hasSize(2);
assertThat(l.get(0)).isEqualTo(0);
assertThat(l.get(1)).isEqualTo(42);
}
@Test
public void testAddIndexedOverTwoElements() {
SmartList<Integer> l = new SmartList<>(0, 1);
assertThat(l).hasSize(2);
int modCount = l.getModificationCount();
l.add(1, 42);
assertThat(l.getModificationCount()).isEqualTo(++modCount);
assertThat(l).hasSize(3);
assertThat(l.get(0)).isEqualTo(0);
assertThat(l.get(1)).isEqualTo(42);
assertThat(l.get(2)).isEqualTo(1);
}
@Test
public void testEmptyToArray() {
SmartList<Integer> l = new SmartList<>();
assertThat(new Integer[]{}).isEqualTo(l.toArray());
assertThat(new Integer[]{}).isEqualTo(l.toArray(new Integer[]{}));
}
@Test
public void testSingleToArray() {
assertThat(new SmartList<>("foo").toArray(ArrayUtilRt.EMPTY_STRING_ARRAY)).containsExactly("foo");
}
@Test
public void testToArray() {
SmartList<Integer> l = new SmartList<>(0, 1);
assertThat(l.toArray()).isEqualTo(new Object[]{0, 1});
assertThat(l.toArray()).isEqualTo(new Integer[]{0, 1});
assertThat(l.toArray(new Integer[0])).isEqualTo(new Integer[]{0, 1});
assertThat(l.toArray(new Integer[4])).containsExactly(0, 1, null, null);
l.remove(1);
checkForEach(l);
assertThat(l.toArray(new Integer[4])).containsExactly(0, null, null, null);
assertThat(l.toArray()).containsExactly(0);
}
@Test
public void testNullIndexOf() {
List<Integer> l = new SmartList<>();
l.add(null);
l.add(null);
assertThat(l.indexOf(null)).isEqualTo(0);
assertThat(l.contains(null)).isTrue();
assertThat(l.indexOf(42)).isEqualTo(-1);
assertThat(l.contains(42)).isFalse();
}
@Test
public void testEqualsSelf() {
List<Integer> list = new SmartList<>();
assertThat(list).isEqualTo(list);
}
@Test
public void testEqualsNonListCollection() {
List<Integer> list = new SmartList<>();
assertThat(list).isNotEqualTo(new HashSet<>());
}
@Test
public void testEqualsEmptyList() {
List<Integer> list = new SmartList<>();
assertThat(list).isEqualTo(new SmartList<>());
assertThat(list).isEqualTo(new ArrayList<>());
assertThat(list).isEqualTo(new LinkedList<>());
assertThat(list).isEqualTo(Collections.emptyList());
assertThat(list).isEqualTo(Arrays.asList());
assertThat(list).isEqualTo(ContainerUtil.emptyList());
assertThat(list).isNotEqualTo(new SmartList<>(1));
assertThat(list).isNotEqualTo(new ArrayList<>(Collections.singletonList(1)));
assertThat(list).isNotEqualTo(new LinkedList<>(Collections.singletonList(1)));
assertThat(list).isNotEqualTo(Arrays.asList(1));
assertThat(list).isNotEqualTo(Collections.singletonList(1));
}
@Test
public void testEqualsListWithSingleNullableElement() {
List<Integer> list = new SmartList<>((Integer)null);
assertThat(list).isEqualTo(new SmartList<>((Integer)null));
assertThat(list).isEqualTo(new ArrayList<>(Collections.singletonList(null)));
assertThat(list).isEqualTo(new LinkedList<>(Collections.singletonList(null)));
assertThat(list).isEqualTo(Arrays.asList(new Integer[]{null}));
assertThat(list).isEqualTo(Collections.singletonList(null));
assertThat(list).isNotEqualTo(new SmartList<>());
assertThat(list).isNotEqualTo(new ArrayList<>());
assertThat(list).isNotEqualTo(new LinkedList<>());
assertThat(list).isNotEqualTo(Collections.emptyList());
assertThat(list).isNotEqualTo(Arrays.asList());
assertThat(list).isNotEqualTo(ContainerUtil.emptyList());
}
@Test
public void testEqualsListWithSingleNonNullElement() {
List<Integer> list = new SmartList<>(1);
checkForEach(list);
assertThat(list).isEqualTo(new SmartList<>(new Integer(1)));
assertThat(list).isEqualTo(new ArrayList<>(Arrays.asList(new Integer(1))));
assertThat(list).isEqualTo(new LinkedList<>(Arrays.asList(new Integer(1))));
assertThat(list).isEqualTo(Arrays.asList(new Integer(1)));
assertThat(list).isEqualTo(Collections.singletonList(new Integer(1)));
assertThat(list).isNotEqualTo(new SmartList<>());
assertThat(list).isNotEqualTo(new ArrayList<>());
assertThat(list).isNotEqualTo(new LinkedList<>());
assertThat(list).isNotEqualTo(Collections.emptyList());
assertThat(list).isNotEqualTo(Arrays.asList());
assertThat(list).isNotEqualTo(ContainerUtil.emptyList());
}
@Test
public void testEqualsListWithMultipleElements() {
List<Integer> list = new SmartList<>(1, null, 3);
checkForEach(list);
assertThat(list).isEqualTo(new SmartList<>(new Integer(1), null, new Integer(3)));
assertThat(list).isEqualTo(new ArrayList<>(Arrays.asList(new Integer(1), null, new Integer(3))));
assertThat(list).isEqualTo(new LinkedList<>(Arrays.asList(new Integer(1), null, new Integer(3))));
assertThat(list).isEqualTo(Arrays.asList(new Integer(1), null, new Integer(3)));
assertThat(list).isNotEqualTo(new SmartList<>(new Integer(1), new Integer(2), new Integer(3)));
assertThat(list).isNotEqualTo(new ArrayList<>(Arrays.asList(new Integer(1), new Integer(2), new Integer(3))));
assertThat(list).isNotEqualTo(new LinkedList<>(Arrays.asList(new Integer(1), new Integer(2), new Integer(3))));
assertThat(list).isNotEqualTo(Arrays.asList(new Integer(1), new Integer(2), new Integer(3)));
}
private static <T> void checkForEach(@NotNull List<T> list) {
List<T> checkList = new ArrayList<>();
//noinspection UseBulkOperation
list.forEach(integer -> checkList.add(integer));
assertThat(list).isEqualTo(checkList);
}
}
| |
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.samples.google.v1p1alpha;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.longrunning.OperationFuture;
import com.google.api.gax.rpc.BidiStreamingCallable;
import com.google.api.gax.rpc.OperationCallable;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.speech.v1p1beta1.*;
import com.google.cloud.speech.v1p1beta1.stub.SpeechStub;
import com.google.cloud.speech.v1p1beta1.stub.SpeechStubSettings;
import com.google.longrunning.Operation;
import com.google.longrunning.OperationsClient;
import javax.annotation.Generated;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Service Description: Service that implements Google Cloud Speech API.
*
* <p>This class provides the ability to make remote calls to the backing service through method
* calls that map to API methods. Sample code to get started:
*
* <pre>{@code
* try (SpeechClient speechClient = SpeechClient.create()) {
* RecognitionConfig config = RecognitionConfig.newBuilder().build();
* RecognitionAudio audio = RecognitionAudio.newBuilder().build();
* RecognizeResponse response = speechClient.recognize(config, audio);
* }
* }</pre>
*
* <p>Note: close() needs to be called on the SpeechClient object to clean up resources such as
* threads. In the example above, try-with-resources is used, which automatically calls close().
*
* <p>The surface of this class includes several types of Java methods for each of the API's
* methods:
*
* <ol>
* <li>A "flattened" method. With this type of method, the fields of the request type have been
* converted into function parameters. It may be the case that not all fields are available as
* parameters, and not every API method will have a flattened method entry point.
* <li>A "request object" method. This type of method only takes one parameter, a request object,
* which must be constructed before the call. Not every API method will have a request object
* method.
* <li>A "callable" method. This type of method takes no parameters and returns an immutable API
* callable object, which can be used to initiate calls to the service.
* </ol>
*
* <p>See the individual methods for example code.
*
* <p>Many parameters require resource names to be formatted in a particular way. To assist with
* these names, this class includes a format method for each type of name, and additionally a parse
* method to extract the individual identifiers contained within names that are returned.
*
* <p>This class can be customized by passing in a custom instance of SpeechSettings to create().
* For example:
*
* <p>To customize credentials:
*
* <pre>{@code
* SpeechSettings speechSettings =
* SpeechSettings.newBuilder()
* .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
* .build();
* SpeechClient speechClient = SpeechClient.create(speechSettings);
* }</pre>
*
* <p>To customize the endpoint:
*
* <pre>{@code
* SpeechSettings speechSettings = SpeechSettings.newBuilder().setEndpoint(myEndpoint).build();
* SpeechClient speechClient = SpeechClient.create(speechSettings);
* }</pre>
*
* <p>Please refer to the GitHub repository's samples for more quickstart code snippets.
*/
@BetaApi
@Generated("by gapic-generator-java")
public class SpeechClient implements BackgroundResource {
private final com.microsoft.samples.google.SpeechSettings settings;
private final SpeechStub stub;
private final OperationsClient operationsClient;
/** Constructs an instance of SpeechClient with default settings. */
public static final SpeechClient create() throws IOException {
return create(com.microsoft.samples.google.SpeechSettings.newBuilder().build());
}
/**
* Constructs an instance of SpeechClient, using the given settings. The channels are created
* based on the settings passed in, or defaults for any settings that are not set.
* Example broken links: {@link "http://tools.ietf.org/html/rfc2616#section-3.7"}
* {@link ApiFutures#immediateFuture(null)}.
*/
public static final SpeechClient create(com.microsoft.samples.google.SpeechSettings settings) throws IOException {
return new SpeechClient(settings);
}
/**
* Constructs an instance of SpeechClient, using the given stub for making calls. This is for
* advanced usage - prefer using create(SpeechSettings).
*/
@BetaApi("A restructuring of stub classes is planned, so this may break in the future")
public static final SpeechClient create(SpeechStub stub) {
return new SpeechClient(stub);
}
/**
* Constructs an instance of SpeechClient, using the given settings. This is protected so that it
* is easy to make a subclass, but otherwise, the static factory methods should be preferred.
*/
protected SpeechClient(com.microsoft.samples.google.SpeechSettings settings) throws IOException {
this.settings = settings;
this.stub = ((SpeechStubSettings) settings.getStubSettings()).createStub();
this.operationsClient = OperationsClient.create(this.stub.getOperationsStub());
}
@BetaApi("A restructuring of stub classes is planned, so this may break in the future")
protected SpeechClient(SpeechStub stub) {
this.settings = null;
this.stub = stub;
this.operationsClient = OperationsClient.create(this.stub.getOperationsStub());
}
public final com.microsoft.samples.google.SpeechSettings getSettings() {
return settings;
}
@BetaApi("A restructuring of stub classes is planned, so this may break in the future")
public SpeechStub getStub() {
return stub;
}
/**
* Returns the OperationsClient that can be used to query the status of a long-running operation
* returned by another API method call.
*/
public final OperationsClient getOperationsClient() {
return operationsClient;
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Performs synchronous speech recognition: receive results after all audio has been sent and
* processed.
*
* <p>Sample code:
*
* <pre>{@code
* try (SpeechClient speechClient = SpeechClient.create()) {
* RecognitionConfig config = RecognitionConfig.newBuilder().build();
* RecognitionAudio audio = RecognitionAudio.newBuilder().build();
* RecognizeResponse response = speechClient.recognize(config, audio);
* }
* }</pre>
*
* @param config Required. Provides information to the recognizer that specifies how to process
* the request.
* @param audio Required. The audio data to be recognized.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final RecognizeResponse recognize(RecognitionConfig config, RecognitionAudio audio) {
RecognizeRequest request =
RecognizeRequest.newBuilder().setConfig(config).setAudio(audio).build();
return recognize(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Performs synchronous speech recognition: receive results after all audio has been sent and
* processed.
*
* <p>Sample code:
*
* <pre>{@code
* try (SpeechClient speechClient = SpeechClient.create()) {
* RecognizeRequest request =
* RecognizeRequest.newBuilder()
* .setConfig(RecognitionConfig.newBuilder().build())
* .setAudio(RecognitionAudio.newBuilder().build())
* .build();
* RecognizeResponse response = speechClient.recognize(request);
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final RecognizeResponse recognize(RecognizeRequest request) {
return recognizeCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Performs synchronous speech recognition: receive results after all audio has been sent and
* processed.
*
* <p>Sample code:
*
* <pre>{@code
* try (SpeechClient speechClient = SpeechClient.create()) {
* RecognizeRequest request =
* RecognizeRequest.newBuilder()
* .setConfig(RecognitionConfig.newBuilder().build())
* .setAudio(RecognitionAudio.newBuilder().build())
* .build();
* ApiFuture<RecognizeResponse> future = speechClient.recognizeCallable().futureCall(request);
* // Do something.
* RecognizeResponse response = future.get();
* }
* }</pre>
*/
public final UnaryCallable<RecognizeRequest, RecognizeResponse> recognizeCallable() {
return stub.recognizeCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Performs asynchronous speech recognition: receive results via the google.longrunning.Operations
* interface. Returns either an `Operation.error` or an `Operation.response` which contains a
* `LongRunningRecognizeResponse` message. For more information on asynchronous speech
* recognition, see the [how-to](https://cloud.google.com/speech-to-text/docs/async-recognize).
*
* <p>Sample code:
*
* <pre>{@code
* try (SpeechClient speechClient = SpeechClient.create()) {
* RecognitionConfig config = RecognitionConfig.newBuilder().build();
* RecognitionAudio audio = RecognitionAudio.newBuilder().build();
* LongRunningRecognizeResponse response =
* speechClient.longRunningRecognizeAsync(config, audio).get();
* }
* }</pre>
*
* @param config Required. Provides information to the recognizer that specifies how to process
* the request.
* @param audio Required. The audio data to be recognized.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final OperationFuture<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>
longRunningRecognizeAsync(RecognitionConfig config, RecognitionAudio audio) {
LongRunningRecognizeRequest request =
LongRunningRecognizeRequest.newBuilder().setConfig(config).setAudio(audio).build();
return longRunningRecognizeAsync(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Performs asynchronous speech recognition: receive results via the google.longrunning.Operations
* interface. Returns either an `Operation.error` or an `Operation.response` which contains a
* `LongRunningRecognizeResponse` message. For more information on asynchronous speech
* recognition, see the [how-to](https://cloud.google.com/speech-to-text/docs/async-recognize).
*
* <p>Sample code:
*
* <pre>{@code
* try (SpeechClient speechClient = SpeechClient.create()) {
* LongRunningRecognizeRequest request =
* LongRunningRecognizeRequest.newBuilder()
* .setConfig(RecognitionConfig.newBuilder().build())
* .setAudio(RecognitionAudio.newBuilder().build())
* .setOutputConfig(TranscriptOutputConfig.newBuilder().build())
* .build();
* LongRunningRecognizeResponse response = speechClient.longRunningRecognizeAsync(request).get();
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final OperationFuture<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>
longRunningRecognizeAsync(LongRunningRecognizeRequest request) {
return longRunningRecognizeOperationCallable().futureCall(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Performs asynchronous speech recognition: receive results via the google.longrunning.Operations
* interface. Returns either an `Operation.error` or an `Operation.response` which contains a
* `LongRunningRecognizeResponse` message. For more information on asynchronous speech
* recognition, see the [how-to](https://cloud.google.com/speech-to-text/docs/async-recognize).
*
* <p>Sample code:
*
* <pre>{@code
* try (SpeechClient speechClient = SpeechClient.create()) {
* LongRunningRecognizeRequest request =
* LongRunningRecognizeRequest.newBuilder()
* .setConfig(RecognitionConfig.newBuilder().build())
* .setAudio(RecognitionAudio.newBuilder().build())
* .setOutputConfig(TranscriptOutputConfig.newBuilder().build())
* .build();
* OperationFuture<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> future =
* speechClient.longRunningRecognizeOperationCallable().futureCall(request);
* // Do something.
* LongRunningRecognizeResponse response = future.get();
* }
* }</pre>
*/
public final OperationCallable<
LongRunningRecognizeRequest, LongRunningRecognizeResponse, LongRunningRecognizeMetadata>
longRunningRecognizeOperationCallable() {
return stub.longRunningRecognizeOperationCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Performs asynchronous speech recognition: receive results via the google.longrunning.Operations
* interface. Returns either an `Operation.error` or an `Operation.response` which contains a
* `LongRunningRecognizeResponse` message. For more information on asynchronous speech
* recognition, see the [how-to](https://cloud.google.com/speech-to-text/docs/async-recognize).
*
* <p>Sample code:
*
* <pre>{@code
* try (SpeechClient speechClient = SpeechClient.create()) {
* LongRunningRecognizeRequest request =
* LongRunningRecognizeRequest.newBuilder()
* .setConfig(RecognitionConfig.newBuilder().build())
* .setAudio(RecognitionAudio.newBuilder().build())
* .setOutputConfig(TranscriptOutputConfig.newBuilder().build())
* .build();
* ApiFuture<Operation> future = speechClient.longRunningRecognizeCallable().futureCall(request);
* // Do something.
* Operation response = future.get();
* }
* }</pre>
*/
public final UnaryCallable<LongRunningRecognizeRequest, Operation>
longRunningRecognizeCallable() {
return stub.longRunningRecognizeCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Performs bidirectional streaming speech recognition: receive results while sending audio. This
* method is only available via the gRPC API (not REST).
*
* <p>Sample code:
*
* <pre>{@code
* try (SpeechClient speechClient = SpeechClient.create()) {
* BidiStream<StreamingRecognizeRequest, StreamingRecognizeResponse> bidiStream =
* speechClient.streamingRecognizeCallable().call();
* StreamingRecognizeRequest request = StreamingRecognizeRequest.newBuilder().build();
* bidiStream.send(request);
* for (StreamingRecognizeResponse response : bidiStream) {
* // Do something when a response is received.
* }
* }
* }</pre>
*/
public final BidiStreamingCallable<StreamingRecognizeRequest, StreamingRecognizeResponse>
streamingRecognizeCallable() {
return stub.streamingRecognizeCallable();
}
@Override
public final void close() {
stub.close();
}
@Override
public void shutdown() {
stub.shutdown();
}
@Override
public boolean isShutdown() {
return stub.isShutdown();
}
@Override
public boolean isTerminated() {
return stub.isTerminated();
}
@Override
public void shutdownNow() {
stub.shutdownNow();
}
@Override
public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
return stub.awaitTermination(duration, unit);
}
}
| |
package com.fsck.k9.activity.compose;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.AsyncTaskLoader;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Contacts.Data;
import android.support.annotation.Nullable;
import com.fsck.k9.R;
import com.fsck.k9.mail.Address;
import com.fsck.k9.view.RecipientSelectView.Recipient;
import com.fsck.k9.view.RecipientSelectView.RecipientCryptoStatus;
public class RecipientLoader extends AsyncTaskLoader<List<Recipient>> {
/*
* Indexes of the fields in the projection. This must match the order in {@link #PROJECTION}.
*/
private static final int INDEX_NAME = 1;
private static final int INDEX_LOOKUP_KEY = 2;
private static final int INDEX_EMAIL = 3;
private static final int INDEX_EMAIL_TYPE = 4;
private static final int INDEX_EMAIL_CUSTOM_LABEL = 5;
private static final int INDEX_CONTACT_ID = 6;
private static final int INDEX_PHOTO_URI = 7;
private static final String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email._ID,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
ContactsContract.Contacts.LOOKUP_KEY,
ContactsContract.CommonDataKinds.Email.DATA,
ContactsContract.CommonDataKinds.Email.TYPE,
ContactsContract.CommonDataKinds.Email.LABEL,
ContactsContract.CommonDataKinds.Email.CONTACT_ID,
ContactsContract.Contacts.PHOTO_THUMBNAIL_URI
};
private static final String SORT_ORDER = "" +
ContactsContract.CommonDataKinds.Email.TIMES_CONTACTED + " DESC, " +
ContactsContract.Contacts.SORT_KEY_PRIMARY;
private static final String[] PROJECTION_NICKNAME = {
ContactsContract.Data.CONTACT_ID,
ContactsContract.CommonDataKinds.Nickname.NAME
};
private static final int INDEX_CONTACT_ID_FOR_NICKNAME = 0;
private static final int INDEX_NICKNAME = 1;
private static final String[] PROJECTION_CRYPTO_STATUS = {
"address",
"uid_key_status",
"autocrypt_key_status"
};
private static final int INDEX_EMAIL_ADDRESS = 0;
private static final int INDEX_EMAIL_STATUS = 1;
private static final int INDEX_AUTOCRYPT_STATUS = 2;
private static final int CRYPTO_PROVIDER_STATUS_UNTRUSTED = 1;
private static final int CRYPTO_PROVIDER_STATUS_TRUSTED = 2;
private final String query;
private final Address[] addresses;
private final Uri contactUri;
private final Uri lookupKeyUri;
private final String cryptoProvider;
private List<Recipient> cachedRecipients;
private ForceLoadContentObserver observerContact, observerKey;
public RecipientLoader(Context context, String cryptoProvider, String query) {
super(context);
this.query = query;
this.lookupKeyUri = null;
this.addresses = null;
this.contactUri = null;
this.cryptoProvider = cryptoProvider;
}
public RecipientLoader(Context context, String cryptoProvider, Address... addresses) {
super(context);
this.query = null;
this.addresses = addresses;
this.contactUri = null;
this.cryptoProvider = cryptoProvider;
this.lookupKeyUri = null;
}
public RecipientLoader(Context context, String cryptoProvider, Uri contactUri, boolean isLookupKey) {
super(context);
this.query = null;
this.addresses = null;
this.contactUri = isLookupKey ? null : contactUri;
this.lookupKeyUri = isLookupKey ? contactUri : null;
this.cryptoProvider = cryptoProvider;
}
@Override
public List<Recipient> loadInBackground() {
List<Recipient> recipients = new ArrayList<>();
Map<String, Recipient> recipientMap = new HashMap<>();
if (addresses != null) {
fillContactDataFromAddresses(addresses, recipients, recipientMap);
} else if (contactUri != null) {
fillContactDataFromEmailContentUri(contactUri, recipients, recipientMap);
} else if (query != null) {
fillContactDataFromQuery(query, recipients, recipientMap);
} else if (lookupKeyUri != null) {
fillContactDataFromLookupKey(lookupKeyUri, recipients, recipientMap);
} else {
throw new IllegalStateException("loader must be initialized with query or list of addresses!");
}
if (recipients.isEmpty()) {
return recipients;
}
if (cryptoProvider != null) {
fillCryptoStatusData(recipientMap);
}
return recipients;
}
private void fillContactDataFromAddresses(Address[] addresses, List<Recipient> recipients,
Map<String, Recipient> recipientMap) {
for (Address address : addresses) {
// TODO actually query contacts - not sure if this is possible in a single query tho :(
Recipient recipient = new Recipient(address);
recipients.add(recipient);
recipientMap.put(address.getAddress(), recipient);
}
}
private void fillContactDataFromEmailContentUri(Uri contactUri, List<Recipient> recipients,
Map<String, Recipient> recipientMap) {
Cursor cursor = getContext().getContentResolver().query(contactUri, PROJECTION, null, null, null);
if (cursor == null) {
return;
}
fillContactDataFromCursor(cursor, recipients, recipientMap);
}
private void fillContactDataFromLookupKey(Uri lookupKeyUri, List<Recipient> recipients,
Map<String, Recipient> recipientMap) {
// We could use the contact id from the URI directly, but getting it from the lookup key is safer
Uri contactContentUri = Contacts.lookupContact(getContext().getContentResolver(), lookupKeyUri);
if (contactContentUri == null) {
return;
}
String contactIdStr = getContactIdFromContactUri(contactContentUri);
Cursor cursor = getContext().getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
PROJECTION, ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=?",
new String[] { contactIdStr }, null);
if (cursor == null) {
return;
}
fillContactDataFromCursor(cursor, recipients, recipientMap);
}
private static String getContactIdFromContactUri(Uri contactUri) {
return contactUri.getLastPathSegment();
}
private Cursor getNicknameCursor(String nickname) {
nickname = "%" + nickname + "%";
Uri queryUriForNickname = ContactsContract.Data.CONTENT_URI;
return getContext().getContentResolver().query(queryUriForNickname,
PROJECTION_NICKNAME,
ContactsContract.CommonDataKinds.Nickname.NAME + " LIKE ? AND " +
Data.MIMETYPE + " = ?",
new String[] { nickname, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE },
null);
}
@SuppressWarnings("ConstantConditions")
private void fillContactDataFromQuery(String query, List<Recipient> recipients,
Map<String, Recipient> recipientMap) {
boolean foundValidCursor = false;
foundValidCursor |= fillContactDataFromNickname(query, recipients, recipientMap);
foundValidCursor |= fillContactDataFromNameAndEmail(query, recipients, recipientMap);
if (foundValidCursor) {
registerContentObserver();
}
}
private void registerContentObserver() {
if (observerContact != null) {
observerContact = new ForceLoadContentObserver();
getContext().getContentResolver().registerContentObserver(Email.CONTENT_URI, false, observerContact);
}
}
@SuppressWarnings("ConstantConditions")
private boolean fillContactDataFromNickname(String nickname, List<Recipient> recipients,
Map<String, Recipient> recipientMap) {
boolean hasContact = false;
final ContentResolver contentResolver = getContext().getContentResolver();
Uri queryUri = Email.CONTENT_URI;
Cursor nicknameCursor = getNicknameCursor(nickname);
if (nicknameCursor == null) {
return hasContact;
}
try {
while (nicknameCursor.moveToNext()) {
String id = nicknameCursor.getString(INDEX_CONTACT_ID_FOR_NICKNAME);
String selection = ContactsContract.Data.CONTACT_ID + " = ?";
Cursor cursor = contentResolver
.query(queryUri, PROJECTION, selection, new String[] { id }, SORT_ORDER);
String contactNickname = nicknameCursor.getString(INDEX_NICKNAME);
fillContactDataFromCursor(cursor, recipients, recipientMap, contactNickname);
hasContact = true;
}
} finally {
nicknameCursor.close();
}
return hasContact;
}
private boolean fillContactDataFromNameAndEmail(String query, List<Recipient> recipients,
Map<String, Recipient> recipientMap) {
ContentResolver contentResolver = getContext().getContentResolver();
query = "%" + query + "%";
Uri queryUri = Email.CONTENT_URI;
String selection = Contacts.DISPLAY_NAME_PRIMARY + " LIKE ? " +
" OR (" + Email.ADDRESS + " LIKE ? AND " + Data.MIMETYPE + " = '" + Email.CONTENT_ITEM_TYPE + "')";
String[] selectionArgs = { query, query };
Cursor cursor = contentResolver.query(queryUri, PROJECTION, selection, selectionArgs, SORT_ORDER);
if (cursor == null) {
return false;
}
fillContactDataFromCursor(cursor, recipients, recipientMap);
return true;
}
private void fillContactDataFromCursor(Cursor cursor, List<Recipient> recipients,
Map<String, Recipient> recipientMap) {
fillContactDataFromCursor(cursor, recipients, recipientMap, null);
}
private void fillContactDataFromCursor(Cursor cursor, List<Recipient> recipients,
Map<String, Recipient> recipientMap, @Nullable String prefilledName) {
while (cursor.moveToNext()) {
String name = prefilledName != null ? prefilledName : cursor.getString(INDEX_NAME);
String email = cursor.getString(INDEX_EMAIL);
long contactId = cursor.getLong(INDEX_CONTACT_ID);
String lookupKey = cursor.getString(INDEX_LOOKUP_KEY);
// already exists? just skip then
if (recipientMap.containsKey(email)) {
// TODO merge? do something else? what do we do?
continue;
}
int addressType = cursor.getInt(INDEX_EMAIL_TYPE);
String addressLabel = null;
switch (addressType) {
case ContactsContract.CommonDataKinds.Email.TYPE_HOME: {
addressLabel = getContext().getString(R.string.address_type_home);
break;
}
case ContactsContract.CommonDataKinds.Email.TYPE_WORK: {
addressLabel = getContext().getString(R.string.address_type_work);
break;
}
case ContactsContract.CommonDataKinds.Email.TYPE_OTHER: {
addressLabel = getContext().getString(R.string.address_type_other);
break;
}
case ContactsContract.CommonDataKinds.Email.TYPE_MOBILE: {
// mobile isn't listed as an option contacts app, but it has a constant so we better support it
addressLabel = getContext().getString(R.string.address_type_mobile);
break;
}
case ContactsContract.CommonDataKinds.Email.TYPE_CUSTOM: {
addressLabel = cursor.getString(INDEX_EMAIL_CUSTOM_LABEL);
break;
}
}
Recipient recipient = new Recipient(name, email, addressLabel, contactId, lookupKey);
if (recipient.isValidEmailAddress()) {
Uri photoUri = cursor.isNull(INDEX_PHOTO_URI) ? null : Uri.parse(cursor.getString(INDEX_PHOTO_URI));
recipient.photoThumbnailUri = photoUri;
recipientMap.put(email, recipient);
recipients.add(recipient);
}
}
cursor.close();
}
private void fillCryptoStatusData(Map<String, Recipient> recipientMap) {
List<String> recipientList = new ArrayList<>(recipientMap.keySet());
String[] recipientAddresses = recipientList.toArray(new String[recipientList.size()]);
Cursor cursor;
Uri queryUri = Uri.parse("content://" + cryptoProvider + ".provider.exported/autocrypt_status");
try {
cursor = getContext().getContentResolver().query(queryUri, PROJECTION_CRYPTO_STATUS, null,
recipientAddresses, null);
} catch (SecurityException e) {
// TODO escalate error to crypto status?
return;
}
initializeCryptoStatusForAllRecipients(recipientMap);
if (cursor == null) {
return;
}
while (cursor.moveToNext()) {
String email = cursor.getString(INDEX_EMAIL_ADDRESS);
int uidStatus = cursor.getInt(INDEX_EMAIL_STATUS);
int autocryptStatus = cursor.getInt(INDEX_AUTOCRYPT_STATUS);
int effectiveStatus = uidStatus > autocryptStatus ? uidStatus : autocryptStatus;
for (Address address : Address.parseUnencoded(email)) {
String emailAddress = address.getAddress();
if (recipientMap.containsKey(emailAddress)) {
Recipient recipient = recipientMap.get(emailAddress);
switch (effectiveStatus) {
case CRYPTO_PROVIDER_STATUS_UNTRUSTED: {
if (recipient.getCryptoStatus() == RecipientCryptoStatus.UNAVAILABLE) {
recipient.setCryptoStatus(RecipientCryptoStatus.AVAILABLE_UNTRUSTED);
}
break;
}
case CRYPTO_PROVIDER_STATUS_TRUSTED: {
if (recipient.getCryptoStatus() != RecipientCryptoStatus.AVAILABLE_TRUSTED) {
recipient.setCryptoStatus(RecipientCryptoStatus.AVAILABLE_TRUSTED);
}
break;
}
}
}
}
}
cursor.close();
if (observerKey != null) {
observerKey = new ForceLoadContentObserver();
getContext().getContentResolver().registerContentObserver(queryUri, false, observerKey);
}
}
private void initializeCryptoStatusForAllRecipients(Map<String, Recipient> recipientMap) {
for (Recipient recipient : recipientMap.values()) {
recipient.setCryptoStatus(RecipientCryptoStatus.UNAVAILABLE);
}
}
@Override
public void deliverResult(List<Recipient> data) {
cachedRecipients = data;
if (isStarted()) {
super.deliverResult(data);
}
}
@Override
protected void onStartLoading() {
if (cachedRecipients != null) {
super.deliverResult(cachedRecipients);
return;
}
if (takeContentChanged() || cachedRecipients == null) {
forceLoad();
}
}
@Override
protected void onAbandon() {
super.onAbandon();
if (observerKey != null) {
getContext().getContentResolver().unregisterContentObserver(observerKey);
}
if (observerContact != null) {
getContext().getContentResolver().unregisterContentObserver(observerContact);
}
}
}
| |
/*
* This file is part of dependency-check-core.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (c) 2012 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.reporting;
import java.time.ZonedDateTime;
import java.util.List;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import javax.annotation.concurrent.NotThreadSafe;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.text.WordUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.owasp.dependencycheck.analyzer.Analyzer;
import org.owasp.dependencycheck.data.nvdcve.DatabaseProperties;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.EvidenceType;
import org.owasp.dependencycheck.exception.ExceptionCollection;
import org.owasp.dependencycheck.exception.ReportException;
import org.owasp.dependencycheck.utils.FileUtils;
import org.owasp.dependencycheck.utils.Settings;
import org.owasp.dependencycheck.utils.XmlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
/**
* The ReportGenerator is used to, as the name implies, generate reports.
* Internally the generator uses the Velocity Templating Engine. The
* ReportGenerator exposes a list of Dependencies to the template when
* generating the report.
*
* @author Jeremy Long
*/
@NotThreadSafe
public class ReportGenerator {
/**
* The logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ReportGenerator.class);
/**
* An enumeration of the report formats.
*/
public enum Format {
/**
* Generate all reports.
*/
ALL,
/**
* Generate XML report.
*/
XML,
/**
* Generate HTML report.
*/
HTML,
/**
* Generate JSON report.
*/
JSON,
/**
* Generate CSV report.
*/
CSV,
/**
* Generate Sarif report.
*/
SARIF,
/**
* Generate JUNIT report.
*/
JUNIT
}
/**
* The Velocity Engine.
*/
private final VelocityEngine velocityEngine;
/**
* The Velocity Engine Context.
*/
private final Context context;
/**
* The configured settings.
*/
private final Settings settings;
//CSOFF: ParameterNumber
//CSOFF: LineLength
/**
* Constructs a new ReportGenerator.
*
* @param applicationName the application name being analyzed
* @param dependencies the list of dependencies
* @param analyzers the list of analyzers used
* @param properties the database properties (containing timestamps of the
* NVD CVE data)
* @param settings a reference to the database settings
* @deprecated Please use
* {@link #ReportGenerator(java.lang.String, java.util.List, java.util.List, DatabaseProperties, Settings, ExceptionCollection)}
*/
@Deprecated
public ReportGenerator(String applicationName, List<Dependency> dependencies, List<Analyzer> analyzers,
DatabaseProperties properties, Settings settings) {
this(applicationName, dependencies, analyzers, properties, settings, null);
}
/**
* Constructs a new ReportGenerator.
*
* @param applicationName the application name being analyzed
* @param dependencies the list of dependencies
* @param analyzers the list of analyzers used
* @param properties the database properties (containing timestamps of the
* NVD CVE data)
* @param settings a reference to the database settings
* @param exceptions a collection of exceptions that may have occurred
* during the analysis
* @since 5.1.0
*/
public ReportGenerator(String applicationName, List<Dependency> dependencies, List<Analyzer> analyzers,
DatabaseProperties properties, Settings settings, ExceptionCollection exceptions) {
this(applicationName, null, null, null, dependencies, analyzers, properties, settings, exceptions);
}
/**
* Constructs a new ReportGenerator.
*
* @param applicationName the application name being analyzed
* @param groupID the group id of the project being analyzed
* @param artifactID the application id of the project being analyzed
* @param version the application version of the project being analyzed
* @param dependencies the list of dependencies
* @param analyzers the list of analyzers used
* @param properties the database properties (containing timestamps of the
* NVD CVE data)
* @param settings a reference to the database settings
* @deprecated Please use
* {@link #ReportGenerator(String, String, String, String, List, List, DatabaseProperties, Settings, ExceptionCollection)}
*/
@Deprecated
public ReportGenerator(String applicationName, String groupID, String artifactID, String version,
List<Dependency> dependencies, List<Analyzer> analyzers, DatabaseProperties properties,
Settings settings) {
this(applicationName, groupID, artifactID, version, dependencies, analyzers, properties, settings, null);
}
/**
* Constructs a new ReportGenerator.
*
* @param applicationName the application name being analyzed
* @param groupID the group id of the project being analyzed
* @param artifactID the application id of the project being analyzed
* @param version the application version of the project being analyzed
* @param dependencies the list of dependencies
* @param analyzers the list of analyzers used
* @param properties the database properties (containing timestamps of the
* NVD CVE data)
* @param settings a reference to the database settings
* @param exceptions a collection of exceptions that may have occurred
* during the analysis
* @since 5.1.0
*/
public ReportGenerator(String applicationName, String groupID, String artifactID, String version,
List<Dependency> dependencies, List<Analyzer> analyzers, DatabaseProperties properties,
Settings settings, ExceptionCollection exceptions) {
this.settings = settings;
velocityEngine = createVelocityEngine();
velocityEngine.init();
context = createContext(applicationName, dependencies, analyzers, properties, groupID,
artifactID, version, exceptions);
}
/**
* Constructs the velocity context used to generate the dependency-check
* reports.
*
* @param applicationName the application name being analyzed
* @param groupID the group id of the project being analyzed
* @param artifactID the application id of the project being analyzed
* @param version the application version of the project being analyzed
* @param dependencies the list of dependencies
* @param analyzers the list of analyzers used
* @param properties the database properties (containing timestamps of the
* NVD CVE data)
* @param exceptions a collection of exceptions that may have occurred
* during the analysis
* @return the velocity context
*/
@SuppressWarnings("JavaTimeDefaultTimeZone")
private VelocityContext createContext(String applicationName, List<Dependency> dependencies,
List<Analyzer> analyzers, DatabaseProperties properties, String groupID,
String artifactID, String version, ExceptionCollection exceptions) {
final ZonedDateTime dt = ZonedDateTime.now();
final String scanDate = DateTimeFormatter.RFC_1123_DATE_TIME.format(dt);
final String scanDateXML = DateTimeFormatter.ISO_INSTANT.format(dt);
final String scanDateJunit = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(dt);
final VelocityContext ctxt = new VelocityContext();
ctxt.put("applicationName", applicationName);
Collections.sort(dependencies, Dependency.NAME_COMPARATOR);
ctxt.put("dependencies", dependencies);
ctxt.put("analyzers", analyzers);
ctxt.put("properties", properties);
ctxt.put("scanDate", scanDate);
ctxt.put("scanDateXML", scanDateXML);
ctxt.put("scanDateJunit", scanDateJunit);
ctxt.put("enc", new EscapeTool());
ctxt.put("rpt", new ReportTool());
ctxt.put("WordUtils", new WordUtils());
ctxt.put("VENDOR", EvidenceType.VENDOR);
ctxt.put("PRODUCT", EvidenceType.PRODUCT);
ctxt.put("VERSION", EvidenceType.VERSION);
ctxt.put("version", settings.getString(Settings.KEYS.APPLICATION_VERSION, "Unknown"));
ctxt.put("settings", settings);
if (version != null) {
ctxt.put("applicationVersion", version);
}
if (artifactID != null) {
ctxt.put("artifactID", artifactID);
}
if (groupID != null) {
ctxt.put("groupID", groupID);
}
if (exceptions != null) {
ctxt.put("exceptions", exceptions.getExceptions());
}
return ctxt;
}
//CSON: ParameterNumber
//CSON: LineLength
/**
* Creates a new Velocity Engine.
*
* @return a velocity engine
*/
private VelocityEngine createVelocityEngine() {
return new VelocityEngine();
}
/**
* Writes the dependency-check report to the given output location.
*
* @param outputLocation the path where the reports should be written
* @param format the format the report should be written in (XML, HTML,
* JSON, CSV, ALL) or even the path to a custom velocity template (either
* fully qualified or the template name on the class path).
* @throws ReportException is thrown if there is an error creating out the
* reports
*/
public void write(String outputLocation, String format) throws ReportException {
Format reportFormat = null;
try {
reportFormat = Format.valueOf(format.toUpperCase());
} catch (IllegalArgumentException ex) {
LOGGER.trace("ignore this exception", ex);
}
if (reportFormat != null) {
write(outputLocation, reportFormat);
} else {
final File out = getReportFile(outputLocation, null);
if (out.isDirectory()) {
throw new ReportException("Unable to write non-standard VSL output to a directory, please specify a file name");
}
processTemplate(format, out);
}
}
/**
* Writes the dependency-check report(s).
*
* @param outputLocation the path where the reports should be written
* @param format the format the report should be written in (XML, HTML, ALL)
* @throws ReportException is thrown if there is an error creating out the
* reports
*/
public void write(String outputLocation, Format format) throws ReportException {
if (format == Format.ALL) {
for (Format f : Format.values()) {
if (f != Format.ALL) {
write(outputLocation, f);
}
}
} else {
final File out = getReportFile(outputLocation, format);
final String templateName = format.toString().toLowerCase() + "Report";
processTemplate(templateName, out);
if (settings.getBoolean(Settings.KEYS.PRETTY_PRINT, false)) {
if (format == Format.JSON || format == Format.SARIF) {
pretifyJson(out.getPath());
} else if (format == Format.XML || format == Format.JUNIT) {
pretifyXml(out.getPath());
}
}
}
}
/**
* Determines the report file name based on the give output location and
* format. If the output location contains a full file name that has the
* correct extension for the given report type then the output location is
* returned. However, if the output location is a directory, this method
* will generate the correct name for the given output format.
*
* @param outputLocation the specified output location
* @param format the report format
* @return the report File
*/
public static File getReportFile(String outputLocation, Format format) {
File outFile = new File(outputLocation);
if (outFile.getParentFile() == null) {
outFile = new File(".", outputLocation);
}
final String pathToCheck = outputLocation.toLowerCase();
if (format == Format.XML && !pathToCheck.endsWith(".xml")) {
return new File(outFile, "dependency-check-report.xml");
}
if (format == Format.HTML && !pathToCheck.endsWith(".html") && !pathToCheck.endsWith(".htm")) {
return new File(outFile, "dependency-check-report.html");
}
if (format == Format.JSON && !pathToCheck.endsWith(".json")) {
return new File(outFile, "dependency-check-report.json");
}
if (format == Format.CSV && !pathToCheck.endsWith(".csv")) {
return new File(outFile, "dependency-check-report.csv");
}
if (format == Format.JUNIT && !pathToCheck.endsWith(".xml")) {
return new File(outFile, "dependency-check-junit.xml");
}
if (format == Format.SARIF && !pathToCheck.endsWith(".sarif")) {
return new File(outFile, "dependency-check-report.sarif");
}
return outFile;
}
/**
* Generates a report from a given Velocity Template. The template name
* provided can be the name of a template contained in the jar file, such as
* 'XmlReport' or 'HtmlReport', or the template name can be the path to a
* template file.
*
* @param template the name of the template to load
* @param file the output file to write the report to
* @throws ReportException is thrown when the report cannot be generated
*/
@SuppressFBWarnings(justification = "try with resources will clean up the output stream", value = {"OBL_UNSATISFIED_OBLIGATION"})
protected void processTemplate(String template, File file) throws ReportException {
ensureParentDirectoryExists(file);
LOGGER.info("Writing report to: " + file.getAbsolutePath());
try (OutputStream output = new FileOutputStream(file)) {
processTemplate(template, output);
} catch (IOException ex) {
throw new ReportException(String.format("Unable to write to file: %s", file), ex);
}
}
/**
* Generates a report from a given Velocity Template. The template name
* provided can be the name of a template contained in the jar file, such as
* 'XmlReport' or 'HtmlReport', or the template name can be the path to a
* template file.
*
* @param templateName the name of the template to load
* @param outputStream the OutputStream to write the report to
* @throws ReportException is thrown when an exception occurs
*/
protected void processTemplate(String templateName, OutputStream outputStream) throws ReportException {
InputStream input = null;
String logTag;
final File f = new File(templateName);
try {
if (f.isFile()) {
try {
logTag = templateName;
input = new FileInputStream(f);
} catch (FileNotFoundException ex) {
throw new ReportException("Unable to locate template file: " + templateName, ex);
}
} else {
logTag = "templates/" + templateName + ".vsl";
input = FileUtils.getResourceAsStream(logTag);
}
if (input == null) {
logTag = templateName;
input = FileUtils.getResourceAsStream(templateName);
}
if (input == null) {
throw new ReportException("Template file doesn't exist: " + logTag);
}
try (InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8);
OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) {
if (!velocityEngine.evaluate(context, writer, logTag, reader)) {
throw new ReportException("Failed to convert the template into html.");
}
writer.flush();
} catch (UnsupportedEncodingException ex) {
throw new ReportException("Unable to generate the report using UTF-8", ex);
}
} catch (IOException ex) {
throw new ReportException("Unable to write the report", ex);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException ex) {
LOGGER.trace("Error closing input", ex);
}
}
}
}
/**
* Validates that the given file's parent directory exists. If the directory
* does not exist an attempt to create the necessary path is made; if that
* fails a ReportException will be raised.
*
* @param file the file or directory directory
* @throws ReportException thrown if the parent directory does not exist and
* cannot be created
*/
private void ensureParentDirectoryExists(File file) throws ReportException {
if (!file.getParentFile().exists()) {
final boolean created = file.getParentFile().mkdirs();
if (!created) {
final String msg = String.format("Unable to create directory '%s'.", file.getParentFile().getAbsolutePath());
throw new ReportException(msg);
}
}
}
/**
* Reformats the given XML file.
*
* @param path the path to the XML file to be reformatted
* @throws ReportException thrown if the given JSON file is malformed
*/
private void pretifyXml(String path) throws ReportException {
final String outputPath = path + ".pretty";
final File in = new File(path);
final File out = new File(outputPath);
try (OutputStream os = new FileOutputStream(out)) {
final TransformerFactory transformerFactory = SAXTransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
final Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
final SAXSource saxs = new SAXSource(new InputSource(path));
final XMLReader saxReader = XmlUtils.buildSecureSaxParser().getXMLReader();
saxs.setXMLReader(saxReader);
transformer.transform(saxs, new StreamResult(new OutputStreamWriter(os, "utf-8")));
} catch (ParserConfigurationException | TransformerConfigurationException ex) {
LOGGER.debug("Configuration exception when pretty printing", ex);
LOGGER.error("Unable to generate pretty report, caused by: {}", ex.getMessage());
} catch (TransformerException | SAXException | IOException ex) {
LOGGER.debug("Malformed XML?", ex);
LOGGER.error("Unable to generate pretty report, caused by: {}", ex.getMessage());
}
if (out.isFile() && in.isFile() && in.delete()) {
try {
Thread.sleep(1000);
org.apache.commons.io.FileUtils.moveFile(out, in);
} catch (IOException ex) {
LOGGER.error("Unable to generate pretty report, caused by: {}", ex.getMessage());
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
LOGGER.error("Unable to generate pretty report, caused by: {}", ex.getMessage());
}
}
}
/**
* Reformats the given JSON file.
*
* @param pathToJson the path to the JSON file to be reformatted
* @throws ReportException thrown if the given JSON file is malformed
*/
private void pretifyJson(String pathToJson) throws ReportException {
LOGGER.debug("pretify json: {}", pathToJson);
final String outputPath = pathToJson + ".pretty";
final File in = new File(pathToJson);
final File out = new File(outputPath);
final JsonFactory factory = new JsonFactory();
try (InputStream is = new FileInputStream(in);
OutputStream os = new FileOutputStream(out)) {
final JsonParser parser = factory.createParser(is);
final JsonGenerator generator = factory.createGenerator(os);
generator.useDefaultPrettyPrinter();
while (parser.nextToken() != null) {
generator.copyCurrentEvent(parser);
}
generator.flush();
} catch (IOException ex) {
LOGGER.debug("Malformed JSON?", ex);
throw new ReportException("Unable to generate json report", ex);
}
if (out.isFile() && in.isFile() && in.delete()) {
try {
Thread.sleep(1000);
org.apache.commons.io.FileUtils.moveFile(out, in);
} catch (IOException ex) {
LOGGER.error("Unable to generate pretty report, caused by: {}", ex.getMessage());
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
LOGGER.error("Unable to generate pretty report, caused by: {}", ex.getMessage());
}
}
}
}
| |
package im.actor.messenger.app.fragment.group;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import im.actor.core.viewmodel.Command;
import im.actor.core.viewmodel.CommandCallback;
import im.actor.messenger.R;
import im.actor.messenger.app.fragment.BaseFragment;
import im.actor.messenger.app.view.HolderAdapter;
import im.actor.messenger.app.view.ViewHolder;
import static im.actor.messenger.app.core.Core.messenger;
public class InviteLinkFragment extends BaseFragment {
private static final String EXTRA_GROUP_ID = "GROUP_ID";
private int chatId;
private ListView listView;
private InviteLincActionsAdapter adapter;
private String link;
private TextView emptyView;
public static InviteLinkFragment create(int gid) {
InviteLinkFragment res = new InviteLinkFragment();
Bundle arguments = new Bundle();
arguments.putInt(EXTRA_GROUP_ID, gid);
res.setArguments(arguments);
return res;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
chatId = getArguments().getInt(EXTRA_GROUP_ID);
Command<String> cmd = messenger().requestInviteLink(chatId);
if (cmd != null) cmd.start(new CommandCallback<String>() {
@Override
public void onResult(String res) {
link = res;
adapter.notifyDataSetChanged();
hideView(emptyView);
showView(listView);
}
@Override
public void onError(Exception e) {
Toast.makeText(getActivity(), getString(R.string.invite_link_error_get_link), Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
});
final ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
View res = inflater.inflate(R.layout.fragment_list, container, false);
listView = (ListView) res.findViewById(R.id.listView);
emptyView = (TextView) res.findViewById(R.id.emptyView);
emptyView.setText(getString(R.string.invite_link_empty_view));
adapter = new InviteLincActionsAdapter(getActivity());
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (link != null && !link.isEmpty()) {
switch (position) {
case 0:
//Link itself
clipboard.setPrimaryClip(ClipData.newPlainText(null, link));
Toast.makeText(getActivity(), getString(R.string.invite_link_copied), Toast.LENGTH_SHORT).show();
break;
case 1:
//Hint
break;
case 2:
//Copy
clipboard.setPrimaryClip(ClipData.newPlainText(null, link));
Toast.makeText(getActivity(), getString(R.string.invite_link_copied), Toast.LENGTH_SHORT).show();
break;
case 3:
//Revoke
new MaterialDialog.Builder(getActivity())
.content(R.string.alert_revoke_link_message)
.positiveText(R.string.alert_revoke_link_yes)
.negativeText(R.string.dialog_cancel)
.callback(new MaterialDialog.ButtonCallback() {
@Override
public void onPositive(MaterialDialog materialDialog1) {
execute(messenger().revokeInviteLink(chatId), R.string.invite_link_action_revoke, new CommandCallback<String>() {
@Override
public void onResult(String res) {
link = res;
adapter.notifyDataSetChanged();
}
@Override
public void onError(Exception e) {
Toast.makeText(getActivity(), getString(R.string.invite_link_error_revoke_link), Toast.LENGTH_SHORT).show();
}
});
}
})
.show();
break;
case 4:
//Share
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT, link);
Intent chooser = Intent.createChooser(i, getString(R.string.invite_link_chooser_title));
if (i.resolveActivity(getActivity().getPackageManager()) != null) {
startActivity(chooser);
}
break;
}
}
}
});
View footer = inflater.inflate(R.layout.fragment_link_item_footer, listView, false);
listView.addFooterView(footer, null, false);
return res;
}
class InviteLincActionsAdapter extends HolderAdapter<Void> {
protected InviteLincActionsAdapter(Context context) {
super(context);
}
@Override
public Void getItem(int position) {
return null;
}
@Override
public int getCount() {
return 5;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
protected ViewHolder<Void> createHolder(Void obj) {
return new ActionHolder();
}
}
private class ActionHolder extends ViewHolder<Void> {
TextView action;
FrameLayout container;
View topShadow;
View botShadow;
View divider;
@Override
public View init(Void data, ViewGroup viewGroup, Context context) {
View res = ((Activity) context).getLayoutInflater().inflate(R.layout.fragment_invite_link_item, viewGroup, false);
action = (TextView) res.findViewById(R.id.action);
container = (FrameLayout) res.findViewById(R.id.linksActionContainer);
topShadow = res.findViewById(R.id.top_shadow);
botShadow = res.findViewById(R.id.bot_shadow);
divider = res.findViewById(R.id.divider);
return res;
}
@Override
public void bind(Void data, int position, Context context) {
switch (position) {
case 0:
action.setText(link);
break;
case 1:
action.setText(getString(R.string.invite_link_hint));
break;
case 2:
action.setText(getString(R.string.invite_link_action_copy));
break;
case 3:
action.setText(getString(R.string.invite_link_action_revoke));
break;
case 4:
action.setText(getString(R.string.invite_link_action_share));
break;
}
//Hint styling
if (position == 1) {
container.setBackgroundColor(getActivity().getResources().getColor(R.color.bg_backyard));
topShadow.setVisibility(View.VISIBLE);
botShadow.setVisibility(View.VISIBLE);
divider.setVisibility(View.INVISIBLE);
action.setTextColor(getActivity().getResources().getColor(R.color.text_hint));
action.setTextSize(14);
} else {
container.setBackgroundColor(Color.TRANSPARENT);
topShadow.setVisibility(View.INVISIBLE);
botShadow.setVisibility(View.INVISIBLE);
divider.setVisibility(View.VISIBLE);
action.setTextColor(getActivity().getResources().getColor(R.color.text_primary));
action.setTextSize(16);
}
}
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.cluster;
import org.elasticsearch.Version;
import org.elasticsearch.action.admin.cluster.node.stats.NodeStats;
import org.elasticsearch.action.admin.indices.stats.CommonStats;
import org.elasticsearch.action.admin.indices.stats.ShardStats;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.ShardRoutingHelper;
import org.elasticsearch.cluster.routing.UnassignedInfo;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.transport.DummyTransportAddress;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.shard.ShardPath;
import org.elasticsearch.index.store.StoreStats;
import org.elasticsearch.monitor.fs.FsInfo;
import org.elasticsearch.test.ESTestCase;
import java.nio.file.Path;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import static org.hamcrest.Matchers.equalTo;
public class DiskUsageTests extends ESTestCase {
public void testDiskUsageCalc() {
DiskUsage du = new DiskUsage("node1", "n1", "random", 100, 40);
assertThat(du.getFreeDiskAsPercentage(), equalTo(40.0));
assertThat(du.getUsedDiskAsPercentage(), equalTo(100.0 - 40.0));
assertThat(du.getFreeBytes(), equalTo(40L));
assertThat(du.getUsedBytes(), equalTo(60L));
assertThat(du.getTotalBytes(), equalTo(100L));
// Test that DiskUsage handles invalid numbers, as reported by some
// filesystems (ZFS & NTFS)
DiskUsage du2 = new DiskUsage("node1", "n1","random", 100, 101);
assertThat(du2.getFreeDiskAsPercentage(), equalTo(101.0));
assertThat(du2.getFreeBytes(), equalTo(101L));
assertThat(du2.getUsedBytes(), equalTo(-1L));
assertThat(du2.getTotalBytes(), equalTo(100L));
DiskUsage du3 = new DiskUsage("node1", "n1", "random",-1, -1);
assertThat(du3.getFreeDiskAsPercentage(), equalTo(100.0));
assertThat(du3.getFreeBytes(), equalTo(-1L));
assertThat(du3.getUsedBytes(), equalTo(0L));
assertThat(du3.getTotalBytes(), equalTo(-1L));
DiskUsage du4 = new DiskUsage("node1", "n1","random", 0, 0);
assertThat(du4.getFreeDiskAsPercentage(), equalTo(100.0));
assertThat(du4.getFreeBytes(), equalTo(0L));
assertThat(du4.getUsedBytes(), equalTo(0L));
assertThat(du4.getTotalBytes(), equalTo(0L));
}
public void testRandomDiskUsage() {
int iters = scaledRandomIntBetween(1000, 10000);
for (int i = 1; i < iters; i++) {
long total = between(Integer.MIN_VALUE, Integer.MAX_VALUE);
long free = between(Integer.MIN_VALUE, Integer.MAX_VALUE);
DiskUsage du = new DiskUsage("random", "random", "random", total, free);
if (total == 0) {
assertThat(du.getFreeBytes(), equalTo(free));
assertThat(du.getTotalBytes(), equalTo(0L));
assertThat(du.getUsedBytes(), equalTo(-free));
assertThat(du.getFreeDiskAsPercentage(), equalTo(100.0));
assertThat(du.getUsedDiskAsPercentage(), equalTo(0.0));
} else {
assertThat(du.getFreeBytes(), equalTo(free));
assertThat(du.getTotalBytes(), equalTo(total));
assertThat(du.getUsedBytes(), equalTo(total - free));
assertThat(du.getFreeDiskAsPercentage(), equalTo(100.0 * ((double) free / total)));
assertThat(du.getUsedDiskAsPercentage(), equalTo(100.0 - (100.0 * ((double) free / total))));
}
}
}
public void testFillShardLevelInfo() {
final Index index = new Index("test", "0xdeadbeef");
ShardRouting test_0 = ShardRouting.newUnassigned(index, 0, null, false, new UnassignedInfo(UnassignedInfo.Reason.INDEX_CREATED, "foo"));
ShardRoutingHelper.initialize(test_0, "node1");
ShardRoutingHelper.moveToStarted(test_0);
Path test0Path = createTempDir().resolve("indices").resolve(index.getUUID()).resolve("0");
CommonStats commonStats0 = new CommonStats();
commonStats0.store = new StoreStats(100, 1);
ShardRouting test_1 = ShardRouting.newUnassigned(index, 1, null, false, new UnassignedInfo(UnassignedInfo.Reason.INDEX_CREATED, "foo"));
ShardRoutingHelper.initialize(test_1, "node2");
ShardRoutingHelper.moveToStarted(test_1);
Path test1Path = createTempDir().resolve("indices").resolve(index.getUUID()).resolve("1");
CommonStats commonStats1 = new CommonStats();
commonStats1.store = new StoreStats(1000, 1);
ShardStats[] stats = new ShardStats[] {
new ShardStats(test_0, new ShardPath(false, test0Path, test0Path, test_0.shardId()), commonStats0 , null),
new ShardStats(test_1, new ShardPath(false, test1Path, test1Path, test_1.shardId()), commonStats1 , null)
};
ImmutableOpenMap.Builder<String, Long> shardSizes = ImmutableOpenMap.builder();
ImmutableOpenMap.Builder<ShardRouting, String> routingToPath = ImmutableOpenMap.builder();
InternalClusterInfoService.buildShardLevelInfo(logger, stats, shardSizes, routingToPath);
assertEquals(2, shardSizes.size());
assertTrue(shardSizes.containsKey(ClusterInfo.shardIdentifierFromRouting(test_0)));
assertTrue(shardSizes.containsKey(ClusterInfo.shardIdentifierFromRouting(test_1)));
assertEquals(100L, shardSizes.get(ClusterInfo.shardIdentifierFromRouting(test_0)).longValue());
assertEquals(1000L, shardSizes.get(ClusterInfo.shardIdentifierFromRouting(test_1)).longValue());
assertEquals(2, routingToPath.size());
assertTrue(routingToPath.containsKey(test_0));
assertTrue(routingToPath.containsKey(test_1));
assertEquals(test0Path.getParent().getParent().getParent().toAbsolutePath().toString(), routingToPath.get(test_0));
assertEquals(test1Path.getParent().getParent().getParent().toAbsolutePath().toString(), routingToPath.get(test_1));
}
public void testFillDiskUsage() {
ImmutableOpenMap.Builder<String, DiskUsage> newLeastAvaiableUsages = ImmutableOpenMap.builder();
ImmutableOpenMap.Builder<String, DiskUsage> newMostAvaiableUsages = ImmutableOpenMap.builder();
FsInfo.Path[] node1FSInfo = new FsInfo.Path[] {
new FsInfo.Path("/middle", "/dev/sda", 100, 90, 80),
new FsInfo.Path("/least", "/dev/sdb", 200, 190, 70),
new FsInfo.Path("/most", "/dev/sdc", 300, 290, 280),
};
FsInfo.Path[] node2FSInfo = new FsInfo.Path[] {
new FsInfo.Path("/least_most", "/dev/sda", 100, 90, 80),
};
FsInfo.Path[] node3FSInfo = new FsInfo.Path[] {
new FsInfo.Path("/least", "/dev/sda", 100, 90, 70),
new FsInfo.Path("/most", "/dev/sda", 100, 90, 80),
};
NodeStats[] nodeStats = new NodeStats[] {
new NodeStats(new DiscoveryNode("node_1", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT), 0,
null,null,null,null,null,new FsInfo(0, node1FSInfo), null,null,null,null,null, null),
new NodeStats(new DiscoveryNode("node_2", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT), 0,
null,null,null,null,null, new FsInfo(0, node2FSInfo), null,null,null,null,null, null),
new NodeStats(new DiscoveryNode("node_3", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT), 0,
null,null,null,null,null, new FsInfo(0, node3FSInfo), null,null,null,null,null, null)
};
InternalClusterInfoService.fillDiskUsagePerNode(logger, nodeStats, newLeastAvaiableUsages, newMostAvaiableUsages);
DiskUsage leastNode_1 = newLeastAvaiableUsages.get("node_1");
DiskUsage mostNode_1 = newMostAvaiableUsages.get("node_1");
assertDiskUsage(mostNode_1, node1FSInfo[2]);
assertDiskUsage(leastNode_1, node1FSInfo[1]);
DiskUsage leastNode_2 = newLeastAvaiableUsages.get("node_2");
DiskUsage mostNode_2 = newMostAvaiableUsages.get("node_2");
assertDiskUsage(leastNode_2, node2FSInfo[0]);
assertDiskUsage(mostNode_2, node2FSInfo[0]);
DiskUsage leastNode_3 = newLeastAvaiableUsages.get("node_3");
DiskUsage mostNode_3 = newMostAvaiableUsages.get("node_3");
assertDiskUsage(leastNode_3, node3FSInfo[0]);
assertDiskUsage(mostNode_3, node3FSInfo[1]);
}
public void testFillDiskUsageSomeInvalidValues() {
ImmutableOpenMap.Builder<String, DiskUsage> newLeastAvailableUsages = ImmutableOpenMap.builder();
ImmutableOpenMap.Builder<String, DiskUsage> newMostAvailableUsages = ImmutableOpenMap.builder();
FsInfo.Path[] node1FSInfo = new FsInfo.Path[] {
new FsInfo.Path("/middle", "/dev/sda", 100, 90, 80),
new FsInfo.Path("/least", "/dev/sdb", -1, -1, -1),
new FsInfo.Path("/most", "/dev/sdc", 300, 290, 280),
};
FsInfo.Path[] node2FSInfo = new FsInfo.Path[] {
new FsInfo.Path("/least_most", "/dev/sda", -2, -1, -1),
};
FsInfo.Path[] node3FSInfo = new FsInfo.Path[] {
new FsInfo.Path("/most", "/dev/sda", 100, 90, 70),
new FsInfo.Path("/least", "/dev/sda", 10, -8, 0),
};
NodeStats[] nodeStats = new NodeStats[] {
new NodeStats(new DiscoveryNode("node_1", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT), 0,
null,null,null,null,null,new FsInfo(0, node1FSInfo), null,null,null,null,null, null),
new NodeStats(new DiscoveryNode("node_2", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT), 0,
null,null,null,null,null, new FsInfo(0, node2FSInfo), null,null,null,null,null, null),
new NodeStats(new DiscoveryNode("node_3", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT), 0,
null,null,null,null,null, new FsInfo(0, node3FSInfo), null,null,null,null,null, null)
};
InternalClusterInfoService.fillDiskUsagePerNode(logger, nodeStats, newLeastAvailableUsages, newMostAvailableUsages);
DiskUsage leastNode_1 = newLeastAvailableUsages.get("node_1");
DiskUsage mostNode_1 = newMostAvailableUsages.get("node_1");
assertNull("node1 should have been skipped", leastNode_1);
assertDiskUsage(mostNode_1, node1FSInfo[2]);
DiskUsage leastNode_2 = newLeastAvailableUsages.get("node_2");
DiskUsage mostNode_2 = newMostAvailableUsages.get("node_2");
assertNull("node2 should have been skipped", leastNode_2);
assertNull("node2 should have been skipped", mostNode_2);
DiskUsage leastNode_3 = newLeastAvailableUsages.get("node_3");
DiskUsage mostNode_3 = newMostAvailableUsages.get("node_3");
assertDiskUsage(leastNode_3, node3FSInfo[1]);
assertDiskUsage(mostNode_3, node3FSInfo[0]);
}
private void assertDiskUsage(DiskUsage usage, FsInfo.Path path) {
assertNotNull(usage);
assertNotNull(path);
assertEquals(usage.toString(), usage.getPath(), path.getPath());
assertEquals(usage.toString(), usage.getTotalBytes(), path.getTotal().bytes());
assertEquals(usage.toString(), usage.getFreeBytes(), path.getAvailable().bytes());
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.query.cache;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.druid.java.util.common.Cacheable;
import org.apache.druid.java.util.common.StringUtils;
import org.junit.Test;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class CacheKeyBuilderTest
{
@Test
public void testCacheKeyBuilder()
{
final Cacheable cacheable = new Cacheable()
{
@Override
public byte[] getCacheKey()
{
return new byte[]{10, 20};
}
};
final byte[] actual = new CacheKeyBuilder((byte) 10)
.appendBoolean(false)
.appendString("test")
.appendInt(10)
.appendFloat(0.1f)
.appendDouble(2.3)
.appendByteArray(CacheKeyBuilder.STRING_SEPARATOR) // test when an item is same with the separator
.appendFloatArray(new float[]{10.0f, 11.0f})
.appendStrings(Lists.newArrayList("test1", "test2"))
.appendCacheable(cacheable)
.appendCacheable(null)
.appendCacheables(Lists.newArrayList(cacheable, null, cacheable))
.build();
final int expectedSize = 1 // id
+ 1 // bool
+ 4 // 'test'
+ Integer.BYTES // 10
+ Float.BYTES // 0.1f
+ Double.BYTES // 2.3
+ CacheKeyBuilder.STRING_SEPARATOR.length // byte array
+ Float.BYTES * 2 // 10.0f, 11.0f
+ Integer.BYTES + 5 * 2 + 1 // 'test1' 'test2'
+ cacheable.getCacheKey().length // cacheable
+ Integer.BYTES + 4 // cacheable list
+ 11; // type keys
assertEquals(expectedSize, actual.length);
final byte[] expected = ByteBuffer.allocate(expectedSize)
.put((byte) 10)
.put(CacheKeyBuilder.BOOLEAN_KEY)
.put((byte) 0)
.put(CacheKeyBuilder.STRING_KEY)
.put(StringUtils.toUtf8("test"))
.put(CacheKeyBuilder.INT_KEY)
.putInt(10)
.put(CacheKeyBuilder.FLOAT_KEY)
.putFloat(0.1f)
.put(CacheKeyBuilder.DOUBLE_KEY)
.putDouble(2.3)
.put(CacheKeyBuilder.BYTE_ARRAY_KEY)
.put(CacheKeyBuilder.STRING_SEPARATOR)
.put(CacheKeyBuilder.FLOAT_ARRAY_KEY)
.putFloat(10.0f)
.putFloat(11.0f)
.put(CacheKeyBuilder.STRING_LIST_KEY)
.putInt(2)
.put(StringUtils.toUtf8("test1"))
.put(CacheKeyBuilder.STRING_SEPARATOR)
.put(StringUtils.toUtf8("test2"))
.put(CacheKeyBuilder.CACHEABLE_KEY)
.put(cacheable.getCacheKey())
.put(CacheKeyBuilder.CACHEABLE_KEY)
.put(CacheKeyBuilder.CACHEABLE_LIST_KEY)
.putInt(3)
.put(cacheable.getCacheKey())
.put(cacheable.getCacheKey())
.array();
assertArrayEquals(expected, actual);
}
@Test
public void testDifferentOrderList()
{
byte[] key1 = new CacheKeyBuilder((byte) 10)
.appendStringsIgnoringOrder(Lists.newArrayList("AB", "BA"))
.build();
byte[] key2 = new CacheKeyBuilder((byte) 10)
.appendStringsIgnoringOrder(Lists.newArrayList("BA", "AB"))
.build();
assertArrayEquals(key1, key2);
final Cacheable cacheable1 = new Cacheable()
{
@Override
public byte[] getCacheKey()
{
return new byte[]{1};
}
};
final Cacheable cacheable2 = new Cacheable()
{
@Override
public byte[] getCacheKey()
{
return new byte[]{2};
}
};
key1 = new CacheKeyBuilder((byte) 10)
.appendCacheablesIgnoringOrder(Lists.newArrayList(cacheable1, cacheable2))
.build();
key2 = new CacheKeyBuilder((byte) 10)
.appendCacheablesIgnoringOrder(Lists.newArrayList(cacheable2, cacheable1))
.build();
assertArrayEquals(key1, key2);
}
@Test
public void testNotEqualStrings()
{
final List<byte[]> keys = new ArrayList<>();
keys.add(
new CacheKeyBuilder((byte) 10)
.appendString("test")
.appendString("test")
.build()
);
keys.add(
new CacheKeyBuilder((byte) 10)
.appendString("testtest")
.build()
);
keys.add(
new CacheKeyBuilder((byte) 10)
.appendString("testtest")
.appendString("")
.build()
);
keys.add(
new CacheKeyBuilder((byte) 10)
.appendString("")
.appendString("testtest")
.build()
);
keys.add(
new CacheKeyBuilder((byte) 10)
.appendStrings(ImmutableList.of("test", "test"))
.build()
);
keys.add(
new CacheKeyBuilder((byte) 10)
.appendStrings(ImmutableList.of("testtest"))
.build()
);
keys.add(
new CacheKeyBuilder((byte) 10)
.appendStrings(ImmutableList.of("testtest", ""))
.build()
);
keys.add(
new CacheKeyBuilder((byte) 10)
.appendStrings(ImmutableList.of("testtest"))
.appendStrings(ImmutableList.of())
.build()
);
keys.add(
new CacheKeyBuilder((byte) 10)
.appendStrings(ImmutableList.of())
.appendStrings(ImmutableList.of("testtest"))
.build()
);
assertNotEqualsEachOther(keys);
}
@Test
public void testNotEqualCacheables()
{
final Cacheable test = new Cacheable()
{
@Override
public byte[] getCacheKey()
{
return StringUtils.toUtf8("test");
}
};
final Cacheable testtest = new Cacheable()
{
@Override
public byte[] getCacheKey()
{
return StringUtils.toUtf8("testtest");
}
};
final List<byte[]> keys = new ArrayList<>();
keys.add(
new CacheKeyBuilder((byte) 10)
.appendCacheable(test)
.appendCacheable(test)
.build()
);
keys.add(
new CacheKeyBuilder((byte) 10)
.appendCacheable(testtest)
.build()
);
keys.add(
new CacheKeyBuilder((byte) 10)
.appendCacheables(Lists.newArrayList(test, test))
.build()
);
keys.add(
new CacheKeyBuilder((byte) 10)
.appendCacheables(Collections.singletonList(testtest))
.build()
);
keys.add(
new CacheKeyBuilder((byte) 10)
.appendCacheables(Collections.singletonList(testtest))
.appendCacheables(new ArrayList<>())
.build()
);
keys.add(
new CacheKeyBuilder((byte) 10)
.appendCacheables(new ArrayList<>())
.appendCacheables(Collections.singletonList(testtest))
.build()
);
assertNotEqualsEachOther(keys);
}
private static void assertNotEqualsEachOther(List<byte[]> keys)
{
for (int i = 0; i < keys.size(); i++) {
for (int j = i + 1; j < keys.size(); j++) {
assertFalse(Arrays.equals(keys.get(i), keys.get(j)));
}
}
}
@Test
public void testEmptyOrNullStringLists()
{
byte[] key1 = new CacheKeyBuilder((byte) 10)
.appendStrings(Lists.newArrayList("", ""))
.build();
byte[] key2 = new CacheKeyBuilder((byte) 10)
.appendStrings(Collections.singletonList(""))
.build();
assertFalse(Arrays.equals(key1, key2));
key1 = new CacheKeyBuilder((byte) 10)
.appendStrings(Collections.singletonList(""))
.build();
key2 = new CacheKeyBuilder((byte) 10)
.appendStrings(Collections.singletonList((String) null))
.build();
assertArrayEquals(key1, key2);
}
@Test
public void testEmptyOrNullCacheables()
{
final byte[] key1 = new CacheKeyBuilder((byte) 10)
.appendCacheables(new ArrayList<>())
.build();
final byte[] key2 = new CacheKeyBuilder((byte) 10)
.appendCacheables(Collections.singletonList((Cacheable) null))
.build();
assertFalse(Arrays.equals(key1, key2));
}
@Test
public void testIgnoringOrder()
{
byte[] actual = new CacheKeyBuilder((byte) 10)
.appendStringsIgnoringOrder(Lists.newArrayList("test2", "test1", "te"))
.build();
byte[] expected = ByteBuffer.allocate(20)
.put((byte) 10)
.put(CacheKeyBuilder.STRING_LIST_KEY)
.putInt(3)
.put(StringUtils.toUtf8("te"))
.put(CacheKeyBuilder.STRING_SEPARATOR)
.put(StringUtils.toUtf8("test1"))
.put(CacheKeyBuilder.STRING_SEPARATOR)
.put(StringUtils.toUtf8("test2"))
.array();
assertArrayEquals(expected, actual);
final Cacheable c1 = new Cacheable()
{
@Override
public byte[] getCacheKey()
{
return StringUtils.toUtf8("te");
}
};
final Cacheable c2 = new Cacheable()
{
@Override
public byte[] getCacheKey()
{
return StringUtils.toUtf8("test1");
}
};
final Cacheable c3 = new Cacheable()
{
@Override
public byte[] getCacheKey()
{
return StringUtils.toUtf8("test2");
}
};
actual = new CacheKeyBuilder((byte) 10)
.appendCacheablesIgnoringOrder(Lists.newArrayList(c3, c2, c1))
.build();
expected = ByteBuffer.allocate(18)
.put((byte) 10)
.put(CacheKeyBuilder.CACHEABLE_LIST_KEY)
.putInt(3)
.put(c1.getCacheKey())
.put(c2.getCacheKey())
.put(c3.getCacheKey())
.array();
assertArrayEquals(expected, actual);
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.orc;
import com.facebook.presto.common.block.Block;
import com.facebook.presto.common.block.BlockBuilder;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.orc.metadata.CompressionKind;
import com.facebook.presto.orc.metadata.statistics.IntegerStatisticsBuilder;
import com.facebook.presto.orc.metadata.statistics.StringStatisticsBuilder;
import com.facebook.presto.orc.writer.ColumnWriter;
import com.facebook.presto.orc.writer.DictionaryColumnWriter;
import com.facebook.presto.orc.writer.LongColumnWriter;
import com.facebook.presto.orc.writer.LongDictionaryColumnWriter;
import com.facebook.presto.orc.writer.SliceDictionaryColumnWriter;
import com.facebook.presto.orc.writer.SliceDirectColumnWriter;
import io.airlift.units.DataSize;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.VerboseMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Random;
import java.util.UUID;
import static com.facebook.presto.common.type.BigintType.BIGINT;
import static com.facebook.presto.common.type.IntegerType.INTEGER;
import static com.facebook.presto.common.type.VarcharType.VARCHAR;
import static com.facebook.presto.orc.OrcEncoding.DWRF;
import static com.facebook.presto.orc.OrcWriterOptions.DEFAULT_MAX_STRING_STATISTICS_LIMIT;
import static com.facebook.presto.orc.metadata.ColumnEncoding.DEFAULT_SEQUENCE_ID;
import static com.google.common.base.Preconditions.checkState;
import static io.airlift.slice.Slices.utf8Slice;
import static io.airlift.units.DataSize.Unit.MEGABYTE;
import static java.lang.Math.max;
import static java.lang.Math.toIntExact;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
@SuppressWarnings("MethodMayBeStatic")
@State(Scope.Thread)
@OutputTimeUnit(MILLISECONDS)
@Fork(2)
@Warmup(iterations = 3, time = 1000, timeUnit = MILLISECONDS)
@Measurement(iterations = 10, time = 1000, timeUnit = MILLISECONDS)
@BenchmarkMode(Mode.AverageTime)
public class BenchmarkDictionaryWriter
{
private static final int COLUMN_INDEX = 0;
private static final int STRING_LIMIT_BYTES = toIntExact(DEFAULT_MAX_STRING_STATISTICS_LIMIT.toBytes());
private final ColumnWriterOptions columnWriterOptions = ColumnWriterOptions.builder().setCompressionKind(CompressionKind.NONE).build();
public static void main(String[] args)
throws Throwable
{
Options options = new OptionsBuilder()
.verbosity(VerboseMode.NORMAL)
.include(".*" + BenchmarkDictionaryWriter.class.getSimpleName() + ".*")
.build();
new Runner(options).run();
}
private StringStatisticsBuilder newStringStatisticsBuilder()
{
return new StringStatisticsBuilder(STRING_LIMIT_BYTES);
}
@Benchmark
public void writeDirect(BenchmarkData data)
{
ColumnWriter columnWriter;
Type type = data.getType();
if (type.equals(VARCHAR)) {
columnWriter = new SliceDirectColumnWriter(COLUMN_INDEX, DEFAULT_SEQUENCE_ID, type, columnWriterOptions, Optional.empty(), DWRF, this::newStringStatisticsBuilder, DWRF.createMetadataWriter());
}
else {
columnWriter = new LongColumnWriter(COLUMN_INDEX, DEFAULT_SEQUENCE_ID, type, columnWriterOptions, Optional.empty(), DWRF, IntegerStatisticsBuilder::new, DWRF.createMetadataWriter());
}
for (Block block : data.getBlocks()) {
columnWriter.beginRowGroup();
columnWriter.writeBlock(block);
columnWriter.finishRowGroup();
}
columnWriter.close();
columnWriter.reset();
}
@Benchmark
public void writeDictionary(BenchmarkData data)
{
ColumnWriter columnWriter = getDictionaryColumnWriter(data);
for (Block block : data.getBlocks()) {
columnWriter.beginRowGroup();
columnWriter.writeBlock(block);
columnWriter.finishRowGroup();
}
columnWriter.close();
columnWriter.reset();
}
@Benchmark
public void writeDictionaryAndConvert(BenchmarkData data)
{
DictionaryColumnWriter columnWriter = getDictionaryColumnWriter(data);
for (Block block : data.getBlocks()) {
columnWriter.beginRowGroup();
columnWriter.writeBlock(block);
columnWriter.finishRowGroup();
}
int maxDirectBytes = toIntExact(new DataSize(512, MEGABYTE).toBytes());
OptionalInt optionalInt = columnWriter.tryConvertToDirect(maxDirectBytes);
checkState(optionalInt.isPresent(), "Column did not covert to direct");
columnWriter.close();
columnWriter.reset();
}
private DictionaryColumnWriter getDictionaryColumnWriter(BenchmarkData data)
{
DictionaryColumnWriter columnWriter;
Type type = data.getType();
if (type.equals(VARCHAR)) {
columnWriter = new SliceDictionaryColumnWriter(COLUMN_INDEX, DEFAULT_SEQUENCE_ID, type, columnWriterOptions, Optional.empty(), DWRF, DWRF.createMetadataWriter());
}
else {
columnWriter = new LongDictionaryColumnWriter(COLUMN_INDEX, DEFAULT_SEQUENCE_ID, type, columnWriterOptions, Optional.empty(), DWRF, DWRF.createMetadataWriter());
}
return columnWriter;
}
@State(Scope.Thread)
public static class BenchmarkData
{
private static final int NUM_BLOCKS = 10_000;
private static final int ROWS_PER_BLOCK = 1_000;
private static final String INTEGER_TYPE = "integer";
private static final String BIGINT_TYPE = "bigint";
private static final String VARCHAR_TYPE = "varchar";
private final Random random = new Random(0);
private final List<Block> blocks;
@Param({
INTEGER_TYPE,
BIGINT_TYPE,
VARCHAR_TYPE
})
private String typeSignature = INTEGER_TYPE;
@Param({
"1",
"5",
"10",
"100"
})
private String uniqueValuesPercentage = "100";
private Type type;
public BenchmarkData()
{
blocks = new ArrayList<>();
}
public List<Block> getBlocks()
{
return blocks;
}
public Type getType()
{
return type;
}
@Setup
public void setUp()
{
type = getType(typeSignature);
for (int i = 0; i < NUM_BLOCKS; i++) {
blocks.add(getBlock(ROWS_PER_BLOCK));
}
}
private Type getType(String typeSignature)
{
switch (typeSignature) {
case VARCHAR_TYPE:
return VARCHAR;
case BIGINT_TYPE:
return BIGINT;
case INTEGER_TYPE:
return INTEGER;
default:
throw new UnsupportedOperationException("Unsupported type " + typeSignature);
}
}
private int getUniqueValues(int numRows)
{
int value = Integer.parseInt(uniqueValuesPercentage);
checkState(value <= 100);
int uniqueValues = (int) (value * numRows / 100.0);
return max(uniqueValues, 1);
}
private List<String> generateStrings(int numRows)
{
int valuesToGenerate = getUniqueValues(numRows);
List<String> strings = new ArrayList<>(numRows);
for (int i = 0; i < valuesToGenerate; i++) {
strings.add(UUID.randomUUID().toString());
}
for (int i = valuesToGenerate; i < numRows; i++) {
int randomIndex = random.nextInt(valuesToGenerate);
strings.add(strings.get(randomIndex));
}
return strings;
}
private List<Integer> generateIntegers(int numRows)
{
int valuesToGenerate = getUniqueValues(numRows);
List<Integer> integers = new ArrayList<>(numRows);
for (int i = 0; i < valuesToGenerate; i++) {
integers.add(random.nextInt());
}
for (int i = valuesToGenerate; i < numRows; i++) {
int randomIndex = random.nextInt(valuesToGenerate);
integers.add(integers.get(randomIndex));
}
return integers;
}
private List<Long> generateLongs(int numRows)
{
int valuesToGenerate = getUniqueValues(numRows);
List<Long> longs = new ArrayList<>(numRows);
for (int i = 0; i < valuesToGenerate; i++) {
longs.add(random.nextLong());
}
for (int i = valuesToGenerate; i < numRows; i++) {
int randomIndex = random.nextInt(valuesToGenerate);
longs.add(longs.get(randomIndex));
}
return longs;
}
private Block getBlock(int numRows)
{
BlockBuilder blockBuilder;
if (type.equals(VARCHAR)) {
blockBuilder = VARCHAR.createBlockBuilder(null, numRows);
for (String string : generateStrings(numRows)) {
VARCHAR.writeSlice(blockBuilder, utf8Slice(string));
}
}
else if (type.equals(BIGINT)) {
blockBuilder = BIGINT.createBlockBuilder(null, numRows);
for (Long value : generateLongs(numRows)) {
BIGINT.writeLong(blockBuilder, value);
}
}
else if (type.equals(INTEGER)) {
blockBuilder = INTEGER.createBlockBuilder(null, numRows);
for (Integer value : generateIntegers(numRows)) {
INTEGER.writeLong(blockBuilder, value.longValue());
}
}
else {
throw new UnsupportedOperationException("Unsupported type " + typeSignature);
}
return blockBuilder.build();
}
}
}
| |
/*******************************************************************************
* Copyright (C) 2016 Kwaku Twumasi-Afriyie <kwaku.twumasi@quakearts.com>.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Kwaku Twumasi-Afriyie <kwaku.twumasi@quakearts.com> - initial API and implementation
******************************************************************************/
package com.quakearts.webapp.facelets.bootstrap.renderers;
import com.quakearts.webapp.facelets.bootstrap.components.BootDateButton;
import com.quakearts.webapp.facelets.bootstrap.renderkit.Attribute;
import com.quakearts.webapp.facelets.bootstrap.renderkit.AttributeManager;
import com.quakearts.webapp.facelets.bootstrap.renderkit.AttributeManager.Key;
import com.quakearts.webapp.facelets.bootstrap.renderkit.html_basic.HtmlBasicInputRenderer;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.TreeMap;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import static com.quakearts.webapp.facelets.bootstrap.renderkit.RenderKitUtils.*;
import static com.quakearts.webapp.facelets.util.UtilityMethods.*;
public class BootDateButtonRenderer extends HtmlBasicInputRenderer {
public static final String RENDERER_TYPE = "com.quakearts.bootstrap.date.renderer";
public static final int[] MONTHDAYS = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
private static final Map<Integer, String> months = new TreeMap<Integer, String>();
private static final Attribute[] ATTRIBUTES = AttributeManager.getAttributes(Key.DATEBUTTON);
static {
months.put(1, "Jan");
months.put(2, "Feb");
months.put(3, "Mar");
months.put(4, "Apr");
months.put(5, "May");
months.put(6, "Jun");
months.put(7, "Jul");
months.put(8, "Aug");
months.put(9, "Sept");
months.put(10, "Oct");
months.put(11, "Nov");
months.put(12, "Dec");
}
@Override
protected void getEndTextToRender(FacesContext context, UIComponent component, String currentValue)
throws IOException {
BootDateButton button;
if (component instanceof BootDateButton) {
button = (BootDateButton) component;
} else {
throw new IOException("Component must be of type " + BootDateButton.class.getName());
}
Calendar date;
date = new GregorianCalendar();
SimpleDateFormat formatter;
formatter = new SimpleDateFormat(button.formatVal().getDateFormatString());
if (currentValue != null) {
try {
date.setTime(formatter.parse(currentValue));
} catch (ParseException e) {
}
} else {
if (!button.nullable())
currentValue = formatter.format(date.getTime());
}
int dayInt;
if (button.formatVal().hasDay())
dayInt = date.get(Calendar.DAY_OF_MONTH);
else
dayInt = 1;
int monthInt;
if (button.formatVal().hasMonth())
monthInt = (date.get(Calendar.MONTH) + 1);
else
monthInt = 1;
int yearInt;
yearInt = date.get(Calendar.YEAR);
int hourInt;
if (button.formatVal().hasHour()) {
hourInt = date.get(button.timeIs24Hours() ? Calendar.HOUR_OF_DAY : Calendar.HOUR);
if (hourInt == 0 && !button.timeIs24Hours())
hourInt = 12;
} else {
hourInt = button.timeIs24Hours() ? 0 : 12;
}
int minuteInt;
if (button.formatVal().hasMinute())
minuteInt = date.get(Calendar.MINUTE);
else
minuteInt = 0;
int secondInt;
if (button.formatVal().hasSeconds())
secondInt = date.get(Calendar.SECOND);
else
secondInt = 0;
boolean isAM = button.timeIs24Hours() ? false : date.get(Calendar.AM_PM) == Calendar.AM;
ResponseWriter writer = context.getResponseWriter();
String id = component.getClientId(context);
writer.startElement("div", component);
writer.writeAttribute("id", id, "id");
writer.writeAttribute("data-day", currentValue == null ? "" : (dayInt < 10 ? "0" + dayInt : "" + dayInt), null);
writer.writeAttribute("data-month", currentValue == null ? "0" : (monthInt + ""), null);
writer.writeAttribute("data-year", currentValue == null ? "" : ("" + yearInt), null);
writer.writeAttribute("data-hour", currentValue == null ? "0" : hourInt + "", null);
writer.writeAttribute("data-min", currentValue == null ? "0" : minuteInt + "", null);
writer.writeAttribute("data-sec", currentValue == null ? "0" : secondInt + "", null);
writer.writeAttribute("data-hrstep", button.hourStepVal() + "", null);
writer.writeAttribute("data-mnstep", button.minuteStepVal() + "", null);
writer.writeAttribute("data-scstep", button.secondStepVal() + "", null);
writer.writeAttribute("data-is24hr", button.timeIs24Hours() + "", null);
writer.writeAttribute("data-isam", isAM + "",null);
writer.writeAttribute("data-datetype", button.formatVal().getFormat(), null);;
renderPassThruAttributes(context, writer, component, ATTRIBUTES);
renderXHTMLStyleBooleanAttributes(writer, component);
renderHTML5DataAttributes(context, component);
String styleClass = button.get("styleClass");
if (styleClass != null)
writer.writeAttribute("class", styleClass, null);
String style = button.get("style");
if (style != null)
writer.writeAttribute("style", style, null);
writer.write("\n");
int offset = 0;
if(button.formatVal().hasMonth()) {
GregorianCalendar firstDay = new GregorianCalendar(date.get(Calendar.YEAR), date.get(Calendar.MONTH), 1);
offset = firstDay.get(Calendar.DAY_OF_WEEK) - 1;
}
String idJs = id.replace("-", "_");
boolean componentDisabled = componentIsDisabled(component);
if (button.formatVal().hasDay()) {
String dayClass = button.get("dayClass");
int days;
if(button.formatVal().hasMonth())
days = MONTHDAYS[date.get(Calendar.MONTH)];
else
days = 31;
generateSelectDay(idJs, dayInt, days, offset, writer, button,
currentValue == null, getDisplayType(button, context, "dayType"), dayClass, componentDisabled,
button.formatVal().hasMonth());
}
if (button.formatVal().hasMonth()) {
writer.write("\n");
String monthClass = button.get("monthClass");
generateSelect("month", idJs, monthInt, months, writer, button, currentValue == null,
getDisplayType(button, context, "monthType"), monthClass, componentDisabled);
}
if (button.formatVal().hasYear()) {
writer.write("\n");
String yearClass = button.get("yearClass");
generateSelect("year", idJs, yearInt, getYearsMap(button.maxAsInt(), button.minAsInt(), yearInt), writer,
button, currentValue == null, getDisplayType(button, context, "yearType"), yearClass,
componentDisabled);
}
if (button.formatVal().hasDay() && button.formatVal().hasHour()) {
writer.write("\n");
writer.startElement("span", component);
writer.writeAttribute("class", "time-text", null);
writer.write("@");
writer.endElement("span");
}
if (button.formatVal().hasHour()
|| button.formatVal().hasMinute()
|| button.formatVal().hasSeconds()) {
writer.write("\n");
writer.startElement("div", component);
String timeClass = button.get("timeClass");
if(timeClass == null)
timeClass = "time-md";
writer.writeAttribute("class", "time-control-group "+timeClass, null);
if(button.formatVal().hasHour()) {
generateTimeControl(writer, component, idJs, "hour", "vhr", "hrup", "hrdown", currentValue == null, hourInt,
getDisplayType(button, context, "hourType"), componentDisabled);
}
if (button.formatVal().hasMinute()) {
generateTimeControl(writer, component, idJs, "min", "vmn", "mnup", "mndown", currentValue == null,
minuteInt, getDisplayType(button, context, "minuteType"), componentDisabled);
}
if (button.formatVal().hasSeconds()) {
generateTimeControl(writer, component, idJs, "sec", "vsc", "scup", "scdown", currentValue == null,
secondInt, getDisplayType(button, context, "secondType"), componentDisabled);
}
writer.endElement("div");
if (!button.timeIs24Hours()) {
String ampmClass = button.get("ampmClass");
writer.write("\n");
writer.startElement("div", component);
writer.writeAttribute("class", "btn-group time-ampm-group", null);
writer.write("\n");
generateAMPMButton(writer, component, idJs, isAM, true, ampmClass);
generateAMPMButton(writer, component, idJs, isAM, false, ampmClass);
writer.endElement("div");
}
}
writer.write("\n");
if (button.nullable() && !componentDisabled) {
writer.startElement("a", component);
writer.writeAttribute("class", "btn-group day", null);
writer.writeAttribute("title", "Clear date", null);
writer.writeAttribute("onclick", "dc_" + idJs + ".cc();", null);
writer.write("×");
writer.endElement("a");
writer.write("\n");
}
writer.write("\n");
writer.startElement("input", button);
writer.writeAttribute("name", id, null);
writer.writeAttribute("id", idJs + "_input", null);
writer.writeAttribute("type", "hidden", null);
writer.writeAttribute("value", currentValue != null ? currentValue : "", "value");
writer.endElement("input");
if(!componentDisabled) {
writer.write("\n");
writer.startElement("input", button);
writer.writeAttribute("id", idJs + "_change", null);
writer.writeAttribute("type", "hidden", null);
renderOnchange(context, component, component.getClientId());
writer.endElement("input");
writer.write("\n");
}
writer.endElement("div");
writer.write("\n");
}
private void generateTimeControl(ResponseWriter writer, UIComponent component, String idJs, String id,
String validateFunction, String upFunction, String downFunction, boolean isNull, int value, String type,
boolean componentDisabled) throws IOException {
writer.write("\n");
writer.startElement("input", component);
writer.writeAttribute("class", "time-form-control", null);
writer.writeAttribute("onblur", "dc_" + idJs + "." + validateFunction + "(this)", null);
writer.writeAttribute("id", idJs + "_" + id, null);
writer.writeAttribute("value", isNull ? "" : value + "", null);
if (componentDisabled)
writer.writeAttribute("disabled", "disabled", "disabled");
writer.endElement("input");
writer.write("\n");
writer.startElement("div", component);
writer.writeAttribute("class", "time-btn-group", null);
generateTimeButtons(writer, component, idJs, upFunction, "up", type, componentDisabled);
generateTimeButtons(writer, component, idJs, downFunction, "down", type, componentDisabled);
writer.write("\n");
writer.endElement("div");
}
private void generateTimeButtons(ResponseWriter writer, UIComponent component, String idJs, String function,
String chevron, String type, boolean componentDisabled) throws IOException {
writer.write("\n");
writer.startElement("button", component);
writer.writeAttribute("class", "btn btn-" + type + " time-btn-" + chevron, null);
writer.writeAttribute("type", "button", null);
writer.writeAttribute("onclick", "dc_" + idJs + "." + function + "(this)", null);
if (componentDisabled)
writer.writeAttribute("disabled", "disabled", "disabled");
writer.write("\n");
writer.startElement("span", component);
writer.writeAttribute("class", "glyphicon glyphicon-chevron-" + chevron, null);
writer.endElement("span");
writer.write("\n");
writer.endElement("button");
}
private void generateAMPMButton(ResponseWriter writer, UIComponent component, String idJs, boolean isAM,
boolean generateAM, String ampmClass) throws IOException {
writer.startElement("button", component);
writer.writeAttribute("class",
"btn btn-default"+(ampmClass != null?" "+ampmClass:"")
+ ((isAM && generateAM) || (!isAM && !generateAM) ? " active" : ""), null);
writer.writeAttribute("onclick", "dc_" + idJs + ".tglampm(this," + generateAM + ")", null);
writer.writeAttribute("type", "button", null);
writer.write(generateAM ? "AM" : "PM");
writer.endElement("button");
writer.write("\n");
}
private void generateSelectDay(String idJs, int value, int days, int offset, ResponseWriter writer,
BootDateButton component, boolean isnull, String type,
String styleClass, boolean componentDisabled, boolean hasMonth)
throws IOException {
writer.startElement("div", component);
writer.writeAttribute("class", "btn-group", null);
writer.write("\n");
writer.startElement("button", component);
writer.writeAttribute("id", idJs + "_btn_day", null);
writer.writeAttribute("class",
"btn btn-" + type + (styleClass != null ? " " + styleClass : "") + " dropdown-toggle", null);
writer.writeAttribute("data-toggle", "dropdown", null);
writer.writeAttribute("aria-expanded", "false", null);
if (componentDisabled)
writer.writeAttribute("disabled", "disabled", "disabled");
writer.write("\n");
writer.startElement("span", component);
writer.writeAttribute("id", idJs + "_day", null);
writer.write(isnull ? " " : value + "");
writer.endElement("span");
writer.write("\n");
writer.startElement("span", component);
writer.writeAttribute("class", "caret", null);
writer.write("\n");
writer.endElement("span");
writer.write("\n");
writer.endElement("button");
writer.write("\n");
writer.startElement("div", component);
writer.writeAttribute("class", "dropdown-menu day-container", null);
writer.writeAttribute("role", "menu", null);
if (!componentDisabled) {
String onChangeEvent = "dc_" + idJs + ".ud(this);";
if(hasMonth) {
writer.write("<span class=\"day-header\">S</span>\r\n" + "<span class=\"day-header\">M</span>\r\n"
+ "<span class=\"day-header\">T</span>\r\n" + "<span class=\"day-header\">W</span>\r\n"
+ "<span class=\"day-header\">T</span>\r\n" + "<span class=\"day-header\">F</span>\r\n"
+ "<span class=\"day-header\">S</span>");
writer.write("<span class=\"day-header buffer\" style=\"width:" + (39 * offset) + "px;\"></span>");
}
for (int i = 1; i <= 31; i++) {
writer.startElement("a", component);
writer.writeAttribute("class", i <= days ? "day" : "collapse", null);
writer.writeAttribute("onclick", onChangeEvent, null);
writer.writeText(i, null);
writer.endElement("a");
writer.write("\n");
}
}
writer.endElement("div");
writer.write("\n");
writer.endElement("div");
}
private void generateSelect(String part, String idJs, int value, Map<Integer, String> options,
ResponseWriter writer, BootDateButton component, boolean isnull, String type, String styleClass,
boolean componentDisabled) throws IOException {
writer.startElement("div", component);
writer.writeAttribute("class", "btn-group", null);
writer.write("\n");
writer.startElement("button", component);
writer.writeAttribute("id", idJs + "_btn_" + part, null);
writer.writeAttribute("class",
"btn btn-" + type + (styleClass != null ? " " + styleClass : "") + " dropdown-toggle", null);
writer.writeAttribute("data-toggle", "dropdown", null);
writer.writeAttribute("aria-expanded", "false", null);
if (componentDisabled)
writer.writeAttribute("disabled", "disabled", "disabled");
writer.write("\n");
writer.startElement("span", component);
writer.writeAttribute("id", idJs + "_" + part, null);
writer.write(isnull ? " " : options.get(value) + "");
writer.endElement("span");
writer.write("\n");
writer.startElement("span", component);
writer.writeAttribute("class", "caret", null);
writer.write("\n");
writer.endElement("span");
writer.write("\n");
writer.endElement("button");
writer.write("\n");
writer.startElement("div", component);
writer.writeAttribute("class", "dropdown-menu date-container", null);
writer.writeAttribute("role", "menu", null);
if (!componentDisabled) {
String onChangeEvent;
if (part.equals("month")) {
onChangeEvent = "dc_" + idJs + ".um(this,val);"
+ (component.formatVal().hasDay() ? "dc_" + idJs + ".sd(val);" : "");
} else {
onChangeEvent = "dc_" + idJs + ".uy(this);";
}
for (Integer option : options.keySet()) {
if (option == 9999 && part.equals("year")) {
writer.startElement("input", component);
writer.writeAttribute("class", "form-control year-inp", null);
writer.writeAttribute("maxlength", "4", null);
writer.writeAttribute("onkeyup", "dc_" + idJs + ".yi(this);", null);
writer.endElement("input");
writer.write("\n");
} else {
writer.startElement("a", component);
writer.writeAttribute("class", "other-date", null);
writer.writeAttribute("onclick",
part.equals("month") ? onChangeEvent.replace("val", option.toString()) : onChangeEvent,
null);
writer.writeText(options.get(option), null);
writer.endElement("a");
writer.write("\n");
}
}
}
writer.endElement("div");
writer.write("\n");
writer.endElement("div");
}
private Map<Integer, String> getYearsMap(int max, int min, int yearInt) {
Map<Integer, String> yearsMap = new TreeMap<Integer, String>();
Calendar cal = new GregorianCalendar();
int minYear = cal.get(Calendar.YEAR) + min;
int range = max - min;
boolean addVarInput = range > 9;
if (addVarInput) {
range = 9;
}
if (yearInt < minYear || yearInt > minYear + range) {
yearsMap.put(yearInt, "" + yearInt);
if (range == 9)
range = 8;
}
String year;
for (int i = 0; i <= range; i++) {
year = "" + (minYear + i);
yearsMap.put(minYear + i, year);
}
if (addVarInput)
yearsMap.put(9999, "");
return yearsMap;
}
private static String getDisplayType(BootDateButton button, FacesContext context, String partType) {
String displayType = button.get(partType);
if (displayType == null || (!displayType.equals("default")) && (!displayType.equals("primary"))
&& (!displayType.equals("success")) && (!displayType.equals("info")) && (!displayType.equals("warning"))
&& (!displayType.equals("danger")))
displayType = "default";
return displayType;
}
@Override
public boolean getRendersChildren() {
return true;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteCompute;
import org.apache.ignite.cache.affinity.Affinity;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.cluster.ClusterTopologyException;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.IgniteKernal;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteCallable;
import org.apache.ignite.lang.IgniteRunnable;
import org.apache.ignite.resources.IgniteInstanceResource;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.failover.always.AlwaysFailoverSpi;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;
/**
* Test for {@link IgniteCompute#affinityCall(String, Object, IgniteCallable)} and
* {@link IgniteCompute#affinityRun(String, Object, IgniteRunnable)}.
*/
public class CacheAffinityCallSelfTest extends GridCommonAbstractTest {
/** */
private static final String CACHE_NAME = "myCache";
/** */
private static final int SRVS = 4;
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
AlwaysFailoverSpi failSpi = new AlwaysFailoverSpi();
cfg.setFailoverSpi(failSpi);
// Do not configure cache on client.
if (igniteInstanceName.equals(getTestIgniteInstanceName(SRVS))) {
cfg.setClientMode(true);
((TcpDiscoverySpi)cfg.getDiscoverySpi()).setForceServerMode(true);
}
else {
CacheConfiguration ccfg = defaultCacheConfiguration();
ccfg.setName(CACHE_NAME);
ccfg.setCacheMode(PARTITIONED);
ccfg.setBackups(1);
cfg.setCacheConfiguration(ccfg);
}
return cfg;
}
/**
* @throws Exception If failed.
*/
@Test
public void testAffinityCallRestartNode() throws Exception {
startGridsMultiThreaded(SRVS);
affinityCallRestartNode();
}
/**
* @throws Exception If failed.
*/
@Test
public void testAffinityCallFromClientRestartNode() throws Exception {
startGridsMultiThreaded(SRVS + 1);
Ignite client = grid(SRVS);
assertTrue(client.configuration().isClientMode());
affinityCallRestartNode();
}
/**
* @throws Exception If failed.
*/
private void affinityCallRestartNode() throws Exception {
final int ITERS = 10;
for (int i = 0; i < ITERS; i++) {
log.info("Iteration: " + i);
Integer key = primaryKey(grid(0).cache(CACHE_NAME));
AffinityTopologyVersion topVer = grid(0).context().discovery().topologyVersionEx();
IgniteInternalFuture<Object> fut = GridTestUtils.runAsync(new Callable<Object>() {
@Override public Object call() throws Exception {
U.sleep(500);
stopGrid(0);
return null;
}
}, "stop-thread");
while (!fut.isDone())
grid(1).compute().affinityCall(CACHE_NAME, key, new CheckCallable(key, topVer));
fut.get();
if (i < ITERS - 1)
startGrid(0);
}
stopAllGrids();
}
/**
* @throws Exception If failed.
*/
@Test
public void testAffinityCallNoServerNode() throws Exception {
startGridsMultiThreaded(SRVS + 1);
final Integer key = 1;
final IgniteEx client = grid(SRVS);
assertTrue(client.configuration().isClientMode());
assertNull(client.context().cache().cache(CACHE_NAME));
final int THREADS = 5;
CyclicBarrier b = new CyclicBarrier(THREADS + 1);
final IgniteInternalFuture<Object> fut = GridTestUtils.runAsync(new Callable<Object>() {
@Override public Object call() throws Exception {
b.await();
for (int i = 0; i < SRVS; ++i)
stopGrid(i, false);
return null;
}
});
try {
GridTestUtils.runMultiThreaded(new Callable<Object>() {
@Override public Void call() throws Exception {
b.await();
while (!fut.isDone())
client.compute().affinityCall(CACHE_NAME, key, new CheckCallable(key, null));
return null;
}
}, THREADS, "test-thread");
}
catch (ClusterTopologyException e) {
log.info("Expected error: " + e);
}
finally {
stopAllGrids();
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testAffinityFailoverNoCacheOnClient() throws Exception {
startGridsMultiThreaded(SRVS + 1);
final Integer key = 1;
final IgniteEx client = grid(SRVS);
assertTrue(client.configuration().isClientMode());
final IgniteInternalFuture<Object> fut = GridTestUtils.runAsync(new Callable<Object>() {
@Override public Object call() throws Exception {
for (int i = 0; i < SRVS - 1; ++i) {
U.sleep(ThreadLocalRandom.current().nextLong(100) + 50);
stopGrid(i, false);
}
return null;
}
});
try {
final Affinity<Integer> aff = client.affinity(CACHE_NAME);
assertNull(client.context().cache().cache(CACHE_NAME));
GridTestUtils.runMultiThreaded(new Runnable() {
@Override public void run() {
while (!fut.isDone())
assertNotNull(aff.mapKeyToNode(key));
}
}, 5, "test-thread");
}
finally {
stopAllGrids();
}
}
/**
* Test callable.
*/
public static class CheckCallable implements IgniteCallable<Object> {
/** Key. */
private final Object key;
/** */
@IgniteInstanceResource
private Ignite ignite;
/** */
private AffinityTopologyVersion topVer;
/**
* @param key Key.
* @param topVer Topology version.
*/
public CheckCallable(Object key, AffinityTopologyVersion topVer) {
this.key = key;
this.topVer = topVer;
}
/** {@inheritDoc} */
@Override public Object call() throws IgniteCheckedException {
if (topVer != null) {
GridCacheAffinityManager aff =
((IgniteKernal)ignite).context().cache().internalCache(CACHE_NAME).context().affinity();
ClusterNode loc = ignite.cluster().localNode();
if (loc.equals(aff.primaryByKey(key, topVer)))
return true;
AffinityTopologyVersion topVer0 = new AffinityTopologyVersion(topVer.topologyVersion() + 1, 0);
assertEquals(loc, aff.primaryByKey(key, topVer0));
}
return null;
}
}
}
| |
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.identitymanagement.model;
import java.io.Serializable;
/**
* <p>
* Contains information about an AWS access key, without its secret key.
* </p>
* <p>
* This data type is used as a response element in the <a>ListAccessKeys</a>
* action.
* </p>
*/
public class AccessKeyMetadata implements Serializable, Cloneable {
/**
* <p>
* The name of the IAM user that the key is associated with.
* </p>
*/
private String userName;
/**
* <p>
* The ID for this access key.
* </p>
*/
private String accessKeyId;
/**
* <p>
* The status of the access key. <code>Active</code> means the key is valid
* for API calls; <code>Inactive</code> means it is not.
* </p>
*/
private String status;
/**
* <p>
* The date when the access key was created.
* </p>
*/
private java.util.Date createDate;
/**
* <p>
* The name of the IAM user that the key is associated with.
* </p>
*
* @param userName
* The name of the IAM user that the key is associated with.
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* <p>
* The name of the IAM user that the key is associated with.
* </p>
*
* @return The name of the IAM user that the key is associated with.
*/
public String getUserName() {
return this.userName;
}
/**
* <p>
* The name of the IAM user that the key is associated with.
* </p>
*
* @param userName
* The name of the IAM user that the key is associated with.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public AccessKeyMetadata withUserName(String userName) {
setUserName(userName);
return this;
}
/**
* <p>
* The ID for this access key.
* </p>
*
* @param accessKeyId
* The ID for this access key.
*/
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
/**
* <p>
* The ID for this access key.
* </p>
*
* @return The ID for this access key.
*/
public String getAccessKeyId() {
return this.accessKeyId;
}
/**
* <p>
* The ID for this access key.
* </p>
*
* @param accessKeyId
* The ID for this access key.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public AccessKeyMetadata withAccessKeyId(String accessKeyId) {
setAccessKeyId(accessKeyId);
return this;
}
/**
* <p>
* The status of the access key. <code>Active</code> means the key is valid
* for API calls; <code>Inactive</code> means it is not.
* </p>
*
* @param status
* The status of the access key. <code>Active</code> means the key is
* valid for API calls; <code>Inactive</code> means it is not.
* @see StatusType
*/
public void setStatus(String status) {
this.status = status;
}
/**
* <p>
* The status of the access key. <code>Active</code> means the key is valid
* for API calls; <code>Inactive</code> means it is not.
* </p>
*
* @return The status of the access key. <code>Active</code> means the key
* is valid for API calls; <code>Inactive</code> means it is not.
* @see StatusType
*/
public String getStatus() {
return this.status;
}
/**
* <p>
* The status of the access key. <code>Active</code> means the key is valid
* for API calls; <code>Inactive</code> means it is not.
* </p>
*
* @param status
* The status of the access key. <code>Active</code> means the key is
* valid for API calls; <code>Inactive</code> means it is not.
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see StatusType
*/
public AccessKeyMetadata withStatus(String status) {
setStatus(status);
return this;
}
/**
* <p>
* The status of the access key. <code>Active</code> means the key is valid
* for API calls; <code>Inactive</code> means it is not.
* </p>
*
* @param status
* The status of the access key. <code>Active</code> means the key is
* valid for API calls; <code>Inactive</code> means it is not.
* @see StatusType
*/
public void setStatus(StatusType status) {
this.status = status.toString();
}
/**
* <p>
* The status of the access key. <code>Active</code> means the key is valid
* for API calls; <code>Inactive</code> means it is not.
* </p>
*
* @param status
* The status of the access key. <code>Active</code> means the key is
* valid for API calls; <code>Inactive</code> means it is not.
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see StatusType
*/
public AccessKeyMetadata withStatus(StatusType status) {
setStatus(status);
return this;
}
/**
* <p>
* The date when the access key was created.
* </p>
*
* @param createDate
* The date when the access key was created.
*/
public void setCreateDate(java.util.Date createDate) {
this.createDate = createDate;
}
/**
* <p>
* The date when the access key was created.
* </p>
*
* @return The date when the access key was created.
*/
public java.util.Date getCreateDate() {
return this.createDate;
}
/**
* <p>
* The date when the access key was created.
* </p>
*
* @param createDate
* The date when the access key was created.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public AccessKeyMetadata withCreateDate(java.util.Date createDate) {
setCreateDate(createDate);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getUserName() != null)
sb.append("UserName: " + getUserName() + ",");
if (getAccessKeyId() != null)
sb.append("AccessKeyId: " + getAccessKeyId() + ",");
if (getStatus() != null)
sb.append("Status: " + getStatus() + ",");
if (getCreateDate() != null)
sb.append("CreateDate: " + getCreateDate());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof AccessKeyMetadata == false)
return false;
AccessKeyMetadata other = (AccessKeyMetadata) obj;
if (other.getUserName() == null ^ this.getUserName() == null)
return false;
if (other.getUserName() != null
&& other.getUserName().equals(this.getUserName()) == false)
return false;
if (other.getAccessKeyId() == null ^ this.getAccessKeyId() == null)
return false;
if (other.getAccessKeyId() != null
&& other.getAccessKeyId().equals(this.getAccessKeyId()) == false)
return false;
if (other.getStatus() == null ^ this.getStatus() == null)
return false;
if (other.getStatus() != null
&& other.getStatus().equals(this.getStatus()) == false)
return false;
if (other.getCreateDate() == null ^ this.getCreateDate() == null)
return false;
if (other.getCreateDate() != null
&& other.getCreateDate().equals(this.getCreateDate()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getUserName() == null) ? 0 : getUserName().hashCode());
hashCode = prime
* hashCode
+ ((getAccessKeyId() == null) ? 0 : getAccessKeyId().hashCode());
hashCode = prime * hashCode
+ ((getStatus() == null) ? 0 : getStatus().hashCode());
hashCode = prime * hashCode
+ ((getCreateDate() == null) ? 0 : getCreateDate().hashCode());
return hashCode;
}
@Override
public AccessKeyMetadata clone() {
try {
return (AccessKeyMetadata) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.fs;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.Iterator;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.DFSClient;
import org.apache.hadoop.hdfs.protocol.DirectoryListing;
import org.apache.hadoop.hdfs.protocol.FSConstants;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.util.Progressable;
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class Hdfs extends AbstractFileSystem {
DFSClient dfs;
private boolean verifyChecksum = true;
static {
Configuration.addDefaultResource("hdfs-default.xml");
Configuration.addDefaultResource("hdfs-site.xml");
}
/**
* This constructor has the signature needed by
* {@link AbstractFileSystem#createFileSystem(URI, Configuration)}
*
* @param theUri
* which must be that of Hdfs
* @param conf
* @throws IOException
*/
Hdfs(final URI theUri, final Configuration conf) throws IOException, URISyntaxException {
super(theUri, FSConstants.HDFS_URI_SCHEME, true, NameNode.DEFAULT_PORT);
if (!theUri.getScheme().equalsIgnoreCase(FSConstants.HDFS_URI_SCHEME)) {
throw new IllegalArgumentException("Passed URI's scheme is not for Hdfs");
}
String host = theUri.getHost();
if (host == null) {
throw new IOException("Incomplete HDFS URI, no host: " + theUri);
}
InetSocketAddress namenode = NameNode.getAddress(theUri.getAuthority());
this.dfs = new DFSClient(namenode, conf, getStatistics());
}
@Override
protected int getUriDefaultPort() {
return NameNode.DEFAULT_PORT;
}
@Override
protected FSDataOutputStream createInternal(Path f,
EnumSet<CreateFlag> createFlag, FsPermission absolutePermission,
int bufferSize, short replication, long blockSize, Progressable progress,
int bytesPerChecksum, boolean createParent) throws IOException {
return new FSDataOutputStream(dfs.primitiveCreate(getUriPath(f),
absolutePermission, createFlag, createParent, replication, blockSize,
progress, bufferSize, bytesPerChecksum), getStatistics());
}
@Override
protected boolean delete(Path f, boolean recursive)
throws IOException, UnresolvedLinkException {
return dfs.delete(getUriPath(f), recursive);
}
@Override
protected BlockLocation[] getFileBlockLocations(Path p, long start, long len)
throws IOException, UnresolvedLinkException {
return dfs.getBlockLocations(getUriPath(p), start, len);
}
@Override
protected FileChecksum getFileChecksum(Path f)
throws IOException, UnresolvedLinkException {
return dfs.getFileChecksum(getUriPath(f));
}
@Override
protected FileStatus getFileStatus(Path f)
throws IOException, UnresolvedLinkException {
HdfsFileStatus fi = dfs.getFileInfo(getUriPath(f));
if (fi != null) {
return makeQualified(fi, f);
} else {
throw new FileNotFoundException("File does not exist: " + f.toString());
}
}
@Override
public FileStatus getFileLinkStatus(Path f)
throws IOException, UnresolvedLinkException {
HdfsFileStatus fi = dfs.getFileLinkInfo(getUriPath(f));
if (fi != null) {
return makeQualified(fi, f);
} else {
throw new FileNotFoundException("File does not exist: " + f);
}
}
private FileStatus makeQualified(HdfsFileStatus f, Path parent) {
// NB: symlink is made fully-qualified in FileContext.
return new FileStatus(f.getLen(), f.isDir(), f.getReplication(),
f.getBlockSize(), f.getModificationTime(),
f.getAccessTime(),
f.getPermission(), f.getOwner(), f.getGroup(),
f.isSymlink() ? new Path(f.getSymlink()) : null,
(f.getFullPath(parent)).makeQualified(
getUri(), null)); // fully-qualify path
}
@Override
protected FsStatus getFsStatus() throws IOException {
return dfs.getDiskStatus();
}
@Override
protected FsServerDefaults getServerDefaults() throws IOException {
return dfs.getServerDefaults();
}
@Override
protected Iterator<FileStatus> listStatusIterator(final Path f)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
return new Iterator<FileStatus>() {
private DirectoryListing thisListing;
private int i;
private String src;
{ // initializer
src = getUriPath(f);
// fetch the first batch of entries in the directory
thisListing = dfs.listPaths(src, HdfsFileStatus.EMPTY_NAME);
if (thisListing == null) { // the directory does not exist
throw new FileNotFoundException("File " + f + " does not exist.");
}
}
@Override
public boolean hasNext() {
if (thisListing == null) {
return false;
}
try {
if (i>=thisListing.getPartialListing().length && thisListing.hasMore()) {
// current listing is exhausted & fetch a new listing
thisListing = dfs.listPaths(src, thisListing.getLastName());
if (thisListing == null) {
return false; // the directory is deleted
}
i = 0;
}
return (i<thisListing.getPartialListing().length);
} catch (IOException ioe) {
return false;
}
}
@Override
public FileStatus next() {
if (hasNext()) {
return makeQualified(thisListing.getPartialListing()[i++], f);
}
throw new java.util.NoSuchElementException("No more entry in " + f);
}
@Override
public void remove() {
throw new UnsupportedOperationException("Remove is not supported");
}
};
}
@Override
protected FileStatus[] listStatus(Path f)
throws IOException, UnresolvedLinkException {
String src = getUriPath(f);
// fetch the first batch of entries in the directory
DirectoryListing thisListing = dfs.listPaths(
src, HdfsFileStatus.EMPTY_NAME);
if (thisListing == null) { // the directory does not exist
throw new FileNotFoundException("File " + f + " does not exist.");
}
HdfsFileStatus[] partialListing = thisListing.getPartialListing();
if (!thisListing.hasMore()) { // got all entries of the directory
FileStatus[] stats = new FileStatus[partialListing.length];
for (int i = 0; i < partialListing.length; i++) {
stats[i] = makeQualified(partialListing[i], f);
}
return stats;
}
// The directory size is too big that it needs to fetch more
// estimate the total number of entries in the directory
int totalNumEntries =
partialListing.length + thisListing.getRemainingEntries();
ArrayList<FileStatus> listing =
new ArrayList<FileStatus>(totalNumEntries);
// add the first batch of entries to the array list
for (HdfsFileStatus fileStatus : partialListing) {
listing.add(makeQualified(fileStatus, f));
}
// now fetch more entries
do {
thisListing = dfs.listPaths(src, thisListing.getLastName());
if (thisListing == null) {
// the directory is deleted
throw new FileNotFoundException("File " + f + " does not exist.");
}
partialListing = thisListing.getPartialListing();
for (HdfsFileStatus fileStatus : partialListing) {
listing.add(makeQualified(fileStatus, f));
}
} while (thisListing.hasMore());
return listing.toArray(new FileStatus[listing.size()]);
}
@Override
protected void mkdir(Path dir, FsPermission permission, boolean createParent)
throws IOException, UnresolvedLinkException {
dfs.mkdirs(getUriPath(dir), permission, createParent);
}
@Override
protected FSDataInputStream open(Path f, int bufferSize)
throws IOException, UnresolvedLinkException {
return new DFSClient.DFSDataInputStream(dfs.open(getUriPath(f),
bufferSize, verifyChecksum));
}
@Override
protected void renameInternal(Path src, Path dst)
throws IOException, UnresolvedLinkException {
dfs.rename(getUriPath(src), getUriPath(dst));
}
@Override
protected void renameInternal(Path src, Path dst, boolean overwrite)
throws IOException, UnresolvedLinkException {
dfs.rename(getUriPath(src), getUriPath(dst),
overwrite ? Options.Rename.OVERWRITE : Options.Rename.NONE);
}
@Override
protected void setOwner(Path f, String username, String groupname)
throws IOException, UnresolvedLinkException {
dfs.setOwner(getUriPath(f), username, groupname);
}
@Override
protected void setPermission(Path f, FsPermission permission)
throws IOException, UnresolvedLinkException {
dfs.setPermission(getUriPath(f), permission);
}
@Override
protected boolean setReplication(Path f, short replication)
throws IOException, UnresolvedLinkException {
return dfs.setReplication(getUriPath(f), replication);
}
@Override
protected void setTimes(Path f, long mtime, long atime)
throws IOException, UnresolvedLinkException {
dfs.setTimes(getUriPath(f), mtime, atime);
}
@Override
protected void setVerifyChecksum(boolean verifyChecksum)
throws IOException {
this.verifyChecksum = verifyChecksum;
}
@Override
protected boolean supportsSymlinks() {
return true;
}
@Override
protected void createSymlink(Path target, Path link, boolean createParent)
throws IOException, UnresolvedLinkException {
dfs.createSymlink(target.toString(), getUriPath(link), createParent);
}
@Override
protected Path getLinkTarget(Path p) throws IOException {
return new Path(dfs.getLinkTarget(getUriPath(p)));
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.aggregation;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.block.BlockBuilderStatus;
import com.facebook.presto.operator.Page;
import com.facebook.presto.spi.type.Type;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import io.airlift.slice.Slice;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import static io.airlift.testing.Assertions.assertLessThan;
import static org.testng.Assert.assertEquals;
public abstract class AbstractTestApproximateCountDistinct
{
public abstract AggregationFunction getAggregationFunction();
public abstract Type getValueType();
public abstract Object randomValue();
@Test
public void testNoPositions()
throws Exception
{
assertCount(ImmutableList.<Object>of(), 0);
}
@Test
public void testSinglePosition()
throws Exception
{
assertCount(ImmutableList.<Object>of(randomValue()), 1);
}
@Test
public void testAllPositionsNull()
throws Exception
{
assertCount(Collections.<Object>nCopies(100, null), 0);
}
@Test
public void testMixedNullsAndNonNulls()
throws Exception
{
List<Object> baseline = createRandomSample(10000, 15000);
List<Object> mixed = new ArrayList<>(baseline);
mixed.addAll(Collections.<Long>nCopies(baseline.size(), null));
Collections.shuffle(mixed);
assertCount(mixed, estimateGroupByCount(baseline));
}
@Test
public void testMultiplePositions()
throws Exception
{
DescriptiveStatistics stats = new DescriptiveStatistics();
for (int i = 0; i < 500; ++i) {
int uniques = ThreadLocalRandom.current().nextInt(20000) + 1;
List<Object> values = createRandomSample(uniques, (int) (uniques * 1.5));
long actual = estimateGroupByCount(values);
double error = (actual - uniques) * 1.0 / uniques;
stats.addValue(error);
}
assertLessThan(stats.getMean(), 1.0e-2);
assertLessThan(Math.abs(stats.getStandardDeviation() - ApproximateCountDistinctAggregation.getStandardError()), 1.0e-2);
}
@Test
public void testMultiplePositionsPartial()
throws Exception
{
for (int i = 0; i < 100; ++i) {
int uniques = ThreadLocalRandom.current().nextInt(20000) + 1;
List<Object> values = createRandomSample(uniques, (int) (uniques * 1.5));
assertEquals(estimateCountPartial(values), estimateGroupByCount(values));
}
}
private void assertCount(List<Object> values, long expectedCount)
{
if (!values.isEmpty()) {
assertEquals(estimateGroupByCount(values), expectedCount);
}
assertEquals(estimateCount(values), expectedCount);
assertEquals(estimateCountPartial(values), expectedCount);
}
private long estimateGroupByCount(List<Object> values)
{
Object result = AggregationTestUtils.groupedAggregation(getAggregationFunction(), 1.0, createPage(values));
return (long) result;
}
private long estimateCount(List<Object> values)
{
Object result = AggregationTestUtils.aggregation(getAggregationFunction(), 1.0, createPage(values));
return (long) result;
}
private long estimateCountPartial(List<Object> values)
{
Object result = AggregationTestUtils.partialAggregation(getAggregationFunction(), 1.0, createPage(values));
return (long) result;
}
private Page createPage(List<Object> values)
{
Page page;
if (values.isEmpty()) {
page = new Page(0);
}
else {
page = new Page(values.size(), createBlock(values));
}
return page;
}
/**
* Produce a block with the given values in the last field.
*/
private Block createBlock(List<Object> values)
{
BlockBuilder blockBuilder = getValueType().createBlockBuilder(new BlockBuilderStatus());
for (Object value : values) {
if (value == null) {
blockBuilder.appendNull();
}
else {
Class<?> javaType = getValueType().getJavaType();
if (javaType == boolean.class) {
blockBuilder.appendBoolean((Boolean) value);
}
else if (javaType == long.class) {
blockBuilder.appendLong((Long) value);
}
else if (javaType == double.class) {
blockBuilder.appendDouble((Double) value);
}
else if (javaType == Slice.class) {
blockBuilder.appendSlice((Slice) value);
}
else {
throw new UnsupportedOperationException("not yet implemented");
}
}
}
return blockBuilder.build();
}
private List<Object> createRandomSample(int uniques, int total)
{
Preconditions.checkArgument(uniques <= total, "uniques (%s) must be <= total (%s)", uniques, total);
List<Object> result = new ArrayList<>(total);
result.addAll(makeRandomSet(uniques));
Random random = ThreadLocalRandom.current();
while (result.size() < total) {
int index = random.nextInt(result.size());
result.add(result.get(index));
}
return result;
}
private Set<Object> makeRandomSet(int count)
{
Set<Object> result = new HashSet<>();
while (result.size() < count) {
result.add(randomValue());
}
return result;
}
}
| |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.index.mapper;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.CannedTokenStream;
import org.apache.lucene.analysis.MockSynonymAnalyzer;
import org.apache.lucene.analysis.StopFilter;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
import org.apache.lucene.analysis.en.EnglishAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.index.DocValuesType;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.IndexableFieldType;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.queries.spans.FieldMaskingSpanQuery;
import org.apache.lucene.queries.spans.SpanNearQuery;
import org.apache.lucene.queries.spans.SpanOrQuery;
import org.apache.lucene.queries.spans.SpanTermQuery;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MultiPhraseQuery;
import org.apache.lucene.search.NormsFieldExistsQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.SynonymQuery;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.lucene.search.MultiPhrasePrefixQuery;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.analysis.AnalyzerScope;
import org.elasticsearch.index.analysis.CharFilterFactory;
import org.elasticsearch.index.analysis.CustomAnalyzer;
import org.elasticsearch.index.analysis.IndexAnalyzers;
import org.elasticsearch.index.analysis.NamedAnalyzer;
import org.elasticsearch.index.analysis.StandardTokenizerFactory;
import org.elasticsearch.index.analysis.TokenFilterFactory;
import org.elasticsearch.index.mapper.TextFieldMapper.TextFieldType;
import org.elasticsearch.index.query.MatchPhrasePrefixQueryBuilder;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.SearchExecutionContext;
import org.elasticsearch.index.search.MatchQueryParser;
import org.elasticsearch.index.search.QueryStringQueryParser;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.core.Is.is;
public class TextFieldMapperTests extends MapperTestCase {
@Override
protected Object getSampleValueForDocument() {
return "value";
}
public final void testExistsQueryIndexDisabled() throws IOException {
MapperService mapperService = createMapperService(fieldMapping(b -> {
minimalMapping(b);
b.field("index", false);
b.field("norms", false);
}));
assertExistsQuery(mapperService);
assertParseMinimalWarnings();
}
public final void testExistsQueryIndexDisabledStoreTrue() throws IOException {
MapperService mapperService = createMapperService(fieldMapping(b -> {
minimalMapping(b);
b.field("index", false);
b.field("norms", false);
b.field("store", true);
}));
assertExistsQuery(mapperService);
assertParseMinimalWarnings();
}
public final void testExistsQueryWithNorms() throws IOException {
MapperService mapperService = createMapperService(fieldMapping(b -> {
minimalMapping(b);
b.field("norms", false);
}));
assertExistsQuery(mapperService);
assertParseMinimalWarnings();
}
@Override
protected void registerParameters(ParameterChecker checker) throws IOException {
checker.registerUpdateCheck(b -> b.field("fielddata", true), m -> {
TextFieldType ft = (TextFieldType) m.fieldType();
assertTrue(ft.fielddata());
});
checker.registerUpdateCheck(b -> {
b.field("fielddata", true);
b.startObject("fielddata_frequency_filter");
{
b.field("min", 10);
b.field("max", 20);
b.field("min_segment_size", 100);
}
b.endObject();
}, m -> {
TextFieldType ft = (TextFieldType) m.fieldType();
assertEquals(10, ft.fielddataMinFrequency(), 0);
assertEquals(20, ft.fielddataMaxFrequency(), 0);
assertEquals(100, ft.fielddataMinSegmentSize());
});
checker.registerUpdateCheck(b -> b.field("eager_global_ordinals", "true"), m -> assertTrue(m.fieldType().eagerGlobalOrdinals()));
checker.registerUpdateCheck(b -> {
b.field("analyzer", "default");
b.field("search_analyzer", "keyword");
}, m -> assertEquals("keyword", m.fieldType().getTextSearchInfo().getSearchAnalyzer().name()));
checker.registerUpdateCheck(b -> {
b.field("analyzer", "default");
b.field("search_analyzer", "keyword");
b.field("search_quote_analyzer", "keyword");
}, m -> assertEquals("keyword", m.fieldType().getTextSearchInfo().getSearchQuoteAnalyzer().name()));
checker.registerConflictCheck("index", b -> b.field("index", false));
checker.registerConflictCheck("store", b -> b.field("store", true));
checker.registerConflictCheck("index_phrases", b -> b.field("index_phrases", true));
checker.registerConflictCheck("index_prefixes", b -> b.startObject("index_prefixes").endObject());
checker.registerConflictCheck("index_options", b -> b.field("index_options", "docs"));
checker.registerConflictCheck("similarity", b -> b.field("similarity", "boolean"));
checker.registerConflictCheck("analyzer", b -> b.field("analyzer", "keyword"));
checker.registerConflictCheck("term_vector", b -> b.field("term_vector", "yes"));
checker.registerConflictCheck("position_increment_gap", b -> b.field("position_increment_gap", 10));
// norms can be set from true to false, but not vice versa
checker.registerConflictCheck("norms", fieldMapping(b -> {
b.field("type", "text");
b.field("norms", false);
}), fieldMapping(b -> {
b.field("type", "text");
b.field("norms", true);
}));
checker.registerUpdateCheck(b -> {
b.field("type", "text");
b.field("norms", true);
}, b -> {
b.field("type", "text");
b.field("norms", false);
}, m -> assertFalse(m.fieldType().getTextSearchInfo().hasNorms()));
}
@Override
protected IndexAnalyzers createIndexAnalyzers(IndexSettings indexSettings) {
NamedAnalyzer dflt = new NamedAnalyzer(
"default",
AnalyzerScope.INDEX,
new StandardAnalyzer(),
TextFieldMapper.Defaults.POSITION_INCREMENT_GAP
);
NamedAnalyzer standard = new NamedAnalyzer("standard", AnalyzerScope.INDEX, new StandardAnalyzer());
NamedAnalyzer keyword = new NamedAnalyzer("keyword", AnalyzerScope.INDEX, new KeywordAnalyzer());
NamedAnalyzer whitespace = new NamedAnalyzer("whitespace", AnalyzerScope.INDEX, new WhitespaceAnalyzer());
NamedAnalyzer stop = new NamedAnalyzer(
"my_stop_analyzer",
AnalyzerScope.INDEX,
new CustomAnalyzer(
new StandardTokenizerFactory(indexSettings, null, "standard", indexSettings.getSettings()),
new CharFilterFactory[0],
new TokenFilterFactory[] { new TokenFilterFactory() {
@Override
public String name() {
return "stop";
}
@Override
public TokenStream create(TokenStream tokenStream) {
return new StopFilter(tokenStream, EnglishAnalyzer.ENGLISH_STOP_WORDS_SET);
}
} }
)
);
return new IndexAnalyzers(
Map.of("default", dflt, "standard", standard, "keyword", keyword, "whitespace", whitespace, "my_stop_analyzer", stop),
Map.of(),
Map.of()
);
}
@Override
protected void minimalMapping(XContentBuilder b) throws IOException {
b.field("type", "text");
}
public void testDefaults() throws IOException {
DocumentMapper mapper = createDocumentMapper(fieldMapping(this::minimalMapping));
assertEquals(Strings.toString(fieldMapping(this::minimalMapping)), mapper.mappingSource().toString());
ParsedDocument doc = mapper.parse(source(b -> b.field("field", "1234")));
IndexableField[] fields = doc.rootDoc().getFields("field");
assertEquals(1, fields.length);
assertEquals("1234", fields[0].stringValue());
IndexableFieldType fieldType = fields[0].fieldType();
assertThat(fieldType.omitNorms(), equalTo(false));
assertTrue(fieldType.tokenized());
assertFalse(fieldType.stored());
assertThat(fieldType.indexOptions(), equalTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS));
assertThat(fieldType.storeTermVectors(), equalTo(false));
assertThat(fieldType.storeTermVectorOffsets(), equalTo(false));
assertThat(fieldType.storeTermVectorPositions(), equalTo(false));
assertThat(fieldType.storeTermVectorPayloads(), equalTo(false));
assertEquals(DocValuesType.NONE, fieldType.docValuesType());
}
public void testBWCSerialization() throws IOException {
MapperService mapperService = createMapperService(fieldMapping(b -> {
b.field("type", "text");
b.field("fielddata", true);
b.startObject("fields");
{
b.startObject("subfield").field("type", "long").endObject();
}
b.endObject();
}));
assertEquals(
"{\"_doc\":{\"properties\":{\"field\":{\"type\":\"text\",\"fields\":{\"subfield\":{\"type\":\"long\"}},\"fielddata\":true}}}}",
Strings.toString(mapperService.documentMapper().mapping())
);
}
public void testEnableStore() throws IOException {
DocumentMapper mapper = createDocumentMapper(fieldMapping(b -> b.field("type", "text").field("store", true)));
ParsedDocument doc = mapper.parse(source(b -> b.field("field", "1234")));
IndexableField[] fields = doc.rootDoc().getFields("field");
assertEquals(1, fields.length);
assertTrue(fields[0].fieldType().stored());
}
public void testDisableIndex() throws IOException {
DocumentMapper mapper = createDocumentMapper(fieldMapping(b -> b.field("type", "text").field("index", false)));
ParsedDocument doc = mapper.parse(source(b -> b.field("field", "1234")));
IndexableField[] fields = doc.rootDoc().getFields("field");
assertEquals(0, fields.length);
}
public void testDisableNorms() throws IOException {
DocumentMapper mapper = createDocumentMapper(fieldMapping(b -> b.field("type", "text").field("norms", false)));
ParsedDocument doc = mapper.parse(source(b -> b.field("field", "1234")));
IndexableField[] fields = doc.rootDoc().getFields("field");
assertEquals(1, fields.length);
assertTrue(fields[0].fieldType().omitNorms());
}
public void testIndexOptions() throws IOException {
Map<String, IndexOptions> supportedOptions = new HashMap<>();
supportedOptions.put("docs", IndexOptions.DOCS);
supportedOptions.put("freqs", IndexOptions.DOCS_AND_FREQS);
supportedOptions.put("positions", IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
supportedOptions.put("offsets", IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type").startObject("properties");
for (String option : supportedOptions.keySet()) {
mapping.startObject(option).field("type", "text").field("index_options", option).endObject();
}
mapping.endObject().endObject().endObject();
DocumentMapper mapper = createDocumentMapper(mapping);
String serialized = Strings.toString(mapper.mapping());
assertThat(serialized, containsString("\"offsets\":{\"type\":\"text\",\"index_options\":\"offsets\"}"));
assertThat(serialized, containsString("\"freqs\":{\"type\":\"text\",\"index_options\":\"freqs\"}"));
assertThat(serialized, containsString("\"docs\":{\"type\":\"text\",\"index_options\":\"docs\"}"));
ParsedDocument doc = mapper.parse(source(b -> {
for (String option : supportedOptions.keySet()) {
b.field(option, "1234");
}
}));
for (Map.Entry<String, IndexOptions> entry : supportedOptions.entrySet()) {
String field = entry.getKey();
IndexOptions options = entry.getValue();
IndexableField[] fields = doc.rootDoc().getFields(field);
assertEquals(1, fields.length);
assertEquals(options, fields[0].fieldType().indexOptions());
}
}
public void testDefaultPositionIncrementGap() throws IOException {
MapperService mapperService = createMapperService(fieldMapping(this::minimalMapping));
ParsedDocument doc = mapperService.documentMapper().parse(source(b -> b.array("field", new String[] { "a", "b" })));
IndexableField[] fields = doc.rootDoc().getFields("field");
assertEquals(2, fields.length);
assertEquals("a", fields[0].stringValue());
assertEquals("b", fields[1].stringValue());
withLuceneIndex(mapperService, iw -> iw.addDocument(doc.rootDoc()), reader -> {
TermsEnum terms = getOnlyLeafReader(reader).terms("field").iterator();
assertTrue(terms.seekExact(new BytesRef("b")));
PostingsEnum postings = terms.postings(null, PostingsEnum.POSITIONS);
assertEquals(0, postings.nextDoc());
assertEquals(TextFieldMapper.Defaults.POSITION_INCREMENT_GAP + 1, postings.nextPosition());
});
}
public void testDefaultPositionIncrementGapOnSubfields() throws IOException {
MapperService mapperService = createMapperService(fieldMapping(b -> {
b.field("type", "text");
b.field("index_phrases", true);
b.startObject("index_prefixes").endObject();
}));
ParsedDocument doc = mapperService.documentMapper().parse(source(b -> b.array("field", "aargle bargle", "foo bar")));
withLuceneIndex(mapperService, iw -> iw.addDocument(doc.rootDoc()), reader -> {
TermsEnum phraseTerms = getOnlyLeafReader(reader).terms("field._index_phrase").iterator();
assertTrue(phraseTerms.seekExact(new BytesRef("foo bar")));
PostingsEnum phrasePostings = phraseTerms.postings(null, PostingsEnum.POSITIONS);
assertEquals(0, phrasePostings.nextDoc());
assertEquals(TextFieldMapper.Defaults.POSITION_INCREMENT_GAP + 1, phrasePostings.nextPosition());
TermsEnum prefixTerms = getOnlyLeafReader(reader).terms("field._index_prefix").iterator();
assertTrue(prefixTerms.seekExact(new BytesRef("foo")));
PostingsEnum prefixPostings = prefixTerms.postings(null, PostingsEnum.POSITIONS);
assertEquals(0, prefixPostings.nextDoc());
assertEquals(TextFieldMapper.Defaults.POSITION_INCREMENT_GAP + 2, prefixPostings.nextPosition());
});
}
public void testPositionIncrementGap() throws IOException {
final int positionIncrementGap = randomIntBetween(1, 1000);
MapperService mapperService = createMapperService(
fieldMapping(b -> b.field("type", "text").field("position_increment_gap", positionIncrementGap))
);
ParsedDocument doc = mapperService.documentMapper().parse(source(b -> b.array("field", new String[] { "a", "b" })));
IndexableField[] fields = doc.rootDoc().getFields("field");
assertEquals(2, fields.length);
assertEquals("a", fields[0].stringValue());
assertEquals("b", fields[1].stringValue());
withLuceneIndex(mapperService, iw -> iw.addDocument(doc.rootDoc()), reader -> {
TermsEnum terms = getOnlyLeafReader(reader).terms("field").iterator();
assertTrue(terms.seekExact(new BytesRef("b")));
PostingsEnum postings = terms.postings(null, PostingsEnum.POSITIONS);
assertEquals(0, postings.nextDoc());
assertEquals(positionIncrementGap + 1, postings.nextPosition());
});
}
public void testPositionIncrementGapOnSubfields() throws IOException {
MapperService mapperService = createMapperService(fieldMapping(b -> {
b.field("type", "text");
b.field("position_increment_gap", 10);
b.field("index_phrases", true);
b.startObject("index_prefixes").endObject();
}));
ParsedDocument doc = mapperService.documentMapper().parse(source(b -> b.array("field", "aargle bargle", "foo bar")));
withLuceneIndex(mapperService, iw -> iw.addDocument(doc.rootDoc()), reader -> {
TermsEnum phraseTerms = getOnlyLeafReader(reader).terms("field._index_phrase").iterator();
assertTrue(phraseTerms.seekExact(new BytesRef("foo bar")));
PostingsEnum phrasePostings = phraseTerms.postings(null, PostingsEnum.POSITIONS);
assertEquals(0, phrasePostings.nextDoc());
assertEquals(11, phrasePostings.nextPosition());
TermsEnum prefixTerms = getOnlyLeafReader(reader).terms("field._index_prefix").iterator();
assertTrue(prefixTerms.seekExact(new BytesRef("foo")));
PostingsEnum prefixPostings = prefixTerms.postings(null, PostingsEnum.POSITIONS);
assertEquals(0, prefixPostings.nextDoc());
assertEquals(12, prefixPostings.nextPosition());
});
}
public void testSearchAnalyzerSerialization() throws IOException {
XContentBuilder mapping = fieldMapping(
b -> b.field("type", "text").field("analyzer", "standard").field("search_analyzer", "keyword")
);
assertEquals(Strings.toString(mapping), createDocumentMapper(mapping).mappingSource().toString());
// special case: default index analyzer
mapping = fieldMapping(b -> b.field("type", "text").field("analyzer", "default").field("search_analyzer", "keyword"));
assertEquals(Strings.toString(mapping), createDocumentMapper(mapping).mappingSource().toString());
// special case: default search analyzer
mapping = fieldMapping(b -> b.field("type", "text").field("analyzer", "keyword").field("search_analyzer", "default"));
assertEquals(Strings.toString(mapping), createDocumentMapper(mapping).mappingSource().toString());
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
createDocumentMapper(fieldMapping(this::minimalMapping)).mapping()
.toXContent(builder, new ToXContent.MapParams(Collections.singletonMap("include_defaults", "true")));
builder.endObject();
String mappingString = Strings.toString(builder);
assertTrue(mappingString.contains("analyzer"));
assertTrue(mappingString.contains("search_analyzer"));
assertTrue(mappingString.contains("search_quote_analyzer"));
}
public void testSearchQuoteAnalyzerSerialization() throws IOException {
XContentBuilder mapping = fieldMapping(
b -> b.field("type", "text")
.field("analyzer", "standard")
.field("search_analyzer", "standard")
.field("search_quote_analyzer", "keyword")
);
assertEquals(Strings.toString(mapping), createDocumentMapper(mapping).mappingSource().toString());
// special case: default index/search analyzer
mapping = fieldMapping(
b -> b.field("type", "text")
.field("analyzer", "default")
.field("search_analyzer", "default")
.field("search_quote_analyzer", "keyword")
);
assertEquals(Strings.toString(mapping), createDocumentMapper(mapping).mappingSource().toString());
}
public void testTermVectors() throws IOException {
XContentBuilder mapping = mapping(
b -> b.startObject("field1")
.field("type", "text")
.field("term_vector", "no")
.endObject()
.startObject("field2")
.field("type", "text")
.field("term_vector", "yes")
.endObject()
.startObject("field3")
.field("type", "text")
.field("term_vector", "with_offsets")
.endObject()
.startObject("field4")
.field("type", "text")
.field("term_vector", "with_positions")
.endObject()
.startObject("field5")
.field("type", "text")
.field("term_vector", "with_positions_offsets")
.endObject()
.startObject("field6")
.field("type", "text")
.field("term_vector", "with_positions_offsets_payloads")
.endObject()
);
DocumentMapper defaultMapper = createDocumentMapper(mapping);
ParsedDocument doc = defaultMapper.parse(
source(
b -> b.field("field1", "1234")
.field("field2", "1234")
.field("field3", "1234")
.field("field4", "1234")
.field("field5", "1234")
.field("field6", "1234")
)
);
assertThat(doc.rootDoc().getField("field1").fieldType().storeTermVectors(), equalTo(false));
assertThat(doc.rootDoc().getField("field1").fieldType().storeTermVectorOffsets(), equalTo(false));
assertThat(doc.rootDoc().getField("field1").fieldType().storeTermVectorPositions(), equalTo(false));
assertThat(doc.rootDoc().getField("field1").fieldType().storeTermVectorPayloads(), equalTo(false));
assertThat(doc.rootDoc().getField("field2").fieldType().storeTermVectors(), equalTo(true));
assertThat(doc.rootDoc().getField("field2").fieldType().storeTermVectorOffsets(), equalTo(false));
assertThat(doc.rootDoc().getField("field2").fieldType().storeTermVectorPositions(), equalTo(false));
assertThat(doc.rootDoc().getField("field2").fieldType().storeTermVectorPayloads(), equalTo(false));
assertThat(doc.rootDoc().getField("field3").fieldType().storeTermVectors(), equalTo(true));
assertThat(doc.rootDoc().getField("field3").fieldType().storeTermVectorOffsets(), equalTo(true));
assertThat(doc.rootDoc().getField("field3").fieldType().storeTermVectorPositions(), equalTo(false));
assertThat(doc.rootDoc().getField("field3").fieldType().storeTermVectorPayloads(), equalTo(false));
assertThat(doc.rootDoc().getField("field4").fieldType().storeTermVectors(), equalTo(true));
assertThat(doc.rootDoc().getField("field4").fieldType().storeTermVectorOffsets(), equalTo(false));
assertThat(doc.rootDoc().getField("field4").fieldType().storeTermVectorPositions(), equalTo(true));
assertThat(doc.rootDoc().getField("field4").fieldType().storeTermVectorPayloads(), equalTo(false));
assertThat(doc.rootDoc().getField("field5").fieldType().storeTermVectors(), equalTo(true));
assertThat(doc.rootDoc().getField("field5").fieldType().storeTermVectorOffsets(), equalTo(true));
assertThat(doc.rootDoc().getField("field5").fieldType().storeTermVectorPositions(), equalTo(true));
assertThat(doc.rootDoc().getField("field5").fieldType().storeTermVectorPayloads(), equalTo(false));
assertThat(doc.rootDoc().getField("field6").fieldType().storeTermVectors(), equalTo(true));
assertThat(doc.rootDoc().getField("field6").fieldType().storeTermVectorOffsets(), equalTo(true));
assertThat(doc.rootDoc().getField("field6").fieldType().storeTermVectorPositions(), equalTo(true));
assertThat(doc.rootDoc().getField("field6").fieldType().storeTermVectorPayloads(), equalTo(true));
}
public void testEagerGlobalOrdinals() throws IOException {
DocumentMapper mapper = createDocumentMapper(fieldMapping(b -> b.field("type", "text").field("eager_global_ordinals", true)));
FieldMapper fieldMapper = (FieldMapper) mapper.mappers().getMapper("field");
assertTrue(fieldMapper.fieldType().eagerGlobalOrdinals());
}
public void testFielddata() throws IOException {
MapperService disabledMapper = createMapperService(fieldMapping(this::minimalMapping));
Exception e = expectThrows(
IllegalArgumentException.class,
() -> disabledMapper.fieldType("field").fielddataBuilder("test", () -> { throw new UnsupportedOperationException(); })
);
assertThat(e.getMessage(), containsString("Text fields are not optimised for operations that require per-document field data"));
MapperService enabledMapper = createMapperService(fieldMapping(b -> b.field("type", "text").field("fielddata", true)));
enabledMapper.fieldType("field").fielddataBuilder("test", () -> { throw new UnsupportedOperationException(); }); // no exception
// this time
e = expectThrows(
MapperParsingException.class,
() -> createMapperService(fieldMapping(b -> b.field("type", "text").field("index", false).field("fielddata", true)))
);
assertThat(e.getMessage(), containsString("Cannot enable fielddata on a [text] field that is not indexed"));
}
public void testFrequencyFilter() throws IOException {
MapperService mapperService = createMapperService(
fieldMapping(
b -> b.field("type", "text")
.field("fielddata", true)
.startObject("fielddata_frequency_filter")
.field("min", 2d)
.field("min_segment_size", 1000)
.endObject()
)
);
TextFieldType fieldType = (TextFieldType) mapperService.fieldType("field");
assertThat(fieldType.fielddataMinFrequency(), equalTo(2d));
assertThat(fieldType.fielddataMaxFrequency(), equalTo((double) Integer.MAX_VALUE));
assertThat(fieldType.fielddataMinSegmentSize(), equalTo(1000));
}
public void testNullConfigValuesFail() throws MapperParsingException {
Exception e = expectThrows(
MapperParsingException.class,
() -> createDocumentMapper(fieldMapping(b -> b.field("type", "text").field("analyzer", (String) null)))
);
assertThat(e.getMessage(), containsString("[analyzer] on mapper [field] of type [text] must not have a [null] value"));
}
public void testNotIndexedFieldPositionIncrement() {
Exception e = expectThrows(
MapperParsingException.class,
() -> createDocumentMapper(fieldMapping(b -> b.field("type", "text").field("index", false).field("position_increment_gap", 10)))
);
assertThat(e.getMessage(), containsString("Cannot set position_increment_gap on field [field] without positions enabled"));
}
public void testAnalyzedFieldPositionIncrementWithoutPositions() {
for (String indexOptions : Arrays.asList("docs", "freqs")) {
Exception e = expectThrows(
MapperParsingException.class,
() -> createDocumentMapper(
fieldMapping(b -> b.field("type", "text").field("index_options", indexOptions).field("position_increment_gap", 10))
)
);
assertThat(e.getMessage(), containsString("Cannot set position_increment_gap on field [field] without positions enabled"));
}
}
public void testIndexPrefixIndexTypes() throws IOException {
{
DocumentMapper mapper = createDocumentMapper(
fieldMapping(
b -> b.field("type", "text")
.field("analyzer", "standard")
.startObject("index_prefixes")
.endObject()
.field("index_options", "offsets")
)
);
ParsedDocument doc = mapper.parse(source(b -> b.field("field", "some text")));
IndexableField field = doc.rootDoc().getField("field._index_prefix");
assertEquals(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, field.fieldType().indexOptions());
}
{
DocumentMapper mapper = createDocumentMapper(
fieldMapping(
b -> b.field("type", "text")
.field("analyzer", "standard")
.startObject("index_prefixes")
.endObject()
.field("index_options", "freqs")
)
);
ParsedDocument doc = mapper.parse(source(b -> b.field("field", "some text")));
IndexableField field = doc.rootDoc().getField("field._index_prefix");
assertEquals(IndexOptions.DOCS, field.fieldType().indexOptions());
assertFalse(field.fieldType().storeTermVectors());
}
{
DocumentMapper mapper = createDocumentMapper(
fieldMapping(
b -> b.field("type", "text")
.field("analyzer", "standard")
.startObject("index_prefixes")
.endObject()
.field("index_options", "positions")
)
);
ParsedDocument doc = mapper.parse(source(b -> b.field("field", "some text")));
IndexableField field = doc.rootDoc().getField("field._index_prefix");
assertEquals(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS, field.fieldType().indexOptions());
assertFalse(field.fieldType().storeTermVectors());
}
{
DocumentMapper mapper = createDocumentMapper(
fieldMapping(
b -> b.field("type", "text")
.field("analyzer", "standard")
.startObject("index_prefixes")
.endObject()
.field("term_vector", "with_positions_offsets")
)
);
ParsedDocument doc = mapper.parse(source(b -> b.field("field", "some text")));
IndexableField field = doc.rootDoc().getField("field._index_prefix");
assertEquals(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS, field.fieldType().indexOptions());
assertTrue(field.fieldType().storeTermVectorOffsets());
}
{
DocumentMapper mapper = createDocumentMapper(
fieldMapping(
b -> b.field("type", "text")
.field("analyzer", "standard")
.startObject("index_prefixes")
.endObject()
.field("term_vector", "with_positions")
)
);
ParsedDocument doc = mapper.parse(source(b -> b.field("field", "some text")));
IndexableField field = doc.rootDoc().getField("field._index_prefix");
assertEquals(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS, field.fieldType().indexOptions());
assertFalse(field.fieldType().storeTermVectorOffsets());
}
}
public void testNestedIndexPrefixes() throws IOException {
{
MapperService mapperService = createMapperService(
mapping(
b -> b.startObject("object")
.field("type", "object")
.startObject("properties")
.startObject("field")
.field("type", "text")
.startObject("index_prefixes")
.endObject()
.endObject()
.endObject()
.endObject()
)
);
MappedFieldType textField = mapperService.fieldType("object.field");
assertNotNull(textField);
assertThat(textField, instanceOf(TextFieldType.class));
MappedFieldType prefix = ((TextFieldType) textField).getPrefixFieldType();
assertEquals(prefix.name(), "object.field._index_prefix");
ParsedDocument doc = mapperService.documentMapper().parse(source(b -> b.field("object.field", "some text")));
IndexableField field = doc.rootDoc().getField("object.field._index_prefix");
assertEquals(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS, field.fieldType().indexOptions());
assertFalse(field.fieldType().storeTermVectorOffsets());
}
{
MapperService mapperService = createMapperService(
mapping(
b -> b.startObject("body")
.field("type", "text")
.startObject("fields")
.startObject("with_prefix")
.field("type", "text")
.startObject("index_prefixes")
.endObject()
.endObject()
.endObject()
.endObject()
)
);
MappedFieldType textField = mapperService.fieldType("body.with_prefix");
assertNotNull(textField);
assertThat(textField, instanceOf(TextFieldType.class));
MappedFieldType prefix = ((TextFieldType) textField).getPrefixFieldType();
assertEquals(prefix.name(), "body.with_prefix._index_prefix");
ParsedDocument doc = mapperService.documentMapper().parse(source(b -> b.field("body", "some text")));
IndexableField field = doc.rootDoc().getField("body.with_prefix._index_prefix");
assertEquals(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS, field.fieldType().indexOptions());
assertFalse(field.fieldType().storeTermVectorOffsets());
}
}
public void testFastPhraseMapping() throws IOException {
MapperService mapperService = createMapperService(mapping(b -> {
b.startObject("field").field("type", "text").field("analyzer", "my_stop_analyzer").field("index_phrases", true).endObject();
// "standard" will be replaced with MockSynonymAnalyzer
b.startObject("synfield").field("type", "text").field("analyzer", "standard").field("index_phrases", true).endObject();
}));
SearchExecutionContext searchExecutionContext = createSearchExecutionContext(mapperService);
Query q = new MatchPhraseQueryBuilder("field", "two words").toQuery(searchExecutionContext);
assertThat(q, is(new PhraseQuery("field._index_phrase", "two words")));
Query q2 = new MatchPhraseQueryBuilder("field", "three words here").toQuery(searchExecutionContext);
assertThat(q2, is(new PhraseQuery("field._index_phrase", "three words", "words here")));
Query q3 = new MatchPhraseQueryBuilder("field", "two words").slop(1).toQuery(searchExecutionContext);
assertThat(q3, is(new PhraseQuery(1, "field", "two", "words")));
Query q4 = new MatchPhraseQueryBuilder("field", "singleton").toQuery(searchExecutionContext);
assertThat(q4, is(new TermQuery(new Term("field", "singleton"))));
Query q5 = new MatchPhraseQueryBuilder("field", "sparkle a stopword").toQuery(searchExecutionContext);
assertThat(q5, is(new PhraseQuery.Builder().add(new Term("field", "sparkle")).add(new Term("field", "stopword"), 2).build()));
MatchQueryParser matchQueryParser = new MatchQueryParser(searchExecutionContext);
matchQueryParser.setAnalyzer(new MockSynonymAnalyzer());
Query q6 = matchQueryParser.parse(MatchQueryParser.Type.PHRASE, "synfield", "motor dogs");
assertThat(
q6,
is(
new MultiPhraseQuery.Builder().add(
new Term[] { new Term("synfield._index_phrase", "motor dogs"), new Term("synfield._index_phrase", "motor dog") }
).build()
)
);
// https://github.com/elastic/elasticsearch/issues/43976
CannedTokenStream cts = new CannedTokenStream(new Token("foo", 1, 0, 2, 2), new Token("bar", 0, 0, 2), new Token("baz", 1, 0, 2));
Analyzer synonymAnalyzer = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
return new TokenStreamComponents(reader -> {}, cts);
}
};
matchQueryParser.setAnalyzer(synonymAnalyzer);
Query q7 = matchQueryParser.parse(MatchQueryParser.Type.BOOLEAN, "synfield", "foo");
assertThat(
q7,
is(
new BooleanQuery.Builder().add(
new BooleanQuery.Builder().add(new TermQuery(new Term("synfield", "foo")), BooleanClause.Occur.SHOULD)
.add(
new PhraseQuery.Builder().add(new Term("synfield._index_phrase", "bar baz")).build(),
BooleanClause.Occur.SHOULD
)
.build(),
BooleanClause.Occur.SHOULD
).build()
)
);
ParsedDocument doc = mapperService.documentMapper()
.parse(source(b -> b.array("field", "Some English text that is going to be very useful", "bad", "Prio 1")));
IndexableField[] fields = doc.rootDoc().getFields("field._index_phrase");
assertEquals(3, fields.length);
try (TokenStream ts = fields[0].tokenStream(mapperService.indexAnalyzer(fields[0].name(), f -> null), null)) {
CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
ts.reset();
assertTrue(ts.incrementToken());
assertEquals("Some English", termAtt.toString());
}
withLuceneIndex(mapperService, iw -> iw.addDocuments(doc.docs()), ir -> {
IndexSearcher searcher = new IndexSearcher(ir);
MatchPhraseQueryBuilder queryBuilder = new MatchPhraseQueryBuilder("field", "Prio 1");
TopDocs td = searcher.search(queryBuilder.toQuery(searchExecutionContext), 1);
assertEquals(1, td.totalHits.value);
});
Exception e = expectThrows(
MapperParsingException.class,
() -> createMapperService(fieldMapping(b -> b.field("type", "text").field("index", "false").field("index_phrases", true)))
);
assertThat(e.getMessage(), containsString("Cannot set index_phrases on unindexed field [field]"));
e = expectThrows(
MapperParsingException.class,
() -> createMapperService(
fieldMapping(b -> b.field("type", "text").field("index_options", "freqs").field("index_phrases", true))
)
);
assertThat(e.getMessage(), containsString("Cannot set index_phrases on field [field] if positions are not enabled"));
}
public void testObjectExistsQuery() throws IOException, ParseException {
MapperService ms = createMapperService(mapping(b -> {
b.startObject("foo");
{
b.field("type", "object");
b.startObject("properties");
{
b.startObject("bar");
{
b.field("type", "text");
b.field("index_phrases", true);
}
b.endObject();
}
b.endObject();
}
b.endObject();
}));
SearchExecutionContext context = createSearchExecutionContext(ms);
QueryStringQueryParser parser = new QueryStringQueryParser(context, "f");
Query q = parser.parse("foo:*");
assertEquals(new ConstantScoreQuery(new NormsFieldExistsQuery("foo.bar")), q);
}
private static void assertAnalyzesTo(Analyzer analyzer, String field, String input, String[] output) throws IOException {
try (TokenStream ts = analyzer.tokenStream(field, input)) {
ts.reset();
CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
for (String t : output) {
assertTrue(ts.incrementToken());
assertEquals(t, termAtt.toString());
}
assertFalse(ts.incrementToken());
ts.end();
}
}
public void testIndexPrefixMapping() throws IOException {
{
MapperService ms = createMapperService(
fieldMapping(
b -> b.field("type", "text")
.field("analyzer", "standard")
.startObject("index_prefixes")
.field("min_chars", 2)
.field("max_chars", 6)
.endObject()
)
);
ParsedDocument doc = ms.documentMapper()
.parse(source(b -> b.field("field", "Some English text that is going to be very useful")));
IndexableField[] fields = doc.rootDoc().getFields("field._index_prefix");
assertEquals(1, fields.length);
withLuceneIndex(ms, iw -> iw.addDocument(doc.rootDoc()), ir -> {}); // check we can index
assertAnalyzesTo(
ms.indexAnalyzer("field._index_prefix", f -> null),
"field._index_prefix",
"tweedledum",
new String[] { "tw", "twe", "twee", "tweed", "tweedl" }
);
}
{
MapperService ms = createMapperService(
fieldMapping(b -> b.field("type", "text").field("analyzer", "standard").startObject("index_prefixes").endObject())
);
assertAnalyzesTo(
ms.indexAnalyzer("field._index_prefix", f -> null),
"field._index_prefix",
"tweedledum",
new String[] { "tw", "twe", "twee", "tweed" }
);
}
{
MapperService ms = createMapperService(fieldMapping(b -> b.field("type", "text").nullField("index_prefixes")));
expectThrows(
Exception.class,
() -> ms.indexAnalyzer("field._index_prefixes", f -> null).tokenStream("field._index_prefixes", "test")
);
}
{
MapperParsingException e = expectThrows(MapperParsingException.class, () -> createMapperService(fieldMapping(b -> {
b.field("type", "text").field("analyzer", "standard");
b.startObject("index_prefixes").field("min_chars", 1).field("max_chars", 10).endObject();
b.startObject("fields").startObject("_index_prefix").field("type", "text").endObject().endObject();
})));
assertThat(e.getMessage(), containsString("Cannot use reserved field name [field._index_prefix]"));
}
{
MapperParsingException e = expectThrows(MapperParsingException.class, () -> createMapperService(fieldMapping(b -> {
b.field("type", "text").field("analyzer", "standard");
b.startObject("index_prefixes").field("min_chars", 11).field("max_chars", 10).endObject();
})));
assertThat(e.getMessage(), containsString("min_chars [11] must be less than max_chars [10]"));
}
{
MapperParsingException e = expectThrows(MapperParsingException.class, () -> createMapperService(fieldMapping(b -> {
b.field("type", "text").field("analyzer", "standard");
b.startObject("index_prefixes").field("min_chars", 0).field("max_chars", 10).endObject();
})));
assertThat(e.getMessage(), containsString("min_chars [0] must be greater than zero"));
}
{
MapperParsingException e = expectThrows(MapperParsingException.class, () -> createMapperService(fieldMapping(b -> {
b.field("type", "text").field("analyzer", "standard");
b.startObject("index_prefixes").field("min_chars", 1).field("max_chars", 25).endObject();
})));
assertThat(e.getMessage(), containsString("max_chars [25] must be less than 20"));
}
{
MapperParsingException e = expectThrows(MapperParsingException.class, () -> createMapperService(fieldMapping(b -> {
b.field("type", "text").field("analyzer", "standard").field("index", false);
b.startObject("index_prefixes").endObject();
})));
assertThat(e.getMessage(), containsString("Cannot set index_prefixes on unindexed field [field]"));
}
}
public void testFastPhrasePrefixes() throws IOException {
MapperService mapperService = createMapperService(mapping(b -> {
b.startObject("field");
{
b.field("type", "text");
b.field("analyzer", "my_stop_analyzer");
b.startObject("index_prefixes").field("min_chars", 2).field("max_chars", 10).endObject();
}
b.endObject();
b.startObject("synfield");
{
b.field("type", "text");
b.field("analyzer", "standard"); // "standard" will be replaced with MockSynonymAnalyzer
b.field("index_phrases", true);
b.startObject("index_prefixes").field("min_chars", 2).field("max_chars", 10).endObject();
}
b.endObject();
}));
ParsedDocument doc = mapperService.documentMapper().parse(source(b -> b.field("synfield", "some text which we will index")));
withLuceneIndex(mapperService, iw -> iw.addDocument(doc.rootDoc()), ir -> {}); // check indexing
SearchExecutionContext searchExecutionContext = createSearchExecutionContext(mapperService);
{
Query q = new MatchPhrasePrefixQueryBuilder("field", "two words").toQuery(searchExecutionContext);
Query expected = new SpanNearQuery.Builder("field", true).addClause(new SpanTermQuery(new Term("field", "two")))
.addClause(new FieldMaskingSpanQuery(new SpanTermQuery(new Term("field._index_prefix", "words")), "field"))
.build();
assertThat(q, equalTo(expected));
}
{
Query q = new MatchPhrasePrefixQueryBuilder("field", "three words here").toQuery(searchExecutionContext);
Query expected = new SpanNearQuery.Builder("field", true).addClause(new SpanTermQuery(new Term("field", "three")))
.addClause(new SpanTermQuery(new Term("field", "words")))
.addClause(new FieldMaskingSpanQuery(new SpanTermQuery(new Term("field._index_prefix", "here")), "field"))
.build();
assertThat(q, equalTo(expected));
}
{
Query q = new MatchPhrasePrefixQueryBuilder("field", "two words").slop(1).toQuery(searchExecutionContext);
MultiPhrasePrefixQuery mpq = new MultiPhrasePrefixQuery("field");
mpq.setSlop(1);
mpq.add(new Term("field", "two"));
mpq.add(new Term("field", "words"));
assertThat(q, equalTo(mpq));
}
{
Query q = new MatchPhrasePrefixQueryBuilder("field", "singleton").toQuery(searchExecutionContext);
assertThat(
q,
is(new SynonymQuery.Builder("field._index_prefix").addTerm(new Term("field._index_prefix", "singleton")).build())
);
}
{
Query q = new MatchPhrasePrefixQueryBuilder("field", "sparkle a stopword").toQuery(searchExecutionContext);
Query expected = new SpanNearQuery.Builder("field", true).addClause(new SpanTermQuery(new Term("field", "sparkle")))
.addGap(1)
.addClause(new FieldMaskingSpanQuery(new SpanTermQuery(new Term("field._index_prefix", "stopword")), "field"))
.build();
assertThat(q, equalTo(expected));
}
{
MatchQueryParser matchQueryParser = new MatchQueryParser(searchExecutionContext);
matchQueryParser.setAnalyzer(new MockSynonymAnalyzer());
Query q = matchQueryParser.parse(MatchQueryParser.Type.PHRASE_PREFIX, "synfield", "motor dogs");
Query expected = new SpanNearQuery.Builder("synfield", true).addClause(new SpanTermQuery(new Term("synfield", "motor")))
.addClause(
new SpanOrQuery(
new FieldMaskingSpanQuery(new SpanTermQuery(new Term("synfield._index_prefix", "dogs")), "synfield"),
new FieldMaskingSpanQuery(new SpanTermQuery(new Term("synfield._index_prefix", "dog")), "synfield")
)
)
.build();
assertThat(q, equalTo(expected));
}
{
MatchQueryParser matchQueryParser = new MatchQueryParser(searchExecutionContext);
matchQueryParser.setPhraseSlop(1);
matchQueryParser.setAnalyzer(new MockSynonymAnalyzer());
Query q = matchQueryParser.parse(MatchQueryParser.Type.PHRASE_PREFIX, "synfield", "two dogs");
MultiPhrasePrefixQuery mpq = new MultiPhrasePrefixQuery("synfield");
mpq.setSlop(1);
mpq.add(new Term("synfield", "two"));
mpq.add(new Term[] { new Term("synfield", "dogs"), new Term("synfield", "dog") });
assertThat(q, equalTo(mpq));
}
{
Query q = new MatchPhrasePrefixQueryBuilder("field", "motor d").toQuery(searchExecutionContext);
MultiPhrasePrefixQuery mpq = new MultiPhrasePrefixQuery("field");
mpq.add(new Term("field", "motor"));
mpq.add(new Term("field", "d"));
assertThat(q, equalTo(mpq));
}
}
public void testSimpleMerge() throws IOException {
XContentBuilder startingMapping = fieldMapping(
b -> b.field("type", "text").startObject("index_prefixes").endObject().field("index_phrases", true)
);
MapperService mapperService = createMapperService(startingMapping);
assertThat(mapperService.documentMapper().mappers().getMapper("field"), instanceOf(TextFieldMapper.class));
merge(mapperService, startingMapping);
assertThat(mapperService.documentMapper().mappers().getMapper("field"), instanceOf(TextFieldMapper.class));
XContentBuilder differentPrefix = fieldMapping(
b -> b.field("type", "text").startObject("index_prefixes").field("min_chars", "3").endObject().field("index_phrases", true)
);
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> merge(mapperService, differentPrefix));
assertThat(e.getMessage(), containsString("Cannot update parameter [index_prefixes]"));
XContentBuilder differentPhrases = fieldMapping(
b -> b.field("type", "text").startObject("index_prefixes").endObject().field("index_phrases", false)
);
e = expectThrows(IllegalArgumentException.class, () -> merge(mapperService, differentPhrases));
assertThat(e.getMessage(), containsString("Cannot update parameter [index_phrases]"));
XContentBuilder newField = mapping(b -> {
b.startObject("field").field("type", "text").startObject("index_prefixes").endObject().field("index_phrases", true).endObject();
b.startObject("other_field").field("type", "keyword").endObject();
});
merge(mapperService, newField);
assertThat(mapperService.documentMapper().mappers().getMapper("field"), instanceOf(TextFieldMapper.class));
assertThat(mapperService.documentMapper().mappers().getMapper("other_field"), instanceOf(KeywordFieldMapper.class));
}
@Override
protected Object generateRandomInputValue(MappedFieldType ft) {
assumeFalse("We don't have a way to assert things here", true);
return null;
}
@Override
protected void randomFetchTestFieldConfig(XContentBuilder b) throws IOException {
assumeFalse("We don't have a way to assert things here", true);
}
}
| |
/*
Derby - Class org.apache.derby.impl.sql.compile.AlterTableNode
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derby.impl.sql.compile;
import org.apache.derby.iapi.reference.SQLState;
import org.apache.derby.iapi.reference.Limits;
import org.apache.derby.iapi.services.sanity.SanityManager;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.sql.compile.C_NodeTypes;
import org.apache.derby.iapi.sql.dictionary.DataDictionary;
import org.apache.derby.iapi.sql.dictionary.SchemaDescriptor;
import org.apache.derby.iapi.sql.dictionary.TableDescriptor;
import org.apache.derby.iapi.sql.execute.ConstantAction;
import org.apache.derby.iapi.types.StringDataValue;
import org.apache.derby.impl.sql.execute.ColumnInfo;
import org.apache.derby.impl.sql.execute.ConstraintConstantAction;
/**
* A AlterTableNode represents a DDL statement that alters a table.
* It contains the name of the object to be created.
*
*/
public class AlterTableNode extends DDLStatementNode
{
// The alter table action
public TableElementList tableElementList = null;
public char lockGranularity;
public boolean compressTable = false;
public boolean sequential = false;
public int behavior; // currently for drop column
public TableDescriptor baseTable;
protected int numConstraints;
private int changeType = UNKNOWN_TYPE;
private boolean truncateTable = false;
// constant action arguments
protected SchemaDescriptor schemaDescriptor = null;
protected ColumnInfo[] colInfos = null;
protected ConstraintConstantAction[] conActions = null;
/**
* Initializer for a TRUNCATE TABLE
*
* @param objectName The name of the table being truncated
* @exception StandardException Thrown on error
*/
public void init(Object objectName)
throws StandardException
{
//truncate table is not suppotted in this release
//semantics are not yet clearly defined by SQL Council yet
//truncate will be allowed only in DEBUG builds for testing purposes.
if (SanityManager.DEBUG)
{
initAndCheck(objectName);
/* For now, this init() only called for truncate table */
truncateTable = true;
schemaDescriptor = getSchemaDescriptor();
}else
{
throw StandardException.newException(SQLState.NOT_IMPLEMENTED,
"truncate table");
}
}
/**
* Initializer for a AlterTableNode for COMPRESS
*
* @param objectName The name of the table being altered
* @param sequential Whether or not the COMPRESS is SEQUENTIAL
*
* @exception StandardException Thrown on error
*/
public void init(Object objectName,
Object sequential)
throws StandardException
{
initAndCheck(objectName);
this.sequential = ((Boolean) sequential).booleanValue();
/* For now, this init() only called for compress table */
compressTable = true;
schemaDescriptor = getSchemaDescriptor();
}
/**
* Initializer for a AlterTableNode
*
* @param objectName The name of the table being altered
* @param tableElementList The alter table action
* @param lockGranularity The new lock granularity, if any
* @param changeType ADD_TYPE or DROP_TYPE
*
* @exception StandardException Thrown on error
*/
public void init(
Object objectName,
Object tableElementList,
Object lockGranularity,
Object changeType,
Object behavior,
Object sequential )
throws StandardException
{
initAndCheck(objectName);
this.tableElementList = (TableElementList) tableElementList;
this.lockGranularity = ((Character) lockGranularity).charValue();
int[] ct = (int[]) changeType, bh = (int[]) behavior;
this.changeType = ct[0];
this.behavior = bh[0];
boolean[] seq = (boolean[]) sequential;
this.sequential = seq[0];
switch ( this.changeType )
{
case ADD_TYPE:
case DROP_TYPE:
case MODIFY_TYPE:
case LOCKING_TYPE:
break;
default:
throw StandardException.newException(SQLState.NOT_IMPLEMENTED);
}
schemaDescriptor = getSchemaDescriptor();
}
/**
* Convert this object to a String. See comments in QueryTreeNode.java
* for how this should be done for tree printing.
*
* @return This object as a String
*/
public String toString()
{
if (SanityManager.DEBUG)
{
return super.toString() +
"objectName: " + "\n" + getObjectName() + "\n" +
"tableElementList: " + "\n" + tableElementList + "\n" +
"lockGranularity: " + "\n" + lockGranularity + "\n" +
"compressTable: " + "\n" + compressTable + "\n" +
"sequential: " + "\n" + sequential + "\n" +
"truncateTable: " + "\n" + truncateTable + "\n";
}
else
{
return "";
}
}
public String statementToString()
{
if(truncateTable)
return "TRUNCATE TABLE";
else
return "ALTER TABLE";
}
public int getChangeType() { return changeType; }
// We inherit the generate() method from DDLStatementNode.
/**
* Bind this AlterTableNode. This means doing any static error
* checking that can be done before actually creating the table.
* For example, verifying that the user is not trying to add a
* non-nullable column.
*
*
* @exception StandardException Thrown on error
*/
public void bindStatement() throws StandardException
{
DataDictionary dd = getDataDictionary();
int numCheckConstraints = 0;
int numBackingIndexes = 0;
/*
** Get the table descriptor. Checks the schema
** and the table.
*/
baseTable = getTableDescriptor();
//throw an exception if user is attempting to alter a temporary table
if (baseTable.getTableType() == TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE)
{
throw StandardException.newException(SQLState.LANG_NOT_ALLOWED_FOR_DECLARED_GLOBAL_TEMP_TABLE);
}
/* Statement is dependent on the TableDescriptor */
getCompilerContext().createDependency(baseTable);
//If we are dealing with add column character type, then set that
//column's collation type to be the collation type of the schema.
//The collation derivation of such a column would be "implicit".
if (changeType == ADD_TYPE) {//the action is of type add.
if (tableElementList != null) {//check if is is add column
for (int i=0; i<tableElementList.size();i++) {
if (tableElementList.elementAt(i) instanceof ColumnDefinitionNode) {
ColumnDefinitionNode cdn = (ColumnDefinitionNode) tableElementList.elementAt(i);
//check if we are dealing with add character column
if (cdn.getType().getTypeId().isStringTypeId()) {
//we found what we are looking for. Set the
//collation type of this column to be the same as
//schema descriptor's collation. Set the collation
//derivation as implicit
cdn.setCollationType(schemaDescriptor.getCollationType());
}
}
}
}
}
if (tableElementList != null)
{
tableElementList.validate(this, dd, baseTable);
/* Only 1012 columns allowed per table */
if ((tableElementList.countNumberOfColumns() + baseTable.getNumberOfColumns()) > Limits.DB2_MAX_COLUMNS_IN_TABLE)
{
throw StandardException.newException(SQLState.LANG_TOO_MANY_COLUMNS_IN_TABLE_OR_VIEW,
String.valueOf(tableElementList.countNumberOfColumns() + baseTable.getNumberOfColumns()),
getRelativeName(),
String.valueOf(Limits.DB2_MAX_COLUMNS_IN_TABLE));
}
/* Number of backing indexes in the alter table statment */
numBackingIndexes = tableElementList.countConstraints(DataDictionary.PRIMARYKEY_CONSTRAINT) +
tableElementList.countConstraints(DataDictionary.FOREIGNKEY_CONSTRAINT) +
tableElementList.countConstraints(DataDictionary.UNIQUE_CONSTRAINT);
/* Check the validity of all check constraints */
numCheckConstraints = tableElementList.countConstraints(
DataDictionary.CHECK_CONSTRAINT);
}
//If the sum of backing indexes for constraints in alter table statement and total number of indexes on the table
//so far is more than 32767, then we need to throw an exception
if ((numBackingIndexes + baseTable.getTotalNumberOfIndexes()) > Limits.DB2_MAX_INDEXES_ON_TABLE)
{
throw StandardException.newException(SQLState.LANG_TOO_MANY_INDEXES_ON_TABLE,
String.valueOf(numBackingIndexes + baseTable.getTotalNumberOfIndexes()),
getRelativeName(),
String.valueOf(Limits.DB2_MAX_INDEXES_ON_TABLE));
}
if (numCheckConstraints > 0)
{
/* In order to check the validity of the check constraints
* we must goober up a FromList containing a single table,
* the table being alter, with an RCL containing the existing and
* new columns and their types. This will allow us to
* bind the constraint definition trees against that
* FromList. When doing this, we verify that there are
* no nodes which can return non-deterministic results.
*/
FromList fromList = (FromList) getNodeFactory().getNode(
C_NodeTypes.FROM_LIST,
getNodeFactory().doJoinOrderOptimization(),
getContextManager());
FromBaseTable table = (FromBaseTable)
getNodeFactory().getNode(
C_NodeTypes.FROM_BASE_TABLE,
getObjectName(),
null,
null,
null,
getContextManager());
fromList.addFromTable(table);
fromList.bindTables(dd,
(FromList) getNodeFactory().getNode(
C_NodeTypes.FROM_LIST,
getNodeFactory().doJoinOrderOptimization(),
getContextManager()));
tableElementList.appendNewColumnsToRCL(table);
/* Now that we've finally goobered stuff up, bind and validate
* the check constraints.
*/
tableElementList.bindAndValidateCheckConstraints(fromList);
}
/* Unlike most other DDL, we will make this ALTER TABLE statement
* dependent on the table being altered. In general, we try to
* avoid this for DDL, but we are already requiring the table to
* exist at bind time (not required for create index) and we don't
* want the column ids to change out from under us before
* execution.
*/
getCompilerContext().createDependency(baseTable);
}
/**
* Return true if the node references SESSION schema tables (temporary or permanent)
*
* @return true if references SESSION schema tables, else false
*
* @exception StandardException Thrown on error
*/
public boolean referencesSessionSchema()
throws StandardException
{
//If alter table is on a SESSION schema table, then return true.
return isSessionSchema(baseTable.getSchemaName());
}
/**
* Create the Constant information that will drive the guts of Execution.
*
* @exception StandardException Thrown on failure
*/
public ConstantAction makeConstantAction() throws StandardException
{
prepConstantAction();
return getGenericConstantActionFactory().getAlterTableConstantAction(schemaDescriptor,
getRelativeName(),
baseTable.getUUID(),
baseTable.getHeapConglomerateId(),
TableDescriptor.BASE_TABLE_TYPE,
colInfos,
conActions,
lockGranularity,
compressTable,
behavior,
sequential,
truncateTable);
}
/**
* Generate arguments to constant action. Called by makeConstantAction() in this class and in
* our subclass RepAlterTableNode.
*
*
* @exception StandardException Thrown on failure
*/
private void prepConstantAction() throws StandardException
{
if (tableElementList != null)
{
genColumnInfo();
}
/* If we've seen a constraint, then build a constraint list */
if (numConstraints > 0)
{
conActions = new ConstraintConstantAction[numConstraints];
tableElementList.genConstraintActions(false, conActions, getRelativeName(), schemaDescriptor,
getDataDictionary());
}
}
/**
* Generate the ColumnInfo argument for the constant action. Return the number of constraints.
*/
public void genColumnInfo()
{
// for each column, stuff system.column
colInfos = new ColumnInfo[tableElementList.countNumberOfColumns()];
numConstraints = tableElementList.genColumnInfos(colInfos);
}
/*
* class interface
*/
}
| |
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.eclipse.ceylon.langtools.tools.javac.parser;
import static org.eclipse.ceylon.langtools.tools.javac.util.LayoutCharacters.*;
import java.nio.*;
import org.eclipse.ceylon.langtools.tools.javac.parser.Tokens.Comment;
import org.eclipse.ceylon.langtools.tools.javac.parser.Tokens.Comment.CommentStyle;
import org.eclipse.ceylon.langtools.tools.javac.util.*;
/** An extension to the base lexical analyzer that captures
* and processes the contents of doc comments. It does so by
* translating Unicode escape sequences and by stripping the
* leading whitespace and starts from each line of the comment.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class JavadocTokenizer extends JavaTokenizer {
/** Create a scanner from the input buffer. buffer must implement
* array() and compact(), and remaining() must be less than limit().
*/
protected JavadocTokenizer(ScannerFactory fac, CharBuffer buffer) {
super(fac, buffer);
}
/** Create a scanner from the input array. The array must have at
* least a single character of extra space.
*/
protected JavadocTokenizer(ScannerFactory fac, char[] input, int inputLength) {
super(fac, input, inputLength);
}
@Override
protected Comment processComment(int pos, int endPos, CommentStyle style) {
char[] buf = reader.getRawCharacters(pos, endPos);
return new JavadocComment(new DocReader(fac, buf, buf.length, pos), style);
}
/**
* This is a specialized version of UnicodeReader that keeps track of the
* column position within a given character stream (used for Javadoc processing),
* and which builds a table for mapping positions in the comment string to
* positions in the source file.
*/
static class DocReader extends UnicodeReader {
int col;
int startPos;
/**
* A buffer for building a table for mapping positions in {@link #sbuf}
* to positions in the source buffer.
*
* The array is organized as a series of pairs of integers: the first
* number in each pair specifies a position in the comment text,
* the second number in each pair specifies the corresponding position
* in the source buffer. The pairs are sorted in ascending order.
*
* Since the mapping function is generally continuous, with successive
* positions in the string corresponding to successive positions in the
* source buffer, the table only needs to record discontinuities in
* the mapping. The values of intermediate positions can be inferred.
*
* Discontinuities may occur in a number of places: when a newline
* is followed by whitespace and asterisks (which are ignored),
* when a tab is expanded into spaces, and when unicode escapes
* are used in the source buffer.
*
* Thus, to find the source position of any position, p, in the comment
* string, find the index, i, of the pair whose string offset
* ({@code pbuf[i] }) is closest to but not greater than p. Then,
* {@code sourcePos(p) = pbuf[i+1] + (p - pbuf[i]) }.
*/
int[] pbuf = new int[128];
/**
* The index of the next empty slot in the pbuf buffer.
*/
int pp = 0;
DocReader(ScannerFactory fac, char[] input, int inputLength, int startPos) {
super(fac, input, inputLength);
this.startPos = startPos;
}
@Override
protected void convertUnicode() {
if (ch == '\\' && unicodeConversionBp != bp) {
bp++; ch = buf[bp]; col++;
if (ch == 'u') {
do {
bp++; ch = buf[bp]; col++;
} while (ch == 'u');
int limit = bp + 3;
if (limit < buflen) {
int d = digit(bp, 16);
int code = d;
while (bp < limit && d >= 0) {
bp++; ch = buf[bp]; col++;
d = digit(bp, 16);
code = (code << 4) + d;
}
if (d >= 0) {
ch = (char)code;
unicodeConversionBp = bp;
return;
}
}
// "illegal.Unicode.esc", reported by base scanner
} else {
bp--;
ch = '\\';
col--;
}
}
}
@Override
protected void scanCommentChar() {
scanChar();
if (ch == '\\') {
if (peekChar() == '\\' && !isUnicode()) {
putChar(ch, false);
bp++; col++;
} else {
convertUnicode();
}
}
}
@Override
protected void scanChar() {
bp++;
ch = buf[bp];
switch (ch) {
case '\r': // return
col = 0;
break;
case '\n': // newline
if (bp == 0 || buf[bp-1] != '\r') {
col = 0;
}
break;
case '\t': // tab
col = (col / TabInc * TabInc) + TabInc;
break;
case '\\': // possible Unicode
col++;
convertUnicode();
break;
default:
col++;
break;
}
}
@Override
public void putChar(char ch, boolean scan) {
// At this point, bp is the position of the current character in buf,
// and sp is the position in sbuf where this character will be put.
// Record a new entry in pbuf if pbuf is empty or if sp and its
// corresponding source position are not equidistant from the
// corresponding values in the latest entry in the pbuf array.
// (i.e. there is a discontinuity in the map function.)
if ((pp == 0)
|| (sp - pbuf[pp - 2] != (startPos + bp) - pbuf[pp - 1])) {
if (pp + 1 >= pbuf.length) {
int[] new_pbuf = new int[pbuf.length * 2];
System.arraycopy(pbuf, 0, new_pbuf, 0, pbuf.length);
pbuf = new_pbuf;
}
pbuf[pp] = sp;
pbuf[pp + 1] = startPos + bp;
pp += 2;
}
super.putChar(ch, scan);
}
}
protected static class JavadocComment extends JavaTokenizer.BasicComment<DocReader> {
/**
* Translated and stripped contents of doc comment
*/
private String docComment = null;
private int[] docPosns = null;
JavadocComment(DocReader reader, CommentStyle cs) {
super(reader, cs);
}
@Override
public String getText() {
if (!scanned && cs == CommentStyle.JAVADOC) {
scanDocComment();
}
return docComment;
}
@Override
public int getSourcePos(int pos) {
// Binary search to find the entry for which the string index is
// less than pos. Since docPosns is a list of pairs of integers
// we must make sure the index is always even.
// If we find an exact match for pos, the other item in the pair
// gives the source pos; otherwise, compute the source position
// relative to the best match found in the array.
if (pos == Position.NOPOS)
return Position.NOPOS;
if (pos < 0 || pos > docComment.length())
throw new StringIndexOutOfBoundsException(String.valueOf(pos));
if (docPosns == null)
return Position.NOPOS;
int start = 0;
int end = docPosns.length;
while (start < end - 2) {
// find an even index midway between start and end
int index = ((start + end) / 4) * 2;
if (docPosns[index] < pos)
start = index;
else if (docPosns[index] == pos)
return docPosns[index + 1];
else
end = index;
}
return docPosns[start + 1] + (pos - docPosns[start]);
}
@Override
@SuppressWarnings("fallthrough")
protected void scanDocComment() {
try {
boolean firstLine = true;
// Skip over first slash
comment_reader.scanCommentChar();
// Skip over first star
comment_reader.scanCommentChar();
// consume any number of stars
while (comment_reader.bp < comment_reader.buflen && comment_reader.ch == '*') {
comment_reader.scanCommentChar();
}
// is the comment in the form /**/, /***/, /****/, etc. ?
if (comment_reader.bp < comment_reader.buflen && comment_reader.ch == '/') {
docComment = "";
return;
}
// skip a newline on the first line of the comment.
if (comment_reader.bp < comment_reader.buflen) {
if (comment_reader.ch == LF) {
comment_reader.scanCommentChar();
firstLine = false;
} else if (comment_reader.ch == CR) {
comment_reader.scanCommentChar();
if (comment_reader.ch == LF) {
comment_reader.scanCommentChar();
firstLine = false;
}
}
}
outerLoop:
// The outerLoop processes the doc comment, looping once
// for each line. For each line, it first strips off
// whitespace, then it consumes any stars, then it
// puts the rest of the line into our buffer.
while (comment_reader.bp < comment_reader.buflen) {
int begin_bp = comment_reader.bp;
char begin_ch = comment_reader.ch;
// The wsLoop consumes whitespace from the beginning
// of each line.
wsLoop:
while (comment_reader.bp < comment_reader.buflen) {
switch(comment_reader.ch) {
case ' ':
comment_reader.scanCommentChar();
break;
case '\t':
comment_reader.col = ((comment_reader.col - 1) / TabInc * TabInc) + TabInc;
comment_reader.scanCommentChar();
break;
case FF:
comment_reader.col = 0;
comment_reader.scanCommentChar();
break;
// Treat newline at beginning of line (blank line, no star)
// as comment text. Old Javadoc compatibility requires this.
/*---------------------------------*
case CR: // (Spec 3.4)
doc_reader.scanCommentChar();
if (ch == LF) {
col = 0;
doc_reader.scanCommentChar();
}
break;
case LF: // (Spec 3.4)
doc_reader.scanCommentChar();
break;
*---------------------------------*/
default:
// we've seen something that isn't whitespace;
// jump out.
break wsLoop;
}
}
// Are there stars here? If so, consume them all
// and check for the end of comment.
if (comment_reader.ch == '*') {
// skip all of the stars
do {
comment_reader.scanCommentChar();
} while (comment_reader.ch == '*');
// check for the closing slash.
if (comment_reader.ch == '/') {
// We're done with the doc comment
// scanChar() and breakout.
break outerLoop;
}
} else if (! firstLine) {
// The current line does not begin with a '*' so we will
// treat it as comment
comment_reader.bp = begin_bp;
comment_reader.ch = begin_ch;
}
// The textLoop processes the rest of the characters
// on the line, adding them to our buffer.
textLoop:
while (comment_reader.bp < comment_reader.buflen) {
switch (comment_reader.ch) {
case '*':
// Is this just a star? Or is this the
// end of a comment?
comment_reader.scanCommentChar();
if (comment_reader.ch == '/') {
// This is the end of the comment,
// set ch and return our buffer.
break outerLoop;
}
// This is just an ordinary star. Add it to
// the buffer.
comment_reader.putChar('*', false);
break;
case ' ':
case '\t':
comment_reader.putChar(comment_reader.ch, false);
comment_reader.scanCommentChar();
break;
case FF:
comment_reader.scanCommentChar();
break textLoop; // treat as end of line
case CR: // (Spec 3.4)
comment_reader.scanCommentChar();
if (comment_reader.ch != LF) {
// Canonicalize CR-only line terminator to LF
comment_reader.putChar((char)LF, false);
break textLoop;
}
/* fall through to LF case */
case LF: // (Spec 3.4)
// We've seen a newline. Add it to our
// buffer and break out of this loop,
// starting fresh on a new line.
comment_reader.putChar(comment_reader.ch, false);
comment_reader.scanCommentChar();
break textLoop;
default:
// Add the character to our buffer.
comment_reader.putChar(comment_reader.ch, false);
comment_reader.scanCommentChar();
}
} // end textLoop
firstLine = false;
} // end outerLoop
if (comment_reader.sp > 0) {
int i = comment_reader.sp - 1;
trailLoop:
while (i > -1) {
switch (comment_reader.sbuf[i]) {
case '*':
i--;
break;
default:
break trailLoop;
}
}
comment_reader.sp = i + 1;
// Store the text of the doc comment
docComment = comment_reader.chars();
docPosns = new int[comment_reader.pp];
System.arraycopy(comment_reader.pbuf, 0, docPosns, 0, docPosns.length);
} else {
docComment = "";
}
} finally {
scanned = true;
comment_reader = null;
if (docComment != null &&
docComment.matches("(?sm).*^\\s*@deprecated( |$).*")) {
deprecatedFlag = true;
}
}
}
}
@Override
public Position.LineMap getLineMap() {
char[] buf = reader.getRawCharacters();
return Position.makeLineMap(buf, buf.length, true);
}
}
| |
/*
* Copyright 2017 LinkedIn Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package com.github.ambry.clustermap;
import com.github.ambry.clustermap.TestUtils.*;
import com.github.ambry.commons.CommonUtils;
import com.github.ambry.config.ClusterMapConfig;
import com.github.ambry.config.HelixPropertyStoreConfig;
import com.github.ambry.config.VerifiableProperties;
import com.github.ambry.utils.Utils;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.helix.AccessOption;
import org.apache.helix.ZNRecord;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.store.HelixPropertyStore;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static com.github.ambry.clustermap.HelixBootstrapUpgradeTool.*;
import static com.github.ambry.clustermap.TestUtils.*;
import static com.github.ambry.utils.TestUtils.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.junit.Assume.*;
@RunWith(Parameterized.class)
public class HelixBootstrapUpgradeToolTest {
private static String tempDirPath;
private static final Map<String, ZkInfo> dcsToZkInfo = new HashMap<>();
private static final String dcs[] = new String[]{"DC0", "DC1"};
private static final byte ids[] = new byte[]{(byte) 0, (byte) 1};
private final String hardwareLayoutPath;
private final String partitionLayoutPath;
private final String zkLayoutPath;
private final JSONObject zkJson;
private final String dcStr;
private Set<String> activeDcSet;
private TestHardwareLayout testHardwareLayout;
private TestPartitionLayout testPartitionLayout;
private static final String CLUSTER_NAME_IN_STATIC_CLUSTER_MAP = "ToolTestStatic";
private static final String CLUSTER_NAME_PREFIX = "Ambry-";
private static final String ROOT_PATH = "/" + CLUSTER_NAME_PREFIX + CLUSTER_NAME_IN_STATIC_CLUSTER_MAP;
private static HelixPropertyStoreConfig propertyStoreConfig;
/**
* Shutdown all Zk servers before exit.
*/
@AfterClass
public static void destroy() {
for (ZkInfo zkInfo : dcsToZkInfo.values()) {
zkInfo.shutdown();
}
}
@BeforeClass
public static void initialize() throws IOException {
tempDirPath = getTempDir("helixBootstrapUpgrade-");
Properties storeProps = new Properties();
storeProps.setProperty("helix.property.store.root.path", ROOT_PATH);
propertyStoreConfig = new HelixPropertyStoreConfig(new VerifiableProperties(storeProps));
int port = 2200;
for (int i = 0; i < dcs.length; i++) {
dcsToZkInfo.put(dcs[i], new ZkInfo(tempDirPath, dcs[i], ids[i], port++, true));
}
}
@After
public void clear() {
for (ZkInfo zkInfo : dcsToZkInfo.values()) {
ZKHelixAdmin admin = new ZKHelixAdmin("localhost:" + zkInfo.getPort());
admin.dropCluster(CLUSTER_NAME_PREFIX + CLUSTER_NAME_IN_STATIC_CLUSTER_MAP);
}
}
@Parameterized.Parameters
public static List<Object[]> data() {
return Arrays.asList(new Object[][]{{"DC1"}, {"DC1, DC0"}, {"all"}});
}
/**
* Initialize ZKInfos for all dcs and start the ZK server.
*/
public HelixBootstrapUpgradeToolTest(String dcStr) {
hardwareLayoutPath = tempDirPath + "/hardwareLayoutTest.json";
partitionLayoutPath = tempDirPath + "/partitionLayoutTest.json";
zkLayoutPath = tempDirPath + "/zkLayoutPath.json";
zkJson = constructZkLayoutJSON(dcsToZkInfo.values());
testHardwareLayout = constructInitialHardwareLayoutJSON(CLUSTER_NAME_IN_STATIC_CLUSTER_MAP);
testPartitionLayout =
constructInitialPartitionLayoutJSON(testHardwareLayout, DEFAULT_MAX_PARTITIONS_PER_RESOURCE, null);
this.dcStr = dcStr;
if (!dcStr.equalsIgnoreCase("all")) {
activeDcSet = Arrays.stream(dcStr.replaceAll("\\p{Space}", "").split(",")).collect(Collectors.toSet());
} else {
activeDcSet = new HashSet<>(Arrays.asList(dcs));
}
}
/**
* Test {@link HelixBootstrapUpgradeUtil#parseAndUpdateDcInfoFromArg(String, String)} method.
*/
@Test
public void testParseDcSet() throws Exception {
assumeTrue(dcStr.equals("all"));
Utils.writeJsonObjectToFile(zkJson, zkLayoutPath);
Utils.writeJsonObjectToFile(testHardwareLayout.getHardwareLayout().toJSONObject(), hardwareLayoutPath);
Utils.writeJsonObjectToFile(testPartitionLayout.getPartitionLayout().toJSONObject(), partitionLayoutPath);
try {
HelixBootstrapUpgradeUtil.parseAndUpdateDcInfoFromArg(null, zkLayoutPath);
fail("Null dc string should fail");
} catch (IllegalArgumentException e) {
}
try {
HelixBootstrapUpgradeUtil.parseAndUpdateDcInfoFromArg("", zkLayoutPath);
fail("Empty dc string should fail");
} catch (IllegalArgumentException e) {
}
try {
HelixBootstrapUpgradeUtil.parseAndUpdateDcInfoFromArg("inv, inv1", zkLayoutPath);
fail("Invalid dc strings should fail");
} catch (IllegalArgumentException e) {
}
Set<String> expected = new HashSet<>(Collections.singletonList("DC1"));
Assert.assertEquals(expected, HelixBootstrapUpgradeUtil.parseAndUpdateDcInfoFromArg("DC1", zkLayoutPath).keySet());
expected.add("DC0");
Assert.assertEquals(expected,
HelixBootstrapUpgradeUtil.parseAndUpdateDcInfoFromArg("DC0, DC1", zkLayoutPath).keySet());
Assert.assertEquals(expected, HelixBootstrapUpgradeUtil.parseAndUpdateDcInfoFromArg("all", zkLayoutPath).keySet());
}
/**
* Test the case where the zkHosts JSON does not have an entry for every Datacenter in the static clustermap.
*/
@Test
public void testIncompleteZKHostInfo() throws Exception {
assumeTrue(dcStr.equalsIgnoreCase("all"));
if (testHardwareLayout.getDatacenterCount() > 1) {
JSONObject partialZkJson =
constructZkLayoutJSON(Collections.singleton(dcsToZkInfo.entrySet().iterator().next().getValue()));
Utils.writeJsonObjectToFile(partialZkJson, zkLayoutPath);
Utils.writeJsonObjectToFile(testHardwareLayout.getHardwareLayout().toJSONObject(), hardwareLayoutPath);
Utils.writeJsonObjectToFile(testPartitionLayout.getPartitionLayout().toJSONObject(), partitionLayoutPath);
try {
HelixBootstrapUpgradeUtil.bootstrapOrUpgrade(hardwareLayoutPath, partitionLayoutPath, zkLayoutPath,
CLUSTER_NAME_PREFIX, dcStr, DEFAULT_MAX_PARTITIONS_PER_RESOURCE, false, false, new HelixAdminFactory());
fail("Should have thrown IllegalArgumentException as a zk host is missing for one of the dcs");
} catch (IllegalArgumentException e) {
// OK
}
}
}
/**
* Tests the method to create instance config and ensures that derived fields are set correctly.
*/
@Test
public void testCreateInstanceConfig() {
DataNode dataNode = (DataNode) ((Partition) testPartitionLayout.getPartitionLayout()
.getPartitions(DEFAULT_PARTITION_CLASS)
.get(0)).getReplicas().get(0).getDataNodeId();
Map<String, Set<String>> partitionToInstances = new HashMap<>();
JSONObject jsonObject = dataNode.toJSONObject();
jsonObject.put("xid", ClusterMapUtils.DEFAULT_XID);
ClusterMapConfig clusterMapConfig = testHardwareLayout.clusterMapConfig;
dataNode = new DataNode(dataNode.getDatacenter(), jsonObject, clusterMapConfig);
InstanceConfig referenceInstanceConfig =
HelixBootstrapUpgradeUtil.createInstanceConfigFromStaticInfo(dataNode, partitionToInstances,
Collections.emptyMap(), null);
// Assert that xid field does not get set in InstanceConfig when it is the default.
assertNull(referenceInstanceConfig.getRecord().getSimpleField(ClusterMapUtils.XID_STR));
// Assert that xid field does get set if not the default.
jsonObject.put("xid", "10");
dataNode = new DataNode(dataNode.getDatacenter(), jsonObject, clusterMapConfig);
InstanceConfig instanceConfig =
HelixBootstrapUpgradeUtil.createInstanceConfigFromStaticInfo(dataNode, partitionToInstances,
Collections.emptyMap(), null);
assertEquals("10", instanceConfig.getRecord().getSimpleField(ClusterMapUtils.XID_STR));
assertThat(referenceInstanceConfig.getRecord(), not(equalTo(instanceConfig.getRecord())));
referenceInstanceConfig = instanceConfig;
// Assert that sealed list being different does not affect equality
List<String> sealedList = Arrays.asList("5", "10");
referenceInstanceConfig.getRecord().setListField(ClusterMapUtils.SEALED_STR, sealedList);
// set the field to null. The created InstanceConfig should not have null fields.
referenceInstanceConfig.getRecord().setListField(ClusterMapUtils.STOPPED_REPLICAS_STR, null);
instanceConfig = HelixBootstrapUpgradeUtil.createInstanceConfigFromStaticInfo(dataNode, partitionToInstances,
Collections.emptyMap(), referenceInstanceConfig);
// Stopped replicas should be an empty list and not null, so set that in referenceInstanceConfig for comparison.
referenceInstanceConfig.getRecord().setListField(ClusterMapUtils.STOPPED_REPLICAS_STR, Collections.emptyList());
assertEquals(instanceConfig.getRecord(), referenceInstanceConfig.getRecord());
// Assert that stopped list being different does not affect equality
List<String> stoppedReplicas = Arrays.asList("11", "15");
referenceInstanceConfig.getRecord().setListField(ClusterMapUtils.STOPPED_REPLICAS_STR, stoppedReplicas);
instanceConfig = HelixBootstrapUpgradeUtil.createInstanceConfigFromStaticInfo(dataNode, partitionToInstances,
Collections.emptyMap(), referenceInstanceConfig);
assertEquals(instanceConfig.getRecord(), referenceInstanceConfig.getRecord());
}
/**
* A single test (for convenience) that tests bootstrap and upgrades.
*/
@Test
public void testEverything() throws Exception {
/* Test bootstrap */
long expectedResourceCount =
(testPartitionLayout.getPartitionLayout().getPartitionCount() - 1) / DEFAULT_MAX_PARTITIONS_PER_RESOURCE + 1;
writeBootstrapOrUpgrade(expectedResourceCount, false);
uploadClusterConfigsAndVerify();
/* Test Simple Upgrade */
int numNewNodes = 4;
int numNewPartitions = 220;
testHardwareLayout.addNewDataNodes(numNewNodes);
testPartitionLayout.addNewPartitions(numNewPartitions, DEFAULT_PARTITION_CLASS, PartitionState.READ_WRITE, null);
expectedResourceCount += (numNewPartitions - 1) / DEFAULT_MAX_PARTITIONS_PER_RESOURCE + 1;
writeBootstrapOrUpgrade(expectedResourceCount, false);
/* Test sealed state update. */
Set<Long> partitionIdsBeforeAddition = new HashSet<>();
for (PartitionId partitionId : testPartitionLayout.getPartitionLayout().getPartitions(null)) {
partitionIdsBeforeAddition.add(((Partition) partitionId).getId());
}
// First, add new nodes and partitions (which are default READ_WRITE)
numNewNodes = 2;
numNewPartitions = 50;
testHardwareLayout.addNewDataNodes(numNewNodes);
testPartitionLayout.addNewPartitions(numNewPartitions, DEFAULT_PARTITION_CLASS, PartitionState.READ_WRITE, null);
// Next, mark all previous partitions as READ_ONLY, and change their replica capacities and partition classes.
for (PartitionId partitionId : testPartitionLayout.getPartitionLayout().getPartitions(null)) {
if (partitionIdsBeforeAddition.contains(((Partition) partitionId).getId())) {
Partition partition = (Partition) partitionId;
partition.partitionState = PartitionState.READ_ONLY;
partition.replicaCapacityInBytes += 1;
partition.partitionClass = "specialPartitionClass";
}
}
expectedResourceCount += (numNewPartitions - 1) / DEFAULT_MAX_PARTITIONS_PER_RESOURCE + 1;
writeBootstrapOrUpgrade(expectedResourceCount, false);
uploadClusterConfigsAndVerify();
// Now, mark the ones that were READ_ONLY as READ_WRITE and vice versa
for (PartitionId partitionId : testPartitionLayout.getPartitionLayout().getPartitions(null)) {
Partition partition = (Partition) partitionId;
if (partitionIdsBeforeAddition.contains(((Partition) partitionId).getId())) {
partition.partitionState = PartitionState.READ_WRITE;
} else {
partition.partitionState = PartitionState.READ_ONLY;
}
}
writeBootstrapOrUpgrade(expectedResourceCount, false);
uploadClusterConfigsAndVerify();
// Now, change the replica count for a partition.
Partition partition1 = (Partition) testPartitionLayout.getPartitionLayout()
.getPartitions(null)
.get(RANDOM.nextInt(testPartitionLayout.getPartitionCount()));
Partition partition2 = (Partition) testPartitionLayout.getPartitionLayout()
.getPartitions(null)
.get(RANDOM.nextInt(testPartitionLayout.getPartitionCount()));
// Add a new replica for partition1. Find a disk on a data node that does not already have a replica for partition1.
HashSet<DataNodeId> partition1Nodes = new HashSet<>();
for (Replica replica : partition1.getReplicas()) {
partition1Nodes.add(replica.getDataNodeId());
}
Disk diskForNewReplica;
do {
diskForNewReplica = testHardwareLayout.getRandomDisk();
} while (partition1Nodes.contains(diskForNewReplica.getDataNode()));
partition1.addReplica(new Replica(partition1, diskForNewReplica, testHardwareLayout.clusterMapConfig));
// Remove a replica from partition2.
partition2.getReplicas().remove(0);
writeBootstrapOrUpgrade(expectedResourceCount, false);
long expectedResourceCountWithoutRemovals = expectedResourceCount;
/* Test instance, partition and resource removal */
// Use the initial static clustermap that does not have the upgrades.
testHardwareLayout = constructInitialHardwareLayoutJSON(CLUSTER_NAME_IN_STATIC_CLUSTER_MAP);
testPartitionLayout =
constructInitialPartitionLayoutJSON(testHardwareLayout, DEFAULT_MAX_PARTITIONS_PER_RESOURCE, null);
long expectedResourceCountWithRemovals =
(testPartitionLayout.getPartitionLayout().getPartitionCount() - 1) / DEFAULT_MAX_PARTITIONS_PER_RESOURCE + 1;
writeBootstrapOrUpgrade(expectedResourceCountWithoutRemovals, false);
writeBootstrapOrUpgrade(expectedResourceCountWithRemovals, true);
}
/**
* Write the layout files out from the constructed in-memory hardware and partition layouts; use the bootstrap tool
* to update the contents in Helix; verify that the information is consistent between the two.
* @param expectedResourceCount number of resources expected in Helix for this cluster in each datacenter.
* @param forceRemove whether the forceRemove option should be passed when doing the bootstrap/upgrade.
* @throws IOException if a file read error is encountered.
* @throws JSONException if a JSON parse error is encountered.
*/
private void writeBootstrapOrUpgrade(long expectedResourceCount, boolean forceRemove) throws Exception {
Utils.writeJsonObjectToFile(zkJson, zkLayoutPath);
Utils.writeJsonObjectToFile(testHardwareLayout.getHardwareLayout().toJSONObject(), hardwareLayoutPath);
Utils.writeJsonObjectToFile(testPartitionLayout.getPartitionLayout().toJSONObject(), partitionLayoutPath);
// This updates and verifies that the information in Helix is consistent with the one in the static cluster map.
HelixBootstrapUpgradeUtil.bootstrapOrUpgrade(hardwareLayoutPath, partitionLayoutPath, zkLayoutPath,
CLUSTER_NAME_PREFIX, dcStr, DEFAULT_MAX_PARTITIONS_PER_RESOURCE, false, forceRemove, new HelixAdminFactory());
verifyResourceCount(testHardwareLayout.getHardwareLayout(), expectedResourceCount);
}
/**
* Write the layout files out from the constructed in-memory hardware and partition layouts; use the upload cluster config
* tool to upload the partition seal states onto Zookeeper; verify that the writable partitions are consistent between the two.
* @throws IOException if a file read error is encountered.
* @throws JSONException if a JSON parse error is encountered.
*/
private void uploadClusterConfigsAndVerify() throws Exception {
List<PartitionId> writablePartitions = testPartitionLayout.getPartitionLayout().getWritablePartitions(null);
Set<String> writableInPartitionLayout = new HashSet<>();
writablePartitions.forEach(k -> writableInPartitionLayout.add(k.toPathString()));
Utils.writeJsonObjectToFile(zkJson, zkLayoutPath);
Utils.writeJsonObjectToFile(testHardwareLayout.getHardwareLayout().toJSONObject(), hardwareLayoutPath);
Utils.writeJsonObjectToFile(testPartitionLayout.getPartitionLayout().toJSONObject(), partitionLayoutPath);
HelixBootstrapUpgradeUtil.uploadClusterConfigs(hardwareLayoutPath, partitionLayoutPath, zkLayoutPath,
CLUSTER_NAME_PREFIX, dcStr, DEFAULT_MAX_PARTITIONS_PER_RESOURCE, new HelixAdminFactory());
// Check writable partitions in each datacenter
for (ZkInfo zkInfo : dcsToZkInfo.values()) {
HelixPropertyStore<ZNRecord> propertyStore =
CommonUtils.createHelixPropertyStore("localhost:" + zkInfo.getPort(), propertyStoreConfig,
Collections.singletonList(propertyStoreConfig.rootPath));
String getPath = ClusterMapUtils.PROPERTYSTORE_ZNODE_PATH;
ZNRecord zNRecord = propertyStore.get(getPath, null, AccessOption.PERSISTENT);
if (!activeDcSet.contains(zkInfo.getDcName())) {
assertNull(zNRecord);
} else {
assertNotNull(zNRecord);
Map<String, Map<String, String>> overridePartition = zNRecord.getMapFields();
Set<String> writableInDC = new HashSet<>();
for (Map.Entry<String, Map<String, String>> entry : overridePartition.entrySet()) {
if (entry.getValue().get(ClusterMapUtils.PARTITION_STATE).equals(ClusterMapUtils.READ_WRITE_STR)) {
writableInDC.add(entry.getKey());
}
}
// Verify writable partitions in DC match writable partitions in Partition Layout
assertEquals("Mismatch in writable partitions for partitionLayout and propertyStore", writableInPartitionLayout,
writableInDC);
}
}
}
/**
* Verify that the number of resources in Helix is as expected.
* @param hardwareLayout the {@link HardwareLayout} of the static clustermap.
* @param expectedResourceCount the expected number of resources in Helix.
*/
private void verifyResourceCount(HardwareLayout hardwareLayout, long expectedResourceCount) {
for (Datacenter dc : hardwareLayout.getDatacenters()) {
ZkInfo zkInfo = dcsToZkInfo.get(dc.getName());
ZKHelixAdmin admin = new ZKHelixAdmin("localhost:" + zkInfo.getPort());
if (!activeDcSet.contains(dc.getName())) {
Assert.assertFalse("Cluster should not be present, as dc " + dc.getName() + " is not enabled",
admin.getClusters().contains(CLUSTER_NAME_PREFIX + CLUSTER_NAME_IN_STATIC_CLUSTER_MAP));
} else {
assertEquals("Resource count mismatch", expectedResourceCount,
admin.getResourcesInCluster(CLUSTER_NAME_PREFIX + CLUSTER_NAME_IN_STATIC_CLUSTER_MAP).size());
}
}
}
}
| |
/*
* generated by Xtext 2.10.0
*/
package hu.bme.aut.protokit.services;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.List;
import org.eclipse.xtext.Alternatives;
import org.eclipse.xtext.Assignment;
import org.eclipse.xtext.CrossReference;
import org.eclipse.xtext.Grammar;
import org.eclipse.xtext.GrammarUtil;
import org.eclipse.xtext.Group;
import org.eclipse.xtext.Keyword;
import org.eclipse.xtext.ParserRule;
import org.eclipse.xtext.RuleCall;
import org.eclipse.xtext.TerminalRule;
import org.eclipse.xtext.common.services.TerminalsGrammarAccess;
import org.eclipse.xtext.service.AbstractElementFinder.AbstractGrammarElementFinder;
import org.eclipse.xtext.service.GrammarProvider;
@Singleton
public class ProtokitDSLGrammarAccess extends AbstractGrammarElementFinder {
public class ProtocolModelElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "hu.bme.aut.protokit.ProtokitDSL.ProtocolModel");
private final Assignment cDatatypesAssignment = (Assignment)rule.eContents().get(1);
private final RuleCall cDatatypesDataTypeParserRuleCall_0 = (RuleCall)cDatatypesAssignment.eContents().get(0);
//ProtocolModel:
// datatypes+=DataType+;
@Override public ParserRule getRule() { return rule; }
//datatypes+=DataType+
public Assignment getDatatypesAssignment() { return cDatatypesAssignment; }
//DataType
public RuleCall getDatatypesDataTypeParserRuleCall_0() { return cDatatypesDataTypeParserRuleCall_0; }
}
public class DataTypeElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "hu.bme.aut.protokit.ProtokitDSL.DataType");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Alternatives cAlternatives_0 = (Alternatives)cGroup.eContents().get(0);
private final Keyword cProtocolKeyword_0_0 = (Keyword)cAlternatives_0.eContents().get(0);
private final Keyword cDatatypeKeyword_0_1 = (Keyword)cAlternatives_0.eContents().get(1);
private final Assignment cNameAssignment_1 = (Assignment)cGroup.eContents().get(1);
private final RuleCall cNameIDTerminalRuleCall_1_0 = (RuleCall)cNameAssignment_1.eContents().get(0);
private final Keyword cLeftCurlyBracketKeyword_2 = (Keyword)cGroup.eContents().get(2);
private final Assignment cFieldsAssignment_3 = (Assignment)cGroup.eContents().get(3);
private final RuleCall cFieldsVariableDefinitionParserRuleCall_3_0 = (RuleCall)cFieldsAssignment_3.eContents().get(0);
private final Keyword cRightCurlyBracketKeyword_4 = (Keyword)cGroup.eContents().get(4);
//DataType:
// ('protocol' | 'datatype') name=ID '{' fields+=VariableDefinition+ '}';
@Override public ParserRule getRule() { return rule; }
//('protocol' | 'datatype') name=ID '{' fields+=VariableDefinition+ '}'
public Group getGroup() { return cGroup; }
//('protocol' | 'datatype')
public Alternatives getAlternatives_0() { return cAlternatives_0; }
//'protocol'
public Keyword getProtocolKeyword_0_0() { return cProtocolKeyword_0_0; }
//'datatype'
public Keyword getDatatypeKeyword_0_1() { return cDatatypeKeyword_0_1; }
//name=ID
public Assignment getNameAssignment_1() { return cNameAssignment_1; }
//ID
public RuleCall getNameIDTerminalRuleCall_1_0() { return cNameIDTerminalRuleCall_1_0; }
//'{'
public Keyword getLeftCurlyBracketKeyword_2() { return cLeftCurlyBracketKeyword_2; }
//fields+=VariableDefinition+
public Assignment getFieldsAssignment_3() { return cFieldsAssignment_3; }
//VariableDefinition
public RuleCall getFieldsVariableDefinitionParserRuleCall_3_0() { return cFieldsVariableDefinitionParserRuleCall_3_0; }
//'}'
public Keyword getRightCurlyBracketKeyword_4() { return cRightCurlyBracketKeyword_4; }
}
public class VariableDefinitionElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "hu.bme.aut.protokit.ProtokitDSL.VariableDefinition");
private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1);
private final RuleCall cIntegerFieldParserRuleCall_0 = (RuleCall)cAlternatives.eContents().get(0);
private final RuleCall cStringFieldParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1);
private final RuleCall cBinaryFieldParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2);
private final RuleCall cBitFieldParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3);
private final RuleCall cListFieldParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4);
private final RuleCall cLengthFieldParserRuleCall_5 = (RuleCall)cAlternatives.eContents().get(5);
private final RuleCall cCountFieldParserRuleCall_6 = (RuleCall)cAlternatives.eContents().get(6);
private final RuleCall cDataTypeFieldParserRuleCall_7 = (RuleCall)cAlternatives.eContents().get(7);
//VariableDefinition Field:
// IntegerField | StringField | BinaryField | BitField | ListField | LengthField | CountField | DataTypeField
@Override public ParserRule getRule() { return rule; }
//IntegerField | StringField | BinaryField | BitField | ListField | LengthField | CountField | DataTypeField
public Alternatives getAlternatives() { return cAlternatives; }
//IntegerField
public RuleCall getIntegerFieldParserRuleCall_0() { return cIntegerFieldParserRuleCall_0; }
//StringField
public RuleCall getStringFieldParserRuleCall_1() { return cStringFieldParserRuleCall_1; }
//BinaryField
public RuleCall getBinaryFieldParserRuleCall_2() { return cBinaryFieldParserRuleCall_2; }
//BitField
public RuleCall getBitFieldParserRuleCall_3() { return cBitFieldParserRuleCall_3; }
//ListField
public RuleCall getListFieldParserRuleCall_4() { return cListFieldParserRuleCall_4; }
//LengthField
public RuleCall getLengthFieldParserRuleCall_5() { return cLengthFieldParserRuleCall_5; }
//CountField
public RuleCall getCountFieldParserRuleCall_6() { return cCountFieldParserRuleCall_6; }
//DataTypeField
public RuleCall getDataTypeFieldParserRuleCall_7() { return cDataTypeFieldParserRuleCall_7; }
}
public class IntegerFieldElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "hu.bme.aut.protokit.ProtokitDSL.IntegerField");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Assignment cTransientFieldAssignment_0 = (Assignment)cGroup.eContents().get(0);
private final Keyword cTransientFieldTransientKeyword_0_0 = (Keyword)cTransientFieldAssignment_0.eContents().get(0);
private final Assignment cIdentityFieldAssignment_1 = (Assignment)cGroup.eContents().get(1);
private final Keyword cIdentityFieldAsteriskKeyword_1_0 = (Keyword)cIdentityFieldAssignment_1.eContents().get(0);
private final Assignment cNameAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cNameIDTerminalRuleCall_2_0 = (RuleCall)cNameAssignment_2.eContents().get(0);
private final Keyword cColonKeyword_3 = (Keyword)cGroup.eContents().get(3);
private final Keyword cIntKeyword_4 = (Keyword)cGroup.eContents().get(4);
private final Group cGroup_5 = (Group)cGroup.eContents().get(5);
private final Keyword cLeftParenthesisKeyword_5_0 = (Keyword)cGroup_5.eContents().get(0);
private final Assignment cByteLenAssignment_5_1 = (Assignment)cGroup_5.eContents().get(1);
private final RuleCall cByteLenINTTerminalRuleCall_5_1_0 = (RuleCall)cByteLenAssignment_5_1.eContents().get(0);
private final Keyword cRightParenthesisKeyword_5_2 = (Keyword)cGroup_5.eContents().get(2);
//IntegerField:
// transientField?='transient'? identityField?='*'? name=ID ':' 'int' ('(' byteLen=INT ')')?;
@Override public ParserRule getRule() { return rule; }
//transientField?='transient'? identityField?='*'? name=ID ':' 'int' ('(' byteLen=INT ')')?
public Group getGroup() { return cGroup; }
//transientField?='transient'?
public Assignment getTransientFieldAssignment_0() { return cTransientFieldAssignment_0; }
//'transient'
public Keyword getTransientFieldTransientKeyword_0_0() { return cTransientFieldTransientKeyword_0_0; }
//identityField?='*'?
public Assignment getIdentityFieldAssignment_1() { return cIdentityFieldAssignment_1; }
//'*'
public Keyword getIdentityFieldAsteriskKeyword_1_0() { return cIdentityFieldAsteriskKeyword_1_0; }
//name=ID
public Assignment getNameAssignment_2() { return cNameAssignment_2; }
//ID
public RuleCall getNameIDTerminalRuleCall_2_0() { return cNameIDTerminalRuleCall_2_0; }
//':'
public Keyword getColonKeyword_3() { return cColonKeyword_3; }
//'int'
public Keyword getIntKeyword_4() { return cIntKeyword_4; }
//('(' byteLen=INT ')')?
public Group getGroup_5() { return cGroup_5; }
//'('
public Keyword getLeftParenthesisKeyword_5_0() { return cLeftParenthesisKeyword_5_0; }
//byteLen=INT
public Assignment getByteLenAssignment_5_1() { return cByteLenAssignment_5_1; }
//INT
public RuleCall getByteLenINTTerminalRuleCall_5_1_0() { return cByteLenINTTerminalRuleCall_5_1_0; }
//')'
public Keyword getRightParenthesisKeyword_5_2() { return cRightParenthesisKeyword_5_2; }
}
public class StringFieldElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "hu.bme.aut.protokit.ProtokitDSL.StringField");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Assignment cTransientFieldAssignment_0 = (Assignment)cGroup.eContents().get(0);
private final Keyword cTransientFieldTransientKeyword_0_0 = (Keyword)cTransientFieldAssignment_0.eContents().get(0);
private final Assignment cIdentityFieldAssignment_1 = (Assignment)cGroup.eContents().get(1);
private final Keyword cIdentityFieldAsteriskKeyword_1_0 = (Keyword)cIdentityFieldAssignment_1.eContents().get(0);
private final Assignment cNameAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cNameIDTerminalRuleCall_2_0 = (RuleCall)cNameAssignment_2.eContents().get(0);
private final Keyword cColonKeyword_3 = (Keyword)cGroup.eContents().get(3);
private final Keyword cStringKeyword_4 = (Keyword)cGroup.eContents().get(4);
private final Alternatives cAlternatives_5 = (Alternatives)cGroup.eContents().get(5);
private final Group cGroup_5_0 = (Group)cAlternatives_5.eContents().get(0);
private final Keyword cLeftParenthesisKeyword_5_0_0 = (Keyword)cGroup_5_0.eContents().get(0);
private final Assignment cByteLenAssignment_5_0_1 = (Assignment)cGroup_5_0.eContents().get(1);
private final RuleCall cByteLenINTTerminalRuleCall_5_0_1_0 = (RuleCall)cByteLenAssignment_5_0_1.eContents().get(0);
private final Keyword cRightParenthesisKeyword_5_0_2 = (Keyword)cGroup_5_0.eContents().get(2);
private final Group cGroup_5_1 = (Group)cAlternatives_5.eContents().get(1);
private final Keyword cLeftParenthesisKeyword_5_1_0 = (Keyword)cGroup_5_1.eContents().get(0);
private final Assignment cUnboundedAssignment_5_1_1 = (Assignment)cGroup_5_1.eContents().get(1);
private final Keyword cUnboundedAsteriskKeyword_5_1_1_0 = (Keyword)cUnboundedAssignment_5_1_1.eContents().get(0);
private final Keyword cRightParenthesisKeyword_5_1_2 = (Keyword)cGroup_5_1.eContents().get(2);
private final Assignment cFormatterAssignment_5_1_3 = (Assignment)cGroup_5_1.eContents().get(3);
private final RuleCall cFormatterFormatterParserRuleCall_5_1_3_0 = (RuleCall)cFormatterAssignment_5_1_3.eContents().get(0);
//StringField:
// transientField?='transient'? identityField?='*'? name=ID ':' 'string' ('(' byteLen=INT ')' | '(' unbounded?='*'? ')'
// formatter=Formatter)?;
@Override public ParserRule getRule() { return rule; }
//transientField?='transient'? identityField?='*'? name=ID ':' 'string' ('(' byteLen=INT ')' | '(' unbounded?='*'? ')'
//formatter=Formatter)?
public Group getGroup() { return cGroup; }
//transientField?='transient'?
public Assignment getTransientFieldAssignment_0() { return cTransientFieldAssignment_0; }
//'transient'
public Keyword getTransientFieldTransientKeyword_0_0() { return cTransientFieldTransientKeyword_0_0; }
//identityField?='*'?
public Assignment getIdentityFieldAssignment_1() { return cIdentityFieldAssignment_1; }
//'*'
public Keyword getIdentityFieldAsteriskKeyword_1_0() { return cIdentityFieldAsteriskKeyword_1_0; }
//name=ID
public Assignment getNameAssignment_2() { return cNameAssignment_2; }
//ID
public RuleCall getNameIDTerminalRuleCall_2_0() { return cNameIDTerminalRuleCall_2_0; }
//':'
public Keyword getColonKeyword_3() { return cColonKeyword_3; }
//'string'
public Keyword getStringKeyword_4() { return cStringKeyword_4; }
//('(' byteLen=INT ')' | '(' unbounded?='*'? ')' formatter=Formatter)?
public Alternatives getAlternatives_5() { return cAlternatives_5; }
//'(' byteLen=INT ')'
public Group getGroup_5_0() { return cGroup_5_0; }
//'('
public Keyword getLeftParenthesisKeyword_5_0_0() { return cLeftParenthesisKeyword_5_0_0; }
//byteLen=INT
public Assignment getByteLenAssignment_5_0_1() { return cByteLenAssignment_5_0_1; }
//INT
public RuleCall getByteLenINTTerminalRuleCall_5_0_1_0() { return cByteLenINTTerminalRuleCall_5_0_1_0; }
//')'
public Keyword getRightParenthesisKeyword_5_0_2() { return cRightParenthesisKeyword_5_0_2; }
//'(' unbounded?='*'? ')' formatter=Formatter
public Group getGroup_5_1() { return cGroup_5_1; }
//'('
public Keyword getLeftParenthesisKeyword_5_1_0() { return cLeftParenthesisKeyword_5_1_0; }
//unbounded?='*'?
public Assignment getUnboundedAssignment_5_1_1() { return cUnboundedAssignment_5_1_1; }
//'*'
public Keyword getUnboundedAsteriskKeyword_5_1_1_0() { return cUnboundedAsteriskKeyword_5_1_1_0; }
//')'
public Keyword getRightParenthesisKeyword_5_1_2() { return cRightParenthesisKeyword_5_1_2; }
//formatter=Formatter
public Assignment getFormatterAssignment_5_1_3() { return cFormatterAssignment_5_1_3; }
//Formatter
public RuleCall getFormatterFormatterParserRuleCall_5_1_3_0() { return cFormatterFormatterParserRuleCall_5_1_3_0; }
}
public class BinaryFieldElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "hu.bme.aut.protokit.ProtokitDSL.BinaryField");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Assignment cTransientFieldAssignment_0 = (Assignment)cGroup.eContents().get(0);
private final Keyword cTransientFieldTransientKeyword_0_0 = (Keyword)cTransientFieldAssignment_0.eContents().get(0);
private final Assignment cIdentityFieldAssignment_1 = (Assignment)cGroup.eContents().get(1);
private final Keyword cIdentityFieldAsteriskKeyword_1_0 = (Keyword)cIdentityFieldAssignment_1.eContents().get(0);
private final Assignment cNameAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cNameIDTerminalRuleCall_2_0 = (RuleCall)cNameAssignment_2.eContents().get(0);
private final Keyword cColonKeyword_3 = (Keyword)cGroup.eContents().get(3);
private final Keyword cBinaryKeyword_4 = (Keyword)cGroup.eContents().get(4);
private final Alternatives cAlternatives_5 = (Alternatives)cGroup.eContents().get(5);
private final Group cGroup_5_0 = (Group)cAlternatives_5.eContents().get(0);
private final Keyword cLeftParenthesisKeyword_5_0_0 = (Keyword)cGroup_5_0.eContents().get(0);
private final Assignment cByteLenAssignment_5_0_1 = (Assignment)cGroup_5_0.eContents().get(1);
private final RuleCall cByteLenINTTerminalRuleCall_5_0_1_0 = (RuleCall)cByteLenAssignment_5_0_1.eContents().get(0);
private final Keyword cRightParenthesisKeyword_5_0_2 = (Keyword)cGroup_5_0.eContents().get(2);
private final Group cGroup_5_1 = (Group)cAlternatives_5.eContents().get(1);
private final Keyword cLeftParenthesisKeyword_5_1_0 = (Keyword)cGroup_5_1.eContents().get(0);
private final Assignment cUnboundedAssignment_5_1_1 = (Assignment)cGroup_5_1.eContents().get(1);
private final Keyword cUnboundedAsteriskKeyword_5_1_1_0 = (Keyword)cUnboundedAssignment_5_1_1.eContents().get(0);
private final Keyword cRightParenthesisKeyword_5_1_2 = (Keyword)cGroup_5_1.eContents().get(2);
//BinaryField:
// transientField?='transient'? identityField?='*'? name=ID ':' 'binary' ('(' byteLen=INT ')' | '(' unbounded?='*'?
// ')');
@Override public ParserRule getRule() { return rule; }
//transientField?='transient'? identityField?='*'? name=ID ':' 'binary' ('(' byteLen=INT ')' | '(' unbounded?='*'? ')')
public Group getGroup() { return cGroup; }
//transientField?='transient'?
public Assignment getTransientFieldAssignment_0() { return cTransientFieldAssignment_0; }
//'transient'
public Keyword getTransientFieldTransientKeyword_0_0() { return cTransientFieldTransientKeyword_0_0; }
//identityField?='*'?
public Assignment getIdentityFieldAssignment_1() { return cIdentityFieldAssignment_1; }
//'*'
public Keyword getIdentityFieldAsteriskKeyword_1_0() { return cIdentityFieldAsteriskKeyword_1_0; }
//name=ID
public Assignment getNameAssignment_2() { return cNameAssignment_2; }
//ID
public RuleCall getNameIDTerminalRuleCall_2_0() { return cNameIDTerminalRuleCall_2_0; }
//':'
public Keyword getColonKeyword_3() { return cColonKeyword_3; }
//'binary'
public Keyword getBinaryKeyword_4() { return cBinaryKeyword_4; }
//('(' byteLen=INT ')' | '(' unbounded?='*'? ')')
public Alternatives getAlternatives_5() { return cAlternatives_5; }
//'(' byteLen=INT ')'
public Group getGroup_5_0() { return cGroup_5_0; }
//'('
public Keyword getLeftParenthesisKeyword_5_0_0() { return cLeftParenthesisKeyword_5_0_0; }
//byteLen=INT
public Assignment getByteLenAssignment_5_0_1() { return cByteLenAssignment_5_0_1; }
//INT
public RuleCall getByteLenINTTerminalRuleCall_5_0_1_0() { return cByteLenINTTerminalRuleCall_5_0_1_0; }
//')'
public Keyword getRightParenthesisKeyword_5_0_2() { return cRightParenthesisKeyword_5_0_2; }
//'(' unbounded?='*'? ')'
public Group getGroup_5_1() { return cGroup_5_1; }
//'('
public Keyword getLeftParenthesisKeyword_5_1_0() { return cLeftParenthesisKeyword_5_1_0; }
//unbounded?='*'?
public Assignment getUnboundedAssignment_5_1_1() { return cUnboundedAssignment_5_1_1; }
//'*'
public Keyword getUnboundedAsteriskKeyword_5_1_1_0() { return cUnboundedAsteriskKeyword_5_1_1_0; }
//')'
public Keyword getRightParenthesisKeyword_5_1_2() { return cRightParenthesisKeyword_5_1_2; }
}
public class BitFieldElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "hu.bme.aut.protokit.ProtokitDSL.BitField");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Assignment cTransientFieldAssignment_0 = (Assignment)cGroup.eContents().get(0);
private final Keyword cTransientFieldTransientKeyword_0_0 = (Keyword)cTransientFieldAssignment_0.eContents().get(0);
private final Assignment cIdentityFieldAssignment_1 = (Assignment)cGroup.eContents().get(1);
private final Keyword cIdentityFieldAsteriskKeyword_1_0 = (Keyword)cIdentityFieldAssignment_1.eContents().get(0);
private final Assignment cNameAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cNameIDTerminalRuleCall_2_0 = (RuleCall)cNameAssignment_2.eContents().get(0);
private final Keyword cColonKeyword_3 = (Keyword)cGroup.eContents().get(3);
private final Keyword cBitfieldKeyword_4 = (Keyword)cGroup.eContents().get(4);
private final Keyword cLeftCurlyBracketKeyword_5 = (Keyword)cGroup.eContents().get(5);
private final Assignment cComponentsAssignment_6 = (Assignment)cGroup.eContents().get(6);
private final RuleCall cComponentsBitfieldComponentParserRuleCall_6_0 = (RuleCall)cComponentsAssignment_6.eContents().get(0);
private final Keyword cRightCurlyBracketKeyword_7 = (Keyword)cGroup.eContents().get(7);
//BitField:
// transientField?='transient'? identityField?='*'? name=ID ':' 'bitfield' '{' components+=BitfieldComponent+ '}';
@Override public ParserRule getRule() { return rule; }
//transientField?='transient'? identityField?='*'? name=ID ':' 'bitfield' '{' components+=BitfieldComponent+ '}'
public Group getGroup() { return cGroup; }
//transientField?='transient'?
public Assignment getTransientFieldAssignment_0() { return cTransientFieldAssignment_0; }
//'transient'
public Keyword getTransientFieldTransientKeyword_0_0() { return cTransientFieldTransientKeyword_0_0; }
//identityField?='*'?
public Assignment getIdentityFieldAssignment_1() { return cIdentityFieldAssignment_1; }
//'*'
public Keyword getIdentityFieldAsteriskKeyword_1_0() { return cIdentityFieldAsteriskKeyword_1_0; }
//name=ID
public Assignment getNameAssignment_2() { return cNameAssignment_2; }
//ID
public RuleCall getNameIDTerminalRuleCall_2_0() { return cNameIDTerminalRuleCall_2_0; }
//':'
public Keyword getColonKeyword_3() { return cColonKeyword_3; }
//'bitfield'
public Keyword getBitfieldKeyword_4() { return cBitfieldKeyword_4; }
//'{'
public Keyword getLeftCurlyBracketKeyword_5() { return cLeftCurlyBracketKeyword_5; }
//components+=BitfieldComponent+
public Assignment getComponentsAssignment_6() { return cComponentsAssignment_6; }
//BitfieldComponent
public RuleCall getComponentsBitfieldComponentParserRuleCall_6_0() { return cComponentsBitfieldComponentParserRuleCall_6_0; }
//'}'
public Keyword getRightCurlyBracketKeyword_7() { return cRightCurlyBracketKeyword_7; }
}
public class BitfieldComponentElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "hu.bme.aut.protokit.ProtokitDSL.BitfieldComponent");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0);
private final RuleCall cNameIDTerminalRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0);
private final Keyword cColonKeyword_1 = (Keyword)cGroup.eContents().get(1);
private final Assignment cBitLenAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cBitLenINTTerminalRuleCall_2_0 = (RuleCall)cBitLenAssignment_2.eContents().get(0);
//BitfieldComponent BitFieldComponent:
// name=ID ':' bitLen=INT
@Override public ParserRule getRule() { return rule; }
//name=ID ':' bitLen=INT
public Group getGroup() { return cGroup; }
//name=ID
public Assignment getNameAssignment_0() { return cNameAssignment_0; }
//ID
public RuleCall getNameIDTerminalRuleCall_0_0() { return cNameIDTerminalRuleCall_0_0; }
//':'
public Keyword getColonKeyword_1() { return cColonKeyword_1; }
//bitLen=INT
public Assignment getBitLenAssignment_2() { return cBitLenAssignment_2; }
//INT
public RuleCall getBitLenINTTerminalRuleCall_2_0() { return cBitLenINTTerminalRuleCall_2_0; }
}
public class ListFieldElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "hu.bme.aut.protokit.ProtokitDSL.ListField");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Assignment cTransientFieldAssignment_0 = (Assignment)cGroup.eContents().get(0);
private final Keyword cTransientFieldTransientKeyword_0_0 = (Keyword)cTransientFieldAssignment_0.eContents().get(0);
private final Assignment cIdentityFieldAssignment_1 = (Assignment)cGroup.eContents().get(1);
private final Keyword cIdentityFieldAsteriskKeyword_1_0 = (Keyword)cIdentityFieldAssignment_1.eContents().get(0);
private final Assignment cNameAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cNameIDTerminalRuleCall_2_0 = (RuleCall)cNameAssignment_2.eContents().get(0);
private final Keyword cColonKeyword_3 = (Keyword)cGroup.eContents().get(3);
private final Keyword cListKeyword_4 = (Keyword)cGroup.eContents().get(4);
private final Keyword cLeftParenthesisKeyword_5 = (Keyword)cGroup.eContents().get(5);
private final Assignment cElementTypeAssignment_6 = (Assignment)cGroup.eContents().get(6);
private final CrossReference cElementTypeDataTypeCrossReference_6_0 = (CrossReference)cElementTypeAssignment_6.eContents().get(0);
private final RuleCall cElementTypeDataTypeIDTerminalRuleCall_6_0_1 = (RuleCall)cElementTypeDataTypeCrossReference_6_0.eContents().get(1);
private final Keyword cRightParenthesisKeyword_7 = (Keyword)cGroup.eContents().get(7);
//ListField:
// transientField?='transient'? identityField?='*'? name=ID ':' 'list' '(' elementType=[DataType] ')';
@Override public ParserRule getRule() { return rule; }
//transientField?='transient'? identityField?='*'? name=ID ':' 'list' '(' elementType=[DataType] ')'
public Group getGroup() { return cGroup; }
//transientField?='transient'?
public Assignment getTransientFieldAssignment_0() { return cTransientFieldAssignment_0; }
//'transient'
public Keyword getTransientFieldTransientKeyword_0_0() { return cTransientFieldTransientKeyword_0_0; }
//identityField?='*'?
public Assignment getIdentityFieldAssignment_1() { return cIdentityFieldAssignment_1; }
//'*'
public Keyword getIdentityFieldAsteriskKeyword_1_0() { return cIdentityFieldAsteriskKeyword_1_0; }
//name=ID
public Assignment getNameAssignment_2() { return cNameAssignment_2; }
//ID
public RuleCall getNameIDTerminalRuleCall_2_0() { return cNameIDTerminalRuleCall_2_0; }
//':'
public Keyword getColonKeyword_3() { return cColonKeyword_3; }
//'list'
public Keyword getListKeyword_4() { return cListKeyword_4; }
//'('
public Keyword getLeftParenthesisKeyword_5() { return cLeftParenthesisKeyword_5; }
//elementType=[DataType]
public Assignment getElementTypeAssignment_6() { return cElementTypeAssignment_6; }
//[DataType]
public CrossReference getElementTypeDataTypeCrossReference_6_0() { return cElementTypeDataTypeCrossReference_6_0; }
//ID
public RuleCall getElementTypeDataTypeIDTerminalRuleCall_6_0_1() { return cElementTypeDataTypeIDTerminalRuleCall_6_0_1; }
//')'
public Keyword getRightParenthesisKeyword_7() { return cRightParenthesisKeyword_7; }
}
public class LengthFieldElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "hu.bme.aut.protokit.ProtokitDSL.LengthField");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Assignment cTransientFieldAssignment_0 = (Assignment)cGroup.eContents().get(0);
private final Keyword cTransientFieldTransientKeyword_0_0 = (Keyword)cTransientFieldAssignment_0.eContents().get(0);
private final Assignment cIdentityFieldAssignment_1 = (Assignment)cGroup.eContents().get(1);
private final Keyword cIdentityFieldAsteriskKeyword_1_0 = (Keyword)cIdentityFieldAssignment_1.eContents().get(0);
private final Assignment cNameAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cNameIDTerminalRuleCall_2_0 = (RuleCall)cNameAssignment_2.eContents().get(0);
private final Keyword cColonKeyword_3 = (Keyword)cGroup.eContents().get(3);
private final Keyword cLengthKeyword_4 = (Keyword)cGroup.eContents().get(4);
private final Keyword cLeftParenthesisKeyword_5 = (Keyword)cGroup.eContents().get(5);
private final Assignment cByteLenAssignment_6 = (Assignment)cGroup.eContents().get(6);
private final RuleCall cByteLenINTTerminalRuleCall_6_0 = (RuleCall)cByteLenAssignment_6.eContents().get(0);
private final Keyword cCommaKeyword_7 = (Keyword)cGroup.eContents().get(7);
private final Assignment cRefAssignment_8 = (Assignment)cGroup.eContents().get(8);
private final CrossReference cRefBinaryFieldCrossReference_8_0 = (CrossReference)cRefAssignment_8.eContents().get(0);
private final RuleCall cRefBinaryFieldIDTerminalRuleCall_8_0_1 = (RuleCall)cRefBinaryFieldCrossReference_8_0.eContents().get(1);
private final Keyword cRightParenthesisKeyword_9 = (Keyword)cGroup.eContents().get(9);
//LengthField:
// transientField?='transient'? identityField?='*'? name=ID ':' 'length' '(' byteLen=INT ',' ref=[BinaryField] ')';
@Override public ParserRule getRule() { return rule; }
//transientField?='transient'? identityField?='*'? name=ID ':' 'length' '(' byteLen=INT ',' ref=[BinaryField] ')'
public Group getGroup() { return cGroup; }
//transientField?='transient'?
public Assignment getTransientFieldAssignment_0() { return cTransientFieldAssignment_0; }
//'transient'
public Keyword getTransientFieldTransientKeyword_0_0() { return cTransientFieldTransientKeyword_0_0; }
//identityField?='*'?
public Assignment getIdentityFieldAssignment_1() { return cIdentityFieldAssignment_1; }
//'*'
public Keyword getIdentityFieldAsteriskKeyword_1_0() { return cIdentityFieldAsteriskKeyword_1_0; }
//name=ID
public Assignment getNameAssignment_2() { return cNameAssignment_2; }
//ID
public RuleCall getNameIDTerminalRuleCall_2_0() { return cNameIDTerminalRuleCall_2_0; }
//':'
public Keyword getColonKeyword_3() { return cColonKeyword_3; }
//'length'
public Keyword getLengthKeyword_4() { return cLengthKeyword_4; }
//'('
public Keyword getLeftParenthesisKeyword_5() { return cLeftParenthesisKeyword_5; }
//byteLen=INT
public Assignment getByteLenAssignment_6() { return cByteLenAssignment_6; }
//INT
public RuleCall getByteLenINTTerminalRuleCall_6_0() { return cByteLenINTTerminalRuleCall_6_0; }
//','
public Keyword getCommaKeyword_7() { return cCommaKeyword_7; }
//ref=[BinaryField]
public Assignment getRefAssignment_8() { return cRefAssignment_8; }
//[BinaryField]
public CrossReference getRefBinaryFieldCrossReference_8_0() { return cRefBinaryFieldCrossReference_8_0; }
//ID
public RuleCall getRefBinaryFieldIDTerminalRuleCall_8_0_1() { return cRefBinaryFieldIDTerminalRuleCall_8_0_1; }
//')'
public Keyword getRightParenthesisKeyword_9() { return cRightParenthesisKeyword_9; }
}
public class CountFieldElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "hu.bme.aut.protokit.ProtokitDSL.CountField");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Assignment cTransientFieldAssignment_0 = (Assignment)cGroup.eContents().get(0);
private final Keyword cTransientFieldTransientKeyword_0_0 = (Keyword)cTransientFieldAssignment_0.eContents().get(0);
private final Assignment cIdentityFieldAssignment_1 = (Assignment)cGroup.eContents().get(1);
private final Keyword cIdentityFieldAsteriskKeyword_1_0 = (Keyword)cIdentityFieldAssignment_1.eContents().get(0);
private final Assignment cNameAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cNameIDTerminalRuleCall_2_0 = (RuleCall)cNameAssignment_2.eContents().get(0);
private final Keyword cColonKeyword_3 = (Keyword)cGroup.eContents().get(3);
private final Keyword cCountKeyword_4 = (Keyword)cGroup.eContents().get(4);
private final Keyword cLeftParenthesisKeyword_5 = (Keyword)cGroup.eContents().get(5);
private final Assignment cByteLenAssignment_6 = (Assignment)cGroup.eContents().get(6);
private final RuleCall cByteLenINTTerminalRuleCall_6_0 = (RuleCall)cByteLenAssignment_6.eContents().get(0);
private final Keyword cCommaKeyword_7 = (Keyword)cGroup.eContents().get(7);
private final Assignment cRefAssignment_8 = (Assignment)cGroup.eContents().get(8);
private final CrossReference cRefListFieldCrossReference_8_0 = (CrossReference)cRefAssignment_8.eContents().get(0);
private final RuleCall cRefListFieldIDTerminalRuleCall_8_0_1 = (RuleCall)cRefListFieldCrossReference_8_0.eContents().get(1);
private final Keyword cRightParenthesisKeyword_9 = (Keyword)cGroup.eContents().get(9);
//CountField:
// transientField?='transient'? identityField?='*'? name=ID ':' 'count' '(' byteLen=INT ',' ref=[ListField] ')';
@Override public ParserRule getRule() { return rule; }
//transientField?='transient'? identityField?='*'? name=ID ':' 'count' '(' byteLen=INT ',' ref=[ListField] ')'
public Group getGroup() { return cGroup; }
//transientField?='transient'?
public Assignment getTransientFieldAssignment_0() { return cTransientFieldAssignment_0; }
//'transient'
public Keyword getTransientFieldTransientKeyword_0_0() { return cTransientFieldTransientKeyword_0_0; }
//identityField?='*'?
public Assignment getIdentityFieldAssignment_1() { return cIdentityFieldAssignment_1; }
//'*'
public Keyword getIdentityFieldAsteriskKeyword_1_0() { return cIdentityFieldAsteriskKeyword_1_0; }
//name=ID
public Assignment getNameAssignment_2() { return cNameAssignment_2; }
//ID
public RuleCall getNameIDTerminalRuleCall_2_0() { return cNameIDTerminalRuleCall_2_0; }
//':'
public Keyword getColonKeyword_3() { return cColonKeyword_3; }
//'count'
public Keyword getCountKeyword_4() { return cCountKeyword_4; }
//'('
public Keyword getLeftParenthesisKeyword_5() { return cLeftParenthesisKeyword_5; }
//byteLen=INT
public Assignment getByteLenAssignment_6() { return cByteLenAssignment_6; }
//INT
public RuleCall getByteLenINTTerminalRuleCall_6_0() { return cByteLenINTTerminalRuleCall_6_0; }
//','
public Keyword getCommaKeyword_7() { return cCommaKeyword_7; }
//ref=[ListField]
public Assignment getRefAssignment_8() { return cRefAssignment_8; }
//[ListField]
public CrossReference getRefListFieldCrossReference_8_0() { return cRefListFieldCrossReference_8_0; }
//ID
public RuleCall getRefListFieldIDTerminalRuleCall_8_0_1() { return cRefListFieldIDTerminalRuleCall_8_0_1; }
//')'
public Keyword getRightParenthesisKeyword_9() { return cRightParenthesisKeyword_9; }
}
public class DataTypeFieldElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "hu.bme.aut.protokit.ProtokitDSL.DataTypeField");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Assignment cTransientFieldAssignment_0 = (Assignment)cGroup.eContents().get(0);
private final Keyword cTransientFieldTransientKeyword_0_0 = (Keyword)cTransientFieldAssignment_0.eContents().get(0);
private final Assignment cIdentityFieldAssignment_1 = (Assignment)cGroup.eContents().get(1);
private final Keyword cIdentityFieldAsteriskKeyword_1_0 = (Keyword)cIdentityFieldAssignment_1.eContents().get(0);
private final Assignment cNameAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cNameIDTerminalRuleCall_2_0 = (RuleCall)cNameAssignment_2.eContents().get(0);
private final Keyword cColonKeyword_3 = (Keyword)cGroup.eContents().get(3);
private final Assignment cDatatypeAssignment_4 = (Assignment)cGroup.eContents().get(4);
private final CrossReference cDatatypeDataTypeCrossReference_4_0 = (CrossReference)cDatatypeAssignment_4.eContents().get(0);
private final RuleCall cDatatypeDataTypeIDTerminalRuleCall_4_0_1 = (RuleCall)cDatatypeDataTypeCrossReference_4_0.eContents().get(1);
//DataTypeField:
// transientField?='transient'? identityField?='*'? name=ID ':' datatype=[DataType];
@Override public ParserRule getRule() { return rule; }
//transientField?='transient'? identityField?='*'? name=ID ':' datatype=[DataType]
public Group getGroup() { return cGroup; }
//transientField?='transient'?
public Assignment getTransientFieldAssignment_0() { return cTransientFieldAssignment_0; }
//'transient'
public Keyword getTransientFieldTransientKeyword_0_0() { return cTransientFieldTransientKeyword_0_0; }
//identityField?='*'?
public Assignment getIdentityFieldAssignment_1() { return cIdentityFieldAssignment_1; }
//'*'
public Keyword getIdentityFieldAsteriskKeyword_1_0() { return cIdentityFieldAsteriskKeyword_1_0; }
//name=ID
public Assignment getNameAssignment_2() { return cNameAssignment_2; }
//ID
public RuleCall getNameIDTerminalRuleCall_2_0() { return cNameIDTerminalRuleCall_2_0; }
//':'
public Keyword getColonKeyword_3() { return cColonKeyword_3; }
//datatype=[DataType]
public Assignment getDatatypeAssignment_4() { return cDatatypeAssignment_4; }
//[DataType]
public CrossReference getDatatypeDataTypeCrossReference_4_0() { return cDatatypeDataTypeCrossReference_4_0; }
//ID
public RuleCall getDatatypeDataTypeIDTerminalRuleCall_4_0_1() { return cDatatypeDataTypeIDTerminalRuleCall_4_0_1; }
}
public class EStringElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "hu.bme.aut.protokit.ProtokitDSL.EString");
private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1);
private final RuleCall cSTRINGTerminalRuleCall_0 = (RuleCall)cAlternatives.eContents().get(0);
private final RuleCall cIDTerminalRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1);
//EString:
// STRING | ID;
@Override public ParserRule getRule() { return rule; }
//STRING | ID
public Alternatives getAlternatives() { return cAlternatives; }
//STRING
public RuleCall getSTRINGTerminalRuleCall_0() { return cSTRINGTerminalRuleCall_0; }
//ID
public RuleCall getIDTerminalRuleCall_1() { return cIDTerminalRuleCall_1; }
}
public class FormatterElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "hu.bme.aut.protokit.ProtokitDSL.Formatter");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Keyword cFormatterKeyword_0 = (Keyword)cGroup.eContents().get(0);
private final Assignment cNameAssignment_1 = (Assignment)cGroup.eContents().get(1);
private final RuleCall cNameIDTerminalRuleCall_1_0 = (RuleCall)cNameAssignment_1.eContents().get(0);
//Formatter:
// 'formatter' name=ID;
@Override public ParserRule getRule() { return rule; }
//'formatter' name=ID
public Group getGroup() { return cGroup; }
//'formatter'
public Keyword getFormatterKeyword_0() { return cFormatterKeyword_0; }
//name=ID
public Assignment getNameAssignment_1() { return cNameAssignment_1; }
//ID
public RuleCall getNameIDTerminalRuleCall_1_0() { return cNameIDTerminalRuleCall_1_0; }
}
private final ProtocolModelElements pProtocolModel;
private final DataTypeElements pDataType;
private final VariableDefinitionElements pVariableDefinition;
private final IntegerFieldElements pIntegerField;
private final StringFieldElements pStringField;
private final BinaryFieldElements pBinaryField;
private final BitFieldElements pBitField;
private final BitfieldComponentElements pBitfieldComponent;
private final ListFieldElements pListField;
private final LengthFieldElements pLengthField;
private final CountFieldElements pCountField;
private final DataTypeFieldElements pDataTypeField;
private final EStringElements pEString;
private final FormatterElements pFormatter;
private final Grammar grammar;
private final TerminalsGrammarAccess gaTerminals;
@Inject
public ProtokitDSLGrammarAccess(GrammarProvider grammarProvider,
TerminalsGrammarAccess gaTerminals) {
this.grammar = internalFindGrammar(grammarProvider);
this.gaTerminals = gaTerminals;
this.pProtocolModel = new ProtocolModelElements();
this.pDataType = new DataTypeElements();
this.pVariableDefinition = new VariableDefinitionElements();
this.pIntegerField = new IntegerFieldElements();
this.pStringField = new StringFieldElements();
this.pBinaryField = new BinaryFieldElements();
this.pBitField = new BitFieldElements();
this.pBitfieldComponent = new BitfieldComponentElements();
this.pListField = new ListFieldElements();
this.pLengthField = new LengthFieldElements();
this.pCountField = new CountFieldElements();
this.pDataTypeField = new DataTypeFieldElements();
this.pEString = new EStringElements();
this.pFormatter = new FormatterElements();
}
protected Grammar internalFindGrammar(GrammarProvider grammarProvider) {
Grammar grammar = grammarProvider.getGrammar(this);
while (grammar != null) {
if ("hu.bme.aut.protokit.ProtokitDSL".equals(grammar.getName())) {
return grammar;
}
List<Grammar> grammars = grammar.getUsedGrammars();
if (!grammars.isEmpty()) {
grammar = grammars.iterator().next();
} else {
return null;
}
}
return grammar;
}
@Override
public Grammar getGrammar() {
return grammar;
}
public TerminalsGrammarAccess getTerminalsGrammarAccess() {
return gaTerminals;
}
//ProtocolModel:
// datatypes+=DataType+;
public ProtocolModelElements getProtocolModelAccess() {
return pProtocolModel;
}
public ParserRule getProtocolModelRule() {
return getProtocolModelAccess().getRule();
}
//DataType:
// ('protocol' | 'datatype') name=ID '{' fields+=VariableDefinition+ '}';
public DataTypeElements getDataTypeAccess() {
return pDataType;
}
public ParserRule getDataTypeRule() {
return getDataTypeAccess().getRule();
}
//VariableDefinition Field:
// IntegerField | StringField | BinaryField | BitField | ListField | LengthField | CountField | DataTypeField
public VariableDefinitionElements getVariableDefinitionAccess() {
return pVariableDefinition;
}
public ParserRule getVariableDefinitionRule() {
return getVariableDefinitionAccess().getRule();
}
//IntegerField:
// transientField?='transient'? identityField?='*'? name=ID ':' 'int' ('(' byteLen=INT ')')?;
public IntegerFieldElements getIntegerFieldAccess() {
return pIntegerField;
}
public ParserRule getIntegerFieldRule() {
return getIntegerFieldAccess().getRule();
}
//StringField:
// transientField?='transient'? identityField?='*'? name=ID ':' 'string' ('(' byteLen=INT ')' | '(' unbounded?='*'? ')'
// formatter=Formatter)?;
public StringFieldElements getStringFieldAccess() {
return pStringField;
}
public ParserRule getStringFieldRule() {
return getStringFieldAccess().getRule();
}
//BinaryField:
// transientField?='transient'? identityField?='*'? name=ID ':' 'binary' ('(' byteLen=INT ')' | '(' unbounded?='*'?
// ')');
public BinaryFieldElements getBinaryFieldAccess() {
return pBinaryField;
}
public ParserRule getBinaryFieldRule() {
return getBinaryFieldAccess().getRule();
}
//BitField:
// transientField?='transient'? identityField?='*'? name=ID ':' 'bitfield' '{' components+=BitfieldComponent+ '}';
public BitFieldElements getBitFieldAccess() {
return pBitField;
}
public ParserRule getBitFieldRule() {
return getBitFieldAccess().getRule();
}
//BitfieldComponent BitFieldComponent:
// name=ID ':' bitLen=INT
public BitfieldComponentElements getBitfieldComponentAccess() {
return pBitfieldComponent;
}
public ParserRule getBitfieldComponentRule() {
return getBitfieldComponentAccess().getRule();
}
//ListField:
// transientField?='transient'? identityField?='*'? name=ID ':' 'list' '(' elementType=[DataType] ')';
public ListFieldElements getListFieldAccess() {
return pListField;
}
public ParserRule getListFieldRule() {
return getListFieldAccess().getRule();
}
//LengthField:
// transientField?='transient'? identityField?='*'? name=ID ':' 'length' '(' byteLen=INT ',' ref=[BinaryField] ')';
public LengthFieldElements getLengthFieldAccess() {
return pLengthField;
}
public ParserRule getLengthFieldRule() {
return getLengthFieldAccess().getRule();
}
//CountField:
// transientField?='transient'? identityField?='*'? name=ID ':' 'count' '(' byteLen=INT ',' ref=[ListField] ')';
public CountFieldElements getCountFieldAccess() {
return pCountField;
}
public ParserRule getCountFieldRule() {
return getCountFieldAccess().getRule();
}
//DataTypeField:
// transientField?='transient'? identityField?='*'? name=ID ':' datatype=[DataType];
public DataTypeFieldElements getDataTypeFieldAccess() {
return pDataTypeField;
}
public ParserRule getDataTypeFieldRule() {
return getDataTypeFieldAccess().getRule();
}
//EString:
// STRING | ID;
public EStringElements getEStringAccess() {
return pEString;
}
public ParserRule getEStringRule() {
return getEStringAccess().getRule();
}
//Formatter:
// 'formatter' name=ID;
public FormatterElements getFormatterAccess() {
return pFormatter;
}
public ParserRule getFormatterRule() {
return getFormatterAccess().getRule();
}
//terminal ID:
// '^'? ('a'..'z' | 'A'..'Z' | '_') ('a'..'z' | 'A'..'Z' | '_' | '0'..'9')*;
public TerminalRule getIDRule() {
return gaTerminals.getIDRule();
}
//terminal INT returns ecore::EInt:
// '0'..'9'+;
public TerminalRule getINTRule() {
return gaTerminals.getINTRule();
}
//terminal STRING:
// '"' ('\\' . | !('\\' | '"'))* '"' | "'" ('\\' . | !('\\' | "'"))* "'";
public TerminalRule getSTRINGRule() {
return gaTerminals.getSTRINGRule();
}
//terminal ML_COMMENT:
// '/ *'->'* /';
public TerminalRule getML_COMMENTRule() {
return gaTerminals.getML_COMMENTRule();
}
//terminal SL_COMMENT:
// '//' !('\n' | '\r')* ('\r'? '\n')?;
public TerminalRule getSL_COMMENTRule() {
return gaTerminals.getSL_COMMENTRule();
}
//terminal WS:
// ' ' | '\t' | '\r' | '\n'+;
public TerminalRule getWSRule() {
return gaTerminals.getWSRule();
}
//terminal ANY_OTHER:
// .;
public TerminalRule getANY_OTHERRule() {
return gaTerminals.getANY_OTHERRule();
}
}
| |
package localsearch.domainspecific.vehiclerouting.apps.truckcontainer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.logging.Level;
import localsearch.domainspecific.vehiclerouting.apps.sharedaride.ShareARide;
import localsearch.domainspecific.vehiclerouting.apps.truckcontainer.model.ContainerTruckMoocInput;
import localsearch.domainspecific.vehiclerouting.apps.truckcontainer.model.Mooc;
import localsearch.domainspecific.vehiclerouting.apps.truckcontainer.model.Truck;
import localsearch.domainspecific.vehiclerouting.vrp.Constants;
import localsearch.domainspecific.vehiclerouting.vrp.ConstraintSystemVR;
import localsearch.domainspecific.vehiclerouting.vrp.IFunctionVR;
import localsearch.domainspecific.vehiclerouting.vrp.VRManager;
import localsearch.domainspecific.vehiclerouting.vrp.VarRoutesVR;
import localsearch.domainspecific.vehiclerouting.vrp.entities.ArcWeightsManager;
import localsearch.domainspecific.vehiclerouting.vrp.entities.Point;
import localsearch.domainspecific.vehiclerouting.vrp.invariants.AccumulatedWeightNodesVR;
import localsearch.domainspecific.vehiclerouting.vrp.invariants.EarliestArrivalTimeVR;
public class SearchOptimumSolution {
TruckContainerSolver tcs;
public SearchOptimumSolution(TruckContainerSolver tcs){
super();
this.tcs = tcs;
}
public void allRemoval(){
System.out.println("all removal");
tcs.mgr.performRemoveAllClientPoints();
for(int i = 0; i < tcs.pickupPoints.size(); i++){
Point pickup = tcs.pickupPoints.get(i);
if(!tcs.rejectPickupPoints.contains(pickup)){
tcs.rejectPickupPoints.add(pickup);
tcs.rejectDeliveryPoints.add(tcs.pickup2Delivery.get(pickup));
}
}
for(int k : tcs.group2marked.keySet())
tcs.group2marked.put(k, 0);
}
public void routeRemoval(){
Random r = new Random();
int k = r.nextInt(tcs.XR.getNbRoutes()) + 1;
System.out.println("routeRemoval: index of removed route = " + k);
Point x = tcs.XR.getStartingPointOfRoute(k);
Point next_x = tcs.XR.next(x);
while(next_x != tcs.XR.getTerminatingPointOfRoute(k)){
x = next_x;
next_x = tcs.XR.next(x);
tcs.mgr.performRemoveOnePoint(x);
tcs.group2marked.put(tcs.point2Group.get(x), 0);
if(tcs.point2Type.get(x) != tcs.START_MOOC
&& tcs.point2Type.get(x) != tcs.END_MOOC){
if(tcs.pickup2Delivery.keySet().contains(x))
tcs.rejectPickupPoints.add(x);
else
tcs.rejectDeliveryPoints.add(x);
}
tcs.nChosed.put(x, tcs.nChosed.get(x)+1);
}
int groupTruck = tcs.point2Group.get(tcs.XR.getStartingPointOfRoute(k));
tcs.group2marked.put(groupTruck, 0);
}
public void randomRequestRemoval(){
Random R = new Random();
int n = R.nextInt(tcs.upper_removal-tcs.lower_removal+1) + tcs.lower_removal;
System.out.println("randomReqRemoval:number of removed request = " + n);
if(n >= tcs.pickupPoints.size()){
tcs.mgr.performRemoveAllClientPoints();
for(int i = 0; i < tcs.pickupPoints.size(); i++){
Point pickup = tcs.pickupPoints.get(i);
if(!tcs.rejectPickupPoints.contains(pickup)){
tcs.rejectPickupPoints.add(pickup);
tcs.rejectDeliveryPoints.add(tcs.pickup2Delivery.get(pickup));
}
}
for(int k : tcs.group2marked.keySet())
tcs.group2marked.put(k, 0);
}
else{
int i = 0;
int c = 0;
while(i < n && c++ < tcs.pickupPoints.size()){
if(tcs.rejectPickupPoints.size() == tcs.pickupPoints.size())
break;
int rand = R.nextInt(tcs.pickupPoints.size());
Point pickup = tcs.pickupPoints.get(rand);
int ridx = tcs.XR.route(pickup);
if(ridx == Constants.NULL_POINT)
continue;
if(!tcs.removeAllowed.get(pickup))
continue;
Point delivery = tcs.pickup2Delivery.get(tcs.pickupPoints.get(rand));
tcs.mgr.performRemoveTwoPoints(pickup, delivery);
tcs.rejectPickupPoints.add(pickup);
tcs.rejectDeliveryPoints.add(delivery);
tcs.group2marked.put(tcs.point2Group.get(pickup), 0);
tcs.group2marked.put(tcs.point2Group.get(delivery), 0);
if(tcs.XR.index(tcs.XR.getTerminatingPointOfRoute(ridx)) <= 1){
int groupTruck = tcs.point2Group.get(tcs.XR.getStartingPointOfRoute(ridx));
tcs.group2marked.put(groupTruck, 0);
}
i++;
tcs.nChosed.put(pickup, tcs.nChosed.get(pickup)+1);
tcs.nChosed.put(delivery, tcs.nChosed.get(delivery)+1);
}
}
}
public void shaw_removal(){
Random R = new Random();
int nRemove = R.nextInt(tcs.upper_removal-tcs.lower_removal+1) + tcs.lower_removal;
System.out.println("Shaw removal : number of request removed = " + nRemove);
int ipRemove;
/*
* select randomly request r1 and its delivery dr1
*/
Point r1 = null;
int c = 0;
do{
if(tcs.rejectPickupPoints.size() == tcs.pickupPoints.size()
|| c++ < tcs.pickupPoints.size()){
r1 = null;
break;
}
ipRemove = R.nextInt(tcs.pickupPoints.size());
r1 = tcs.pickupPoints.get(ipRemove);
}while(nRemove > 0 && (tcs.rejectPickupPoints.contains(r1) || !tcs.removeAllowed.get(r1)));
Point dr1 = null;
if(r1 != null)
dr1 = tcs.pickup2Delivery.get(r1);
/*
* Remove request most related with r1
*/
int inRemove = 0;
while(inRemove++ != nRemove && r1 != null && dr1 != null){
Point removedPickup = null;
Point removedDelivery = null;
double relatedMin = Double.MAX_VALUE;
int routeOfR1 = tcs.XR.route(r1);
/*
* Compute arrival time at request r1 and its delivery dr1
*/
System.out.println(r1 + " " + inRemove);
System.out.println(routeOfR1);
double arrivalTimeR1 = tcs.eat.getEarliestArrivalTime(tcs.XR.prev(r1))+
tcs.serviceDuration.get(tcs.XR.prev(r1))+
tcs.awm.getDistance(tcs.XR.prev(r1), r1);
double serviceTimeR1 = 1.0*tcs.earliestAllowedArrivalTime.get(r1);
serviceTimeR1 = arrivalTimeR1 > serviceTimeR1 ? arrivalTimeR1 : serviceTimeR1;
double depatureTimeR1 = serviceTimeR1 + tcs.serviceDuration.get(r1);
double arrivalTimeDR1 = tcs.eat.getEarliestArrivalTime(tcs.XR.prev(dr1))+
tcs.serviceDuration.get(tcs.XR.prev(dr1))+
tcs.awm.getDistance(tcs.XR.prev(dr1), dr1);
double serviceTimeDR1 = 1.0*tcs.earliestAllowedArrivalTime.get(dr1);
serviceTimeDR1 = arrivalTimeDR1 > serviceTimeDR1 ? arrivalTimeDR1 : serviceTimeDR1;
double depatureTimeDR1 = serviceTimeDR1 + tcs.serviceDuration.get(dr1);
tcs.rejectPickupPoints.add(r1);
tcs.rejectDeliveryPoints.add(dr1);
tcs.nChosed.put(r1, tcs.nChosed.get(r1)+1);
tcs.nChosed.put(dr1, tcs.nChosed.get(dr1)+1);
int ridx = tcs.XR.route(r1);
tcs.group2marked.put(tcs.point2Group.get(r1), 0);
tcs.group2marked.put(tcs.point2Group.get(dr1), 0);
tcs.mgr.performRemoveTwoPoints(r1, dr1);
if(tcs.XR.index(tcs.XR.getTerminatingPointOfRoute(ridx)) <= 1){
int groupTruck = tcs.point2Group.get(tcs.XR.getStartingPointOfRoute(ridx));
tcs.group2marked.put(groupTruck, 0);
}
/*
* find the request is the most related with r1
*/
for(int k=1; k<=tcs.XR.getNbRoutes(); k++){
Point x = tcs.XR.getStartingPointOfRoute(k);
for(x = tcs.XR.next(x); x != tcs.XR.getTerminatingPointOfRoute(k); x = tcs.XR.next(x)){
if(!tcs.removeAllowed.get(x))
continue;
Point dX = tcs.pickup2Delivery.get(x);
if(dX == null)
continue;
/*
* Compute arrival time of x and its delivery dX
*/
double arrivalTimeX = tcs.eat.getEarliestArrivalTime(tcs.XR.prev(x))+
tcs.serviceDuration.get(tcs.XR.prev(x))+
tcs.awm.getDistance(tcs.XR.prev(x), x);
double serviceTimeX = 1.0*tcs.earliestAllowedArrivalTime.get(x);
serviceTimeX = arrivalTimeX > serviceTimeX ? arrivalTimeX : serviceTimeX;
double depatureTimeX = serviceTimeX + tcs.serviceDuration.get(x);
double arrivalTimeDX = tcs.eat.getEarliestArrivalTime(tcs.XR.prev(dX))+
tcs.serviceDuration.get(tcs.XR.prev(dX))+
tcs.awm.getDistance(tcs.XR.prev(dX), dX);
double serviceTimeDX = 1.0*tcs.earliestAllowedArrivalTime.get(dX);
serviceTimeDX = arrivalTimeDX > serviceTimeDX ? arrivalTimeDX : serviceTimeDX;
double depatureTimeDX = serviceTimeDX + tcs.serviceDuration.get(dX);
/*
* Compute related between r1 and x
*/
int lr1x;
if(routeOfR1 == k){
lr1x = 1;
}else{
lr1x = -1;
}
double related = tcs.shaw1st*(tcs.awm.getDistance(r1, x) + tcs.awm.getDistance(dX, dr1))+
tcs.shaw2nd*(Math.abs(depatureTimeR1-depatureTimeX) + Math.abs(depatureTimeDX-depatureTimeDR1))+
tcs.shaw3rd*lr1x;
if(related < relatedMin){
relatedMin = related;
removedPickup = x;
removedDelivery = dX;
}
}
}
r1 = removedPickup;
dr1 = removedDelivery;
if(r1 != null){
tcs.nChosed.put(r1, tcs.nChosed.get(r1)+1);
tcs.nChosed.put(dr1, tcs.nChosed.get(dr1)+1);
}
}
}
public void worst_removal(){
Random R = new Random();
int nRemove = R.nextInt(tcs.upper_removal-tcs.lower_removal+1) + tcs.lower_removal;
System.out.println("worstRemoval: nRemove = " + nRemove);
int inRemove = 0;
int c = 0;
while(inRemove++ != nRemove && c++ < tcs.pickupPoints.size()){
if(tcs.rejectPickupPoints.size() == tcs.pickupPoints.size())
break;
double maxCost = Double.MIN_VALUE;
Point removedPickup = null;
Point removedDelivery = null;
for(int k=1; k<=tcs.XR.getNbRoutes(); k++){
Point x = tcs.XR.getStartingPointOfRoute(k);
for(x = tcs.XR.next(x); x != tcs.XR.getTerminatingPointOfRoute(k); x = tcs.XR.next(x)){
if(!tcs.removeAllowed.get(x))
continue;
Point dX = tcs.pickup2Delivery.get(x);
if(dX == null){
continue;
}
double cost = tcs.objective.evaluateRemoveTwoPoints(x, dX);
if(cost > maxCost){
maxCost = cost;
removedPickup = x;
removedDelivery = dX;
}
}
}
if(removedDelivery == null || removedPickup == null)
break;
int ridx = tcs.XR.route(removedPickup);
tcs.rejectPickupPoints.add(removedPickup);
tcs.rejectDeliveryPoints.add(removedDelivery);
tcs.nChosed.put(removedDelivery, tcs.nChosed.get(removedDelivery)+1);
tcs.nChosed.put(removedPickup, tcs.nChosed.get(removedPickup)+1);
tcs.group2marked.put(tcs.point2Group.get(removedPickup), 0);
tcs.group2marked.put(tcs.point2Group.get(removedDelivery), 0);
tcs.mgr.performRemoveTwoPoints(removedPickup, removedDelivery);
if(tcs.XR.index(tcs.XR.getTerminatingPointOfRoute(ridx)) <= 1){
int groupTruck = tcs.point2Group.get(tcs.XR.getStartingPointOfRoute(ridx));
tcs.group2marked.put(groupTruck, 0);
}
}
}
public void forbidden_removal(int nRemoval){
System.out.println("forbidden_removal");
for(int i=0; i < tcs.pickupPoints.size(); i++){
Point pi = tcs.pickupPoints.get(i);
Point pj = tcs.pickup2Delivery.get(pi);
if(tcs.nChosed.get(pi) > tcs.nTabu){
tcs.removeAllowed.put(pi, false);
tcs.removeAllowed.put(pj, false);
}
}
switch(nRemoval){
case 0: routeRemoval(); break;
case 1: randomRequestRemoval(); break;
case 2: shaw_removal(); break;
case 3: worst_removal(); break;
}
for(int i=0; i < tcs.pickupPoints.size(); i++){
Point pi = tcs.pickupPoints.get(i);
tcs.removeAllowed.put(pi, true);
Point pj = tcs.pickup2Delivery.get(pi);
tcs.removeAllowed.put(pj, true);
}
}
public void greedyInsertion(){
System.out.println("greedyInsertion");
int c = 0;
for(int i = 0; i < tcs.rejectPickupPoints.size(); i++){
Point pickup = tcs.rejectPickupPoints.get(i);
int groupId = tcs.point2Group.get(pickup);
if(tcs.XR.route(pickup) != Constants.NULL_POINT
|| tcs.group2marked.get(groupId) == 1)
continue;
//System.out.println(c++);
Point delivery = tcs.pickup2Delivery.get(pickup);
//add the request to route
Point pre_pick = null;
Point pre_delivery = null;
double best_objective = Double.MAX_VALUE;
for(int r = 1; r <= tcs.XR.getNbRoutes(); r++){
Point st = tcs.XR.getStartingPointOfRoute(r);
int groupTruck = tcs.point2Group.get(st);
if(tcs.group2marked.get(groupTruck) == 1
&& tcs.XR.index(tcs.XR.getTerminatingPointOfRoute(r)) <= 1)
continue;
for(Point p = st; p != tcs.XR.getTerminatingPointOfRoute(r); p = tcs.XR.next(p)){
for(Point q = p; q != tcs.XR.getTerminatingPointOfRoute(r); q = tcs.XR.next(q)){
// if((tcs.XR.prev(p)!= null && tcs.XR.prev(p).getID() % 2 == 1
// && p.getID() % 2 == 1
// && pickup.getID() % 2 == 1)
// || (tcs.XR.next(p) != null && tcs.XR.next(p).getID() % 2 == 1
// && p.getID() % 2 == 1
// && pickup.getID() % 2 == 1))
// System.out.println("bug");
tcs.mgr.performAddTwoPoints(pickup, p, delivery, q);
tcs.insertMoocToRoutes(r);
if(tcs.S.violations() == 0){
double cost = tcs.objective.getValue();
if( cost < best_objective){
best_objective = cost;
pre_pick = p;
pre_delivery = q;
}
}
tcs.mgr.performRemoveTwoPoints(pickup, delivery);
tcs.removeMoocOnRoutes(r);
}
}
}
if(pre_pick != null && pre_delivery != null){
tcs.mgr.performAddTwoPoints(pickup, pre_pick, delivery, pre_delivery);
Point st = tcs.XR.getStartingPointOfRoute(tcs.XR.route(pre_pick));
tcs.rejectPickupPoints.remove(pickup);
tcs.rejectDeliveryPoints.remove(delivery);
int groupTruck = tcs.point2Group.get(st);
tcs.group2marked.put(groupTruck, 1);
tcs.group2marked.put(groupId, 1);
i--;
}
}
tcs.insertMoocForAllRoutes();
}
public void greedyInsertionWithNoise(){
System.out.println("greedyInsertionWithNoise");
// HashMap<Truck, Integer> truck2marked = new HashMap<Truck, Integer>();
// Truck[] trucks = tcs.input.getTrucks();
// for(int i = 0; i < trucks.length; i++)
// truck2marked.put(trucks[i], 0);
// for(int r = 1; r <= tcs.XR.getNbRoutes(); r++){
// if(tcs.XR.index(tcs.XR.getTerminatingPointOfRoute(r)) > 1){
// Point st = tcs.XR.getStartingPointOfRoute(r);
// Truck truck = tcs.startPoint2Truck.get(st);
// truck2marked.put(truck, 1);
// }
// }
for(int i = 0; i < tcs.rejectPickupPoints.size(); i++){
Point pickup = tcs.rejectPickupPoints.get(i);
int groupId = tcs.point2Group.get(pickup);
if(tcs.XR.route(pickup) != Constants.NULL_POINT
|| tcs.group2marked.get(groupId) == 1)
continue;
Point delivery = tcs.pickup2Delivery.get(pickup);
//add the request to route
Point pre_pick = null;
Point pre_delivery = null;
double best_objective = Double.MAX_VALUE;
for(int r = 1; r <= tcs.XR.getNbRoutes(); r++){
Point st = tcs.XR.getStartingPointOfRoute(r);
int groupTruck = tcs.point2Group.get(st);
if(tcs.group2marked.get(groupTruck) == 1 && tcs.XR.index(tcs.XR.getTerminatingPointOfRoute(r)) <= 1)
continue;
for(Point p = st; p != tcs.XR.getTerminatingPointOfRoute(r); p = tcs.XR.next(p)){
for(Point q = p; q != tcs.XR.getTerminatingPointOfRoute(r); q = tcs.XR.next(q)){
// if((tcs.XR.prev(p)!= null && tcs.XR.prev(p).getID() % 2 == 1
// && p.getID() % 2 == 1
// && pickup.getID() % 2 == 1)
// || (tcs.XR.next(p) != null && tcs.XR.next(p).getID() % 2 == 1
// && p.getID() % 2 == 1
// && pickup.getID() % 2 == 1))
// System.out.println("bug");
tcs.mgr.performAddTwoPoints(pickup, p, delivery, q);
tcs.insertMoocToRoutes(r);
if(tcs.S.violations() == 0){
double cost = tcs.objective.getValue();
double ran = Math.random()*2-1;
cost += TruckContainerSolver.MAX_TRAVELTIME*0.1*ran;
if( cost < best_objective){
best_objective = cost;
pre_pick = p;
pre_delivery = q;
}
}
tcs.mgr.performRemoveTwoPoints(pickup, delivery);
tcs.removeMoocOnRoutes(r);
}
}
}
if(pre_pick != null && pre_delivery != null){
tcs.mgr.performAddTwoPoints(pickup, pre_pick, delivery, pre_delivery);
Point st = tcs.XR.getStartingPointOfRoute(tcs.XR.route(pre_pick));
int groupTruck = tcs.point2Group.get(st);
tcs.group2marked.put(groupTruck, 1);
tcs.rejectPickupPoints.remove(pickup);
tcs.rejectDeliveryPoints.remove(delivery);
tcs.group2marked.put(groupId, 1);
i--;
}
}
tcs.insertMoocForAllRoutes();
}
public void regret_n_insertion(int n){
System.out.println("regret insertion n = " + n);
for(int i = 0; i < tcs.rejectPickupPoints.size(); i++){
Point pickup = tcs.rejectPickupPoints.get(i);
int groupId = tcs.point2Group.get(pickup);
if(tcs.XR.route(pickup) != Constants.NULL_POINT
|| tcs.group2marked.get(groupId) == 1)
continue;
Point delivery = tcs.pickup2Delivery.get(pickup);
//add the request to route
Point pre_pick = null;
Point pre_delivery = null;
double n_best_objective[] = new double[n];
double best_regret_value = Double.MIN_VALUE;
for(int it=0; it<n; it++){
n_best_objective[it] = Double.MAX_VALUE;
}
for(int r = 1; r <= tcs.XR.getNbRoutes(); r++){
Point st = tcs.XR.getStartingPointOfRoute(r);
int groupTruck = tcs.point2Group.get(st);
if(tcs.group2marked.get(groupTruck) == 1 && tcs.XR.index(tcs.XR.getTerminatingPointOfRoute(r)) <= 1)
continue;
for(Point p = st; p != tcs.XR.getTerminatingPointOfRoute(r); p = tcs.XR.next(p)){
for(Point q = p; q != tcs.XR.getTerminatingPointOfRoute(r); q = tcs.XR.next(q)){
// if((tcs.XR.prev(p)!= null && tcs.XR.prev(p).getID() % 2 == 1
// && p.getID() % 2 == 1
// && pickup.getID() % 2 == 1)
// || (tcs.XR.next(p) != null && tcs.XR.next(p).getID() % 2 == 1
// && p.getID() % 2 == 1
// && pickup.getID() % 2 == 1))
// System.out.println("bug");
tcs.mgr.performAddTwoPoints(pickup, p, delivery, q);
tcs.insertMoocToRoutes(r);
if(tcs.S.violations() == 0){
double cost = tcs.objective.getValue();
for(int it=0; it<n; it++){
if(n_best_objective[it] > cost){
for(int it2 = n-1; it2 > it; it2--){
n_best_objective[it2] = n_best_objective[it2-1];
}
n_best_objective[it] = cost;
break;
}
}
double regret_value = 0;
for(int it=1; it<n; it++){
regret_value += Math.abs(n_best_objective[it] - n_best_objective[0]);
}
if(regret_value > best_regret_value){
best_regret_value = regret_value;
pre_pick = p;
pre_delivery = q;
}
}
tcs.mgr.performRemoveTwoPoints(pickup, delivery);
tcs.removeMoocOnRoutes(r);
}
}
}
if(pre_pick != null && pre_delivery != null){
tcs.mgr.performAddTwoPoints(pickup, pre_pick, delivery, pre_delivery);
Point st = tcs.XR.getStartingPointOfRoute(tcs.XR.route(pre_pick));
int groupTruck = tcs.point2Group.get(st);
tcs.group2marked.put(groupTruck, 1);
tcs.rejectPickupPoints.remove(pickup);
tcs.rejectDeliveryPoints.remove(delivery);
tcs.group2marked.put(groupId, 1);
i--;
}
}
tcs.insertMoocForAllRoutes();
}
public void first_possible_insertion(){
System.out.println("first_possible_insertion");
for(int i = 0; i < tcs.rejectPickupPoints.size(); i++){
Point pickup = tcs.rejectPickupPoints.get(i);
int groupId = tcs.point2Group.get(pickup);
if(tcs.XR.route(pickup) != Constants.NULL_POINT
|| tcs.group2marked.get(groupId) == 1)
continue;
Point delivery = tcs.pickup2Delivery.get(pickup);
//add the request to route
Point pre_pick = null;
Point pre_delivery = null;
double best_objective = Double.MAX_VALUE;
boolean finded = false;
for(int r = 1; r <= tcs.XR.getNbRoutes(); r++){
if(finded)
break;
Point st = tcs.XR.getStartingPointOfRoute(r);
int groupTruck = tcs.point2Group.get(st);
if(tcs.group2marked.get(groupTruck) == 1 && tcs.XR.index(tcs.XR.getTerminatingPointOfRoute(r)) <= 1)
continue;
for(Point p = st; p != tcs.XR.getTerminatingPointOfRoute(r); p = tcs.XR.next(p)){
if(finded)
break;
for(Point q = p; q != tcs.XR.getTerminatingPointOfRoute(r); q = tcs.XR.next(q)){
// if((tcs.XR.prev(p)!= null && tcs.XR.prev(p).getID() % 2 == 1
// && p.getID() % 2 == 1
// && pickup.getID() % 2 == 1)
// || (tcs.XR.next(p) != null && tcs.XR.next(p).getID() % 2 == 1
// && p.getID() % 2 == 1
// && pickup.getID() % 2 == 1))
// System.out.println("bug");
tcs.mgr.performAddTwoPoints(pickup, p, delivery, q);
tcs.insertMoocToRoutes(r);
if(tcs.S.violations() == 0){
double cost = tcs.objective.getValue();
if( cost < best_objective){
tcs.removeMoocOnRoutes(r);
tcs.group2marked.put(groupTruck, 1);
tcs.rejectPickupPoints.remove(pickup);
tcs.rejectDeliveryPoints.remove(delivery);
tcs.group2marked.put(groupId, 1);
finded = true;
i--;
break;
}
}
tcs.mgr.performRemoveTwoPoints(pickup, delivery);
tcs.removeMoocOnRoutes(r);
}
}
}
}
tcs.insertMoocForAllRoutes();
}
public void sort_before_insertion(int iInsertion){
System.out.println("sort_before_insertion");
sort_reject_people();
switch(iInsertion){
case 0: greedyInsertion(); break;
case 1: greedyInsertionWithNoise(); break;
case 2: regret_n_insertion(2); break;
case 3: first_possible_insertion(); break;
}
Collections.shuffle(tcs.rejectPickupPoints);
}
private void sort_reject_people(){
HashMap<Point, Integer> time_flexibility = new HashMap<Point, Integer>();
for(int i = 0; i < tcs.rejectPickupPoints.size(); i++){
Point pickup = tcs.rejectPickupPoints.get(i);
Point delivery = tcs.pickup2Delivery.get(pickup);
int lp = tcs.lastestAllowedArrivalTime.get(pickup);
int ud = tcs.earliestAllowedArrivalTime.get(delivery);
time_flexibility.put(pickup, ud-lp);
}
List<Point> keys = new ArrayList<Point>(time_flexibility.keySet());
List<Integer> values = new ArrayList<Integer>(time_flexibility.values());
Collections.sort(values);
ArrayList<Point> rejectPointSorted = new ArrayList<Point>();
for(int i = 0; i < values.size(); i++){
int v = values.get(i);
for(int j = 0; j < keys.size(); j++){
Point p = keys.get(j);
int vs = time_flexibility.get(p);
if(vs == v){
rejectPointSorted.add(p);
keys.remove(p);
break;
}
}
}
tcs.rejectPickupPoints = rejectPointSorted;
}
}
| |
package com.croconaut.tictactoe.communication;
import android.content.Context;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.Size;
import android.util.Log;
import com.croconaut.cpt.data.Communication;
import com.croconaut.cpt.data.OutgoingMessage;
import com.croconaut.cpt.data.OutgoingPayload;
import com.croconaut.ratemebuddy.AppData;
import com.croconaut.ratemebuddy.utils.pojo.profiles.Profile;
import com.croconaut.tictactoe.model.board.GameSeed;
import com.croconaut.tictactoe.payload.games.Game;
import com.croconaut.tictactoe.payload.games.GameSize;
import com.croconaut.tictactoe.payload.games.GameState;
import com.croconaut.tictactoe.payload.invites.InviteRequest;
import com.croconaut.tictactoe.payload.invites.InviteResponse;
import com.croconaut.tictactoe.payload.moves.Move;
import com.croconaut.tictactoe.payload.moves.Surrender;
import com.croconaut.tictactoe.storage.GameRepository;
import com.croconaut.tictactoe.storage.database.SQLiteDbHelper;
import com.croconaut.tictactoe.storage.repository.GameRepositoryImpl;
import com.croconaut.tictactoe.ui.notifications.InviteNotificationManager;
import com.croconaut.tictactoe.utils.GameIdGenerator;
import com.croconaut.tictactoe.utils.StateUtils;
import java.io.IOException;
import java.util.List;
import static com.croconaut.tictactoe.model.board.Board.BOARD_SIZE_MINIMUM;
import static com.croconaut.tictactoe.payload.games.GameState.WIN_NOUGHT;
import static com.croconaut.tictactoe.utils.Assertions.assertIsBiggerThan;
import static com.croconaut.tictactoe.utils.Assertions.assertIsSeed;
import static com.croconaut.tictactoe.utils.Assertions.assertNotNull;
import static com.croconaut.tictactoe.utils.StateUtils.PENDING_STATES;
import static com.croconaut.tictactoe.utils.StateUtils.isGameInProgress;
public final class GameCommunication {
@NonNull
private static final String TAG = GameCommunication.class.getName();
@NonNull
private final Context mContext;
@NonNull
private final GameRepository mGameRepository;
public GameCommunication(@NonNull final Context context) {
assertNotNull(context, "context");
this.mContext = context;
this.mGameRepository = new GameRepositoryImpl(new SQLiteDbHelper(mContext));
}
@CheckResult
@Nullable
public Game inviteToGame(@NonNull @Size(min = 1) final String remotePlayerId,
@GameSeed final int seed,
@GameSize final int gameSize) {
assertNotNull(remotePlayerId, "remotePlayerId");
assertIsBiggerThan(remotePlayerId.length(), 1, "remotePlayerId");
assertIsBiggerThan(gameSize, BOARD_SIZE_MINIMUM, "gameSize");
assertIsSeed(seed, "seed");
try {
final Game game = new Game(
GameIdGenerator.newGameId(), System.currentTimeMillis(),
remotePlayerId, seed, gameSize, GameState.PENDING_WAITING_FOR_INVITE_RESPONSE);
final InviteRequest gameInvite = new InviteRequest(game);
if (mGameRepository.isInviteLockPresent(remotePlayerId) != null) {
Log.e(TAG, "INVITE LOCK - UPDATING INVITE LOCK");
mGameRepository.updateInviteLock(remotePlayerId, gameInvite);
} else {
final OutgoingPayload outgoingPayload = new OutgoingPayload(gameInvite);
final OutgoingMessage outgoingMessage = new OutgoingMessage(remotePlayerId, outgoingPayload);
Communication.newMessage(mContext, outgoingMessage);
}
mGameRepository.insertGame(game);
return game;
} catch (IOException ioException) {
Log.e(TAG, "Invite to game failed.", ioException);
return null;
}
}
@CheckResult
public boolean processInviteRequest(@NonNull final AppData appData,
@NonNull @Size(min = 1) final String remotePlayerId,
@NonNull final InviteRequest inviteRequest) {
assertNotNull(inviteRequest, "inviteRequest");
assertNotNull(remotePlayerId, "remotePlayerId");
assertIsBiggerThan(remotePlayerId.length(), 1, "remotePlayerId");
final Profile profile = appData.getProfileDataSource().getProfileByCrocoId(remotePlayerId);
final List<Game> playerGames = mGameRepository.getGamesByPlayerId(remotePlayerId);
final Game gameInPendingState = StateUtils.isGameInState(PENDING_STATES, playerGames);
if (null != gameInPendingState) {
if (gameInPendingState.getGameTimestamp() > inviteRequest.getGameTimestamp()) {
insertPendingGame(remotePlayerId, inviteRequest);
mGameRepository.deleteGame(gameInPendingState);
InviteNotificationManager
.createInviteRequestNotification(appData, profile, inviteRequest, true);
}
} else {
insertPendingGame(remotePlayerId, inviteRequest);
InviteNotificationManager
.createInviteRequestNotification(appData, profile, inviteRequest, false);
}
return true;
}
private void insertPendingGame(@NonNull @Size(min = 1) String remotePlayerId,
@NonNull InviteRequest inviteRequest) {
final @GameState int gameState = GameState.PENDING_WAITING_FOR_INVITE_REQUEST;
final @GameSeed int gameSeed = inviteRequest.getSeed() == GameSeed.CROSS
? GameSeed.NOUGHT
: GameSeed.CROSS;
final Game game = new Game(
inviteRequest.getGameId(), inviteRequest.getGameTimestamp(), remotePlayerId,
gameSeed, inviteRequest.getGameSize(), gameState);
mGameRepository.insertGame(game);
Log.e(TAG, "INVITE NEW processInviteRequest: "
+ remotePlayerId + " for game " + inviteRequest.getGameId());
}
@CheckResult
public boolean processInviteResponse(@NonNull final AppData appData,
@NonNull @Size(min = 1) final String remotePlayerId,
@NonNull final InviteResponse inviteResponse) {
assertNotNull(inviteResponse, "inviteResponse");
assertNotNull(remotePlayerId, "remotePlayerId");
assertIsBiggerThan(remotePlayerId.length(), 1, "remotePlayerId");
boolean valid = false;
final Profile profile = appData.getProfileDataSource().getProfileByCrocoId(remotePlayerId);
final Game game = mGameRepository.getGameByGameId(inviteResponse.getGameId());
if (null != game) {
valid = true;
if (!StateUtils.isGameInProgress(game.getGameState())) {
return valid;
}
if (inviteResponse.isGameAccepted()) {
@GameState final int newGameState = game.getGameSeed() == GameSeed.CROSS
? GameState.PLAYING_NEXT_MOVE_CROSS
: GameState.PLAYING_NEXT_MOVE_NOUGHT;
mGameRepository.updateGameState(game, newGameState);
} else {
Log.e(TAG, "Game was rejected by remote player");
mGameRepository.deleteGame(game);
}
InviteNotificationManager
.createInviteResponseNotification(appData, profile, inviteResponse);
}
return valid;
}
@CheckResult
@Nullable
public Game acceptInvite(@NonNull @Size(min = 1) final String remotePlayerId,
@NonNull final String gameId, @GameSeed final int gameSeed) {
assertNotNull(gameId, "gameId");
assertNotNull(remotePlayerId, "remotePlayerId");
assertIsBiggerThan(remotePlayerId.length(), 1, "remotePlayerId");
try {
final @GameState int gameState = gameSeed == GameSeed.CROSS
? GameState.PLAYING_NEXT_MOVE_CROSS
: GameState.PLAYING_NEXT_MOVE_NOUGHT;
final Game game = mGameRepository.getGameByGameId(gameId);
assertNotNull(game, "game");
mGameRepository.updateGameState(game, gameState);
final InviteResponse inviteResponse = new InviteResponse(game.getGameId(), true);
final OutgoingPayload outgoingPayload = new OutgoingPayload(inviteResponse);
final OutgoingMessage outgoingMessage = new OutgoingMessage(remotePlayerId, outgoingPayload);
Communication.newMessage(mContext, outgoingMessage);
return game;
} catch (IOException ioException) {
Log.e(TAG, "Accept invite failed", ioException);
return null;
}
}
public void declineInvite(@NonNull @Size(min = 1) final String remotePlayerId,
@NonNull final String gameId) {
assertNotNull(remotePlayerId, "remotePlayerId");
assertNotNull(gameId, "gameId");
try {
final Game game = mGameRepository.getGameByGameId(gameId);
assertNotNull(game, "game");
mGameRepository.deleteGame(game);
final InviteResponse inviteResponse = new InviteResponse(gameId, false);
final OutgoingPayload outgoingPayload = new OutgoingPayload(inviteResponse);
final OutgoingMessage outgoingMessage = new OutgoingMessage(remotePlayerId, outgoingPayload);
Communication.newMessage(mContext, outgoingMessage);
} catch (IOException ioException) {
Log.e(TAG, "Decline invite failed", ioException);
}
}
@CheckResult
public long sendMove(@NonNull @Size(min = 1) final String remotePlayerId,
@NonNull final Move move) {
assertNotNull(remotePlayerId, "remotePlayerId");
assertNotNull(move, "move");
try {
final Game game = mGameRepository.getGameByGameId(move.getGameId());
assertNotNull(game, "game");
final OutgoingPayload outgoingPayload = new OutgoingPayload(move);
final OutgoingMessage outgoingMessage = new OutgoingMessage(remotePlayerId, outgoingPayload);
Communication.newMessage(mContext, outgoingMessage);
mGameRepository.insertMove(move);
return outgoingMessage.getCreationDate().getTime();
} catch (IOException ioException) {
Log.e(TAG, "Send move failed.", ioException);
return 0;
}
}
@CheckResult
public boolean processMove(@NonNull final Move move) {
assertNotNull(move, "move");
boolean valid = false;
final Game game = mGameRepository.getGameByGameId(move.getGameId());
if (null != game && isGameInProgress(game.getGameState())) {
final List<Move> allMoves = mGameRepository.getAllMovesByGameId(game.getGameId());
if (!allMoves.contains(move)) {
valid = true;
mGameRepository.insertMove(move);
mGameRepository.updateGameState(game, move.getGameState());
} else {
Log.e(TAG, "Already received: " + move);
}
} else {
Log.e(TAG, "No game found for ID: " + move.getGameId());
}
return valid;
}
public void sendSurrender(@NonNull final String gameId) {
assertNotNull(gameId, "game");
try {
final Game game = mGameRepository.getGameByGameId(gameId);
assertNotNull(game, "game"); //should not happen
final Surrender surrender = new Surrender(game.getGameId());
final OutgoingPayload outgoingPayload = new OutgoingPayload(surrender);
final OutgoingMessage outgoingMessage
= new OutgoingMessage(game.getRemoteProfileId(), outgoingPayload);
Communication.newMessage(mContext, outgoingMessage);
mGameRepository.updateGameState(
game, game.getGameSeed() == GameSeed.CROSS ? WIN_NOUGHT : GameState.WIN_CROSS);
} catch (IOException ioException) {
Log.e(TAG, "Send Surrender failed.", ioException);
}
}
@CheckResult
public boolean processSurrender(@NonNull final Surrender surrender) {
assertNotNull(surrender, "surrender");
boolean valid = false;
final Game game = mGameRepository.getGameByGameId(surrender.getGameId());
if (null != game) {
if (StateUtils.PLAYING_STATES.contains(game.getGameState())) {
mGameRepository.updateGameState(
game, game.getGameSeed() == GameSeed.CROSS ? GameState.WIN_CROSS : GameState.WIN_NOUGHT);
valid = true;
} else if (StateUtils.PENDING_STATES.contains(game.getGameState())) {
mGameRepository.deleteGame(game);
}
} else {
Log.e(TAG, "No game found for ID: " + surrender.getGameId());
}
return valid; //could be game != null
}
public GameRepository getGameRepository() {
return mGameRepository;
}
}
| |
/*
* Copyright (C) 2011 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.android.wifi;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.util.Log;
import com.google.zxing.client.result.WifiParsedResult;
import java.util.regex.Pattern;
/**
* @author Vikram Aggarwal
* @author Sean Owen
*/
public final class WifiConfigManager extends AsyncTask<WifiParsedResult, Object, Object> {
private static final String TAG = WifiConfigManager.class.getSimpleName();
private static final Pattern HEX_DIGITS = Pattern.compile("[0-9A-Fa-f]+");
private final WifiManager wifiManager;
public WifiConfigManager(WifiManager wifiManager) {
this.wifiManager = wifiManager;
}
@Override
protected Object doInBackground(WifiParsedResult... args) {
WifiParsedResult theWifiResult = args[0];
// Start WiFi, otherwise nothing will work
if (!wifiManager.isWifiEnabled()) {
Log.i(TAG, "Enabling wi-fi...");
if (wifiManager.setWifiEnabled(true)) {
Log.i(TAG, "Wi-fi enabled");
} else {
Log.w(TAG, "Wi-fi could not be enabled!");
return null;
}
// This happens very quickly, but need to wait for it to enable. A little busy wait?
int count = 0;
while (!wifiManager.isWifiEnabled()) {
if (count >= 10) {
Log.i(TAG, "Took too long to enable wi-fi, quitting");
return null;
}
Log.i(TAG, "Still waiting for wi-fi to enable...");
try {
Thread.sleep(1000L);
} catch (InterruptedException ie) {
// continue
}
count++;
}
}
String networkTypeString = theWifiResult.getNetworkEncryption();
NetworkType networkType;
try {
networkType = NetworkType.forIntentValue(networkTypeString);
} catch (IllegalArgumentException ignored) {
Log.w(TAG, "Bad network type; see NetworkType values: " + networkTypeString);
return null;
}
if (networkType == NetworkType.NO_PASSWORD) {
changeNetworkUnEncrypted(wifiManager, theWifiResult);
} else {
String password = theWifiResult.getPassword();
if (password != null && !password.isEmpty()) {
if (networkType == NetworkType.WEP) {
changeNetworkWEP(wifiManager, theWifiResult);
} else if (networkType == NetworkType.WPA) {
changeNetworkWPA(wifiManager, theWifiResult);
}
}
}
return null;
}
/**
* Update the network: either create a new network or modify an existing network
*
* @param config the new network configuration
*/
private static void updateNetwork(WifiManager wifiManager, WifiConfiguration config) {
Integer foundNetworkID = findNetworkInExistingConfig(wifiManager, config.SSID);
if (foundNetworkID != null) {
Log.i(TAG, "Removing old configuration for network " + config.SSID);
wifiManager.removeNetwork(foundNetworkID);
wifiManager.saveConfiguration();
}
int networkId = wifiManager.addNetwork(config);
if (networkId >= 0) {
// Try to disable the current network and start a new one.
if (wifiManager.enableNetwork(networkId, true)) {
Log.i(TAG, "Associating to network " + config.SSID);
wifiManager.saveConfiguration();
} else {
Log.w(TAG, "Failed to enable network " + config.SSID);
}
} else {
Log.w(TAG, "Unable to add network " + config.SSID);
}
}
private static WifiConfiguration changeNetworkCommon(WifiParsedResult wifiResult) {
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
// Android API insists that an ascii SSID must be quoted to be correctly handled.
config.SSID = quoteNonHex(wifiResult.getSsid());
config.hiddenSSID = wifiResult.isHidden();
return config;
}
// Adding a WEP network
private static void changeNetworkWEP(WifiManager wifiManager, WifiParsedResult wifiResult) {
WifiConfiguration config = changeNetworkCommon(wifiResult);
config.wepKeys[0] = quoteNonHex(wifiResult.getPassword(), 10, 26, 58);
config.wepTxKeyIndex = 0;
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
updateNetwork(wifiManager, config);
}
// Adding a WPA or WPA2 network
private static void changeNetworkWPA(WifiManager wifiManager, WifiParsedResult wifiResult) {
WifiConfiguration config = changeNetworkCommon(wifiResult);
// Hex passwords that are 64 bits long are not to be quoted.
config.preSharedKey = quoteNonHex(wifiResult.getPassword(), 64);
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
config.allowedProtocols.set(WifiConfiguration.Protocol.WPA); // For WPA
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN); // For WPA2
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
updateNetwork(wifiManager, config);
}
// Adding an open, unsecured network
private static void changeNetworkUnEncrypted(WifiManager wifiManager, WifiParsedResult wifiResult) {
WifiConfiguration config = changeNetworkCommon(wifiResult);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
updateNetwork(wifiManager, config);
}
private static Integer findNetworkInExistingConfig(WifiManager wifiManager, String ssid) {
Iterable<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();
for (WifiConfiguration existingConfig : existingConfigs) {
if (existingConfig.SSID.equals(ssid)) {
return existingConfig.networkId;
}
}
return null;
}
private static String quoteNonHex(String value, int... allowedLengths) {
return isHexOfLength(value, allowedLengths) ? value : convertToQuotedString(value);
}
/**
* Encloses the incoming string inside double quotes, if it isn't already quoted.
*
* @param s the input string
* @return a quoted string, of the form "input". If the input string is null, it returns null
* as well.
*/
private static String convertToQuotedString(String s) {
if (s == null || s.isEmpty()) {
return null;
}
// If already quoted, return as-is
if (s.charAt(0) == '"' && s.charAt(s.length() - 1) == '"') {
return s;
}
return '\"' + s + '\"';
}
/**
* @param value input to check
* @param allowedLengths allowed lengths, if any
* @return true if value is a non-null, non-empty string of hex digits, and if allowed lengths are given, has
* an allowed length
*/
private static boolean isHexOfLength(CharSequence value, int... allowedLengths) {
if (value == null || !HEX_DIGITS.matcher(value).matches()) {
return false;
}
if (allowedLengths.length == 0) {
return true;
}
for (int length : allowedLengths) {
if (value.length() == length) {
return true;
}
}
return false;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.tests.java.text;
import java.math.RoundingMode;
import java.text.ChoiceFormat;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Currency;
import java.util.Locale;
public class NumberFormatTest extends junit.framework.TestCase {
/**
* @tests java.text.NumberFormat#format(java.lang.Object,
* java.lang.StringBuffer, java.text.FieldPosition)
*/
public void test_formatLjava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition() {
FieldPosition pos;
StringBuffer out;
DecimalFormat format = (DecimalFormat) NumberFormat
.getInstance(Locale.US);
pos = new FieldPosition(0);
out = format.format(new Long(Long.MAX_VALUE), new StringBuffer(), pos);
assertEquals("Wrong result L1: " + out, "9,223,372,036,854,775,807",
out.toString());
pos = new FieldPosition(0);
out = format.format(new Long(Long.MIN_VALUE), new StringBuffer(), pos);
assertEquals("Wrong result L2: " + out, "-9,223,372,036,854,775,808",
out.toString());
pos = new FieldPosition(0);
out = format.format(new java.math.BigInteger(String
.valueOf(Long.MAX_VALUE)), new StringBuffer(), pos);
assertEquals("Wrong result BI1: " + out, "9,223,372,036,854,775,807",
out.toString());
pos = new FieldPosition(0);
out = format.format(new java.math.BigInteger(String
.valueOf(Long.MIN_VALUE)), new StringBuffer(), pos);
assertEquals("Wrong result BI2: " + out, "-9,223,372,036,854,775,808",
out.toString());
java.math.BigInteger big;
pos = new FieldPosition(0);
big = new java.math.BigInteger(String.valueOf(Long.MAX_VALUE))
.add(new java.math.BigInteger("1"));
out = format.format(big, new StringBuffer(), pos);
assertEquals("Wrong result BI3: " + out, "9,223,372,036,854,775,808",
out.toString());
pos = new FieldPosition(0);
big = new java.math.BigInteger(String.valueOf(Long.MIN_VALUE))
.add(new java.math.BigInteger("-1"));
out = format.format(big, new StringBuffer(), pos);
assertEquals("Wrong result BI4: " + out, "-9,223,372,036,854,775,809",
out.toString());
pos = new FieldPosition(0);
out = format.format(new java.math.BigDecimal("51.348"),
new StringBuffer(), pos);
assertEquals("Wrong result BD1: " + out, "51.348", out.toString());
pos = new FieldPosition(0);
out = format.format(new java.math.BigDecimal("51"), new StringBuffer(),
pos);
assertEquals("Wrong result BD2: " + out, "51", out.toString());
try {
format.format(this, new StringBuffer(), pos);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// Expected
}
try {
format.format(null, new StringBuffer(), pos);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// Expected
}
try {
format.format(new Long(0), null, pos);
fail("Should throw NullPointerException");
} catch (NullPointerException e) {
// Expected
}
try {
format.format(new Long(0), new StringBuffer(), null);
fail("Should throw NullPointerException");
} catch (NullPointerException e) {
// Expected
}
}
/**
* @tests java.text.NumberFormat#getIntegerInstance()
*/
public void test_getIntegerInstance() throws ParseException {
// Test for method java.text.NumberFormat getIntegerInstance()
Locale origLocale = Locale.getDefault();
Locale.setDefault(Locale.US);
DecimalFormat format = (DecimalFormat) NumberFormat
.getIntegerInstance();
assertEquals(
"Test1: NumberFormat.getIntegerInstance().toPattern() returned wrong pattern",
"#,##0", format.toPattern());
assertEquals(
"Test2: NumberFormat.getIntegerInstance().format(35.76) returned wrong value",
"36", format.format(35.76));
assertEquals(
"Test3: NumberFormat.getIntegerInstance().parse(\"35.76\") returned wrong number",
new Long(35), format.parse("35.76"));
assertEquals(
"Test4: NumberFormat.getIntegerInstance().parseObject(\"35.76\") returned wrong number",
new Long(35), format.parseObject("35.76"));
Locale.setDefault(origLocale);
}
/**
* @tests java.text.NumberFormat#getIntegerInstance(java.util.Locale)
*/
public void test_getIntegerInstanceLjava_util_Locale()
throws ParseException {
// Test for method java.text.NumberFormat
// getIntegerInstance(java.util.Locale)
Locale usLocale = Locale.US;
Locale arLocale = new Locale("ar", "AE");
DecimalFormat format = (DecimalFormat) NumberFormat
.getIntegerInstance(usLocale);
assertEquals(
"Test1: NumberFormat.getIntegerInstance().toPattern() returned wrong pattern",
"#,##0", format.toPattern());
assertEquals(
"Test2: NumberFormat.getIntegerInstance().format(-35.76) returned wrong value",
"-36", format.format(-35.76));
assertEquals(
"Test3: NumberFormat.getIntegerInstance().parse(\"-36\") returned wrong number",
new Long(-36), format.parse("-36"));
assertEquals(
"Test4: NumberFormat.getIntegerInstance().parseObject(\"-36\") returned wrong number",
new Long(-36), format.parseObject("-36"));
assertEquals(
"Test5: NumberFormat.getIntegerInstance().getMaximumFractionDigits() returned wrong value",
0, format.getMaximumFractionDigits());
assertTrue("Test6: NumberFormat.getIntegerInstance().isParseIntegerOnly() returned wrong value",
format.isParseIntegerOnly());
// try with a locale that has a different integer pattern
format = (DecimalFormat) NumberFormat.getIntegerInstance(arLocale);
// Previous versions of android use just the positive format string (ICU4C) although now we
// use '<positive_format>;<negative_format>' because of ICU4J denormalization.
String variant = (format.toPattern().indexOf(';') > 0) ? "#,##0;-#,##0" : "#,##0";
assertEquals(
"Test7: NumberFormat.getIntegerInstance(new Locale(\"ar\", \"AE\")).toPattern() returned wrong pattern",
variant, format.toPattern());
/* J2ObjC: MacOS doesn't seem to have the Arabic symbols.
assertEquals(
"Test8: NumberFormat.getIntegerInstance(new Locale(\"ar\", \"AE\")).format(-6) returned wrong value",
"-\u0666", format.format(-6));*/
assertEquals(
"Test9: NumberFormat.getIntegerInstance(new Locale(\"ar\", \"AE\")).parse(\"-36-\") returned wrong number",
new Long(36), format.parse("36-"));
assertEquals(
"Test10: NumberFormat.getIntegerInstance(new Locale(\"ar\", \"AE\")).parseObject(\"36-\") returned wrong number",
new Long(36), format.parseObject("36-"));
assertEquals(
"Test11: NumberFormat.getIntegerInstance(new Locale(\"ar\", \"AE\")).getMaximumFractionDigits() returned wrong value",
0, format.getMaximumFractionDigits());
assertTrue(
"Test12: NumberFormat.getIntegerInstance(new Locale(\"ar\", \"AE\")).isParseIntegerOnly() returned wrong value",
format.isParseIntegerOnly());
}
/**
* @tests java.text.NumberFormat#getCurrency()
*/
public void test_getCurrency() {
// Test for method java.util.Currency getCurrency()
// a subclass that supports currency formatting
Currency currH = Currency.getInstance("HUF");
NumberFormat format = NumberFormat.getInstance(new Locale("hu", "HU"));
assertSame("Returned incorrect currency", currH, format.getCurrency());
// a subclass that doesn't support currency formatting
ChoiceFormat cformat = new ChoiceFormat(
"0#Less than one|1#one|1<Between one and two|2<Greater than two");
try {
((NumberFormat) cformat).getCurrency();
fail("Expected UnsupportedOperationException");
} catch (UnsupportedOperationException e) {
}
}
/**
* @tests java.text.NumberFormat#getMaximumIntegerDigits()
*/
public void test_getMaximumIntegerDigits() {
NumberFormat format = NumberFormat.getInstance();
format.setMaximumIntegerDigits(2);
assertEquals("Wrong result", "23", format.format(123));
}
/**
* @tests java.text.NumberFormat#setCurrency(java.util.Currency)
*/
public void test_setCurrencyLjava_util_Currency() {
// Test for method void setCurrency(java.util.Currency)
// a subclass that supports currency formatting
Currency currA = Currency.getInstance("ARS");
NumberFormat format = NumberFormat.getInstance(new Locale("hu", "HU"));
format.setCurrency(currA);
assertSame("Returned incorrect currency", currA, format.getCurrency());
// a subclass that doesn't support currency formatting
ChoiceFormat cformat = new ChoiceFormat(
"0#Less than one|1#one|1<Between one and two|2<Greater than two");
try {
((NumberFormat) cformat).setCurrency(currA);
fail("Expected UnsupportedOperationException");
} catch (UnsupportedOperationException e) {
}
}
/**
* @tests java.text.NumberFormat#parseObject(java.lang.String, java.text.ParsePosition)
*/
public void test_parseObjectLjava_lang_StringLjava_text_ParsePosition() {
// regression test for HARMONY-1003
assertNull(NumberFormat.getInstance().parseObject("0", new ParsePosition(-1)));
// Regression for HARMONY-1685
try {
NumberFormat.getInstance().parseObject("test", null);
fail("NullPointerException expected");
} catch (NullPointerException e) {
//expected
}
}
protected void setUp() {
}
protected void tearDown() {
}
public void test_setRoundingMode_NullRoundingMode() {
try {
// Create a subclass ChoiceFormat which doesn't support
// RoundingMode
ChoiceFormat choiceFormat = new ChoiceFormat(
"0#Less than one|1#one|1<Between one and two|2<Greater than two");
((NumberFormat) choiceFormat).setRoundingMode(null);
// Follow the behavior of RI
fail("UnsupportedOperationException expected");
} catch (UnsupportedOperationException e) {
// expected
}
}
public void test_setRoundingMode_Normal() {
try {
// Create a subclass ChoiceFormat which doesn't support
// RoundingMode
ChoiceFormat choiceFormat = new ChoiceFormat(
"0#Less than one|1#one|1<Between one and two|2<Greater than two");
((NumberFormat) choiceFormat).setRoundingMode(RoundingMode.CEILING);
fail("UnsupportedOperationException expected");
} catch (UnsupportedOperationException e) {
// expected
}
}
}
| |
/*
* Autopsy Forensic Browser
*
* Copyright 2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.livetriage;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.logging.Level;
import java.awt.Dimension;
import java.awt.Point;
import javax.swing.SwingWorker;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.coreutils.LocalDisk;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.PlatformUtil;
/**
* Dialog to allow for live triage drive selection.
*/
@SuppressWarnings("PMD.SingularField") // UI widgets cause lots of false positives
class SelectDriveDialog extends javax.swing.JDialog {
private List<LocalDisk> disks = new ArrayList<>();
private final LocalDiskModel model = new LocalDiskModel();
private final java.awt.Frame parent;
private String drivePath = "";
/**
* Creates new form SelectDriveDialog
*/
@NbBundle.Messages({"SelectDriveDialog.title=Create Live Triage Drive"})
SelectDriveDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
this.parent = parent;
model.loadDisks();
bnOk.setEnabled(false);
diskTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (diskTable.getSelectedRow() >= 0 && diskTable.getSelectedRow() < disks.size()) {
bnOk.setEnabled(true);
} else { //The selection changed to nothing valid being selected, such as with ctrl+click
bnOk.setEnabled(false);
}
}
});
}
void display() {
this.setTitle(Bundle.SelectDriveDialog_title());
final Dimension parentSize = parent.getSize();
final Point parentLocationOnScreen = parent.getLocationOnScreen();
final Dimension childSize = this.getSize();
int x;
int y;
x = (parentSize.width - childSize.width) / 2;
y = (parentSize.height - childSize.height) / 2;
x += parentLocationOnScreen.x;
y += parentLocationOnScreen.y;
setLocation(x, y);
setVisible(true);
}
String getSelectedDrive() {
return this.drivePath;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
diskTable = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
bnRefresh = new javax.swing.JButton();
bnOk = new javax.swing.JButton();
errorLabel = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
bnCancel = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
diskTable.setModel(model);
jScrollPane1.setViewportView(diskTable);
org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(SelectDriveDialog.class, "SelectDriveDialog.jLabel1.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(bnRefresh, org.openide.util.NbBundle.getMessage(SelectDriveDialog.class, "SelectDriveDialog.bnRefresh.text")); // NOI18N
bnRefresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bnRefreshActionPerformed(evt);
}
});
org.openide.awt.Mnemonics.setLocalizedText(bnOk, org.openide.util.NbBundle.getMessage(SelectDriveDialog.class, "SelectDriveDialog.bnOk.text")); // NOI18N
bnOk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bnOkActionPerformed(evt);
}
});
org.openide.awt.Mnemonics.setLocalizedText(errorLabel, org.openide.util.NbBundle.getMessage(SelectDriveDialog.class, "SelectDriveDialog.errorLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(bnCancel, org.openide.util.NbBundle.getMessage(SelectDriveDialog.class, "SelectDriveDialog.bnCancel.text")); // NOI18N
bnCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bnCancelActionPerformed(evt);
}
});
jScrollPane2.setBorder(null);
jTextArea1.setBackground(new java.awt.Color(240, 240, 240));
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
jTextArea1.setRows(5);
jTextArea1.setText(org.openide.util.NbBundle.getMessage(SelectDriveDialog.class, "SelectDriveDialog.jTextArea1.text")); // NOI18N
jTextArea1.setBorder(null);
jScrollPane2.setViewportView(jTextArea1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(bnRefresh, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 48, Short.MAX_VALUE)
.addComponent(bnOk, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jSeparator1)
.addComponent(errorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bnRefresh)
.addComponent(bnCancel)
.addComponent(bnOk))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(errorLabel)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void bnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bnRefreshActionPerformed
model.loadDisks();
}//GEN-LAST:event_bnRefreshActionPerformed
private void bnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bnOkActionPerformed
if (diskTable.getSelectedRow() >= 0 && diskTable.getSelectedRow() < disks.size()) {
LocalDisk selectedDisk = disks.get(diskTable.getSelectedRow());
drivePath = selectedDisk.getPath();
} else {
drivePath = "";
}
dispose();
}//GEN-LAST:event_bnOkActionPerformed
private void bnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bnCancelActionPerformed
dispose();
}//GEN-LAST:event_bnCancelActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton bnCancel;
private javax.swing.JButton bnOk;
private javax.swing.JButton bnRefresh;
private javax.swing.JTable diskTable;
private javax.swing.JLabel errorLabel;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration//GEN-END:variables
/**
* Table model for displaying information from LocalDisk Objects in a table.
*/
@NbBundle.Messages({"SelectDriveDialog.localDiskModel.loading.msg=",
"SelectDriveDialog.localDiskModel.nodrives.msg=Executable could not be found",
"SelectDriveDialog.diskTable.column1.title=Disk Name",
"SelectDriveDialog.diskTable.column2.title=Disk Size",
"SelectDriveDialog.errLabel.disksNotDetected.text=Disks were not detected. On some systems it requires admin privileges",
"SelectDriveDialog.errLabel.disksNotDetected.toolTipText=Disks were not detected."
})
private class LocalDiskModel implements TableModel {
private LocalDiskThread worker = null;
private boolean ready = false;
private volatile boolean loadingDisks = false;
//private String SELECT = "Select a local disk:";
private final String LOADING = NbBundle.getMessage(this.getClass(), "SelectDriveDialog.localDiskModel.loading.msg");
private final String NO_DRIVES = NbBundle.getMessage(this.getClass(), "SelectDriveDialog.localDiskModel.nodrives.msg");
private void loadDisks() {
// if there is a worker already building the lists, then cancel it first.
if (loadingDisks && worker != null) {
worker.cancel(false);
}
// Clear the lists
errorLabel.setText("");
diskTable.setEnabled(false);
ready = false;
loadingDisks = true;
worker = new LocalDiskThread();
worker.execute();
}
@Override
public int getRowCount() {
if (disks.isEmpty()) {
return 0;
}
return disks.size();
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case 0:
return NbBundle.getMessage(this.getClass(), "SelectDriveDialog.diskTable.column1.title");
case 1:
return NbBundle.getMessage(this.getClass(), "SelectDriveDialog.diskTable.column2.title");
default:
return "Unnamed"; //NON-NLS
}
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (ready) {
if (disks.isEmpty()) {
return NO_DRIVES;
}
switch (columnIndex) {
case 0:
return disks.get(rowIndex).getName();
case 1:
return disks.get(rowIndex).getReadableSize();
default:
return disks.get(rowIndex).getPath();
}
} else {
return LOADING;
}
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
//setter does nothing they should not be able to modify table
}
@Override
public void addTableModelListener(TableModelListener l) {
}
@Override
public void removeTableModelListener(TableModelListener l) {
}
/**
* Gets the lists of physical drives and partitions and combines them
* into a list of disks.
*/
class LocalDiskThread extends SwingWorker<Object, Void> {
private final Logger logger = Logger.getLogger(LocalDiskThread.class.getName());
private List<LocalDisk> partitions = new ArrayList<>();
@Override
protected Object doInBackground() throws Exception {
// Populate the lists
partitions = new ArrayList<>();
partitions = PlatformUtil.getPartitions();
return null;
}
/**
* Display any error messages that might of occurred when getting
* the lists of physical drives or partitions.
*/
private void displayErrors() {
if (partitions.isEmpty()) {
if (PlatformUtil.isWindowsOS()) {
errorLabel.setText(
NbBundle.getMessage(this.getClass(), "SelectDriveDialog.errLabel.disksNotDetected.text"));
errorLabel.setToolTipText(NbBundle.getMessage(this.getClass(),
"SelectDriveDialog.errLabel.disksNotDetected.toolTipText"));
} else {
errorLabel.setText(
NbBundle.getMessage(this.getClass(), "SelectDriveDialog.errLabel.drivesNotDetected.text"));
errorLabel.setToolTipText(NbBundle.getMessage(this.getClass(),
"SelectDriveDialog.errLabel.drivesNotDetected.toolTipText"));
}
errorLabel.setVisible(true);
diskTable.setEnabled(false);
}
}
@Override
protected void done() {
try {
super.get(); //block and get all exceptions thrown while doInBackground()
} catch (CancellationException ex) {
logger.log(Level.INFO, "Loading local disks was canceled."); //NON-NLS
} catch (InterruptedException ex) {
logger.log(Level.INFO, "Loading local disks was interrupted."); //NON-NLS
} catch (Exception ex) {
logger.log(Level.SEVERE, "Fatal error when loading local disks", ex); //NON-NLS
} finally {
if (!this.isCancelled()) {
displayErrors();
worker = null;
loadingDisks = false;
disks = new ArrayList<>();
disks.addAll(partitions);
if (disks.size() > 0) {
diskTable.setEnabled(true);
diskTable.clearSelection();
}
ready = true;
}
}
diskTable.revalidate();
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.builder.component.dsl;
import javax.annotation.Generated;
import org.apache.camel.Component;
import org.apache.camel.builder.component.AbstractComponentBuilder;
import org.apache.camel.builder.component.ComponentBuilder;
import org.apache.camel.component.ahc.ws.WsComponent;
/**
* Exchange data with external Websocket servers using Async Http Client.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.ComponentDslMojo")
public interface AhcWsComponentBuilderFactory {
/**
* Async HTTP Client (AHC) Websocket (camel-ahc-ws)
* Exchange data with external Websocket servers using Async Http Client.
*
* Category: websocket
* Since: 2.14
* Maven coordinates: org.apache.camel:camel-ahc-ws
*/
static AhcWsComponentBuilder ahcWs() {
return new AhcWsComponentBuilderImpl();
}
/**
* Builder for the Async HTTP Client (AHC) Websocket component.
*/
interface AhcWsComponentBuilder extends ComponentBuilder<WsComponent> {
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*/
default AhcWsComponentBuilder bridgeErrorHandler(
boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*/
default AhcWsComponentBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether to allow java serialization when a request uses
* context-type=application/x-java-serialized-object This is by default
* turned off. If you enable this then be aware that Java will
* deserialize the incoming data from the request to Java and that can
* be a potential security risk.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AhcWsComponentBuilder allowJavaSerializedObject(
boolean allowJavaSerializedObject) {
doSetProperty("allowJavaSerializedObject", allowJavaSerializedObject);
return this;
}
/**
* Whether the component should use basic property binding (Camel 2.x)
* or the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
@Deprecated
default AhcWsComponentBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* To use a custom AhcBinding which allows to control how to bind
* between AHC and Camel.
*
* The option is a:
* <code>org.apache.camel.component.ahc.AhcBinding</code> type.
*
* Group: advanced
*/
default AhcWsComponentBuilder binding(
org.apache.camel.component.ahc.AhcBinding binding) {
doSetProperty("binding", binding);
return this;
}
/**
* To use a custom AsyncHttpClient.
*
* The option is a: <code>org.asynchttpclient.AsyncHttpClient</code>
* type.
*
* Group: advanced
*/
default AhcWsComponentBuilder client(
org.asynchttpclient.AsyncHttpClient client) {
doSetProperty("client", client);
return this;
}
/**
* To configure the AsyncHttpClient to use a custom
* com.ning.http.client.AsyncHttpClientConfig instance.
*
* The option is a:
* <code>org.asynchttpclient.AsyncHttpClientConfig</code> type.
*
* Group: advanced
*/
default AhcWsComponentBuilder clientConfig(
org.asynchttpclient.AsyncHttpClientConfig clientConfig) {
doSetProperty("clientConfig", clientConfig);
return this;
}
/**
* To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter
* header to and from Camel message.
*
* The option is a:
* <code>org.apache.camel.spi.HeaderFilterStrategy</code> type.
*
* Group: filter
*/
default AhcWsComponentBuilder headerFilterStrategy(
org.apache.camel.spi.HeaderFilterStrategy headerFilterStrategy) {
doSetProperty("headerFilterStrategy", headerFilterStrategy);
return this;
}
/**
* Reference to a org.apache.camel.support.jsse.SSLContextParameters in
* the Registry. Note that configuring this option will override any
* SSL/TLS configuration options provided through the clientConfig
* option at the endpoint or component level.
*
* The option is a:
* <code>org.apache.camel.support.jsse.SSLContextParameters</code> type.
*
* Group: security
*/
default AhcWsComponentBuilder sslContextParameters(
org.apache.camel.support.jsse.SSLContextParameters sslContextParameters) {
doSetProperty("sslContextParameters", sslContextParameters);
return this;
}
/**
* Enable usage of global SSL context parameters.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: security
*/
default AhcWsComponentBuilder useGlobalSslContextParameters(
boolean useGlobalSslContextParameters) {
doSetProperty("useGlobalSslContextParameters", useGlobalSslContextParameters);
return this;
}
}
class AhcWsComponentBuilderImpl
extends
AbstractComponentBuilder<WsComponent>
implements
AhcWsComponentBuilder {
@Override
protected WsComponent buildConcreteComponent() {
return new WsComponent();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "bridgeErrorHandler": ((WsComponent) component).setBridgeErrorHandler((boolean) value); return true;
case "lazyStartProducer": ((WsComponent) component).setLazyStartProducer((boolean) value); return true;
case "allowJavaSerializedObject": ((WsComponent) component).setAllowJavaSerializedObject((boolean) value); return true;
case "basicPropertyBinding": ((WsComponent) component).setBasicPropertyBinding((boolean) value); return true;
case "binding": ((WsComponent) component).setBinding((org.apache.camel.component.ahc.AhcBinding) value); return true;
case "client": ((WsComponent) component).setClient((org.asynchttpclient.AsyncHttpClient) value); return true;
case "clientConfig": ((WsComponent) component).setClientConfig((org.asynchttpclient.AsyncHttpClientConfig) value); return true;
case "headerFilterStrategy": ((WsComponent) component).setHeaderFilterStrategy((org.apache.camel.spi.HeaderFilterStrategy) value); return true;
case "sslContextParameters": ((WsComponent) component).setSslContextParameters((org.apache.camel.support.jsse.SSLContextParameters) value); return true;
case "useGlobalSslContextParameters": ((WsComponent) component).setUseGlobalSslContextParameters((boolean) value); return true;
default: return false;
}
}
}
}
| |
/*
* Copyright 2016-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.go;
import com.facebook.buck.io.BuildCellRelativePath;
import com.facebook.buck.io.MorePaths;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.rules.AbstractBuildRuleWithDeclaredAndExtraDeps;
import com.facebook.buck.rules.AddToRuleKey;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildableContext;
import com.facebook.buck.rules.ExplicitBuildTargetSourcePath;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SymlinkTree;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.facebook.buck.step.fs.MkdirStep;
import com.facebook.buck.step.fs.SymlinkFileStep;
import com.facebook.buck.step.fs.TouchStep;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.nio.file.Path;
import java.util.Optional;
public class GoCompile extends AbstractBuildRuleWithDeclaredAndExtraDeps {
@AddToRuleKey private final Tool compiler;
@AddToRuleKey private final Tool assembler;
@AddToRuleKey private final Tool packer;
@AddToRuleKey(stringify = true)
private final Path packageName;
@AddToRuleKey private final ImmutableSet<SourcePath> srcs;
@AddToRuleKey private final ImmutableList<String> compilerFlags;
@AddToRuleKey private final ImmutableList<String> assemblerFlags;
@AddToRuleKey private final GoPlatform platform;
// TODO(mikekap): Make these part of the rule key.
private final ImmutableList<Path> assemblerIncludeDirs;
private final ImmutableMap<Path, Path> importPathMap;
private final SymlinkTree symlinkTree;
private final Path output;
public GoCompile(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleParams params,
SymlinkTree symlinkTree,
Path packageName,
ImmutableMap<Path, Path> importPathMap,
ImmutableSet<SourcePath> srcs,
ImmutableList<String> compilerFlags,
Tool compiler,
ImmutableList<String> assemblerFlags,
ImmutableList<Path> assemblerIncludeDirs,
Tool assembler,
Tool packer,
GoPlatform platform) {
super(buildTarget, projectFilesystem, params);
this.importPathMap = importPathMap;
this.srcs = srcs;
this.symlinkTree = symlinkTree;
this.packageName = packageName;
this.compilerFlags = compilerFlags;
this.compiler = compiler;
this.assemblerFlags = assemblerFlags;
this.assemblerIncludeDirs = assemblerIncludeDirs;
this.assembler = assembler;
this.packer = packer;
this.platform = platform;
this.output =
BuildTargets.getGenPath(
getProjectFilesystem(),
getBuildTarget(),
"%s/" + getBuildTarget().getShortName() + ".a");
}
@Override
public ImmutableList<Step> getBuildSteps(
BuildContext context, BuildableContext buildableContext) {
buildableContext.recordArtifact(output);
ImmutableList.Builder<Path> compileSrcListBuilder = ImmutableList.builder();
ImmutableList.Builder<Path> headerSrcListBuilder = ImmutableList.builder();
ImmutableList.Builder<Path> asmSrcListBuilder = ImmutableList.builder();
for (SourcePath path : srcs) {
Path srcPath = context.getSourcePathResolver().getAbsolutePath(path);
String extension = MorePaths.getFileExtension(srcPath).toLowerCase();
if (extension.equals("s")) {
asmSrcListBuilder.add(srcPath);
} else if (extension.equals("go")) {
compileSrcListBuilder.add(srcPath);
} else {
headerSrcListBuilder.add(srcPath);
}
}
ImmutableList<Path> compileSrcs = compileSrcListBuilder.build();
ImmutableList<Path> headerSrcs = headerSrcListBuilder.build();
ImmutableList<Path> asmSrcs = asmSrcListBuilder.build();
ImmutableList.Builder<Step> steps = ImmutableList.builder();
steps.add(
MkdirStep.of(
BuildCellRelativePath.fromCellRelativePath(
context.getBuildCellRootPath(), getProjectFilesystem(), output.getParent())));
Optional<Path> asmHeaderPath;
if (!asmSrcs.isEmpty()) {
asmHeaderPath =
Optional.of(
BuildTargets.getScratchPath(
getProjectFilesystem(),
getBuildTarget(),
"%s/" + getBuildTarget().getShortName() + "__asm_hdr")
.resolve("go_asm.h"));
steps.add(
MkdirStep.of(
BuildCellRelativePath.fromCellRelativePath(
context.getBuildCellRootPath(),
getProjectFilesystem(),
asmHeaderPath.get().getParent())));
} else {
asmHeaderPath = Optional.empty();
}
boolean allowExternalReferences = !asmSrcs.isEmpty();
if (compileSrcs.isEmpty()) {
steps.add(new TouchStep(getProjectFilesystem(), output));
} else {
steps.add(
new GoCompileStep(
getProjectFilesystem().getRootPath(),
compiler.getEnvironment(context.getSourcePathResolver()),
compiler.getCommandPrefix(context.getSourcePathResolver()),
compilerFlags,
packageName,
compileSrcs,
importPathMap,
ImmutableList.of(symlinkTree.getRoot()),
asmHeaderPath,
allowExternalReferences,
platform,
output));
}
if (!asmSrcs.isEmpty()) {
Path asmIncludeDir =
BuildTargets.getScratchPath(
getProjectFilesystem(),
getBuildTarget(),
"%s/" + getBuildTarget().getShortName() + "__asm_includes");
steps.addAll(
MakeCleanDirectoryStep.of(
BuildCellRelativePath.fromCellRelativePath(
context.getBuildCellRootPath(), getProjectFilesystem(), asmIncludeDir)));
if (!headerSrcs.isEmpty()) {
// TODO(mikekap): Allow header-map style input.
for (Path header : FluentIterable.from(headerSrcs).append(asmSrcs)) {
steps.add(
SymlinkFileStep.builder()
.setFilesystem(getProjectFilesystem())
.setExistingFile(header)
.setDesiredLink(asmIncludeDir.resolve(header.getFileName()))
.build());
}
}
Path asmOutputDir =
BuildTargets.getScratchPath(
getProjectFilesystem(),
getBuildTarget(),
"%s/" + getBuildTarget().getShortName() + "__asm_compile");
steps.addAll(
MakeCleanDirectoryStep.of(
BuildCellRelativePath.fromCellRelativePath(
context.getBuildCellRootPath(), getProjectFilesystem(), asmOutputDir)));
ImmutableList.Builder<Path> asmOutputs = ImmutableList.builder();
for (Path asmSrc : asmSrcs) {
Path outputPath =
asmOutputDir.resolve(asmSrc.getFileName().toString().replaceAll("\\.[sS]$", ".o"));
steps.add(
new GoAssembleStep(
getProjectFilesystem().getRootPath(),
assembler.getEnvironment(context.getSourcePathResolver()),
assembler.getCommandPrefix(context.getSourcePathResolver()),
assemblerFlags,
asmSrc,
ImmutableList.<Path>builder()
.addAll(assemblerIncludeDirs)
.add(asmHeaderPath.get().getParent())
.add(asmIncludeDir)
.build(),
platform,
outputPath));
asmOutputs.add(outputPath);
}
steps.add(
new GoPackStep(
getProjectFilesystem().getRootPath(),
packer.getEnvironment(context.getSourcePathResolver()),
packer.getCommandPrefix(context.getSourcePathResolver()),
GoPackStep.Operation.APPEND,
asmOutputs.build(),
output));
}
return steps.build();
}
@Override
public SourcePath getSourcePathToOutput() {
return new ExplicitBuildTargetSourcePath(getBuildTarget(), output);
}
}
| |
package shijimi.gui.rule;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Future;
import java.util.stream.IntStream;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultRowSorter;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.RowSorterEvent;
import javax.swing.event.RowSorterListener;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import shijimi.app.GuiEnvironment;
import shijimi.app.GuiRuleSet;
import shijimi.app.GuiUpdateManager;
import shijimi.app.GuiUpdateParameterTarget;
import shijimi.app.GuiUpdateTarget;
import shijimi.app.RuleInfoBinding;
import shijimi.app.GuiUpdateManager.UpdateSession;
import shijimi.base.ReflectionShell;
import shijimi.gui.app.GuiComponentPreferences;
import shijimi.gui.rule.ObjectPaneRule.LazyActionTargetNetEntry;
import shijimi.gui.rule.table.GuiTableColumnRule;
import shijimi.gui.rule.table.TableColumnSource;
import shijimi.gui.rule.table.TableColumnSourceImpl;
import shijimi.gui.rule.table.TableSelection;
import shijimi.gui.swing.PopupMenuHidingListener;
import shijimi.gui.swing.WheelAccelrateScroller;
import shijimi.info.CollectionTypeInfo;
import shijimi.info.ObjectTypeInfo;
import shijimi.info.PropertyInfo;
import shijimi.info.TypeInfo;
/**
* <pre>
* List<P> prop;
* public Collection<P> getProp() {
* if (prop == null) {
* prop = new ArrayList<P>();
* prop.add(...);
* ...
* }
* return prop;
* }
* </pre>
*
*
* <pre>
* //modifying the list
* List<P> prop = new MyList<P>();
* public Collection<P> getProp() {
* return prop;
* }
* public void myUpdateAction() {
* List<P> ps = new MyList<P>();
* prop.addAll(ps);
* prop.add(...);
* prop = ps;
* }
* static class MyList<E> extends ArraryList<E> {
* public boolean equals(Object o) {
* return o == this;
* }
* public int hashCode() {
* return System.identityHashCode(o);
* }
* }
* </pre>
*
*
* <pre>
* List<P> prop = UtilShell.v().arrayListForIdenticalEquality();
* public Collection<P> getProp() {
* return prop;
* }
* </pre>
*
*/
public class CollectionTableRule implements GuiComponentRule {
public static Object NULL = new Object();
/** set of GuiTableColumnRule */
protected GuiRuleSet subRules;
public CollectionTableRule(GuiRuleSet subRules) {
this.subRules = subRules;
}
public void setSubRules(GuiRuleSet subRules) {
this.subRules = subRules;
}
public GuiRuleSet getSubRules() {
return subRules;
}
@Override
public boolean match(RuleInfoBinding context, ReflectionShell refSh) {
if (context.getInfo() instanceof CollectionTypeInfo) {
CollectionTypeInfo typeInfo = (CollectionTypeInfo) context.getInfo();
TypeInfo elemInfo = typeInfo.getElementType();
if (elemInfo instanceof ObjectTypeInfo) {
return matchObjectType(context, refSh);
} else if (!(elemInfo instanceof CollectionTypeInfo)) {
return matchCollectionType(context, refSh);
}
}
return false;
}
private boolean matchObjectType(RuleInfoBinding context, ReflectionShell refSh) {
context.setRule(this);
for (RuleInfoBinding b : context.getChildCandidates()) {
//unique list element
b.addToParent();
for (RuleInfoBinding prop : b.getChildCandidates()) {
if (subRules != null && subRules.match(prop, refSh)) {
prop.addToParent();
}
}
}
return true;
}
private boolean matchCollectionType(RuleInfoBinding context, ReflectionShell refSh) {
context.setRule(this);
for (RuleInfoBinding b : context.getChildCandidates()) {
if (subRules != null && subRules.match(b, refSh)) {
b.addToParent();
}
}
return true;
}
@SuppressWarnings("unchecked")
@Override
public JComponent create(RuleInfoBinding context, Object o, GuiEnvironment env) {
return new Create().create(context, o, env);
}
public static class Create {
protected RuleInfoBinding context;
protected Object o;
protected GuiEnvironment env;
protected TableSelectionTarget actionTarget;
protected Action selectAction = null;
protected ObjectTableModel tableModel;
protected JToolBar bar;
protected JTable table;
protected JScrollPane scrollPane;
protected JComponent component;
public JComponent create(RuleInfoBinding context, Object o, GuiEnvironment env) {
this.context = context;
this.o = o;
this.env = env;
createTableModel();
createColumns();
createTable();
return component;
}
@SuppressWarnings("unchecked")
public void createTableModel() {
tableModel = new ObjectTableModel((Collection<Object>) o, env, context.getPath());
tableModel.addColumn(new TableColumnSourceImpl.IndexTableColumnSource(tableModel.getColumnCount()));
bar = ObjectPaneRule.createToolBar();
actionTarget = new TableSelectionTarget();
selectAction = null;
}
/** requires { tableModel, bar, actionTarget } */
public void createColumns() {
env.getUpdateManager().begin();
for (RuleInfoBinding b : context.getChildren()) {
if (b.getRule() != null && b.getRule() instanceof GuiTableColumnRule) {
createColumn(b);
} else {
for (RuleInfoBinding prop : b.getChildren()) {
if (prop.getRule() != null
&& prop.getRule() instanceof GuiTableColumnRule
&& prop.getInfo() instanceof PropertyInfo) {
createColumn(prop);
} else if (prop.getRule() != null && prop.getRule() instanceof GuiActionRule) {
createAction(prop);
}
}
}
}
//setting up frequent updating columns
env.getUpdateManager().addTarget(new ColumnFrequentRefreshTarget(tableModel));
env.getUpdateManager().end();
tableModel.emitGUI(env.getNewUpdateSession(context.getPath()));
}
public void createColumn(RuleInfoBinding prop) {
TableColumnSource col = ((GuiTableColumnRule) prop.getRule()).createColumn(tableModel.getColumnCount(), prop, env);
if (col != null) {
tableModel.addColumn(col);
}
}
/** requires { bar, actionTarget } */
public void createAction(RuleInfoBinding prop) {
Action act = ((GuiActionRule) prop.getRule()).createAction(prop, actionTarget, env);
ObjectPaneRule.addActionToToolBar(bar, act);
if (prop.getInfo().getName().equals("select")) { //special rule
selectAction = act;
}
}
public void createTable() {
setupTable();
setupScrollPane();
setupRowSorter();
setupTableAndContainerLookAndFeel();
setupTableRowHeight();
setupActionTarget();
registerToParentUpdatingPane();
createComponent();
}
/** requires { tableModel, selectAction } */
private void setupTable() {
table = new UpdatingTable(tableModel, tableModel.getColumnModel());
table.setAutoCreateRowSorter(true);
TablePopup popup = new TablePopup(table, tableModel);
{
table.addMouseListener(popup);
table.getTableHeader().addMouseListener(popup);
}
if (selectAction != null) {
table.getSelectionModel().addListSelectionListener(new TableSelectionActionInvoker(table, selectAction));
}
tableModel.setTable(table);
}
/** requires {tableModel, table} */
private void setupScrollPane() {
scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
private static final long serialVersionUID = 1L;
public String toString() {
return "JScrollPane(" + getViewport().getView() + ")";
}
};
new WheelAccelrateScroller().installToPanelAndSetup(scrollPane, table);
setPreferredSizeFromColumn(scrollPane);
}
/** requires {tableModel} */
private void setPreferredSizeFromColumn(JComponent pane) {
int w = 0;
for (TableColumnSource col : tableModel.getColumns()) {
w += col.getTableColumn().getWidth();
}
pane.setPreferredSize(new Dimension(w, 100));
}
/** requires {tableModel} */
public void setupRowSorter() {
List<String> path = context.getPath();
DefaultTableColumnModel model = tableModel.getColumnModel();
ColumnUpdater colUpdater = new ColumnUpdater(table, model, env, path);
TableRowSorter<? extends TableModel> sorter = (TableRowSorter<? extends TableModel>) table.getRowSorter();
if (sorter instanceof DefaultRowSorter) {
sorter.setSortsOnUpdates(true);
}
for (int i = 0, len = tableModel.getColumnCount(); i < len; ++i) {
Comparator<?> comp = tableModel.getColumns().get(i).getComparator();
if (comp != null) {
sorter.setComparator(i, comp);
}
}
colUpdater.setupRowSorter();
model.addColumnModelListener(colUpdater);
sorter.addRowSorterListener(colUpdater);
}
/** requires {scrollPane, table} */
private void setupTableAndContainerLookAndFeel() {
Color backColor = new Color(238, 238, 238);
scrollPane.getViewport().setBackground(backColor);
scrollPane.setBackground(backColor);
table.setBackground(backColor);
table.getColumnModel().setColumnMargin(0);
table.setRowMargin(0);
table.setGridColor(backColor);
}
/** requires {table, tableModel} and columns */
private void setupTableRowHeight() {
int h = table.getRowHeight();
h += 3;
for (TableColumnSource col : tableModel.getColumns()) {
int ch = col.getRowHeight();
if (ch > h) {
h = ch;
}
}
table.setRowHeight(h);
}
/** requires {actionTarget, table, tableModel} */
private void setupActionTarget() {
actionTarget.setTable(table);
actionTarget.setModel(tableModel);
ObjectPaneRule.LazyActionTargetNetEntry net = ObjectPaneRule.getFishingNet().getEntry(LazyActionTargetNetEntry.class);
net.addParameter((CollectionTypeInfo) context.getInfo(), actionTarget);
}
/** requires {table} */
private void registerToParentUpdatingPane() {
if (context.getParent() != null) {
String name = context.getParent().getInfo().getName();
CollectionTableSelectionRule.CollectionSelectionNetEntry e = ObjectPaneRule.getFishingNet().getEntry(CollectionTableSelectionRule.CollectionSelectionNetEntry.class);
e.addTable(name, table);
}
}
/** requires {scrollPane, bar, table } */
private void createComponent() {
component = ObjectPaneRule.addToolBar(scrollPane, bar);
env.registerComponentMap(table, o); //Collection -> JTable
}
}
@Override
public boolean isComponentResizeable() {
return true;
}
public static class UpdatingTable extends JTable implements GuiUpdateParameterTarget {
private static final long serialVersionUID = 1L;
protected Object object;
public UpdatingTable(TableModel model, TableColumnModel colModel) {
super(model, colModel, null);
}
@Override
public void emitGUIOwner(UpdateSession session, Object object) {
TableModel model = getModel();
this.object = object;
if (model instanceof GuiUpdateParameterTarget) {
((GuiUpdateParameterTarget) model).emitGUIOwner(session, object);
}
}
@Override
public Object getGUIOwner() {
return object;
}
@Override
public Object getGUIValue() {
return object;
}
@Override
public String toString() {
return "UpdatingTable()";
}
}
public static class ColumnUpdater implements TableColumnModelListener, RowSorterListener {
protected JTable table;
protected DefaultTableColumnModel columnModel;
protected GuiEnvironment env;
protected List<String> path;
protected GuiComponentPreferences.TablePreferences prefs;
public ColumnUpdater(JTable table, DefaultTableColumnModel columnModel, GuiEnvironment env, List<String> path) {
this.table = table;
this.columnModel = columnModel;
this.env = env;
this.path = path;
setupFromEnv();
}
public void setupFromEnv() {
prefs = env.getPreferences().getComponent(path).getLayoutForClass(GuiComponentPreferences.TablePreferences.class);
prefs.applyTo(table);
}
public void setupRowSorter() {
prefs.applyRowSortTo(table);
}
@Override
public void columnMoved(TableColumnModelEvent e) {
prefs.setColumnOrderFrom(table);
}
@Override
public void columnMarginChanged(ChangeEvent e) {
prefs.setColumnWidthFrom(table);
}
@Override
public void columnSelectionChanged(ListSelectionEvent e) {}
@Override
public void columnRemoved(TableColumnModelEvent e) {}
@Override
public void columnAdded(TableColumnModelEvent e) {}
@Override
public void sorterChanged(RowSorterEvent e) {
prefs.setRowSortFrom(table);
}
}
public static class ObjectTableModel extends AbstractTableModel implements GuiUpdateTarget, GuiUpdateParameterTarget {
private static final long serialVersionUID = 1L;
protected Collection<Object> sourceCollection;
protected List<Object> source;
protected Object[][] propertyTable;
protected List<TableColumnSource> columns = new ArrayList<TableColumnSource>();
protected GuiEnvironment env;
protected List<String> path;
protected DefaultTableColumnModel columnModel;
protected JTable table;
public ObjectTableModel(Collection<Object> source, GuiEnvironment env, List<String> path) {
this.sourceCollection = source;
this.env = env;
this.path = path;
columnModel = new DefaultTableColumnModel();
setSourceFromSourceCollection();
}
public GuiEnvironment getEnv() {
return env;
}
public List<String> getPath() {
return path;
}
public void setSourceFromSourceCollection() {
if (sourceCollection == null) {
this.source = new ArrayList<Object>(0);
} else if (sourceCollection instanceof List<?>) {
this.source = (List<Object>) sourceCollection;
} else {
this.source = new ArrayList<Object>(sourceCollection);
}
}
public void setTable(JTable table) {
this.table = table;
}
public JTable getTable() {
return table;
}
public DefaultTableColumnModel getColumnModel() {
return columnModel;
}
public void addColumn(TableColumnSource column) {
columns.add(column);
columnModel.addColumn(column.getTableColumn());
}
public List<TableColumnSource> getColumns() {
return columns;
}
@Override
public String getColumnName(int column) {
return columns.get(column).getName();
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return columns.get(columnIndex).getValueType();
}
@SuppressWarnings("unchecked")
@Override
public void emitGUIOwner(UpdateSession session, Object object) {
if (env.isRefreshSession(session) || sourceCollection != object) {
env.updateComponentMap(sourceCollection, object);
sourceCollection = (Collection<Object>) object;
setSourceFromSourceCollection();
emitGUI(session);
}
}
@Override
public Object getGUIOwner() {
return sourceCollection;
}
@Override
public Object getGUIValue() {
return sourceCollection;
}
@Override
public void emitGUI(UpdateSession session) {
propertyTable = null;
int rows = source.size();
int cols = columns.size();
propertyTable = new Object[rows][cols];
//if (session instanceof GuiUpdateManager.PathRedisplaySession) { //commented out for avoiding frequent selection events.
if (table != null) {
table.getSelectionModel().clearSelection();
}
fireTableDataChanged();
}
@Override
public void fireTableDataChanged() {
int[] sels = null;
Rectangle vrect = null;
if (table != null) {
sels = table.getSelectedRows();
vrect = table.getVisibleRect();
for (int i = 0, l = sels.length; i < l; ++i) { //model indices
sels[i] = table.convertRowIndexToModel(sels[i]);
}
}
super.fireTableDataChanged();
if (table != null && sels != null) {
final int[] newsels = sels;
final JTable uptable = table;
final int rows = source.size();
final Rectangle newrect = vrect;
SwingUtilities.invokeLater(new Runnable() {public void run() {
for (int i : newsels) {
if (i < rows) {
i = table.convertRowIndexToView(i);
uptable.getSelectionModel().addSelectionInterval(i, i); //view indices
}
}
table.scrollRectToVisible(newrect);
}});
}
}
@Override
public int getColumnCount() {
return columns.size();
}
@Override
public int getRowCount() {
return propertyTable.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
try {
Object[] data = propertyTable[rowIndex];
Object value = data[columnIndex];
if (value == null) {
value = setColumnValue(data, rowIndex, columnIndex);
}
if (value.equals(NULL)) {
return null;
} else {
return value;
}
} catch (Exception ex) {
env.handleException(ex);
return null;
}
}
/**
* @return never null. If value is null, returns NULL
*/
public Object setColumnValue(Object[] data, int rowIndex, int columnIndex) {
Object o = source.get(rowIndex);
TableColumnSource column = columns.get(columnIndex);
Object value = column.getValue(o, rowIndex, columnIndex);
if (value != null && value instanceof Future<?>) {
Future<?> future = (Future<?>) value;
value = NULL;
data[columnIndex] = value;
setColumnValueAtFuture(future, data, new int[] {rowIndex, columnIndex});
} else {
if (value == null) {
value = NULL;
}
data[columnIndex] = value;
}
return value;
}
public void setColumnValueAtFuture(final Future<?> future, final Object[] data, final int[] rowAndColumnIndex) {
//Implementation note: If the future is a task under env.taskRunner,
// this runnable task may be blocked until the future's end and after the end, it immediately run the task.
// Otherwise, the task runs and awaits the future, and it will show progress bar after 1 sec.
env.submitAndWait(new Runnable() {public void run() {
try {
Object value = future.get();
if (value == null) {
value = NULL;
}
final Object cellValue = value;
SwingUtilities.invokeLater(new Runnable() {public void run() {
int rowIndex = rowAndColumnIndex[0];
int columnIndex = rowAndColumnIndex[1];
//Object[] data = propertyTable[rowIndex];
data[columnIndex] = cellValue;
fireTableCellUpdated(rowIndex, columnIndex);
//sortUpdate.cellSet();
}});
} catch (Exception ex) {
env.handleException(ex);
}
}}, 1000);
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
try {
Object[] data = propertyTable[rowIndex];
//clear values at same row for updating
for (int i = 0, len = data.length; i < len; ++i) {
data[i] = null;
}
data[columnIndex] = (aValue == null ? NULL : aValue);
Object o = source.get(rowIndex);
env.submitAndWait(getSetValueAtTask(o, aValue, new int[] {rowIndex, columnIndex}), 2000);
} catch (Exception ex) {
env.handleException(ex);
}
}
public Runnable getSetValueAtTask(final Object o, final Object aValue, final int[] rowAndColIndex) {
return new Runnable() {public void run() {
final int rowIndex = rowAndColIndex[0];
int columnIndex = rowAndColIndex[1];
columns.get(columnIndex).setValue(o, aValue, rowIndex, columnIndex);
SwingUtilities.invokeLater(new Runnable() {public void run() {
refreshRow(rowIndex);
env.getUpdateManager().emitGUI(env.getNewUpdateSession(path));
}});
}};
}
/**
* (in event)
*/
public void refreshRow(int rowIndex) {
Object[] data = propertyTable[rowIndex];
//clear values at same row for updating
for (int i = 0, len = data.length; i < len; ++i) {
data[i] = null;
}
fireTableRowsUpdated(rowIndex, rowIndex);
env.getUpdateManager().emitGUI(env.getNewUpdateSession(path));
}
/**
* (in event)
* rows are model indices.
*/
public void refreshRows(int[] rows) {
int min = -1;
int max = -1;
for (int rowIndex : rows) {
if (min == -1 || rowIndex < min) {
min = rowIndex;
}
if (max == -1 || rowIndex > max) {
max = rowIndex;
}
Object[] data = propertyTable[rowIndex];
for (int i = 0, len = data.length; i < len; ++i) {
data[i] = null;
}
}
fireTableRowsUpdated(min, max);
env.getUpdateManager().emitGUI(env.getNewUpdateSession(path));
}
/**
* updating existing rows without re-selecting
*/
public void fireTableAllRowsUpdated() {
final int rs = getRowCount();
if (rs > 0) {
SwingUtilities.invokeLater(new Runnable() {public void run() {
int n = rs;
int rs2 = getRowCount();
if (rs2 < n) {
n = rs2;
}
if (n > 0) {
fireTableRowsUpdated(0, n - 1);
}
}});
}
}
/**
* (in event)
* It only clears the columns and does not call emitGUI to the update manager.
*/
public void refreshColumns(Collection<Integer> cols) {
for (Object[] data : propertyTable) {
for (int col : cols) {
data[col] = null;
}
}
fireTableAllRowsUpdated();
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
TableColumn col = columns.get(columnIndex).getTableColumn();
return col.getCellEditor() != null;
}
public List<Object> getSource() {
return source;
}
public Object getSourceAtRow(int row) {
return source.get(row);
}
}
public static class ColumnFrequentRefreshTarget implements GuiUpdateTarget {
protected ObjectTableModel tableModel;
public ColumnFrequentRefreshTarget(ObjectTableModel tableModel) {
this.tableModel = tableModel;
}
@Override
public void emitGUI(UpdateSession session) {
if (session instanceof GuiUpdateManager.PathRedisplaySession) {
return;
}
List<Integer> cols = new ArrayList<Integer>(tableModel.getColumnCount());
int i = 0;
for (TableColumnSource src : tableModel.getColumns()) {
if (src.isFrequentUpdating()) {
cols.add(i);
}
++i;
}
tableModel.refreshColumns(cols);
}
}
public static class TableSelectionTarget implements GuiActionRule.LazyActionTarget {
protected JTable table;
protected ObjectTableModel model;
public TableSelectionTarget() {
}
public TableSelectionTarget(JTable table, ObjectTableModel model) {
this.table = table;
this.model = model;
}
public void setTable(JTable table) {
this.table = table;
}
public void setModel(ObjectTableModel model) {
this.model = model;
}
@Override
public List<Object> getTargets() {
List<Object> src = model.getSource();
int size = src.size();
int rowSize = table.getRowCount();
int[] selRows = table.getSelectedRows();
List<Object> result = new ArrayList<Object>(selRows.length);
for (int i : selRows) {
if (i >= 0 && i < rowSize) {
int si = table.convertRowIndexToModel(i);
if (si >= 0 && si < size) {
result.add(src.get(si));
}
}
}
return result;
}
/**
* (in event)
*/
public void refresh() {
// consider frequent updating columns.
int[] rs = table.getSelectedRows();
if (rs != null) {
for (int i = 0, l = rs.length; i < l; ++i) {
rs[i] = table.convertRowIndexToModel(rs[i]);
}
}
model.refreshRows(rs);
//update all rows without re-selecting
model.fireTableAllRowsUpdated();
}
@Override
public String toString() {
return "TableSelectionTarget(" + table + "," + model + ")";
}
}
public static class NumberRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
public NumberRenderer() {
setHorizontalAlignment(JLabel.RIGHT);
}
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
row, column);
setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
return this;
}
}
public static class ComparableComparator implements Comparator<Object> {
@SuppressWarnings("unchecked")
@Override
public int compare(Object o1, Object o2) {
return ((Comparable<Object>) o1).compareTo((Comparable<Object>) o2);
}
}
public static class TablePopup implements MouseListener {
protected JPopupMenu menu;
protected JTable table;
protected ObjectTableModel model;
public TablePopup(JTable table, ObjectTableModel model) {
this.table = table;
this.model = model;
menu = new JPopupMenu();
new PopupMenuHidingListener(menu);
}
public void popup(MouseEvent e) {
if (e.isPopupTrigger()) {
try {
int col = table.columnAtPoint(e.getPoint());
int row = table.rowAtPoint(e.getPoint());
int mcol = col < 0 ? -1 : table.convertColumnIndexToModel(col);
int mrow = row < 0 ? -1 : table.convertRowIndexToModel(row);
menu.removeAll();
if (mcol >= 0 && mcol < model.getColumnCount()) {
//popup for selected rows
int[] rows = table.getSelectedRows();
for (int i = 0, l = rows.length; i < l; ++i) {
rows[i] = table.convertRowIndexToModel(rows[i]);
}
if (rows.length == 0 && mrow >= 0 && mrow < model.getRowCount()) {
rows = new int[] {mrow};
}
TableColumnSource.PopupSource src = model.getColumns().get(mcol).getPopupSource();
if (src != null) {
if (mrow >= 0 && mrow < model.getRowCount()) {
//popup for a cell
if (GuiEnvironment.DEBUG) {
System.err.println("menu " + mrow + ": " + model.getSourceAtRow(mrow) + " : " + model.getValueAt(mrow, mcol));
}
src.setupMenu(menu, model, model.getSourceAtRow(mrow), model.getValueAt(mrow, mcol), mrow, mcol);
} else {
src.setupMenu(menu, model, rows, mcol);
}
}
List<List<Action>> acts = TableSelection.getActions(model.getColumns(), rows, new int[] {mcol}, model.getSource(), TableSelection.defaultPresetList);
int count = menu.getComponentCount();
for (List<Action> as : acts) {
if (count > 0) {
menu.addSeparator();
}
count = 0;
for (Action a : as) {
menu.add(a);
++count;
}
}
}
if (menu.getComponentCount() > 0) {
menu.show(table, e.getX(), e.getY());
if (row >= 0 && !isSelected(row)) {
table.getSelectionModel().setSelectionInterval(row, row);
}
}
} catch (Exception ex) {
model.getEnv().handleException(ex);
}
}
}
public boolean isSelected(int row) {
for (int sr : table.getSelectedRows()) {
if (sr == row) {
return true;
}
}
return false;
}
@Override
public void mousePressed(MouseEvent e) {
popup(e);
}
@Override
public void mouseReleased(MouseEvent e) {
popup(e);
}
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
}
public static String SELECT_COMMAND = "select";
public static class TableSelectionActionInvoker implements ListSelectionListener, GuiActionRule.ViewUpdatingActionSource {
protected int previous = -1;
protected JTable table;
protected Action action;
public TableSelectionActionInvoker(JTable table, Action action) {
this.table = table;
this.action = action;
}
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
int[] rs = table.getSelectedRows();
if (rs == null || rs.length == 0 || rs.length > 1) {
previous = -1;
} else if (rs.length == 1) {
if (previous != rs[0]) {
action.actionPerformed(new ActionEvent(this, 0, SELECT_COMMAND, System.currentTimeMillis(), 0));
previous = rs[0];
}
}
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hawtjms.provider.stomp.message;
import static io.hawtjms.provider.stomp.StompConstants.CONTENT_LENGTH;
import static io.hawtjms.provider.stomp.StompConstants.CORRELATION_ID;
import static io.hawtjms.provider.stomp.StompConstants.DESTINATION;
import static io.hawtjms.provider.stomp.StompConstants.EXPIRATION_TIME;
import static io.hawtjms.provider.stomp.StompConstants.FALSE;
import static io.hawtjms.provider.stomp.StompConstants.JMSX_DELIVERY_COUNT;
import static io.hawtjms.provider.stomp.StompConstants.JMSX_GROUP_ID;
import static io.hawtjms.provider.stomp.StompConstants.JMSX_GROUP_SEQUENCE;
import static io.hawtjms.provider.stomp.StompConstants.MESSAGE_ID;
import static io.hawtjms.provider.stomp.StompConstants.PERSISTENT;
import static io.hawtjms.provider.stomp.StompConstants.PRIORITY;
import static io.hawtjms.provider.stomp.StompConstants.RECEIPT_REQUESTED;
import static io.hawtjms.provider.stomp.StompConstants.REDELIVERED;
import static io.hawtjms.provider.stomp.StompConstants.REPLY_TO;
import static io.hawtjms.provider.stomp.StompConstants.SUBSCRIPTION;
import static io.hawtjms.provider.stomp.StompConstants.TIMESTAMP;
import static io.hawtjms.provider.stomp.StompConstants.TRANSFORMATION;
import static io.hawtjms.provider.stomp.StompConstants.TRUE;
import static io.hawtjms.provider.stomp.StompConstants.TYPE;
import static io.hawtjms.provider.stomp.StompConstants.USERID;
import io.hawtjms.jms.JmsDestination;
import io.hawtjms.jms.message.JmsMessageFacade;
import io.hawtjms.jms.meta.JmsMessageId;
import io.hawtjms.provider.stomp.StompConnection;
import io.hawtjms.provider.stomp.StompFrame;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import javax.jms.JMSException;
/**
* A STOMP based JmsMessageFacade that wraps a given STOMP frame containing a
* MESSAGE command. The facade will map the standard JMS properties onto the
* appropriate STOMP properties and
*/
public class StompJmsMessageFacade implements JmsMessageFacade {
static HashSet<String> RESERVED_HEADER_NAMES = new HashSet<String>();
static{
RESERVED_HEADER_NAMES.add(DESTINATION);
RESERVED_HEADER_NAMES.add(REPLY_TO);
RESERVED_HEADER_NAMES.add(MESSAGE_ID);
RESERVED_HEADER_NAMES.add(CORRELATION_ID);
RESERVED_HEADER_NAMES.add(EXPIRATION_TIME);
RESERVED_HEADER_NAMES.add(TIMESTAMP);
RESERVED_HEADER_NAMES.add(PRIORITY);
RESERVED_HEADER_NAMES.add(REDELIVERED);
RESERVED_HEADER_NAMES.add(TYPE);
RESERVED_HEADER_NAMES.add(PERSISTENT);
RESERVED_HEADER_NAMES.add(RECEIPT_REQUESTED);
RESERVED_HEADER_NAMES.add(TRANSFORMATION);
RESERVED_HEADER_NAMES.add(SUBSCRIPTION);
RESERVED_HEADER_NAMES.add(CONTENT_LENGTH);
RESERVED_HEADER_NAMES.add(JMSX_DELIVERY_COUNT);
RESERVED_HEADER_NAMES.add(JMSX_GROUP_ID);
RESERVED_HEADER_NAMES.add(JMSX_GROUP_SEQUENCE);
}
private final StompFrame message;
private final StompConnection connection;
/**
* Creates a new wrapper around the StompFrame Message instance.
*
* @param message
* the STOMP message to wrap.
* @param connection
* the STOMP connection instance to assign to this Facade.
*/
public StompJmsMessageFacade(StompFrame message, StompConnection connection) {
this.message = message;
this.connection = connection;
}
/**
* @return the underlying STOMP frame that backs this Facade.
*/
public StompFrame getStompMessage() {
return this.message;
}
/**
* @return the StompConnection for this message facade.
*/
public StompConnection getStompConnection() {
return this.connection;
}
@Override
public Map<String, Object> getProperties() throws IOException {
Map<String, Object> properties = new HashMap<String, Object>();
for (Entry<String, String> entry : message.getProperties().entrySet()) {
if (!RESERVED_HEADER_NAMES.contains(entry.getKey())) {
properties.put(entry.getKey(), entry.getValue());
}
}
return Collections.unmodifiableMap(properties);
}
@Override
public boolean propertyExists(String key) throws IOException {
return message.getProperty(key) != null;
}
@Override
public Object getProperty(String key) throws IOException {
return message.getProperty(key);
}
@Override
public void setProperty(String key, Object value) throws IOException {
if (!RESERVED_HEADER_NAMES.contains(key)) {
message.setProperty(key, value.toString());
}
}
@Override
public void onSend() throws JMSException {
// TODO - Nothing yet needed here.
}
@Override
public void clearBody() {
message.setContent(null);
}
@Override
public void clearProperties() {
message.getProperties().entrySet().retainAll(RESERVED_HEADER_NAMES);
}
@Override
public JmsMessageFacade copy() {
return new StompJmsMessageFacade(message.clone(), connection);
}
@Override
public JmsMessageId getMessageId() {
return new JmsMessageId(message.getProperty(MESSAGE_ID));
}
@Override
public void setMessageId(JmsMessageId messageId) {
message.setProperty(MESSAGE_ID, messageId.toString());
}
@Override
public long getTimestamp() {
return or(getLongProperty(TIMESTAMP), 0L);
}
@Override
public void setTimestamp(long timestamp) {
setLongProperty(TIMESTAMP, timestamp);
}
@Override
public String getCorrelationId() {
return message.getProperty(CORRELATION_ID);
}
@Override
public void setCorrelationId(String correlationId) {
setStringProperty(CORRELATION_ID, correlationId);
}
@Override
public boolean isPersistent() {
return or(getBooleanProperty(PERSISTENT), false);
}
@Override
public void setPersistent(boolean value) {
setBooleanProperty(PERSISTENT, value);
}
@Override
public int getRedeliveryCounter() {
return or(getIntProperty(JMSX_DELIVERY_COUNT), 0);
}
@Override
public void setRedeliveryCounter(int redeliveryCount) {
setIntegerProperty(JMSX_DELIVERY_COUNT, redeliveryCount);
}
@Override
public String getType() {
return message.getProperty(TYPE);
}
@Override
public void setType(String type) {
setStringProperty(TYPE, type);
}
@Override
public byte getPriority() {
return or(getByteProperty(PRIORITY), (byte) 4);
}
@Override
public void setPriority(byte priority) {
setByteProperty(PRIORITY, priority);
}
@Override
public long getExpiration() {
return or(getLongProperty(EXPIRATION_TIME), 0L);
}
@Override
public void setExpiration(long expiration) {
setLongProperty(EXPIRATION_TIME, expiration);
}
@Override
public JmsDestination getDestination() throws JMSException {
return toJmsDestination(message.getProperty(DESTINATION));
}
@Override
public void setDestination(JmsDestination destination) {
setStringProperty(DESTINATION, toStompDestination(destination));
}
@Override
public JmsDestination getReplyTo() throws JMSException {
return toJmsDestination(message.getProperty(REPLY_TO));
}
@Override
public void setReplyTo(JmsDestination replyTo) {
setStringProperty(REPLY_TO, toStompDestination(replyTo));
}
@Override
public String getUserId() {
return message.getProperty(USERID);
}
@Override
public void setUserId(String userId) {
setStringProperty(USERID, userId);
}
@Override
public String getGroupId() {
return message.getProperty(JMSX_GROUP_ID);
}
@Override
public void setGroupId(String groupId) {
setStringProperty(JMSX_GROUP_ID, groupId);
}
@Override
public int getGroupSequence() {
return or(getIntProperty(JMSX_GROUP_SEQUENCE), 0);
}
@Override
public void setGroupSequence(int groupSequence) {
setIntegerProperty(JMSX_GROUP_SEQUENCE, groupSequence);
}
private void setStringProperty(String key, String value) {
if (value == null) {
message.removeProperty(key);
} else {
message.setProperty(key, value);
}
}
private void setLongProperty(String key, Long value) {
if (value == null) {
message.removeProperty(key);
} else {
message.setProperty(key, value.toString());
}
}
private Long getLongProperty(String key) {
String vale = message.getProperty(key);
if (vale == null) {
return null;
} else {
return Long.parseLong(vale.toString());
}
}
private Integer getIntProperty(String key) {
String vale = message.getProperty(key);
if (vale == null) {
return null;
} else {
return Integer.parseInt(vale.toString());
}
}
private void setIntegerProperty(String key, Integer value) {
if (value == null) {
message.removeProperty(key);
} else {
message.setProperty(key, value.toString());
}
}
private Byte getByteProperty(String key) {
String vale = message.getProperty(key);
if (vale == null) {
return null;
} else {
return Byte.parseByte(vale.toString());
}
}
private void setByteProperty(String key, Byte value) {
if (value == null) {
message.removeProperty(key);
} else {
message.setProperty(key, value.toString());
}
}
private Boolean getBooleanProperty(String key) {
String vale = message.getProperty(key);
if (vale == null) {
return null;
} else {
return Boolean.parseBoolean(vale.toString());
}
}
private void setBooleanProperty(String key, Boolean value) {
if (value == null) {
message.removeProperty(key);
} else {
message.setProperty(key, value.booleanValue() ? TRUE : FALSE);
}
}
private <T> T or(T value, T other) {
if (value != null) {
return value;
} else {
return other;
}
}
private String toStompDestination(JmsDestination destination) {
return connection.getServerAdapter().toStompDestination(destination);
}
private JmsDestination toJmsDestination(String destinationName) throws JMSException {
return connection.getServerAdapter().toJmsDestination(destinationName);
}
}
| |
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.webapp.control;
import static org.ofbiz.base.util.UtilGenerics.checkMap;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ofbiz.base.util.CachedClassLoader;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.StringUtil;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilObject;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.DelegatorFactory;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.security.Security;
import org.ofbiz.security.SecurityConfigurationException;
import org.ofbiz.security.SecurityFactory;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceContainer;
import org.ofbiz.webapp.website.WebSiteWorker;
/**
* ContextFilter - Restricts access to raw files and configures servlet objects.
*/
public class ContextFilter implements Filter {
public static final String module = ContextFilter.class.getName();
public static final String FORWARDED_FROM_SERVLET = "_FORWARDED_FROM_SERVLET_";
protected ClassLoader localCachedClassLoader = null;
protected FilterConfig config = null;
protected boolean debug = false;
/**
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig config) throws ServletException {
this.config = config;
// puts all init-parameters in ServletContext attributes for easier parameterization without code changes
this.putAllInitParametersInAttributes();
// initialize the cached class loader for this application
ClassLoader loader = Thread.currentThread().getContextClassLoader();
localCachedClassLoader = new CachedClassLoader(loader, (String) config.getServletContext().getAttribute("webSiteId"));
// set debug
this.debug = "true".equalsIgnoreCase(config.getInitParameter("debug"));
if (!debug) {
debug = Debug.verboseOn();
}
// check the serverId
getServerId();
// initialize the delegator
getDelegator(config.getServletContext());
// initialize security
getSecurity();
// initialize the services dispatcher
getDispatcher(config.getServletContext());
// this will speed up the initial sessionId generation
new java.security.SecureRandom().nextLong();
}
/**
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
// Debug.logInfo("Running ContextFilter.doFilter", module);
// ----- Servlet Object Setup -----
// set the cached class loader for more speedy running in this thread
String disableCachedClassloader = config.getInitParameter("disableCachedClassloader");
if (disableCachedClassloader == null || !"Y".equalsIgnoreCase(disableCachedClassloader)) {
Thread.currentThread().setContextClassLoader(localCachedClassLoader);
}
// set the ServletContext in the request for future use
httpRequest.setAttribute("servletContext", config.getServletContext());
// set the webSiteId in the session
if (UtilValidate.isEmpty(httpRequest.getSession().getAttribute("webSiteId"))){
httpRequest.getSession().setAttribute("webSiteId", WebSiteWorker.getWebSiteId(httpRequest));
}
// set the filesystem path of context root.
httpRequest.setAttribute("_CONTEXT_ROOT_", config.getServletContext().getRealPath("/"));
// set the server root url
StringBuffer serverRootUrl = UtilHttp.getServerRootUrl(httpRequest);
httpRequest.setAttribute("_SERVER_ROOT_URL_", serverRootUrl.toString());
// request attributes from redirect call
String reqAttrMapHex = (String) httpRequest.getSession().getAttribute("_REQ_ATTR_MAP_");
if (UtilValidate.isNotEmpty(reqAttrMapHex)) {
byte[] reqAttrMapBytes = StringUtil.fromHexString(reqAttrMapHex);
Map<String, Object> reqAttrMap = checkMap(UtilObject.getObject(reqAttrMapBytes), String.class, Object.class);
if (reqAttrMap != null) {
for (Map.Entry<String, Object> entry: reqAttrMap.entrySet()) {
httpRequest.setAttribute(entry.getKey(), entry.getValue());
}
}
httpRequest.getSession().removeAttribute("_REQ_ATTR_MAP_");
}
// ----- Context Security -----
// check if we are disabled
String disableSecurity = config.getInitParameter("disableContextSecurity");
if (disableSecurity != null && "Y".equalsIgnoreCase(disableSecurity)) {
chain.doFilter(httpRequest, httpResponse);
return;
}
// check if we are told to redirect everthing
String redirectAllTo = config.getInitParameter("forceRedirectAll");
if (UtilValidate.isNotEmpty(redirectAllTo)) {
// little trick here so we don't loop on ourself
if (httpRequest.getSession().getAttribute("_FORCE_REDIRECT_") == null) {
httpRequest.getSession().setAttribute("_FORCE_REDIRECT_", "true");
Debug.logWarning("Redirecting user to: " + redirectAllTo, module);
if (!redirectAllTo.toLowerCase().startsWith("http")) {
redirectAllTo = httpRequest.getContextPath() + redirectAllTo;
}
httpResponse.sendRedirect(redirectAllTo);
return;
} else {
httpRequest.getSession().removeAttribute("_FORCE_REDIRECT_");
chain.doFilter(httpRequest, httpResponse);
return;
}
}
// test to see if we have come through the control servlet already, if not do the processing
String requestPath = null;
String contextUri = null;
if (httpRequest.getAttribute(ContextFilter.FORWARDED_FROM_SERVLET) == null) {
// Debug.logInfo("In ContextFilter.doFilter, FORWARDED_FROM_SERVLET is NOT set", module);
String allowedPath = config.getInitParameter("allowedPaths");
String redirectPath = config.getInitParameter("redirectPath");
String errorCode = config.getInitParameter("errorCode");
List<String> allowList = StringUtil.split(allowedPath, ":");
allowList.add("/"); // No path is allowed.
allowList.add(""); // No path is allowed.
if (debug) Debug.logInfo("[Domain]: " + httpRequest.getServerName() + " [Request]: " + httpRequest.getRequestURI(), module);
requestPath = httpRequest.getServletPath();
if (requestPath == null) requestPath = "";
if (requestPath.lastIndexOf("/") > 0) {
if (requestPath.indexOf("/") == 0) {
requestPath = "/" + requestPath.substring(1, requestPath.indexOf("/", 1));
} else {
requestPath = requestPath.substring(1, requestPath.indexOf("/"));
}
}
String requestInfo = httpRequest.getServletPath();
if (requestInfo == null) requestInfo = "";
if (requestInfo.lastIndexOf("/") >= 0) {
requestInfo = requestInfo.substring(0, requestInfo.lastIndexOf("/")) + "/*";
}
StringBuilder contextUriBuffer = new StringBuilder();
if (httpRequest.getContextPath() != null) {
contextUriBuffer.append(httpRequest.getContextPath());
}
if (httpRequest.getServletPath() != null) {
contextUriBuffer.append(httpRequest.getServletPath());
}
if (httpRequest.getPathInfo() != null) {
contextUriBuffer.append(httpRequest.getPathInfo());
}
contextUri = contextUriBuffer.toString();
// Verbose Debugging
if (Debug.verboseOn()) {
for (String allow: allowList) {
Debug.logVerbose("[Allow]: " + allow, module);
}
Debug.logVerbose("[Request path]: " + requestPath, module);
Debug.logVerbose("[Request info]: " + requestInfo, module);
Debug.logVerbose("[Servlet path]: " + httpRequest.getServletPath(), module);
}
// check to make sure the requested url is allowed
if (!allowList.contains(requestPath) && !allowList.contains(requestInfo) && !allowList.contains(httpRequest.getServletPath())) {
String filterMessage = "[Filtered request]: " + contextUri;
if (redirectPath == null) {
int error = 404;
if (UtilValidate.isNotEmpty(errorCode)) {
try {
error = Integer.parseInt(errorCode);
} catch (NumberFormatException nfe) {
Debug.logWarning(nfe, "Error code specified would not parse to Integer : " + errorCode, module);
}
}
filterMessage = filterMessage + " (" + error + ")";
httpResponse.sendError(error, contextUri);
request.setAttribute("filterRequestUriError", contextUri);
} else {
filterMessage = filterMessage + " (" + redirectPath + ")";
if (!redirectPath.toLowerCase().startsWith("http")) {
redirectPath = httpRequest.getContextPath() + redirectPath;
}
httpResponse.sendRedirect(redirectPath);
}
Debug.logWarning(filterMessage, module);
return;
}
}
// check if multi tenant is enabled
String useMultitenant = UtilProperties.getPropertyValue("general.properties", "multitenant");
if ("Y".equals(useMultitenant)) {
// get tenant delegator by domain name
String serverName = httpRequest.getServerName();
try {
// if tenant was specified, replace delegator with the new per-tenant delegator and set tenantId to session attribute
Delegator delegator = getDelegator(config.getServletContext());
List<GenericValue> tenants = delegator.findList("Tenant", EntityCondition.makeCondition("domainName", serverName), null, UtilMisc.toList("-createdStamp"), null, false);
if (UtilValidate.isNotEmpty(tenants)) {
GenericValue tenant = EntityUtil.getFirst(tenants);
String tenantId = tenant.getString("tenantId");
// if the request path is a root mount then redirect to the initial path
if (UtilValidate.isNotEmpty(requestPath) && requestPath.equals(contextUri)) {
String initialPath = tenant.getString("initialPath");
if (UtilValidate.isNotEmpty(initialPath) && !"/".equals(initialPath)) {
((HttpServletResponse)response).sendRedirect(initialPath);
return;
}
}
// make that tenant active, setup a new delegator and a new dispatcher
String tenantDelegatorName = delegator.getDelegatorBaseName() + "#" + tenantId;
httpRequest.getSession().setAttribute("delegatorName", tenantDelegatorName);
// after this line the delegator is replaced with the new per-tenant delegator
delegator = DelegatorFactory.getDelegator(tenantDelegatorName);
config.getServletContext().setAttribute("delegator", delegator);
// clear web context objects
config.getServletContext().setAttribute("security", null);
config.getServletContext().setAttribute("dispatcher", null);
// initialize security
Security security = getSecurity();
// initialize the services dispatcher
LocalDispatcher dispatcher = getDispatcher(config.getServletContext());
// set web context objects
request.setAttribute("dispatcher", dispatcher);
request.setAttribute("security", security);
request.setAttribute("tenantId", tenantId);
}
// NOTE DEJ20101130: do NOT always put the delegator name in the user's session because the user may
// have logged in and specified a tenant, and even if no Tenant record with a matching domainName field
// is found this will change the user's delegator back to the base one instead of the one for the
// tenant specified on login
// httpRequest.getSession().setAttribute("delegatorName", delegator.getDelegatorName());
} catch (GenericEntityException e) {
Debug.logWarning(e, "Unable to get Tenant", module);
}
}
// we're done checking; continue on
chain.doFilter(httpRequest, httpResponse);
}
/**
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
getDispatcher(config.getServletContext()).deregister();
config = null;
}
protected static LocalDispatcher getDispatcher(ServletContext servletContext) {
LocalDispatcher dispatcher = (LocalDispatcher) servletContext.getAttribute("dispatcher");
if (dispatcher == null) {
Delegator delegator = getDelegator(servletContext);
dispatcher = makeWebappDispatcher(servletContext, delegator);
servletContext.setAttribute("dispatcher", dispatcher);
}
return dispatcher;
}
/** This method only sets up a dispatcher for the current webapp and passed in delegator, it does not save it to the ServletContext or anywhere else, just returns it */
public static LocalDispatcher makeWebappDispatcher(ServletContext servletContext, Delegator delegator) {
if (delegator == null) {
Debug.logError("[ContextFilter.init] ERROR: delegator not defined.", module);
return null;
}
// get the unique name of this dispatcher
String dispatcherName = servletContext.getInitParameter("localDispatcherName");
if (dispatcherName == null) {
Debug.logError("No localDispatcherName specified in the web.xml file", module);
dispatcherName = delegator.getDelegatorName();
}
LocalDispatcher dispatcher = ServiceContainer.getLocalDispatcher(dispatcherName, delegator);
if (dispatcher == null) {
Debug.logError("[ContextFilter.init] ERROR: dispatcher could not be initialized.", module);
}
return dispatcher;
}
protected static Delegator getDelegator(ServletContext servletContext) {
Delegator delegator = (Delegator) servletContext.getAttribute("delegator");
if (delegator == null) {
String delegatorName = servletContext.getInitParameter("entityDelegatorName");
if (delegatorName == null || delegatorName.length() <= 0) {
delegatorName = "default";
}
if (Debug.verboseOn()) Debug.logVerbose("Setup Entity Engine Delegator with name " + delegatorName, module);
delegator = DelegatorFactory.getDelegator(delegatorName);
servletContext.setAttribute("delegator", delegator);
if (delegator == null) {
Debug.logError("[ContextFilter.init] ERROR: delegator factory returned null for delegatorName \"" + delegatorName + "\"", module);
}
}
return delegator;
}
protected Security getSecurity() {
Security security = (Security) config.getServletContext().getAttribute("security");
if (security == null) {
Delegator delegator = (Delegator) config.getServletContext().getAttribute("delegator");
if (delegator != null) {
try {
security = SecurityFactory.getInstance(delegator);
} catch (SecurityConfigurationException e) {
Debug.logError(e, "Unable to obtain an instance of the security object.", module);
}
}
config.getServletContext().setAttribute("security", security);
if (security == null) {
Debug.logError("An invalid (null) Security object has been set in the servlet context.", module);
}
}
return security;
}
protected void putAllInitParametersInAttributes() {
Enumeration<String> initParamEnum = UtilGenerics.cast(config.getServletContext().getInitParameterNames());
while (initParamEnum.hasMoreElements()) {
String initParamName = initParamEnum.nextElement();
String initParamValue = config.getServletContext().getInitParameter(initParamName);
if (Debug.verboseOn()) Debug.logVerbose("Adding web.xml context-param to application attribute with name [" + initParamName + "] and value [" + initParamValue + "]", module);
config.getServletContext().setAttribute(initParamName, initParamValue);
}
String GeronimoMultiOfbizInstances = (String) config.getServletContext().getAttribute("GeronimoMultiOfbizInstances");
if (UtilValidate.isNotEmpty(GeronimoMultiOfbizInstances)) {
String ofbizHome = System.getProperty("ofbiz.home");
if (GeronimoMultiOfbizInstances.equalsIgnoreCase("true") && UtilValidate.isEmpty(ofbizHome)) {
ofbizHome = System.getProperty("ofbiz.home"); // This is only used in case of Geronimo or WASCE using OFBiz multi-instances. It allows to retrieve ofbiz.home value set in JVM env
System.out.println("Set OFBIZ_HOME to - " + ofbizHome);
System.setProperty("ofbiz.home", ofbizHome);
}
}
}
protected String getServerId() {
String serverId = (String) config.getServletContext().getAttribute("_serverId");
if (serverId == null) {
serverId = config.getServletContext().getInitParameter("ofbizServerName");
config.getServletContext().setAttribute("_serverId", serverId);
}
return serverId;
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.cloudbuild.v1beta1.model;
/**
* A step in the build pipeline.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Build API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class BuildStep extends com.google.api.client.json.GenericJson {
/**
* A list of arguments that will be presented to the step when it is started. If the image used to
* run the step's container has an entrypoint, the `args` are used as arguments to that
* entrypoint. If the image does not define an entrypoint, the first element in args is used as
* the entrypoint, and the remainder will be used as arguments.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> args;
/**
* Working directory to use when running this step's container. If this value is a relative path,
* it is relative to the build's working directory. If this value is absolute, it may be outside
* the build's working directory, in which case the contents of the path may not be persisted
* across build step executions, unless a `volume` for that path is specified. If the build
* specifies a `RepoSource` with `dir` and a step with a `dir`, which specifies an absolute path,
* the `RepoSource` `dir` is ignored for the step's execution.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String dir;
/**
* Entrypoint to be used instead of the build step image's default entrypoint. If unset, the
* image's default entrypoint is used.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String entrypoint;
/**
* A list of environment variable definitions to be used when running a step. The elements are of
* the form "KEY=VALUE" for the environment variable "KEY" being given the value "VALUE".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> env;
/**
* Unique identifier for this build step, used in `wait_for` to reference this build step as a
* dependency.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String id;
/**
* Required. The name of the container image that will run this particular build step. If the
* image is available in the host's Docker daemon's cache, it will be run directly. If not, the
* host will attempt to pull the image first, using the builder service account's credentials if
* necessary. The Docker daemon's cache will already have the latest versions of all of the
* officially supported build steps ([https://github.com/GoogleCloudPlatform/cloud-
* builders](https://github.com/GoogleCloudPlatform/cloud-builders)). The Docker daemon will also
* have cached many of the layers for some popular images, like "ubuntu", "debian", but they will
* be refreshed at the time you attempt to use them. If you built an image in a previous build
* step, it will be stored in the host's Docker daemon's cache and is available to use as the name
* for a later build step.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Output only. Stores timing information for pulling this build step's builder image only.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TimeSpan pullTiming;
/**
* A shell script to be executed in the step. When script is provided, the user cannot specify the
* entrypoint or args.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String script;
/**
* A list of environment variables which are encrypted using a Cloud Key Management Service crypto
* key. These values must be specified in the build's `Secret`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> secretEnv;
/**
* Output only. Status of the build step. At this time, build step status is only updated on build
* completion; step status is not updated in real-time as the build progresses.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String status;
/**
* Time limit for executing this build step. If not defined, the step has no time limit and will
* be allowed to continue to run until either it completes or the build itself times out.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String timeout;
/**
* Output only. Stores timing information for executing this build step.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TimeSpan timing;
/**
* List of volumes to mount into the build step. Each volume is created as an empty volume prior
* to execution of the build step. Upon completion of the build, volumes and their contents are
* discarded. Using a named volume in only one step is not valid as it is indicative of a build
* request with an incorrect configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Volume> volumes;
/**
* The ID(s) of the step(s) that this build step depends on. This build step will not start until
* all the build steps in `wait_for` have completed successfully. If `wait_for` is empty, this
* build step will start when all previous build steps in the `Build.Steps` list have completed
* successfully.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> waitFor;
/**
* A list of arguments that will be presented to the step when it is started. If the image used to
* run the step's container has an entrypoint, the `args` are used as arguments to that
* entrypoint. If the image does not define an entrypoint, the first element in args is used as
* the entrypoint, and the remainder will be used as arguments.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getArgs() {
return args;
}
/**
* A list of arguments that will be presented to the step when it is started. If the image used to
* run the step's container has an entrypoint, the `args` are used as arguments to that
* entrypoint. If the image does not define an entrypoint, the first element in args is used as
* the entrypoint, and the remainder will be used as arguments.
* @param args args or {@code null} for none
*/
public BuildStep setArgs(java.util.List<java.lang.String> args) {
this.args = args;
return this;
}
/**
* Working directory to use when running this step's container. If this value is a relative path,
* it is relative to the build's working directory. If this value is absolute, it may be outside
* the build's working directory, in which case the contents of the path may not be persisted
* across build step executions, unless a `volume` for that path is specified. If the build
* specifies a `RepoSource` with `dir` and a step with a `dir`, which specifies an absolute path,
* the `RepoSource` `dir` is ignored for the step's execution.
* @return value or {@code null} for none
*/
public java.lang.String getDir() {
return dir;
}
/**
* Working directory to use when running this step's container. If this value is a relative path,
* it is relative to the build's working directory. If this value is absolute, it may be outside
* the build's working directory, in which case the contents of the path may not be persisted
* across build step executions, unless a `volume` for that path is specified. If the build
* specifies a `RepoSource` with `dir` and a step with a `dir`, which specifies an absolute path,
* the `RepoSource` `dir` is ignored for the step's execution.
* @param dir dir or {@code null} for none
*/
public BuildStep setDir(java.lang.String dir) {
this.dir = dir;
return this;
}
/**
* Entrypoint to be used instead of the build step image's default entrypoint. If unset, the
* image's default entrypoint is used.
* @return value or {@code null} for none
*/
public java.lang.String getEntrypoint() {
return entrypoint;
}
/**
* Entrypoint to be used instead of the build step image's default entrypoint. If unset, the
* image's default entrypoint is used.
* @param entrypoint entrypoint or {@code null} for none
*/
public BuildStep setEntrypoint(java.lang.String entrypoint) {
this.entrypoint = entrypoint;
return this;
}
/**
* A list of environment variable definitions to be used when running a step. The elements are of
* the form "KEY=VALUE" for the environment variable "KEY" being given the value "VALUE".
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getEnv() {
return env;
}
/**
* A list of environment variable definitions to be used when running a step. The elements are of
* the form "KEY=VALUE" for the environment variable "KEY" being given the value "VALUE".
* @param env env or {@code null} for none
*/
public BuildStep setEnv(java.util.List<java.lang.String> env) {
this.env = env;
return this;
}
/**
* Unique identifier for this build step, used in `wait_for` to reference this build step as a
* dependency.
* @return value or {@code null} for none
*/
public java.lang.String getId() {
return id;
}
/**
* Unique identifier for this build step, used in `wait_for` to reference this build step as a
* dependency.
* @param id id or {@code null} for none
*/
public BuildStep setId(java.lang.String id) {
this.id = id;
return this;
}
/**
* Required. The name of the container image that will run this particular build step. If the
* image is available in the host's Docker daemon's cache, it will be run directly. If not, the
* host will attempt to pull the image first, using the builder service account's credentials if
* necessary. The Docker daemon's cache will already have the latest versions of all of the
* officially supported build steps ([https://github.com/GoogleCloudPlatform/cloud-
* builders](https://github.com/GoogleCloudPlatform/cloud-builders)). The Docker daemon will also
* have cached many of the layers for some popular images, like "ubuntu", "debian", but they will
* be refreshed at the time you attempt to use them. If you built an image in a previous build
* step, it will be stored in the host's Docker daemon's cache and is available to use as the name
* for a later build step.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Required. The name of the container image that will run this particular build step. If the
* image is available in the host's Docker daemon's cache, it will be run directly. If not, the
* host will attempt to pull the image first, using the builder service account's credentials if
* necessary. The Docker daemon's cache will already have the latest versions of all of the
* officially supported build steps ([https://github.com/GoogleCloudPlatform/cloud-
* builders](https://github.com/GoogleCloudPlatform/cloud-builders)). The Docker daemon will also
* have cached many of the layers for some popular images, like "ubuntu", "debian", but they will
* be refreshed at the time you attempt to use them. If you built an image in a previous build
* step, it will be stored in the host's Docker daemon's cache and is available to use as the name
* for a later build step.
* @param name name or {@code null} for none
*/
public BuildStep setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Output only. Stores timing information for pulling this build step's builder image only.
* @return value or {@code null} for none
*/
public TimeSpan getPullTiming() {
return pullTiming;
}
/**
* Output only. Stores timing information for pulling this build step's builder image only.
* @param pullTiming pullTiming or {@code null} for none
*/
public BuildStep setPullTiming(TimeSpan pullTiming) {
this.pullTiming = pullTiming;
return this;
}
/**
* A shell script to be executed in the step. When script is provided, the user cannot specify the
* entrypoint or args.
* @return value or {@code null} for none
*/
public java.lang.String getScript() {
return script;
}
/**
* A shell script to be executed in the step. When script is provided, the user cannot specify the
* entrypoint or args.
* @param script script or {@code null} for none
*/
public BuildStep setScript(java.lang.String script) {
this.script = script;
return this;
}
/**
* A list of environment variables which are encrypted using a Cloud Key Management Service crypto
* key. These values must be specified in the build's `Secret`.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSecretEnv() {
return secretEnv;
}
/**
* A list of environment variables which are encrypted using a Cloud Key Management Service crypto
* key. These values must be specified in the build's `Secret`.
* @param secretEnv secretEnv or {@code null} for none
*/
public BuildStep setSecretEnv(java.util.List<java.lang.String> secretEnv) {
this.secretEnv = secretEnv;
return this;
}
/**
* Output only. Status of the build step. At this time, build step status is only updated on build
* completion; step status is not updated in real-time as the build progresses.
* @return value or {@code null} for none
*/
public java.lang.String getStatus() {
return status;
}
/**
* Output only. Status of the build step. At this time, build step status is only updated on build
* completion; step status is not updated in real-time as the build progresses.
* @param status status or {@code null} for none
*/
public BuildStep setStatus(java.lang.String status) {
this.status = status;
return this;
}
/**
* Time limit for executing this build step. If not defined, the step has no time limit and will
* be allowed to continue to run until either it completes or the build itself times out.
* @return value or {@code null} for none
*/
public String getTimeout() {
return timeout;
}
/**
* Time limit for executing this build step. If not defined, the step has no time limit and will
* be allowed to continue to run until either it completes or the build itself times out.
* @param timeout timeout or {@code null} for none
*/
public BuildStep setTimeout(String timeout) {
this.timeout = timeout;
return this;
}
/**
* Output only. Stores timing information for executing this build step.
* @return value or {@code null} for none
*/
public TimeSpan getTiming() {
return timing;
}
/**
* Output only. Stores timing information for executing this build step.
* @param timing timing or {@code null} for none
*/
public BuildStep setTiming(TimeSpan timing) {
this.timing = timing;
return this;
}
/**
* List of volumes to mount into the build step. Each volume is created as an empty volume prior
* to execution of the build step. Upon completion of the build, volumes and their contents are
* discarded. Using a named volume in only one step is not valid as it is indicative of a build
* request with an incorrect configuration.
* @return value or {@code null} for none
*/
public java.util.List<Volume> getVolumes() {
return volumes;
}
/**
* List of volumes to mount into the build step. Each volume is created as an empty volume prior
* to execution of the build step. Upon completion of the build, volumes and their contents are
* discarded. Using a named volume in only one step is not valid as it is indicative of a build
* request with an incorrect configuration.
* @param volumes volumes or {@code null} for none
*/
public BuildStep setVolumes(java.util.List<Volume> volumes) {
this.volumes = volumes;
return this;
}
/**
* The ID(s) of the step(s) that this build step depends on. This build step will not start until
* all the build steps in `wait_for` have completed successfully. If `wait_for` is empty, this
* build step will start when all previous build steps in the `Build.Steps` list have completed
* successfully.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getWaitFor() {
return waitFor;
}
/**
* The ID(s) of the step(s) that this build step depends on. This build step will not start until
* all the build steps in `wait_for` have completed successfully. If `wait_for` is empty, this
* build step will start when all previous build steps in the `Build.Steps` list have completed
* successfully.
* @param waitFor waitFor or {@code null} for none
*/
public BuildStep setWaitFor(java.util.List<java.lang.String> waitFor) {
this.waitFor = waitFor;
return this;
}
@Override
public BuildStep set(String fieldName, Object value) {
return (BuildStep) super.set(fieldName, value);
}
@Override
public BuildStep clone() {
return (BuildStep) super.clone();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.cloudstack.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import org.jclouds.javax.annotation.Nullable;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/**
* Class SnapshotPolicy
*/
public class SnapshotPolicy {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromSnapshotPolicy(this);
}
public abstract static class Builder<T extends Builder<T>> {
protected abstract T self();
protected String id;
protected Snapshot.Interval interval;
protected long numberToRetain;
protected String schedule;
protected String timezone;
protected String volumeId;
/**
* @see SnapshotPolicy#getId()
*/
public T id(String id) {
this.id = id;
return self();
}
/**
* @see SnapshotPolicy#getInterval()
*/
public T interval(Snapshot.Interval interval) {
this.interval = interval;
return self();
}
/**
* @see SnapshotPolicy#getNumberToRetain()
*/
public T numberToRetain(long numberToRetain) {
this.numberToRetain = numberToRetain;
return self();
}
/**
* @see SnapshotPolicy#getSchedule()
*/
public T schedule(String schedule) {
this.schedule = schedule;
return self();
}
/**
* @see SnapshotPolicy#getTimezone()
*/
public T timezone(String timezone) {
this.timezone = timezone;
return self();
}
/**
* @see SnapshotPolicy#getVolumeId()
*/
public T volumeId(String volumeId) {
this.volumeId = volumeId;
return self();
}
public SnapshotPolicy build() {
return new SnapshotPolicy(id, interval, numberToRetain, schedule, timezone, volumeId);
}
public T fromSnapshotPolicy(SnapshotPolicy in) {
return this
.id(in.getId())
.interval(in.getInterval())
.numberToRetain(in.getNumberToRetain())
.schedule(in.getSchedule())
.timezone(in.getTimezone())
.volumeId(in.getVolumeId());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final String id;
private final Snapshot.Interval interval;
private final long numberToRetain;
private final String schedule;
private final String timezone;
private final String volumeId;
@ConstructorProperties({
"id", "intervaltype", "maxsnaps", "schedule", "timezone", "volumeid"
})
protected SnapshotPolicy(String id, @Nullable Snapshot.Interval interval, long numberToRetain, @Nullable String schedule,
@Nullable String timezone, @Nullable String volumeId) {
this.id = checkNotNull(id, "id");
this.interval = interval;
this.numberToRetain = numberToRetain;
this.schedule = schedule;
this.timezone = timezone;
this.volumeId = volumeId;
}
/**
* @return the ID of the snapshot policy
*/
public String getId() {
return this.id;
}
/**
* @return valid types are hourly, daily, weekly, monthly, template, and none.
*/
@Nullable
public Snapshot.Interval getInterval() {
return this.interval;
}
/**
* @return maximum number of snapshots retained
*/
public long getNumberToRetain() {
return this.numberToRetain;
}
/**
* @return time the snapshot is scheduled to be taken.
*/
@Nullable
public String getSchedule() {
return this.schedule;
}
/**
* @return the time zone of the snapshot policy
*/
@Nullable
public String getTimezone() {
return this.timezone;
}
/**
* @return ID of the disk volume
*/
@Nullable
public String getVolumeId() {
return this.volumeId;
}
@Override
public int hashCode() {
return Objects.hashCode(id, interval, numberToRetain, schedule, timezone, volumeId);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
SnapshotPolicy that = SnapshotPolicy.class.cast(obj);
return Objects.equal(this.id, that.id)
&& Objects.equal(this.interval, that.interval)
&& Objects.equal(this.numberToRetain, that.numberToRetain)
&& Objects.equal(this.schedule, that.schedule)
&& Objects.equal(this.timezone, that.timezone)
&& Objects.equal(this.volumeId, that.volumeId);
}
protected ToStringHelper string() {
return Objects.toStringHelper(this)
.add("id", id).add("interval", interval).add("numberToRetain", numberToRetain).add("schedule", schedule).add("timezone", timezone)
.add("volumeId", volumeId);
}
@Override
public String toString() {
return string().toString();
}
}
| |
/**
*
* Modified the application, so it doesn't get reopened each time tag is connected
* The screenshot conversion verified to work
*
* the folder where screenshots are saved might change. (currently path is hardcoded for sdcard/screenshots/)
*
* This application doesn't take screenshots itself. It uses third party application:
* screenshot (by KasterSoft). Set the image to bmp format (no compression)
* It is possible to extract images from the frame buffer on rooted phone but I found it problematic.
*
* Tested on Galaxy Nexus (Samsung) and Nexus S (Samsung)
*/
package se.kth.prodreal.dumbdevices.dumbdisplayhelper.ui;
///////////////////////////////////////////////////////////////////////////////
// IMPORTS
///////////////////////////////////////////////////////////////////////////////
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.ByteBuffer;
import se.kth.prodreal.dumbdevices.dumbdisplayhelper.nfc.SendFileToWISP;
import se.kth.prodreal.dumbdevices.dumbdisplayhelper.util.ImageManipulation;
import se.kth.prodreal.dumbdevices.dumbdisplayhelper.util.Utilities;
public class MainActivity extends Activity {
///////////////////////////////////////////////////////////////////////////////
//CONSTANTS
///////////////////////////////////////////////////////////////////////////////
private static final String TAG = "NFCWriteTag"; // Used in debugging?
// public static final String SDCARD_SCREENSHOTS = "/sdcard/screenshots";
public static final String SDCARD_SCREENSHOTS = "/storage/emulated/0/Pictures/Screenshots";
///////////////////////////////////////////////////////////////////////////////
// FIELDS
///////////////////////////////////////////////////////////////////////////////
public TextView myStatusTextView;
public IsoDep isoDep;
private NfcAdapter mNfcAdapter; // Represents phone's NFC transceiver
private IntentFilter[] mWriteTagFilters;
private PendingIntent mNfcPendingIntent;
private Context context;
private ImageView mImage;
private byte[] imageBuffer; // Global for storing image data to relay to tag
private PowerManager mPowerManager;
private WakeLock mWakeLock;
private SendFileToWISP fileSender;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
mWakeLock = mPowerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, getClass().getName());
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mNfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP), 0);
IntentFilter discovery = new IntentFilter(
NfcAdapter.ACTION_TAG_DISCOVERED);
fileSender = new SendFileToWISP(this);
// Intent filters for writing to a tag
mWriteTagFilters = new IntentFilter[] { discovery };
retrieveScreenShot();
Log.d(TAG, "START");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onResume() {
super.onResume();
mWakeLock.acquire(); // Keep the phone awake while app is active
if (mNfcAdapter != null) {
if (!mNfcAdapter.isEnabled()) {
Intent setnfc = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(setnfc);
}
mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent,
mWriteTagFilters, null);
} else {
Toast.makeText(context, "Sorry, No NFC Adapter found.",
Toast.LENGTH_SHORT).show();
}// end if
}// on resume end
@Override
protected void onPause() {
super.onPause();
mWakeLock.release(); // Let the phone go to sleep
if (mNfcAdapter != null)
mNfcAdapter.disableForegroundDispatch(this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d(TAG, "onNewIntent Called");
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
// validate that this tag can be written....
myStatusTextView.setText("tag detected");
Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Log.d(TAG, detectedTag.toString());
Log.d(TAG, detectedTag.getTechList().toString());
this.isoDep = IsoDep.get(detectedTag);
// Have the background task send the image
fileSender.execute(imageBuffer);
}// end if
}// end onNewIntent
/**
* Convert screenshot or image to the eink format
*
* @todo optimize this function
*/
public void retrieveScreenShot() {
// Find the latest file
// Delete the info.txt file and config.dat to avoid
File dir = new File(SDCARD_SCREENSHOTS);
File f = new File(SDCARD_SCREENSHOTS + "/info.txt");
f.delete();
File g = new File(SDCARD_SCREENSHOTS + "/config.dat");
g.delete();
// Find the last modified file, presumably with the latest image
File[] files = dir.listFiles();
if (files.length == 0) {
Log.d("TEST", "No files");
}
File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
if (lastModifiedFile.lastModified() < files[i].lastModified()) {
lastModifiedFile = files[i];
}
}
Log.d("TEST", lastModifiedFile.toString());
Bitmap image;
Bitmap image_rotated;
Bitmap image_rotated_resized;
Bitmap image_rotated_resized_monochrome;
image = BitmapFactory.decodeFile(lastModifiedFile.toString());
image_rotated = ImageManipulation.rotate(image, 90);
image_rotated_resized = ImageManipulation.getResizedBitmap(
image_rotated, 176, 264);
image_rotated_resized_monochrome = ImageManipulation
.createBlackAndWhite(image_rotated_resized);
mImage.setImageBitmap(ImageManipulation.rotate(
image_rotated_resized_monochrome, 270)); // Update the screen
// with the new
// image
int bytes = image_rotated_resized_monochrome.getRowBytes()
* image_rotated_resized_monochrome.getHeight();
ByteBuffer buffer = ByteBuffer.allocate(bytes);
image_rotated_resized_monochrome.copyPixelsToBuffer(buffer);
byte[] array = buffer.array();
Log.d("TEST", "Array length: " + Integer.toString(array.length));
String foo = "";
String test = "";
int count = 0;
int count_bytes = 0;
byte[] image_array = new byte[33 * image_rotated_resized_monochrome.getHeight()];
// TODO Rewrite the following more efficiently (Without string conversion and int parsing, etc)
// For each line in the image
for (int m = 0; m < image_rotated_resized_monochrome.getHeight(); m++) {
// For each pixel of each line
for (int i = 0; i < image_rotated_resized_monochrome.getWidth(); i++) {
if (image_rotated_resized_monochrome.getPixel(i, m) == -1) {
test = test.concat("0");
}// end if
else {
test = test.concat("1");
}// end else
count++;
// Assemble a byte
if (count == 8) {
count = 0;
test = Utilities.reverse(test);
// Log.d("TEST", "teststring: " + test);
byte numberByte = (byte) Integer.parseInt(test, 2);
// System.out.println(numberByte);
image_array[count_bytes] = numberByte;
// numberByte.toString();
count_bytes++;
test = "";
}// end if
}// end for
}// end for
Log.d("TEST", Integer.toString(count_bytes));
imageBuffer = image_array;
Log.d("TEST", Integer.toString(foo.length()));
foo = Utilities.getHexParsed(image_array);
try {
// TODO Don't use hardcoded /sdcard/ path, or any hardcoded path here!
BufferedWriter out = new BufferedWriter(new FileWriter(
"/sdcard/byteArrayImage.txt"));
out.write(foo);
out.close();
} catch (IOException e) {
}
}// end takescreenshot
};// end class
| |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2020_05_01.implementation;
import java.util.List;
import com.microsoft.azure.SubResource;
import com.microsoft.azure.management.network.v2020_05_01.OfficeTrafficCategory;
import com.microsoft.azure.management.network.v2020_05_01.ProvisioningState;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.rest.SkipParentValidation;
import com.microsoft.azure.Resource;
/**
* VirtualWAN Resource.
*/
@JsonFlatten
@SkipParentValidation
public class VirtualWANInner extends Resource {
/**
* Vpn encryption to be disabled or not.
*/
@JsonProperty(value = "properties.disableVpnEncryption")
private Boolean disableVpnEncryption;
/**
* List of VirtualHubs in the VirtualWAN.
*/
@JsonProperty(value = "properties.virtualHubs", access = JsonProperty.Access.WRITE_ONLY)
private List<SubResource> virtualHubs;
/**
* List of VpnSites in the VirtualWAN.
*/
@JsonProperty(value = "properties.vpnSites", access = JsonProperty.Access.WRITE_ONLY)
private List<SubResource> vpnSites;
/**
* True if branch to branch traffic is allowed.
*/
@JsonProperty(value = "properties.allowBranchToBranchTraffic")
private Boolean allowBranchToBranchTraffic;
/**
* True if Vnet to Vnet traffic is allowed.
*/
@JsonProperty(value = "properties.allowVnetToVnetTraffic")
private Boolean allowVnetToVnetTraffic;
/**
* The office local breakout category. Possible values include: 'Optimize',
* 'OptimizeAndAllow', 'All', 'None'.
*/
@JsonProperty(value = "properties.office365LocalBreakoutCategory")
private OfficeTrafficCategory office365LocalBreakoutCategory;
/**
* The provisioning state of the virtual WAN resource. Possible values
* include: 'Succeeded', 'Updating', 'Deleting', 'Failed'.
*/
@JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY)
private ProvisioningState provisioningState;
/**
* The type of the VirtualWAN.
*/
@JsonProperty(value = "properties.type")
private String virtualWANType;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
@JsonProperty(value = "etag", access = JsonProperty.Access.WRITE_ONLY)
private String etag;
/**
* Resource ID.
*/
@JsonProperty(value = "id")
private String id;
/**
* Get vpn encryption to be disabled or not.
*
* @return the disableVpnEncryption value
*/
public Boolean disableVpnEncryption() {
return this.disableVpnEncryption;
}
/**
* Set vpn encryption to be disabled or not.
*
* @param disableVpnEncryption the disableVpnEncryption value to set
* @return the VirtualWANInner object itself.
*/
public VirtualWANInner withDisableVpnEncryption(Boolean disableVpnEncryption) {
this.disableVpnEncryption = disableVpnEncryption;
return this;
}
/**
* Get list of VirtualHubs in the VirtualWAN.
*
* @return the virtualHubs value
*/
public List<SubResource> virtualHubs() {
return this.virtualHubs;
}
/**
* Get list of VpnSites in the VirtualWAN.
*
* @return the vpnSites value
*/
public List<SubResource> vpnSites() {
return this.vpnSites;
}
/**
* Get true if branch to branch traffic is allowed.
*
* @return the allowBranchToBranchTraffic value
*/
public Boolean allowBranchToBranchTraffic() {
return this.allowBranchToBranchTraffic;
}
/**
* Set true if branch to branch traffic is allowed.
*
* @param allowBranchToBranchTraffic the allowBranchToBranchTraffic value to set
* @return the VirtualWANInner object itself.
*/
public VirtualWANInner withAllowBranchToBranchTraffic(Boolean allowBranchToBranchTraffic) {
this.allowBranchToBranchTraffic = allowBranchToBranchTraffic;
return this;
}
/**
* Get true if Vnet to Vnet traffic is allowed.
*
* @return the allowVnetToVnetTraffic value
*/
public Boolean allowVnetToVnetTraffic() {
return this.allowVnetToVnetTraffic;
}
/**
* Set true if Vnet to Vnet traffic is allowed.
*
* @param allowVnetToVnetTraffic the allowVnetToVnetTraffic value to set
* @return the VirtualWANInner object itself.
*/
public VirtualWANInner withAllowVnetToVnetTraffic(Boolean allowVnetToVnetTraffic) {
this.allowVnetToVnetTraffic = allowVnetToVnetTraffic;
return this;
}
/**
* Get the office local breakout category. Possible values include: 'Optimize', 'OptimizeAndAllow', 'All', 'None'.
*
* @return the office365LocalBreakoutCategory value
*/
public OfficeTrafficCategory office365LocalBreakoutCategory() {
return this.office365LocalBreakoutCategory;
}
/**
* Set the office local breakout category. Possible values include: 'Optimize', 'OptimizeAndAllow', 'All', 'None'.
*
* @param office365LocalBreakoutCategory the office365LocalBreakoutCategory value to set
* @return the VirtualWANInner object itself.
*/
public VirtualWANInner withOffice365LocalBreakoutCategory(OfficeTrafficCategory office365LocalBreakoutCategory) {
this.office365LocalBreakoutCategory = office365LocalBreakoutCategory;
return this;
}
/**
* Get the provisioning state of the virtual WAN resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed'.
*
* @return the provisioningState value
*/
public ProvisioningState provisioningState() {
return this.provisioningState;
}
/**
* Get the type of the VirtualWAN.
*
* @return the virtualWANType value
*/
public String virtualWANType() {
return this.virtualWANType;
}
/**
* Set the type of the VirtualWAN.
*
* @param virtualWANType the virtualWANType value to set
* @return the VirtualWANInner object itself.
*/
public VirtualWANInner withVirtualWANType(String virtualWANType) {
this.virtualWANType = virtualWANType;
return this;
}
/**
* Get a unique read-only string that changes whenever the resource is updated.
*
* @return the etag value
*/
public String etag() {
return this.etag;
}
/**
* Get resource ID.
*
* @return the id value
*/
public String id() {
return this.id;
}
/**
* Set resource ID.
*
* @param id the id value to set
* @return the VirtualWANInner object itself.
*/
public VirtualWANInner withId(String id) {
this.id = id;
return this;
}
}
| |
package org.apache.lucene.util;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
/**
* <code>TestBitVector</code> tests the <code>BitVector</code>, obviously.
*
* @author "Peter Mularien" <pmularien@deploy.com>
* @version $Id$
*/
public class TestBitVector extends TestCase
{
public TestBitVector(String s) {
super(s);
}
/**
* Test the default constructor on BitVectors of various sizes.
* @throws Exception
*/
public void testConstructSize() throws Exception {
doTestConstructOfSize(8);
doTestConstructOfSize(20);
doTestConstructOfSize(100);
doTestConstructOfSize(1000);
}
private void doTestConstructOfSize(int n) {
BitVector bv = new BitVector(n);
assertEquals(n,bv.size());
}
/**
* Test the get() and set() methods on BitVectors of various sizes.
* @throws Exception
*/
public void testGetSet() throws Exception {
doTestGetSetVectorOfSize(8);
doTestGetSetVectorOfSize(20);
doTestGetSetVectorOfSize(100);
doTestGetSetVectorOfSize(1000);
}
private void doTestGetSetVectorOfSize(int n) {
BitVector bv = new BitVector(n);
for(int i=0;i<bv.size();i++) {
// ensure a set bit can be git'
assertFalse(bv.get(i));
bv.set(i);
assertTrue(bv.get(i));
}
}
/**
* Test the clear() method on BitVectors of various sizes.
* @throws Exception
*/
public void testClear() throws Exception {
doTestClearVectorOfSize(8);
doTestClearVectorOfSize(20);
doTestClearVectorOfSize(100);
doTestClearVectorOfSize(1000);
}
private void doTestClearVectorOfSize(int n) {
BitVector bv = new BitVector(n);
for(int i=0;i<bv.size();i++) {
// ensure a set bit is cleared
assertFalse(bv.get(i));
bv.set(i);
assertTrue(bv.get(i));
bv.clear(i);
assertFalse(bv.get(i));
}
}
/**
* Test the count() method on BitVectors of various sizes.
* @throws Exception
*/
public void testCount() throws Exception {
doTestCountVectorOfSize(8);
doTestCountVectorOfSize(20);
doTestCountVectorOfSize(100);
doTestCountVectorOfSize(1000);
}
private void doTestCountVectorOfSize(int n) {
BitVector bv = new BitVector(n);
// test count when incrementally setting bits
for(int i=0;i<bv.size();i++) {
assertFalse(bv.get(i));
assertEquals(i,bv.count());
bv.set(i);
assertTrue(bv.get(i));
assertEquals(i+1,bv.count());
}
bv = new BitVector(n);
// test count when setting then clearing bits
for(int i=0;i<bv.size();i++) {
assertFalse(bv.get(i));
assertEquals(0,bv.count());
bv.set(i);
assertTrue(bv.get(i));
assertEquals(1,bv.count());
bv.clear(i);
assertFalse(bv.get(i));
assertEquals(0,bv.count());
}
}
/**
* Test writing and construction to/from Directory.
* @throws Exception
*/
public void testWriteRead() throws Exception {
doTestWriteRead(8);
doTestWriteRead(20);
doTestWriteRead(100);
doTestWriteRead(1000);
}
private void doTestWriteRead(int n) throws Exception {
Directory d = new RAMDirectory();
BitVector bv = new BitVector(n);
// test count when incrementally setting bits
for(int i=0;i<bv.size();i++) {
assertFalse(bv.get(i));
assertEquals(i,bv.count());
bv.set(i);
assertTrue(bv.get(i));
assertEquals(i+1,bv.count());
bv.write(d, "TESTBV");
BitVector compare = new BitVector(d, "TESTBV");
// compare bit vectors with bits set incrementally
assertTrue(doCompare(bv,compare));
}
}
/**
* Test r/w when size/count cause switching between bit-set and d-gaps file formats.
* @throws Exception
*/
public void testDgaps() throws IOException {
doTestDgaps(1,0,1);
doTestDgaps(10,0,1);
doTestDgaps(100,0,1);
doTestDgaps(1000,4,7);
doTestDgaps(10000,40,43);
doTestDgaps(100000,415,418);
doTestDgaps(1000000,3123,3126);
}
private void doTestDgaps(int size, int count1, int count2) throws IOException {
Directory d = new RAMDirectory();
BitVector bv = new BitVector(size);
for (int i=0; i<count1; i++) {
bv.set(i);
assertEquals(i+1,bv.count());
}
bv.write(d, "TESTBV");
// gradually increase number of set bits
for (int i=count1; i<count2; i++) {
BitVector bv2 = new BitVector(d, "TESTBV");
assertTrue(doCompare(bv,bv2));
bv = bv2;
bv.set(i);
assertEquals(i+1,bv.count());
bv.write(d, "TESTBV");
}
// now start decreasing number of set bits
for (int i=count2-1; i>=count1; i--) {
BitVector bv2 = new BitVector(d, "TESTBV");
assertTrue(doCompare(bv,bv2));
bv = bv2;
bv.clear(i);
assertEquals(i,bv.count());
bv.write(d, "TESTBV");
}
}
/**
* Compare two BitVectors.
* This should really be an equals method on the BitVector itself.
* @param bv One bit vector
* @param compare The second to compare
*/
private boolean doCompare(BitVector bv, BitVector compare) {
boolean equal = true;
for(int i=0;i<bv.size();i++) {
// bits must be equal
if(bv.get(i)!=compare.get(i)) {
equal = false;
break;
}
}
return equal;
}
}
| |
package abi40_0_0.expo.modules.network;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import abi40_0_0.org.unimodules.core.ExportedModule;
import abi40_0_0.org.unimodules.core.ModuleRegistry;
import abi40_0_0.org.unimodules.core.Promise;
import abi40_0_0.org.unimodules.core.interfaces.ActivityProvider;
import abi40_0_0.org.unimodules.core.interfaces.ExpoMethod;
import abi40_0_0.org.unimodules.core.interfaces.RegistryLifecycleListener;
import abi40_0_0.org.unimodules.interfaces.constants.ConstantsInterface;
import host.exp.exponent.utils.ToastHelper;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.nio.ByteOrder;
import java.util.Collections;
import java.util.List;
public class NetworkModule extends ExportedModule implements RegistryLifecycleListener {
private static final String NAME = "ExpoNetwork";
private static final String TAG = NetworkModule.class.getSimpleName();
private Context mContext;
private ModuleRegistry mModuleRegistry;
private ActivityProvider mActivityProvider;
private Activity mActivity;
private JSONObject mManifest;
public static enum NetworkStateType {
NONE("NONE"),
UNKNOWN("UNKNOWN"),
CELLULAR("CELLULAR"),
WIFI("WIFI"),
BLUETOOTH("BLUETOOTH"),
ETHERNET("ETHERNET"),
WIMAX("WIMAX"),
VPN("VPN"),
OTHER("OTHER");
private final String value;
NetworkStateType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public boolean equal(String value) {
return this.value.equals(value);
}
}
public NetworkModule(Context context) {
super(context);
mContext = context;
}
@Override
public String getName() {
return NAME;
}
@Override
public void onCreate(ModuleRegistry moduleRegistry) {
mModuleRegistry = moduleRegistry;
mActivityProvider = moduleRegistry.getModule(ActivityProvider.class);
mActivity = mActivityProvider.getCurrentActivity();
ConstantsInterface constants = moduleRegistry.getModule(ConstantsInterface.class);
if (constants != null && constants.getConstants().containsKey("manifest")) {
try {
mManifest = new JSONObject((String) constants.getConstants().get("manifest"));
} catch (ClassCastException | JSONException exception) {
exception.printStackTrace();
}
}
}
private WifiInfo getWifiInfo() {
try {
WifiManager manager = (WifiManager) mContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = manager.getConnectionInfo();
return wifiInfo;
} catch (Exception e) {
Log.e(TAG, e.getMessage());
throw e;
}
}
private NetworkStateType getConnectionType(NetworkInfo netinfo) {
switch (netinfo.getType()) {
case ConnectivityManager.TYPE_MOBILE:
case ConnectivityManager.TYPE_MOBILE_DUN:
return NetworkStateType.CELLULAR;
case ConnectivityManager.TYPE_WIFI:
return NetworkStateType.WIFI;
case ConnectivityManager.TYPE_BLUETOOTH:
return NetworkStateType.BLUETOOTH;
case ConnectivityManager.TYPE_ETHERNET:
return NetworkStateType.ETHERNET;
case ConnectivityManager.TYPE_WIMAX:
return NetworkStateType.WIMAX;
case ConnectivityManager.TYPE_VPN:
return NetworkStateType.VPN;
default:
return NetworkStateType.UNKNOWN;
}
}
private NetworkStateType getNetworkCapabilities(NetworkCapabilities nc) {
if (nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) return NetworkStateType.CELLULAR;
if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI_AWARE))
return NetworkStateType.WIFI;
if (nc.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH)) return NetworkStateType.BLUETOOTH;
if (nc.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) return NetworkStateType.ETHERNET;
if (nc.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) return NetworkStateType.VPN;
return NetworkStateType.UNKNOWN;
}
@ExpoMethod
public void getNetworkStateAsync(Promise promise) {
Bundle result = new Bundle();
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
//use getActiveNetworkInfo before api level 29
if (Build.VERSION.SDK_INT < 29) {
try {
NetworkInfo netInfo = cm.getActiveNetworkInfo();
result.putBoolean("isInternetReachable", netInfo.isConnected());
NetworkStateType mConnectionType = getConnectionType(netInfo);
result.putString("type", mConnectionType.getValue());
result.putBoolean("isConnected", !mConnectionType.equal("NONE") && !mConnectionType.equal("UNKNOWN"));
promise.resolve(result);
} catch (Exception e) {
promise.reject("ERR_NETWORK_NO_ACCESS_NETWORKINFO", "Unable to access network information", e);
}
} else {
try {
Network network = cm.getActiveNetwork();
boolean isInternetReachable = network != null;
NetworkStateType mConnectionType = null;
if (isInternetReachable) {
NetworkCapabilities nc = cm.getNetworkCapabilities(network);
mConnectionType = getNetworkCapabilities(nc);
result.putString("type", mConnectionType.getValue());
} else {
result.putString("type", NetworkStateType.NONE.getValue());
}
result.putBoolean("isInternetReachable", isInternetReachable);
result.putBoolean("isConnected", mConnectionType != null && !mConnectionType.equal("NONE") && !mConnectionType.equal("UNKNOWN"));
promise.resolve(result);
} catch (Exception e) {
promise.reject("ERR_NETWORK_NO_ACCESS_NETWORKINFO", "Unable to access network information", e);
}
}
}
@ExpoMethod
public void getIpAddressAsync(Promise promise) {
try {
Integer ipAddress = getWifiInfo().getIpAddress();
// Convert little-endian to big-endianif needed
if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
ipAddress = Integer.reverseBytes(ipAddress);
}
byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();
String ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
promise.resolve(ipAddressString);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
promise.reject("ERR_NETWORK_IP_ADDRESS", "Unknown Host Exception", e);
}
}
@ExpoMethod
public void getMacAddressAsync(String interfaceName, Promise promise) {
ToastHelper.INSTANCE.functionMayNotWorkOnAndroidRWarning("Network.getMacAddressAsync", mManifest);
promise.resolve("02:00:00:00:00:00");
}
@ExpoMethod
public void isAirplaneModeEnabledAsync(Promise promise) {
boolean isAirPlaneMode = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
promise.resolve(isAirPlaneMode);
}
}
| |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.ml.inference;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.action.support.master.MasterNodeRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.OriginSettingClient;
import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.routing.IndexRoutingTable;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.component.LifecycleListener;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.indices.InvalidAliasNameException;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.threadpool.Scheduler;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentFactory;
import org.elasticsearch.xpack.core.ml.MlMetadata;
import org.elasticsearch.xpack.core.ml.MlStatsIndex;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.InferenceStats;
import org.elasticsearch.xpack.core.ml.job.messages.Messages;
import org.elasticsearch.xpack.core.ml.job.persistence.ElasticsearchMappings;
import org.elasticsearch.xpack.core.ml.utils.ToXContentParams;
import org.elasticsearch.xpack.ml.MachineLearning;
import org.elasticsearch.xpack.ml.utils.persistence.ResultsPersisterService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
public class TrainedModelStatsService {
private static final Logger logger = LogManager.getLogger(TrainedModelStatsService.class);
private static final TimeValue PERSISTENCE_INTERVAL = TimeValue.timeValueSeconds(1);
private static final String STATS_UPDATE_SCRIPT_TEMPLATE = ""
+ " ctx._source.{0} += params.{0};\n"
+ " ctx._source.{1} += params.{1};\n"
+ " ctx._source.{2} += params.{2};\n"
+ " ctx._source.{3} += params.{3};\n"
+ " ctx._source.{4} = params.{4};";
// Script to only update if stats have increased since last persistence
private static final String STATS_UPDATE_SCRIPT = Messages.getMessage(
STATS_UPDATE_SCRIPT_TEMPLATE,
InferenceStats.MISSING_ALL_FIELDS_COUNT.getPreferredName(),
InferenceStats.INFERENCE_COUNT.getPreferredName(),
InferenceStats.FAILURE_COUNT.getPreferredName(),
InferenceStats.CACHE_MISS_COUNT.getPreferredName(),
InferenceStats.TIMESTAMP.getPreferredName()
);
private static final ToXContent.Params FOR_INTERNAL_STORAGE_PARAMS = new ToXContent.MapParams(
Collections.singletonMap(ToXContentParams.FOR_INTERNAL_STORAGE, "true")
);
private final Map<String, InferenceStats> statsQueue;
private final ResultsPersisterService resultsPersisterService;
private final OriginSettingClient client;
private final IndexNameExpressionResolver indexNameExpressionResolver;
private final ThreadPool threadPool;
private volatile Scheduler.Cancellable scheduledFuture;
private volatile boolean stopped;
private volatile ClusterState clusterState;
public TrainedModelStatsService(
ResultsPersisterService resultsPersisterService,
OriginSettingClient client,
IndexNameExpressionResolver indexNameExpressionResolver,
ClusterService clusterService,
ThreadPool threadPool
) {
this.resultsPersisterService = resultsPersisterService;
this.client = client;
this.indexNameExpressionResolver = indexNameExpressionResolver;
this.threadPool = threadPool;
this.statsQueue = new ConcurrentHashMap<>();
clusterService.addLifecycleListener(new LifecycleListener() {
@Override
public void beforeStart() {
start();
}
@Override
public void beforeStop() {
stop();
}
});
clusterService.addListener(this::setClusterState);
}
// visible for testing
void setClusterState(ClusterChangedEvent event) {
clusterState = event.state();
}
/**
* Queues the stats for storing.
* @param stats The stats to store or increment
* @param flush When `true`, this indicates that stats should be written as soon as possible.
* If `false`, stats are not persisted until the next periodic persistence action.
*/
public void queueStats(InferenceStats stats, boolean flush) {
if (stats.hasStats()) {
statsQueue.compute(
InferenceStats.docId(stats.getModelId(), stats.getNodeId()),
(k, previousStats) -> previousStats == null
? stats
: InferenceStats.accumulator(stats).merge(previousStats).currentStats(stats.getTimeStamp())
);
}
if (flush) {
threadPool.executor(MachineLearning.UTILITY_THREAD_POOL_NAME).execute(this::updateStats);
}
}
void stop() {
logger.debug("About to stop TrainedModelStatsService");
stopped = true;
statsQueue.clear();
ThreadPool.Cancellable cancellable = this.scheduledFuture;
if (cancellable != null) {
cancellable.cancel();
}
}
private boolean shouldStop() {
return stopped || MlMetadata.getMlMetadata(clusterState).isResetMode() || MlMetadata.getMlMetadata(clusterState).isUpgradeMode();
}
void start() {
logger.debug("About to start TrainedModelStatsService");
stopped = false;
scheduledFuture = threadPool.scheduleWithFixedDelay(
this::updateStats,
PERSISTENCE_INTERVAL,
MachineLearning.UTILITY_THREAD_POOL_NAME
);
}
void updateStats() {
if (clusterState == null || statsQueue.isEmpty() || stopped) {
return;
}
boolean isInUpgradeMode = MlMetadata.getMlMetadata(clusterState).isUpgradeMode();
if (isInUpgradeMode) {
logger.debug("Model stats not persisted as ml upgrade mode is enabled");
return;
}
if (MlMetadata.getMlMetadata(clusterState).isResetMode()) {
logger.debug("Model stats not persisted as ml reset_mode is enabled");
return;
}
if (verifyIndicesExistAndPrimaryShardsAreActive(clusterState, indexNameExpressionResolver) == false) {
try {
logger.debug("About to create the stats index as it does not exist yet");
createStatsIndexIfNecessary();
} catch (Exception e) {
// This exception occurs if, for some reason, the `createStatsIndexAndAliasIfNecessary` fails due to
// a concrete index of the alias name already existing. This error is recoverable eventually, but
// should NOT cause us to lose statistics.
if ((e instanceof InvalidAliasNameException) == false) {
logger.error("failure creating ml stats index for storing model stats", e);
return;
}
}
}
List<InferenceStats> stats = new ArrayList<>(statsQueue.size());
// We want a copy as the underlying concurrent map could be changed while iterating
// We don't want to accidentally grab updates twice
Set<String> keys = new HashSet<>(statsQueue.keySet());
for (String k : keys) {
InferenceStats inferenceStats = statsQueue.remove(k);
if (inferenceStats != null) {
stats.add(inferenceStats);
}
}
if (stats.isEmpty()) {
return;
}
BulkRequest bulkRequest = new BulkRequest();
stats.stream().map(TrainedModelStatsService::buildUpdateRequest).filter(Objects::nonNull).forEach(bulkRequest::add);
bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
if (bulkRequest.requests().isEmpty()) {
return;
}
if (shouldStop()) {
return;
}
String jobPattern = stats.stream().map(InferenceStats::getModelId).collect(Collectors.joining(","));
try {
resultsPersisterService.bulkIndexWithRetry(bulkRequest, jobPattern, () -> shouldStop() == false, (msg) -> {});
} catch (ElasticsearchException ex) {
logger.warn(() -> new ParameterizedMessage("failed to store stats for [{}]", jobPattern), ex);
}
}
static boolean verifyIndicesExistAndPrimaryShardsAreActive(ClusterState clusterState, IndexNameExpressionResolver expressionResolver) {
String[] indices = expressionResolver.concreteIndexNames(
clusterState,
IndicesOptions.LENIENT_EXPAND_OPEN_HIDDEN,
MlStatsIndex.writeAlias()
);
// If there are no indices, we need to make sure we attempt to create it properly
if (indices.length == 0) {
return false;
}
for (String index : indices) {
if (clusterState.metadata().hasIndex(index) == false) {
return false;
}
IndexRoutingTable routingTable = clusterState.getRoutingTable().index(index);
if (routingTable == null || routingTable.allPrimaryShardsActive() == false) {
return false;
}
}
return true;
}
private void createStatsIndexIfNecessary() {
final PlainActionFuture<Boolean> listener = new PlainActionFuture<>();
MlStatsIndex.createStatsIndexAndAliasIfNecessary(
client,
clusterState,
indexNameExpressionResolver,
MasterNodeRequest.DEFAULT_MASTER_NODE_TIMEOUT,
ActionListener.wrap(
r -> ElasticsearchMappings.addDocMappingIfMissing(
MlStatsIndex.writeAlias(),
MlStatsIndex::wrappedMapping,
client,
clusterState,
MasterNodeRequest.DEFAULT_MASTER_NODE_TIMEOUT,
listener
),
listener::onFailure
)
);
listener.actionGet();
logger.debug("Created stats index");
}
static UpdateRequest buildUpdateRequest(InferenceStats stats) {
try (XContentBuilder builder = XContentFactory.jsonBuilder()) {
Map<String, Object> params = new HashMap<>();
params.put(InferenceStats.FAILURE_COUNT.getPreferredName(), stats.getFailureCount());
params.put(InferenceStats.MISSING_ALL_FIELDS_COUNT.getPreferredName(), stats.getMissingAllFieldsCount());
params.put(InferenceStats.TIMESTAMP.getPreferredName(), stats.getTimeStamp().toEpochMilli());
params.put(InferenceStats.INFERENCE_COUNT.getPreferredName(), stats.getInferenceCount());
params.put(InferenceStats.CACHE_MISS_COUNT.getPreferredName(), stats.getCacheMissCount());
stats.toXContent(builder, FOR_INTERNAL_STORAGE_PARAMS);
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.upsert(builder)
.index(MlStatsIndex.writeAlias())
// Usually, there shouldn't be a conflict, but if there is, only around a single update should have happened
// out of band. If there is MANY more than that, something strange is happening and it should fail.
.retryOnConflict(3)
.id(InferenceStats.docId(stats.getModelId(), stats.getNodeId()))
.script(new Script(ScriptType.INLINE, "painless", STATS_UPDATE_SCRIPT, params))
.setRequireAlias(true);
return updateRequest;
} catch (IOException ex) {
logger.error(
() -> new ParameterizedMessage("[{}] [{}] failed to serialize stats for update.", stats.getModelId(), stats.getNodeId()),
ex
);
}
return null;
}
}
| |
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.master.file.meta;
import alluxio.AlluxioURI;
import alluxio.exception.AccessControlException;
import alluxio.exception.ExceptionMessage;
import alluxio.exception.FileAlreadyExistsException;
import alluxio.exception.InvalidPathException;
import alluxio.master.file.meta.options.MountInfo;
import alluxio.master.file.options.MountOptions;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
/**
* Unit tests for {@link MountTable}.
*/
public final class MountTableTest {
private MountTable mMountTable;
private final MountOptions mDefaultOptions = MountOptions.defaults();
/**
* Sets up a new {@link MountTable} before a test runs.
*/
@Before
public void before() {
mMountTable = new MountTable();
}
/**
* Tests the different methods of the {@link MountTable} class with a path.
*/
@Test
public void path() throws Exception {
// Test add()
mMountTable.add(new AlluxioURI("/mnt/foo"), new AlluxioURI("/foo"), mDefaultOptions);
mMountTable.add(new AlluxioURI("/mnt/bar"), new AlluxioURI("/bar"), mDefaultOptions);
try {
mMountTable.add(new AlluxioURI("/mnt/foo"), new AlluxioURI("/foo2"), mDefaultOptions);
Assert.fail("Should not be able to add a mount to an existing mount.");
} catch (FileAlreadyExistsException e) {
// Exception expected
Assert.assertEquals(ExceptionMessage.MOUNT_POINT_ALREADY_EXISTS.getMessage("/mnt/foo"),
e.getMessage());
}
try {
mMountTable.add(new AlluxioURI("/mnt/bar/baz"), new AlluxioURI("/baz"), mDefaultOptions);
} catch (InvalidPathException e) {
// Exception expected
Assert.assertEquals(
ExceptionMessage.MOUNT_POINT_PREFIX_OF_ANOTHER.getMessage("/mnt/bar", "/mnt/bar/baz"),
e.getMessage());
}
// Test resolve()
Assert.assertEquals(new AlluxioURI("/foo"),
mMountTable.resolve(new AlluxioURI("/mnt/foo")).getUri());
Assert.assertEquals(new AlluxioURI("/foo/x"),
mMountTable.resolve(new AlluxioURI("/mnt/foo/x")).getUri());
Assert.assertEquals(new AlluxioURI("/bar"),
mMountTable.resolve(new AlluxioURI("/mnt/bar")).getUri());
Assert.assertEquals(new AlluxioURI("/bar/y"),
mMountTable.resolve(new AlluxioURI("/mnt/bar/y")).getUri());
Assert.assertEquals(new AlluxioURI("/bar/baz"),
mMountTable.resolve(new AlluxioURI("/mnt/bar/baz")).getUri());
Assert.assertEquals(new AlluxioURI("/foobar"),
mMountTable.resolve(new AlluxioURI("/foobar")).getUri());
Assert.assertEquals(new AlluxioURI("/"), mMountTable.resolve(new AlluxioURI("/")).getUri());
// Test getMountPoint()
Assert.assertEquals("/mnt/foo", mMountTable.getMountPoint(new AlluxioURI("/mnt/foo")));
Assert.assertEquals("/mnt/foo", mMountTable.getMountPoint(new AlluxioURI("/mnt/foo/x")));
Assert.assertEquals("/mnt/bar", mMountTable.getMountPoint(new AlluxioURI("/mnt/bar")));
Assert.assertEquals("/mnt/bar", mMountTable.getMountPoint(new AlluxioURI("/mnt/bar/y")));
Assert.assertEquals("/mnt/bar", mMountTable.getMountPoint(new AlluxioURI("/mnt/bar/baz")));
Assert.assertNull(mMountTable.getMountPoint(new AlluxioURI("/mnt")));
Assert.assertNull(mMountTable.getMountPoint(new AlluxioURI("/")));
// Test isMountPoint()
Assert.assertFalse(mMountTable.isMountPoint(new AlluxioURI("/")));
Assert.assertTrue(mMountTable.isMountPoint(new AlluxioURI("/mnt/foo")));
Assert.assertFalse(mMountTable.isMountPoint(new AlluxioURI("/mnt/foo/bar")));
Assert.assertFalse(mMountTable.isMountPoint(new AlluxioURI("/mnt")));
Assert.assertFalse(mMountTable.isMountPoint(new AlluxioURI("/mnt/foo3")));
Assert.assertTrue(mMountTable.isMountPoint(new AlluxioURI("/mnt/bar")));
Assert.assertFalse(mMountTable.isMountPoint(new AlluxioURI("/mnt/bar/baz")));
// Test delete()
Assert.assertTrue(mMountTable.delete(new AlluxioURI("/mnt/bar")));
Assert.assertTrue(mMountTable.delete(new AlluxioURI("/mnt/foo")));
Assert.assertFalse(mMountTable.delete(new AlluxioURI("/mnt/foo")));
Assert.assertFalse(mMountTable.delete(new AlluxioURI("/")));
}
/**
* Tests the different methods of the {@link MountTable} class with a URI.
*/
@Test
public void uri() throws Exception {
// Test add()
mMountTable.add(new AlluxioURI("alluxio://localhost:1234/mnt/foo"),
new AlluxioURI("file://localhost:5678/foo"), mDefaultOptions);
mMountTable.add(new AlluxioURI("alluxio://localhost:1234/mnt/bar"),
new AlluxioURI("file://localhost:5678/bar"), mDefaultOptions);
try {
mMountTable.add(new AlluxioURI("alluxio://localhost:1234/mnt/foo"),
new AlluxioURI("hdfs://localhost:5678/foo2"), mDefaultOptions);
} catch (FileAlreadyExistsException e) {
// Exception expected
Assert.assertEquals(ExceptionMessage.MOUNT_POINT_ALREADY_EXISTS.getMessage("/mnt/foo"),
e.getMessage());
}
try {
mMountTable.add(new AlluxioURI("alluxio://localhost:1234/mnt/bar/baz"),
new AlluxioURI("hdfs://localhost:5678/baz"), mDefaultOptions);
} catch (InvalidPathException e) {
Assert.assertEquals(
ExceptionMessage.MOUNT_POINT_PREFIX_OF_ANOTHER.getMessage("/mnt/bar", "/mnt/bar/baz"),
e.getMessage());
}
// Test resolve()
Assert.assertEquals(new AlluxioURI("file://localhost:5678/foo"),
mMountTable.resolve(new AlluxioURI("alluxio://localhost:1234/mnt/foo")).getUri());
Assert.assertEquals(new AlluxioURI("file://localhost:5678/bar"),
mMountTable.resolve(new AlluxioURI("alluxio://localhost:1234/mnt/bar")).getUri());
Assert.assertEquals(new AlluxioURI("file://localhost:5678/bar/y"),
mMountTable.resolve(new AlluxioURI("alluxio://localhost:1234/mnt/bar/y")).getUri());
Assert.assertEquals(new AlluxioURI("file://localhost:5678/bar/baz"),
mMountTable.resolve(new AlluxioURI("alluxio://localhost:1234/mnt/bar/baz")).getUri());
// Test getMountPoint()
Assert.assertEquals("/mnt/foo",
mMountTable.getMountPoint(new AlluxioURI("alluxio://localhost:1234/mnt/foo")));
Assert.assertEquals("/mnt/bar",
mMountTable.getMountPoint(new AlluxioURI("alluxio://localhost:1234/mnt/bar")));
Assert.assertEquals("/mnt/bar",
mMountTable.getMountPoint(new AlluxioURI("alluxio://localhost:1234/mnt/bar/y")));
Assert.assertEquals("/mnt/bar",
mMountTable.getMountPoint(new AlluxioURI("alluxio://localhost:1234/mnt/bar/baz")));
Assert.assertNull(mMountTable.getMountPoint(new AlluxioURI("alluxio://localhost:1234/mnt")));
Assert.assertNull(mMountTable.getMountPoint(new AlluxioURI("alluxio://localhost:1234/")));
// Test isMountPoint()
Assert.assertFalse(mMountTable.isMountPoint(new AlluxioURI("alluxio://localhost:1234/")));
Assert.assertTrue(mMountTable.isMountPoint(new AlluxioURI("alluxio://localhost:1234/mnt/foo")));
Assert.assertFalse(
mMountTable.isMountPoint(new AlluxioURI("alluxio://localhost:1234/mnt/foo/bar")));
Assert.assertFalse(mMountTable.isMountPoint(new AlluxioURI("alluxio://localhost:1234/mnt")));
Assert
.assertFalse(mMountTable.isMountPoint(new AlluxioURI("alluxio://localhost:1234/mnt/foo2")));
Assert
.assertFalse(mMountTable.isMountPoint(new AlluxioURI("alluxio://localhost:1234/mnt/foo3")));
Assert.assertTrue(mMountTable.isMountPoint(new AlluxioURI("alluxio://localhost:1234/mnt/bar")));
Assert.assertFalse(
mMountTable.isMountPoint(new AlluxioURI("alluxio://localhost:1234/mnt/bar/baz")));
// Test delete()
Assert.assertTrue(mMountTable.delete(new AlluxioURI("alluxio://localhost:1234/mnt/bar")));
Assert.assertTrue(mMountTable.delete(new AlluxioURI("alluxio://localhost:1234/mnt/foo")));
Assert.assertFalse(mMountTable.delete(new AlluxioURI("alluxio://localhost:1234/mnt/foo")));
Assert.assertFalse(mMountTable.delete(new AlluxioURI("alluxio://localhost:1234/")));
}
/**
* Tests check of readonly mount points.
*/
@Test
public void readOnlyMount() throws Exception {
MountOptions options = MountOptions.defaults().setReadOnly(true);
String mountPath = "/mnt/foo";
AlluxioURI alluxioUri = new AlluxioURI("alluxio://localhost:1234" + mountPath);
mMountTable.add(alluxioUri, new AlluxioURI("hdfs://localhost:5678/foo"), options);
try {
mMountTable.checkUnderWritableMountPoint(alluxioUri);
Assert.fail("Readonly mount point should not be writable.");
} catch (AccessControlException e) {
// Exception expected
Assert.assertEquals(ExceptionMessage.MOUNT_READONLY.getMessage(alluxioUri, mountPath),
e.getMessage());
}
try {
String path = mountPath + "/sub/directory";
alluxioUri = new AlluxioURI("alluxio://localhost:1234" + path);
mMountTable.checkUnderWritableMountPoint(alluxioUri);
Assert.fail("Readonly mount point should not be writable.");
} catch (AccessControlException e) {
// Exception expected
Assert.assertEquals(ExceptionMessage.MOUNT_READONLY.getMessage(alluxioUri, mountPath),
e.getMessage());
}
}
/**
* Tests check of writable mount points.
*/
@Test
public void writableMount() throws Exception {
String mountPath = "/mnt/foo";
AlluxioURI alluxioUri = new AlluxioURI("alluxio://localhost:1234" + mountPath);
mMountTable
.add(alluxioUri, new AlluxioURI("hdfs://localhost:5678/foo"), MountOptions.defaults());
try {
mMountTable.checkUnderWritableMountPoint(alluxioUri);
} catch (AccessControlException e) {
Assert.fail("Default mount point should be writable.");
}
try {
String path = mountPath + "/sub/directory";
alluxioUri = new AlluxioURI("alluxio://localhost:1234" + path);
mMountTable.checkUnderWritableMountPoint(alluxioUri);
} catch (AccessControlException e) {
Assert.fail("Default mount point should be writable.");
}
}
/**
* Tests the method for getting a copy of the current mount table.
*/
@Test
public void getMountTable() throws Exception {
Map<String, MountInfo> mountTable = new HashMap<>(2);
mountTable.put("/mnt/foo", new MountInfo(new AlluxioURI("hdfs://localhost:5678/foo"),
MountOptions.defaults()));
mountTable.put("/mnt/bar", new MountInfo(new AlluxioURI("hdfs://localhost:5678/bar"),
MountOptions.defaults()));
for (Map.Entry<String, MountInfo> mountPoint : mountTable.entrySet()) {
MountInfo mountInfo = mountPoint.getValue();
mMountTable.add(new AlluxioURI("alluxio://localhost:1234" + mountPoint.getKey()),
mountInfo.getUfsUri(), mountInfo.getOptions());
}
Assert.assertEquals(mountTable, mMountTable.getMountTable());
}
}
| |
/*
* Copyright (c) 2007 BUSINESS OBJECTS SOFTWARE LIMITED
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Business Objects nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* SourceModelParenStripper.java
* Created: Jun 27, 2007
* By: mbyne
*/
package org.openquark.cal.compiler;
import org.openquark.cal.compiler.SourceModel.ArgBindings;
import org.openquark.cal.compiler.SourceModel.CALDoc;
import org.openquark.cal.compiler.SourceModel.Constraint;
import org.openquark.cal.compiler.SourceModel.Expr;
import org.openquark.cal.compiler.SourceModel.InstanceDefn;
import org.openquark.cal.compiler.SourceModel.Name;
import org.openquark.cal.compiler.SourceModel.TypeClassDefn;
import org.openquark.cal.compiler.SourceModel.TypeExprDefn;
import org.openquark.cal.compiler.SourceModel.TypeSignature;
/**
* This class is used to make a copy of a SourceModel with all the user
* inserted parentheses removed.
*
* @author Magnus Byne
*/
public class SourceModelParenStripper extends SourceModelCopier<Void> {
/**
* This does not copy the paren node
* @param parenthesized the source model element to be copied
* @param arg unused argument
* @return a deep copy of the source model element contained within the paren
*/
@Override
public Expr visit_Expr_Parenthesized(
Expr.Parenthesized parenthesized, Void arg) {
SourceModel.verifyArg(parenthesized, "parenthesized");
return (Expr)parenthesized.getExpression().accept(this, arg);
}
/**
* This does not copy the paren node
* @param parenthesized the source model element to be copied
* @param arg unused argument
* @return a deep copy of the source model element contained within the paren
*/
@Override
public TypeExprDefn visit_TypeExprDefn_Parenthesized(
TypeExprDefn.Parenthesized parenthesized, Void arg) {
return (TypeExprDefn)parenthesized.getTypeExprDefn().accept(this, arg);
}
/**
* This does not copy the paren field
* @param signature the source model element to be copied
* @param arg unused argument
* @return a deep copy of the source model element ignoring paren
*/
@Override
public TypeSignature visit_TypeSignature(
TypeSignature signature, Void arg) {
SourceModel.verifyArg(signature, "signature");
Constraint[] newConstraints = new Constraint[signature.getNConstraints()];
for (int i = 0; i < signature.getNConstraints(); i++) {
newConstraints[i] = (Constraint)signature.getNthConstraint(i).accept(this, arg);
}
return TypeSignature.make(
newConstraints,
(TypeExprDefn)signature.getTypeExprDefn().accept(this, arg));
}
/**
* @param defn the source model element to be copied
* @param arg unused argument
* @return a deep copy of the source model element ignoring parens
*/
@Override
public InstanceDefn visit_InstanceDefn(
InstanceDefn defn, Void arg) {
SourceModel.verifyArg(defn, "defn");
CALDoc.Comment.Instance newCALDocComment = null;
if (defn.getCALDocComment() != null) {
newCALDocComment = (CALDoc.Comment.Instance)defn.getCALDocComment().accept(this, arg);
}
Constraint.TypeClass[] newConstraints =
new Constraint.TypeClass[defn.getNConstraints()];
for (int i = 0; i < defn.getNConstraints(); i++) {
newConstraints[i] =
(Constraint.TypeClass)defn.getNthConstraint(i).accept(this, arg);
}
InstanceDefn.InstanceMethod[] newInstanceMethods =
new InstanceDefn.InstanceMethod[defn.getNInstanceMethods()];
for (int i = 0; i < defn.getNInstanceMethods(); i++) {
newInstanceMethods[i] =
(InstanceDefn.InstanceMethod)defn.getNthInstanceMethod(i).accept(this, arg);
}
return InstanceDefn.makeAnnotated(
newCALDocComment,
(Name.TypeClass)defn.getTypeClassName().accept(this, arg),
(InstanceDefn.InstanceTypeCons)defn.getInstanceTypeCons().accept(this, arg),
newConstraints,
newInstanceMethods,
defn.getSourceRange());
}
/**
* @param defn the source model element to be copied
* @param arg unused argument
* @return a deep copy of the source model element ignoring parens
*/
@Override
public TypeClassDefn visit_TypeClassDefn(
TypeClassDefn defn, Void arg) {
SourceModel.verifyArg(defn, "defn");
CALDoc.Comment.TypeClass newCALDocComment = null;
if (defn.getCALDocComment() != null) {
newCALDocComment = (CALDoc.Comment.TypeClass)defn.getCALDocComment().accept(this, arg);
}
Constraint.TypeClass[] newParentClassConstraints =
new Constraint.TypeClass[defn.getNParentClassConstraints()];
for (int i = 0; i < defn.getNParentClassConstraints(); i++) {
newParentClassConstraints[i] =
(Constraint.TypeClass)defn.getNthParentClassConstraint(i).accept(this, arg);
}
TypeClassDefn.ClassMethodDefn[] newClassMethodDefns =
new TypeClassDefn.ClassMethodDefn[defn.getNClassMethodDefns()];
for (int i = 0; i < defn.getNClassMethodDefns(); i++) {
newClassMethodDefns[i] =
(TypeClassDefn.ClassMethodDefn)defn.getNthClassMethodDefn(i).accept(this, arg);
}
return TypeClassDefn.makeAnnotated(
newCALDocComment, defn.getTypeClassName(),
(Name.TypeVar)defn.getTypeVar().accept(this, arg),
defn.getScope(), defn.isScopeExplicitlySpecified(),
newParentClassConstraints, newClassMethodDefns, defn.getSourceRange(), defn.getSourceRangeOfDefn(), false);
}
/**
* @param cons the source model element to be copied
* @param arg unused argument
* @return a deep copy of the source model element with explicit parens removed
*/
@Override
public InstanceDefn.InstanceTypeCons visit_InstanceDefn_InstanceTypeCons_TypeCons(
InstanceDefn.InstanceTypeCons.TypeCons cons, Void arg) {
SourceModel.verifyArg(cons, "cons");
final Name.TypeVar[] typeVars = cons.getTypeVars();
final int nTypeVars = typeVars.length;
final Name.TypeVar[] newTypeVars = new Name.TypeVar[nTypeVars];
for (int i = 0; i < nTypeVars; i++) {
newTypeVars[i] = (Name.TypeVar)typeVars[i].accept(this, arg);
}
return InstanceDefn.InstanceTypeCons.TypeCons.makeAnnotated(
(Name.TypeCons)cons.getTypeConsName().accept(this, arg),
newTypeVars,
cons.getSourceRange(),
cons.getSourceRangeOfDefn(),
false);
}
/**
* @param cons the source model element to be copied
* @param arg unused argument
* @return a deep copy of the source model element ignoring parens
*/
@Override
public Expr.Case.Alt visit_Expr_Case_Alt_UnpackDataCons(
Expr.Case.Alt.UnpackDataCons cons, Void arg) {
SourceModel.verifyArg(cons, "cons");
int nDataConsNames = cons.getNDataConsNames();
Name.DataCons[] newDataConsNameArray = new Name.DataCons[nDataConsNames];
for (int i = 0; i < nDataConsNames; i++) {
newDataConsNameArray[i] = (Name.DataCons)cons.getNthDataConsName(i).accept(this, arg);
}
return Expr.Case.Alt.UnpackDataCons.makeAnnotated(
newDataConsNameArray,
(ArgBindings)cons.getArgBindings().accept(this,arg),
(Expr)cons.getAltExpr().accept(this, arg), cons.getSourceRange());
}
}
| |
/*
* Copyright (c) 2011-2012, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: AxesWalker.java,v 1.2.4.1 2005/09/14 19:45:22 jeffsuttor Exp $
*/
package com.sun.org.apache.xpath.internal.axes;
import java.util.Vector;
import com.sun.org.apache.xalan.internal.res.XSLMessages;
import com.sun.org.apache.xml.internal.dtm.DTM;
import com.sun.org.apache.xml.internal.dtm.DTMAxisTraverser;
import com.sun.org.apache.xml.internal.dtm.DTMIterator;
import com.sun.org.apache.xpath.internal.Expression;
import com.sun.org.apache.xpath.internal.ExpressionOwner;
import com.sun.org.apache.xpath.internal.XPathContext;
import com.sun.org.apache.xpath.internal.XPathVisitor;
import com.sun.org.apache.xpath.internal.compiler.Compiler;
import com.sun.org.apache.xpath.internal.res.XPATHErrorResources;
/**
* Serves as common interface for axes Walkers, and stores common
* state variables.
*/
public class AxesWalker extends PredicatedNodeTest
implements Cloneable, PathComponent, ExpressionOwner
{
static final long serialVersionUID = -2966031951306601247L;
/**
* Construct an AxesWalker using a LocPathIterator.
*
* @param locPathIterator non-null reference to the parent iterator.
*/
public AxesWalker(LocPathIterator locPathIterator, int axis)
{
super( locPathIterator );
m_axis = axis;
}
public final WalkingIterator wi()
{
return (WalkingIterator)m_lpi;
}
/**
* Initialize an AxesWalker during the parse of the XPath expression.
*
* @param compiler The Compiler object that has information about this
* walker in the op map.
* @param opPos The op code position of this location step.
* @param stepType The type of location step.
*
* @throws javax.xml.transform.TransformerException
*/
public void init(Compiler compiler, int opPos, int stepType)
throws javax.xml.transform.TransformerException
{
initPredicateInfo(compiler, opPos);
// int testType = compiler.getOp(nodeTestOpPos);
}
/**
* Get a cloned AxesWalker.
*
* @return A new AxesWalker that can be used without mutating this one.
*
* @throws CloneNotSupportedException
*/
public Object clone() throws CloneNotSupportedException
{
// Do not access the location path itterator during this operation!
AxesWalker clone = (AxesWalker) super.clone();
//clone.setCurrentNode(clone.m_root);
// clone.m_isFresh = true;
return clone;
}
/**
* Do a deep clone of this walker, including next and previous walkers.
* If the this AxesWalker is on the clone list, don't clone but
* return the already cloned version.
*
* @param cloneOwner non-null reference to the cloned location path
* iterator to which this clone will be added.
* @param cloneList non-null vector of sources in odd elements, and the
* corresponding clones in even vectors.
*
* @return non-null clone, which may be a new clone, or may be a clone
* contained on the cloneList.
*/
AxesWalker cloneDeep(WalkingIterator cloneOwner, Vector cloneList)
throws CloneNotSupportedException
{
AxesWalker clone = findClone(this, cloneList);
if(null != clone)
return clone;
clone = (AxesWalker)this.clone();
clone.setLocPathIterator(cloneOwner);
if(null != cloneList)
{
cloneList.addElement(this);
cloneList.addElement(clone);
}
if(wi().m_lastUsedWalker == this)
cloneOwner.m_lastUsedWalker = clone;
if(null != m_nextWalker)
clone.m_nextWalker = m_nextWalker.cloneDeep(cloneOwner, cloneList);
// If you don't check for the cloneList here, you'll go into an
// recursive infinate loop.
if(null != cloneList)
{
if(null != m_prevWalker)
clone.m_prevWalker = m_prevWalker.cloneDeep(cloneOwner, cloneList);
}
else
{
if(null != m_nextWalker)
clone.m_nextWalker.m_prevWalker = clone;
}
return clone;
}
/**
* Find a clone that corresponds to the key argument.
*
* @param key The original AxesWalker for which there may be a clone.
* @param cloneList vector of sources in odd elements, and the
* corresponding clones in even vectors, may be null.
*
* @return A clone that corresponds to the key, or null if key not found.
*/
static AxesWalker findClone(AxesWalker key, Vector cloneList)
{
if(null != cloneList)
{
// First, look for clone on list.
int n = cloneList.size();
for (int i = 0; i < n; i+=2)
{
if(key == cloneList.elementAt(i))
return (AxesWalker)cloneList.elementAt(i+1);
}
}
return null;
}
/**
* Detaches the walker from the set which it iterated over, releasing
* any computational resources and placing the iterator in the INVALID
* state.
*/
public void detach()
{
m_currentNode = DTM.NULL;
m_dtm = null;
m_traverser = null;
m_isFresh = true;
m_root = DTM.NULL;
}
//=============== TreeWalker Implementation ===============
/**
* The root node of the TreeWalker, as specified in setRoot(int root).
* Note that this may actually be below the current node.
*
* @return The context node of the step.
*/
public int getRoot()
{
return m_root;
}
/**
* Get the analysis bits for this walker, as defined in the WalkerFactory.
* @return One of WalkerFactory#BIT_DESCENDANT, etc.
*/
public int getAnalysisBits()
{
int axis = getAxis();
int bit = WalkerFactory.getAnalysisBitFromAxes(axis);
return bit;
}
/**
* Set the root node of the TreeWalker.
* (Not part of the DOM2 TreeWalker interface).
*
* @param root The context node of this step.
*/
public void setRoot(int root)
{
// %OPT% Get this directly from the lpi.
XPathContext xctxt = wi().getXPathContext();
m_dtm = xctxt.getDTM(root);
m_traverser = m_dtm.getAxisTraverser(m_axis);
m_isFresh = true;
m_foundLast = false;
m_root = root;
m_currentNode = root;
if (DTM.NULL == root)
{
throw new RuntimeException(
XSLMessages.createXPATHMessage(XPATHErrorResources.ER_SETTING_WALKER_ROOT_TO_NULL, null)); //"\n !!!! Error! Setting the root of a walker to null!!!");
}
resetProximityPositions();
}
/**
* The node at which the TreeWalker is currently positioned.
* <br> The value must not be null. Alterations to the DOM tree may cause
* the current node to no longer be accepted by the TreeWalker's
* associated filter. currentNode may also be explicitly set to any node,
* whether or not it is within the subtree specified by the root node or
* would be accepted by the filter and whatToShow flags. Further
* traversal occurs relative to currentNode even if it is not part of the
* current view by applying the filters in the requested direction (not
* changing currentNode where no traversal is possible).
*
* @return The node at which the TreeWalker is currently positioned, only null
* if setRoot has not yet been called.
*/
public final int getCurrentNode()
{
return m_currentNode;
}
/**
* Set the next walker in the location step chain.
*
*
* @param walker Reference to AxesWalker derivative, or may be null.
*/
public void setNextWalker(AxesWalker walker)
{
m_nextWalker = walker;
}
/**
* Get the next walker in the location step chain.
*
*
* @return Reference to AxesWalker derivative, or null.
*/
public AxesWalker getNextWalker()
{
return m_nextWalker;
}
/**
* Set or clear the previous walker reference in the location step chain.
*
*
* @param walker Reference to previous walker reference in the location
* step chain, or null.
*/
public void setPrevWalker(AxesWalker walker)
{
m_prevWalker = walker;
}
/**
* Get the previous walker reference in the location step chain.
*
*
* @return Reference to previous walker reference in the location
* step chain, or null.
*/
public AxesWalker getPrevWalker()
{
return m_prevWalker;
}
/**
* This is simply a way to bottle-neck the return of the next node, for
* diagnostic purposes.
*
* @param n Node to return, or null.
*
* @return The argument.
*/
private int returnNextNode(int n)
{
return n;
}
/**
* Get the next node in document order on the axes.
*
* @return the next node in document order on the axes, or null.
*/
protected int getNextNode()
{
if (m_foundLast)
return DTM.NULL;
if (m_isFresh)
{
m_currentNode = m_traverser.first(m_root);
m_isFresh = false;
}
// I shouldn't have to do this the check for current node, I think.
// numbering\numbering24.xsl fails if I don't do this. I think
// it occurs as the walkers are backing up. -sb
else if(DTM.NULL != m_currentNode)
{
m_currentNode = m_traverser.next(m_root, m_currentNode);
}
if (DTM.NULL == m_currentNode)
this.m_foundLast = true;
return m_currentNode;
}
/**
* Moves the <code>TreeWalker</code> to the next visible node in document
* order relative to the current node, and returns the new node. If the
* current node has no next node, or if the search for nextNode attempts
* to step upward from the TreeWalker's root node, returns
* <code>null</code> , and retains the current node.
* @return The new node, or <code>null</code> if the current node has no
* next node in the TreeWalker's logical view.
*/
public int nextNode()
{
int nextNode = DTM.NULL;
AxesWalker walker = wi().getLastUsedWalker();
while (true)
{
if (null == walker)
break;
nextNode = walker.getNextNode();
if (DTM.NULL == nextNode)
{
walker = walker.m_prevWalker;
}
else
{
if (walker.acceptNode(nextNode) != DTMIterator.FILTER_ACCEPT)
{
continue;
}
if (null == walker.m_nextWalker)
{
wi().setLastUsedWalker(walker);
// return walker.returnNextNode(nextNode);
break;
}
else
{
AxesWalker prev = walker;
walker = walker.m_nextWalker;
walker.setRoot(nextNode);
walker.m_prevWalker = prev;
continue;
}
} // if(null != nextNode)
} // while(null != walker)
return nextNode;
}
//============= End TreeWalker Implementation =============
/**
* Get the index of the last node that can be itterated to.
*
*
* @param xctxt XPath runtime context.
*
* @return the index of the last node that can be itterated to.
*/
public int getLastPos(XPathContext xctxt)
{
int pos = getProximityPosition();
AxesWalker walker;
try
{
walker = (AxesWalker) clone();
}
catch (CloneNotSupportedException cnse)
{
return -1;
}
walker.setPredicateCount(m_predicateIndex);
walker.setNextWalker(null);
walker.setPrevWalker(null);
WalkingIterator lpi = wi();
AxesWalker savedWalker = lpi.getLastUsedWalker();
try
{
lpi.setLastUsedWalker(walker);
int next;
while (DTM.NULL != (next = walker.nextNode()))
{
pos++;
}
// TODO: Should probably save this in the iterator.
}
finally
{
lpi.setLastUsedWalker(savedWalker);
}
// System.out.println("pos: "+pos);
return pos;
}
//============= State Data =============
/**
* The DTM for the root. This can not be used, or must be changed,
* for the filter walker, or any walker that can have nodes
* from multiple documents.
* Never, ever, access this value without going through getDTM(int node).
*/
private DTM m_dtm;
/**
* Set the DTM for this walker.
*
* @param dtm Non-null reference to a DTM.
*/
public void setDefaultDTM(DTM dtm)
{
m_dtm = dtm;
}
/**
* Get the DTM for this walker.
*
* @return Non-null reference to a DTM.
*/
public DTM getDTM(int node)
{
//
return wi().getXPathContext().getDTM(node);
}
/**
* Returns true if all the nodes in the iteration well be returned in document
* order.
* Warning: This can only be called after setRoot has been called!
*
* @return true as a default.
*/
public boolean isDocOrdered()
{
return true;
}
/**
* Returns the axis being iterated, if it is known.
*
* @return Axis.CHILD, etc., or -1 if the axis is not known or is of multiple
* types.
*/
public int getAxis()
{
return m_axis;
}
/**
* This will traverse the heararchy, calling the visitor for
* each member. If the called visitor method returns
* false, the subtree should not be called.
*
* @param owner The owner of the visitor, where that path may be
* rewritten if needed.
* @param visitor The visitor whose appropriate method will be called.
*/
public void callVisitors(ExpressionOwner owner, XPathVisitor visitor)
{
if(visitor.visitStep(owner, this))
{
callPredicateVisitors(visitor);
if(null != m_nextWalker)
{
m_nextWalker.callVisitors(this, visitor);
}
}
}
/**
* @see ExpressionOwner#getExpression()
*/
public Expression getExpression()
{
return m_nextWalker;
}
/**
* @see ExpressionOwner#setExpression(Expression)
*/
public void setExpression(Expression exp)
{
exp.exprSetParent(this);
m_nextWalker = (AxesWalker)exp;
}
/**
* @see Expression#deepEquals(Expression)
*/
public boolean deepEquals(Expression expr)
{
if (!super.deepEquals(expr))
return false;
AxesWalker walker = (AxesWalker)expr;
if(this.m_axis != walker.m_axis)
return false;
return true;
}
/**
* The root node of the TreeWalker, as specified when it was created.
*/
transient int m_root = DTM.NULL;
/**
* The node at which the TreeWalker is currently positioned.
*/
private transient int m_currentNode = DTM.NULL;
/** True if an itteration has not begun. */
transient boolean m_isFresh;
/** The next walker in the location step chain.
* @serial */
protected AxesWalker m_nextWalker;
/** The previous walker in the location step chain, or null.
* @serial */
AxesWalker m_prevWalker;
/** The traversal axis from where the nodes will be filtered. */
protected int m_axis = -1;
/** The DTM inner traversal class, that corresponds to the super axis. */
protected DTMAxisTraverser m_traverser;
}
| |
package org.apache.helix.rest.server.resources.helix;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixException;
import org.apache.helix.PropertyPathBuilder;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.HelixConfigScope;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.ResourceConfig;
import org.apache.helix.model.StateModelDefinition;
import org.apache.helix.model.builder.HelixConfigScopeBuilder;
import org.apache.helix.zookeeper.api.client.RealmAwareZkClient;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.node.ObjectNode;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Path("/clusters/{clusterId}/resources")
public class ResourceAccessor extends AbstractHelixResource {
private final static Logger _logger = LoggerFactory.getLogger(ResourceAccessor.class);
public enum ResourceProperties {
idealState,
idealStates,
externalView,
externalViews,
resourceConfig,
}
public enum HealthStatus {
HEALTHY,
PARTIAL_HEALTHY,
UNHEALTHY
}
@GET
public Response getResources(@PathParam("clusterId") String clusterId) {
ObjectNode root = JsonNodeFactory.instance.objectNode();
root.put(Properties.id.name(), JsonNodeFactory.instance.textNode(clusterId));
RealmAwareZkClient zkClient = getRealmAwareZkClient();
ArrayNode idealStatesNode = root.putArray(ResourceProperties.idealStates.name());
ArrayNode externalViewsNode = root.putArray(ResourceProperties.externalViews.name());
List<String> idealStates = zkClient.getChildren(PropertyPathBuilder.idealState(clusterId));
List<String> externalViews = zkClient.getChildren(PropertyPathBuilder.externalView(clusterId));
if (idealStates != null) {
idealStatesNode.addAll((ArrayNode) OBJECT_MAPPER.valueToTree(idealStates));
} else {
return notFound();
}
if (externalViews != null) {
externalViewsNode.addAll((ArrayNode) OBJECT_MAPPER.valueToTree(externalViews));
}
return JSONRepresentation(root);
}
/**
* Returns health profile of all resources in the cluster
* @param clusterId
* @return JSON result
*/
@GET
@Path("health")
public Response getResourceHealth(@PathParam("clusterId") String clusterId) {
RealmAwareZkClient zkClient = getRealmAwareZkClient();
List<String> resourcesInIdealState =
zkClient.getChildren(PropertyPathBuilder.idealState(clusterId));
List<String> resourcesInExternalView =
zkClient.getChildren(PropertyPathBuilder.externalView(clusterId));
Map<String, String> resourceHealthResult = new HashMap<>();
for (String resourceName : resourcesInIdealState) {
if (resourcesInExternalView.contains(resourceName)) {
Map<String, String> partitionHealth = computePartitionHealth(clusterId, resourceName);
if (partitionHealth.isEmpty()
|| partitionHealth.values().contains(HealthStatus.UNHEALTHY.name())) {
// No partitions for a resource or there exists one or more UNHEALTHY partitions in this
// resource, UNHEALTHY
resourceHealthResult.put(resourceName, HealthStatus.UNHEALTHY.name());
} else if (partitionHealth.values().contains(HealthStatus.PARTIAL_HEALTHY.name())) {
// No UNHEALTHY partition, but one or more partially healthy partitions, resource is
// partially healthy
resourceHealthResult.put(resourceName, HealthStatus.PARTIAL_HEALTHY.name());
} else {
// No UNHEALTHY or partially healthy partitions and non-empty, resource is healthy
resourceHealthResult.put(resourceName, HealthStatus.HEALTHY.name());
}
} else {
// If a resource is not in ExternalView, then it is UNHEALTHY
resourceHealthResult.put(resourceName, HealthStatus.UNHEALTHY.name());
}
}
return JSONRepresentation(resourceHealthResult);
}
/**
* Returns health profile of all partitions for the corresponding resource in the cluster
* @param clusterId
* @param resourceName
* @return JSON result
* @throws IOException
*/
@GET
@Path("{resourceName}/health")
public Response getPartitionHealth(@PathParam("clusterId") String clusterId,
@PathParam("resourceName") String resourceName) {
return JSONRepresentation(computePartitionHealth(clusterId, resourceName));
}
@GET
@Path("{resourceName}")
public Response getResource(@PathParam("clusterId") String clusterId,
@PathParam("resourceName") String resourceName,
@DefaultValue("getResource") @QueryParam("command") String command) {
// Get the command. If not provided, the default would be "getResource"
Command cmd;
try {
cmd = Command.valueOf(command);
} catch (Exception e) {
return badRequest("Invalid command : " + command);
}
ConfigAccessor accessor = getConfigAccessor();
HelixAdmin admin = getHelixAdmin();
switch (cmd) {
case getResource:
ResourceConfig resourceConfig = accessor.getResourceConfig(clusterId, resourceName);
IdealState idealState = admin.getResourceIdealState(clusterId, resourceName);
ExternalView externalView = admin.getResourceExternalView(clusterId, resourceName);
Map<String, ZNRecord> resourceMap = new HashMap<>();
if (idealState != null) {
resourceMap.put(ResourceProperties.idealState.name(), idealState.getRecord());
} else {
return notFound();
}
resourceMap.put(ResourceProperties.resourceConfig.name(), null);
resourceMap.put(ResourceProperties.externalView.name(), null);
if (resourceConfig != null) {
resourceMap.put(ResourceProperties.resourceConfig.name(), resourceConfig.getRecord());
}
if (externalView != null) {
resourceMap.put(ResourceProperties.externalView.name(), externalView.getRecord());
}
return JSONRepresentation(resourceMap);
case validateWeight:
// Validate ResourceConfig for WAGED rebalance
Map<String, Boolean> validationResultMap;
try {
validationResultMap = admin.validateResourcesForWagedRebalance(clusterId,
Collections.singletonList(resourceName));
} catch (HelixException e) {
return badRequest(e.getMessage());
}
return JSONRepresentation(validationResultMap);
default:
_logger.error("Unsupported command :" + command);
return badRequest("Unsupported command :" + command);
}
}
@PUT
@Path("{resourceName}")
public Response addResource(@PathParam("clusterId") String clusterId,
@PathParam("resourceName") String resourceName,
@DefaultValue("-1") @QueryParam("numPartitions") int numPartitions,
@DefaultValue("") @QueryParam("stateModelRef") String stateModelRef,
@DefaultValue("SEMI_AUTO") @QueryParam("rebalancerMode") String rebalancerMode,
@DefaultValue("DEFAULT") @QueryParam("rebalanceStrategy") String rebalanceStrategy,
@DefaultValue("0") @QueryParam("bucketSize") int bucketSize,
@DefaultValue("-1") @QueryParam("maxPartitionsPerInstance") int maxPartitionsPerInstance,
@DefaultValue("addResource") @QueryParam("command") String command, String content) {
// Get the command. If not provided, the default would be "addResource"
Command cmd;
try {
cmd = Command.valueOf(command);
} catch (Exception e) {
return badRequest("Invalid command : " + command);
}
HelixAdmin admin = getHelixAdmin();
try {
switch (cmd) {
case addResource:
if (content.length() != 0) {
ZNRecord record;
try {
record = toZNRecord(content);
} catch (IOException e) {
_logger.error("Failed to deserialize user's input " + content + ", Exception: " + e);
return badRequest("Input is not a valid ZNRecord!");
}
if (record.getSimpleFields() != null) {
admin.addResource(clusterId, resourceName, new IdealState(record));
}
} else {
admin.addResource(clusterId, resourceName, numPartitions, stateModelRef, rebalancerMode,
rebalanceStrategy, bucketSize, maxPartitionsPerInstance);
}
break;
case addWagedResource:
// Check if content is valid
if (content == null || content.length() == 0) {
_logger.error("Input is null or empty!");
return badRequest("Input is null or empty!");
}
Map<String, ZNRecord> input;
// Content must supply both IdealState and ResourceConfig
try {
TypeReference<Map<String, ZNRecord>> typeRef =
new TypeReference<Map<String, ZNRecord>>() {
};
input = OBJECT_MAPPER.readValue(content, typeRef);
} catch (IOException e) {
_logger.error("Failed to deserialize user's input {}, Exception: {}", content, e);
return badRequest("Input is not a valid map of String-ZNRecord pairs!");
}
// Check if the map contains both IdealState and ResourceConfig
ZNRecord idealStateRecord =
input.get(ResourceAccessor.ResourceProperties.idealState.name());
ZNRecord resourceConfigRecord =
input.get(ResourceAccessor.ResourceProperties.resourceConfig.name());
if (idealStateRecord == null || resourceConfigRecord == null) {
_logger.error("Input does not contain both IdealState and ResourceConfig!");
return badRequest("Input does not contain both IdealState and ResourceConfig!");
}
// Add using HelixAdmin API
try {
admin.addResourceWithWeight(clusterId, new IdealState(idealStateRecord),
new ResourceConfig(resourceConfigRecord));
} catch (HelixException e) {
String errMsg = String.format("Failed to add resource %s with weight in cluster %s!",
idealStateRecord.getId(), clusterId);
_logger.error(errMsg, e);
return badRequest(errMsg);
}
break;
default:
_logger.error("Unsupported command :" + command);
return badRequest("Unsupported command :" + command);
}
} catch (Exception e) {
_logger.error("Error in adding a resource: " + resourceName, e);
return serverError(e);
}
return OK();
}
@POST
@Path("{resourceName}")
public Response updateResource(@PathParam("clusterId") String clusterId,
@PathParam("resourceName") String resourceName, @QueryParam("command") String command,
@DefaultValue("-1") @QueryParam("replicas") int replicas,
@DefaultValue("") @QueryParam("keyPrefix") String keyPrefix,
@DefaultValue("") @QueryParam("group") String group) {
Command cmd;
try {
cmd = Command.valueOf(command);
} catch (Exception e) {
return badRequest("Invalid command : " + command);
}
HelixAdmin admin = getHelixAdmin();
try {
switch (cmd) {
case enable:
admin.enableResource(clusterId, resourceName, true);
break;
case disable:
admin.enableResource(clusterId, resourceName, false);
break;
case rebalance:
if (replicas == -1) {
return badRequest("Number of replicas is needed for rebalancing!");
}
keyPrefix = keyPrefix.length() == 0 ? resourceName : keyPrefix;
admin.rebalance(clusterId, resourceName, replicas, keyPrefix, group);
break;
case enableWagedRebalance:
try {
admin.enableWagedRebalance(clusterId, Collections.singletonList(resourceName));
} catch (HelixException e) {
return badRequest(e.getMessage());
}
break;
default:
_logger.error("Unsupported command :" + command);
return badRequest("Unsupported command :" + command);
}
} catch (Exception e) {
_logger.error("Failed in updating resource : " + resourceName, e);
return badRequest(e.getMessage());
}
return OK();
}
@DELETE
@Path("{resourceName}")
public Response deleteResource(@PathParam("clusterId") String clusterId,
@PathParam("resourceName") String resourceName) {
HelixAdmin admin = getHelixAdmin();
try {
admin.dropResource(clusterId, resourceName);
} catch (Exception e) {
_logger.error("Error in deleting a resource: " + resourceName, e);
return serverError();
}
return OK();
}
@GET
@Path("{resourceName}/configs")
public Response getResourceConfig(@PathParam("clusterId") String clusterId,
@PathParam("resourceName") String resourceName) {
ConfigAccessor accessor = getConfigAccessor();
ResourceConfig resourceConfig = accessor.getResourceConfig(clusterId, resourceName);
if (resourceConfig != null) {
return JSONRepresentation(resourceConfig.getRecord());
}
return notFound();
}
@POST
@Path("{resourceName}/configs")
public Response updateResourceConfig(@PathParam("clusterId") String clusterId,
@PathParam("resourceName") String resourceName, @QueryParam("command") String commandStr,
String content) {
Command command;
if (commandStr == null || commandStr.isEmpty()) {
command = Command.update; // Default behavior to keep it backward-compatible
} else {
try {
command = getCommand(commandStr);
} catch (HelixException ex) {
return badRequest(ex.getMessage());
}
}
ZNRecord record;
try {
record = toZNRecord(content);
} catch (IOException e) {
_logger.error("Failed to deserialize user's input " + content + ", Exception: " + e);
return badRequest("Input is not a valid ZNRecord!");
}
ResourceConfig resourceConfig = new ResourceConfig(record);
ConfigAccessor configAccessor = getConfigAccessor();
try {
switch (command) {
case update:
configAccessor.updateResourceConfig(clusterId, resourceName, resourceConfig);
break;
case delete:
HelixConfigScope resourceScope =
new HelixConfigScopeBuilder(HelixConfigScope.ConfigScopeProperty.RESOURCE)
.forCluster(clusterId).forResource(resourceName).build();
configAccessor.remove(resourceScope, record);
break;
default:
return badRequest(String.format("Unsupported command: %s", command));
}
} catch (HelixException ex) {
return notFound(ex.getMessage());
} catch (Exception ex) {
_logger.error(String.format("Error in update resource config for resource: %s", resourceName),
ex);
return serverError(ex);
}
return OK();
}
@GET
@Path("{resourceName}/idealState")
public Response getResourceIdealState(@PathParam("clusterId") String clusterId,
@PathParam("resourceName") String resourceName) {
HelixAdmin admin = getHelixAdmin();
IdealState idealState = admin.getResourceIdealState(clusterId, resourceName);
if (idealState != null) {
return JSONRepresentation(idealState.getRecord());
}
return notFound();
}
@POST
@Path("{resourceName}/idealState")
public Response updateResourceIdealState(@PathParam("clusterId") String clusterId,
@PathParam("resourceName") String resourceName, @QueryParam("command") String commandStr,
String content) {
Command command;
if (commandStr == null || commandStr.isEmpty()) {
command = Command.update; // Default behavior is update
} else {
try {
command = getCommand(commandStr);
} catch (HelixException ex) {
return badRequest(ex.getMessage());
}
}
ZNRecord record;
try {
record = toZNRecord(content);
} catch (IOException e) {
_logger.error("Failed to deserialize user's input " + content + ", Exception: " + e);
return badRequest("Input is not a valid ZNRecord!");
}
IdealState idealState = new IdealState(record);
HelixAdmin helixAdmin = getHelixAdmin();
try {
switch (command) {
case update:
helixAdmin.updateIdealState(clusterId, resourceName, idealState);
break;
case delete: {
helixAdmin.removeFromIdealState(clusterId, resourceName, idealState);
}
break;
default:
return badRequest(String.format("Unsupported command: %s", command));
}
} catch (HelixException ex) {
return notFound(ex.getMessage()); // HelixAdmin throws a HelixException if it doesn't
// exist already
} catch (Exception ex) {
_logger.error(String.format("Failed to update the IdealState for resource: %s", resourceName),
ex);
return serverError(ex);
}
return OK();
}
@GET
@Path("{resourceName}/externalView")
public Response getResourceExternalView(@PathParam("clusterId") String clusterId,
@PathParam("resourceName") String resourceName) {
HelixAdmin admin = getHelixAdmin();
ExternalView externalView = admin.getResourceExternalView(clusterId, resourceName);
if (externalView != null) {
return JSONRepresentation(externalView.getRecord());
}
return notFound();
}
private Map<String, String> computePartitionHealth(String clusterId, String resourceName) {
HelixAdmin admin = getHelixAdmin();
IdealState idealState = admin.getResourceIdealState(clusterId, resourceName);
ExternalView externalView = admin.getResourceExternalView(clusterId, resourceName);
StateModelDefinition stateModelDef =
admin.getStateModelDef(clusterId, idealState.getStateModelDefRef());
String initialState = stateModelDef.getInitialState();
List<String> statesPriorityList = stateModelDef.getStatesPriorityList();
statesPriorityList = statesPriorityList.subList(0, statesPriorityList.indexOf(initialState)); // Trim
// stateList
// to
// initialState
// and
// above
int minActiveReplicas = idealState.getMinActiveReplicas();
// Start the logic that determines the health status of each partition
Map<String, String> partitionHealthResult = new HashMap<>();
Set<String> allPartitionNames = idealState.getPartitionSet();
if (!allPartitionNames.isEmpty()) {
for (String partitionName : allPartitionNames) {
int replicaCount =
idealState.getReplicaCount(idealState.getPreferenceList(partitionName).size());
// Simplify expectedStateCountMap by assuming that all instances are available to reduce
// computation load on this REST endpoint
LinkedHashMap<String, Integer> expectedStateCountMap =
stateModelDef.getStateCountMap(replicaCount, replicaCount);
// Extract all states into Collections from ExternalView
Map<String, String> stateMapInExternalView = externalView.getStateMap(partitionName);
Collection<String> allReplicaStatesInExternalView =
(stateMapInExternalView != null && !stateMapInExternalView.isEmpty())
? stateMapInExternalView.values()
: Collections.<String> emptyList();
int numActiveReplicasInExternalView = 0;
HealthStatus status = HealthStatus.HEALTHY;
// Go through all states that are "active" states (higher priority than InitialState)
for (int statePriorityIndex = 0; statePriorityIndex < statesPriorityList
.size(); statePriorityIndex++) {
String currentState = statesPriorityList.get(statePriorityIndex);
int currentStateCountInIdealState = expectedStateCountMap.get(currentState);
int currentStateCountInExternalView =
Collections.frequency(allReplicaStatesInExternalView, currentState);
numActiveReplicasInExternalView += currentStateCountInExternalView;
// Top state counts must match, if not, unhealthy
if (statePriorityIndex == 0
&& currentStateCountInExternalView != currentStateCountInIdealState) {
status = HealthStatus.UNHEALTHY;
break;
} else if (currentStateCountInExternalView < currentStateCountInIdealState) {
// For non-top states, if count in ExternalView is less than count in IdealState,
// partially healthy
status = HealthStatus.PARTIAL_HEALTHY;
}
}
if (numActiveReplicasInExternalView < minActiveReplicas) {
// If this partition does not satisfy the number of minimum active replicas, unhealthy
status = HealthStatus.UNHEALTHY;
}
partitionHealthResult.put(partitionName, status.name());
}
}
return partitionHealthResult;
}
}
| |
/*
* Copyright (c) 2006-2017 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.dmdirc.ui;
import com.dmdirc.logger.ErrorReportStatus;
import com.dmdirc.logger.ErrorReportingRunnable;
import com.dmdirc.logger.ProgramError;
import com.dmdirc.logger.SentryErrorReporter;
import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.CountDownLatch;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
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.JTextPane;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
/**
* The fatal error dialog is used to inform the user that a fatal error has occurred and to give them
* a chance to quit or restart the client.
*/
public final class FatalErrorDialog extends JDialog implements ActionListener {
/** Serialisation version ID. */
private static final long serialVersionUID = 3;
/** Fatal error to be shown in this dialog. */
private final ProgramError error;
/** Countdown latch. */
private final CountDownLatch countDownLatch;
/** Are we auto sending errors? */
private final boolean sendReports;
/** Restart client Button. */
private JButton restartButton;
/** Quit client button. */
private JButton quitButton;
/** Send error button. */
private JButton sendButton;
/** Info panel, informs the user what is happening. */
private JTextPane infoLabel;
/** Message label, contains details error information. */
private JTextPane messageLabel;
/** Fatal error icon. */
private ImageIcon icon;
/** Stack trace scroll pane. */
private JScrollPane scrollPane;
/** Do we need to restart? Else we quit. */
private boolean restart = true;
/**
* Creates a new fatal error dialog.
*
* @param error Error
*/
public FatalErrorDialog(final ProgramError error, final SentryErrorReporter sentryErrorReporter,
final CountDownLatch countDownLatch, final boolean sendReports) {
super(null, Dialog.ModalityType.TOOLKIT_MODAL);
setModal(true);
this.error = error;
this.countDownLatch = countDownLatch;
this.sendReports = sendReports;
initComponents();
layoutComponents();
new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() {
new ErrorReportingRunnable(sentryErrorReporter, error).run();
return null;
}
@Override
protected void done() {
allowClose();
}
}.execute();
setResizable(false);
CoreUIUtils.centreWindow(this);
}
/**
* Initialises the components for this dialog.
*/
private void initComponents() {
final JTextArea stacktraceField = new JTextArea();
infoLabel = new JTextPane(new DefaultStyledDocument());
infoLabel.setOpaque(false);
infoLabel.setEditable(false);
infoLabel.setHighlighter(null);
messageLabel = new JTextPane(new DefaultStyledDocument());
messageLabel.setOpaque(false);
messageLabel.setEditable(false);
messageLabel.setHighlighter(null);
final MutableAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setAlignment(sas, StyleConstants.ALIGN_JUSTIFIED);
scrollPane = new JScrollPane();
restartButton = new JButton();
sendButton = new JButton();
quitButton = new JButton();
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setTitle("DMDirc: Fatal Error");
infoLabel.setText("DMDirc has encountered a fatal error, and is "
+ "not able to recover. \nThe application will now terminate.");
messageLabel.setText("Description: " + error.getMessage());
((StyledDocument) infoLabel.getDocument()).setParagraphAttributes(0,
infoLabel.getText().length(), sas, false);
((StyledDocument) messageLabel.getDocument()).setParagraphAttributes(0,
messageLabel.getText().length(), sas, false);
icon = new ImageIcon(FatalErrorDialog.class.getResource("/com/dmdirc/res/error.png"));
stacktraceField.setEditable(false);
error.getThrowableAsString().ifPresent(stacktraceField::append);
stacktraceField.setCaretPosition(0);
scrollPane.setViewportView(stacktraceField);
restartButton.setText("Restart");
quitButton.setText("Quit");
sendButton.setText("Send");
final ErrorReportStatus status = error.getReportStatus();
restartButton.setEnabled(status.isTerminal());
quitButton.setEnabled(status.isTerminal());
updateSendButtonText(status);
restartButton.addActionListener(this);
sendButton.addActionListener(this);
quitButton.addActionListener(this);
}
/**
* lays the components out in the dialog.
*/
private void layoutComponents() {
final JPanel panel = new JPanel();
final JPanel blurb = new JPanel();
final JPanel info = new JPanel();
final JPanel buttons = new JPanel();
blurb.setLayout(new BorderLayout(5, 5));
info.setLayout(new BorderLayout(5, 5));
buttons.setLayout(new BoxLayout(buttons, BoxLayout.LINE_AXIS));
blurb.add(new JLabel(icon), BorderLayout.LINE_START);
blurb.add(infoLabel, BorderLayout.CENTER);
info.add(messageLabel, BorderLayout.NORTH);
info.add(scrollPane, BorderLayout.CENTER);
buttons.add(Box.createHorizontalGlue());
buttons.add(sendButton);
buttons.add(Box.createHorizontalStrut(5));
buttons.add(quitButton);
buttons.add(Box.createHorizontalStrut(5));
buttons.add(restartButton);
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panel.setLayout(new BorderLayout(5, 5));
panel.add(blurb, BorderLayout.NORTH);
panel.add(info, BorderLayout.CENTER);
panel.add(buttons, BorderLayout.SOUTH);
getContentPane().add(panel);
setSize(new Dimension(550, 260));
}
@Override
public void actionPerformed(final ActionEvent actionEvent) {
if (actionEvent.getSource() == sendButton) {
sendButton.setText("Sending...");
restartButton.setEnabled(false);
sendButton.setEnabled(false);
} else if (actionEvent.getSource() == quitButton) {
restart = false;
dispose();
} else {
dispose();
}
if (!sendReports) {
countDownLatch.countDown();
}
countDownLatch.countDown();
}
/**
* Returns the restart response of this dialog. This will default to true if the user is yet to
* make a choice.
*
* @return Whether to restart after this error
*/
public boolean getRestart() {
return restart;
}
/**
* Updates the send button with the specified status.
*
* @param status New error status
*/
private void updateSendButtonText(final ErrorReportStatus status) {
switch (status) {
case WAITING:
sendButton.setText("Send");
sendButton.setEnabled(true);
break;
case QUEUED:
sendButton.setText("Queued");
sendButton.setEnabled(false);
break;
case SENDING:
sendButton.setText("Sending");
sendButton.setEnabled(false);
break;
case ERROR:
sendButton.setText("Error, resend");
sendButton.setEnabled(true);
break;
case FINISHED:
sendButton.setText("Sent");
sendButton.setEnabled(false);
break;
case NOT_APPLICABLE:
sendButton.setText("N/A");
sendButton.setEnabled(false);
break;
default:
sendButton.setText("Send");
sendButton.setEnabled(true);
break;
}
}
private void allowClose() {
final ErrorReportStatus status = error.getReportStatus();
restartButton.setEnabled(status.isTerminal());
updateSendButtonText(status);
countDownLatch.countDown();
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.jstorm.daemon.supervisor;
import com.alibaba.jstorm.config.SupervisorRefreshConfig;
import com.alibaba.jstorm.metric.JStormMetricsReporter;
import java.io.File;
import java.util.Map;
import java.util.UUID;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import com.alibaba.jstorm.daemon.worker.WorkerReportError;
import com.alibaba.jstorm.utils.DefaultUncaughtExceptionHandler;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import backtype.storm.Config;
import backtype.storm.messaging.IContext;
import backtype.storm.utils.LocalState;
import backtype.storm.utils.Utils;
import com.alibaba.jstorm.callback.AsyncLoopRunnable;
import com.alibaba.jstorm.callback.AsyncLoopThread;
import com.alibaba.jstorm.client.ConfigExtension;
import com.alibaba.jstorm.cluster.Cluster;
import com.alibaba.jstorm.cluster.Common;
import com.alibaba.jstorm.cluster.StormClusterState;
import com.alibaba.jstorm.cluster.StormConfig;
import com.alibaba.jstorm.daemon.worker.hearbeat.SyncContainerHb;
import com.alibaba.jstorm.event.EventManagerImp;
import com.alibaba.jstorm.event.EventManagerPusher;
import com.alibaba.jstorm.utils.JStormServerUtils;
import com.alibaba.jstorm.utils.JStormUtils;
/**
* Supervisor workflow
*
* 1. write SupervisorInfo to ZK
*
* 2. Every 10 seconds run SynchronizeSupervisor
* 2.1 download new topology
* 2.2 release useless worker
* 2.3 assign new task to /local-dir/supervisor/localstate
* 2.4 add one syncProcesses event
*
* 3. Every supervisor.monitor.frequency.secs run SyncProcesses
* 3.1 kill useless worker
* 3.2 start new worker
*
* 4. create heartbeat thread every supervisor.heartbeat.frequency.secs, write SupervisorInfo to ZK
*
* @author Johnfang (xiaojian.fxj@alibaba-inc.com)
*/
@SuppressWarnings({"unchecked", "unused"})
public class Supervisor {
private static Logger LOG = LoggerFactory.getLogger(Supervisor.class);
volatile MachineCheckStatus checkStatus = new MachineCheckStatus();
//volatile HealthStatus healthStatus = new HealthStatus();
/**
* create and start a supervisor
*
* @param conf : configuration (default.yaml & storm.yaml)
* @param sharedContext : null (right now)
* @return SupervisorManger: which is used to shutdown all workers and supervisor
*/
@SuppressWarnings("rawtypes")
public SupervisorManger mkSupervisor(Map conf, IContext sharedContext) throws Exception {
LOG.info("Starting Supervisor with conf " + conf);
/**
* Step 1: cleanup all files in /storm-local-dir/supervisor/tmp
*/
String path = StormConfig.supervisorTmpDir(conf);
FileUtils.cleanDirectory(new File(path));
/**
* Step 2: create ZK operation instance StormClusterState
*/
StormClusterState stormClusterState = Cluster.mk_storm_cluster_state(conf);
String hostName = JStormServerUtils.getHostName(conf);
WorkerReportError workerReportError = new WorkerReportError(stormClusterState, hostName);
/**
* Step 3, create LocalStat (a simple KV store)
* 3.1 create LocalState instance;
* 3.2 get supervisorId, if there's no supervisorId, create one
*/
LocalState localState = StormConfig.supervisorState(conf);
String supervisorId = (String) localState.get(Common.LS_ID);
if (supervisorId == null) {
supervisorId = UUID.randomUUID().toString();
localState.put(Common.LS_ID, supervisorId);
}
//clean LocalStat's zk-assignment & versions
localState.remove(Common.LS_LOCAl_ZK_ASSIGNMENTS);
localState.remove(Common.LS_LOCAL_ZK_ASSIGNMENT_VERSION);
Vector<AsyncLoopThread> threads = new Vector<>();
// Step 4 create HeartBeat
// every supervisor.heartbeat.frequency.secs, write SupervisorInfo to ZK
// sync heartbeat to nimbus
Heartbeat hb = new Heartbeat(conf, stormClusterState, supervisorId, localState, checkStatus);
hb.update();
AsyncLoopThread heartbeat = new AsyncLoopThread(hb, false, null, Thread.MIN_PRIORITY, true);
threads.add(heartbeat);
// Sync heartbeat to Apsara Container
AsyncLoopThread syncContainerHbThread = SyncContainerHb.mkSupervisorInstance(conf);
if (syncContainerHbThread != null) {
threads.add(syncContainerHbThread);
}
// Step 5 create and start sync Supervisor thread
// every supervisor.monitor.frequency.secs second run SyncSupervisor
ConcurrentHashMap<String, String> workerThreadPids = new ConcurrentHashMap<>();
SyncProcessEvent syncProcessEvent = new SyncProcessEvent(
supervisorId, conf, localState, workerThreadPids, sharedContext, workerReportError);
EventManagerImp syncSupEventManager = new EventManagerImp();
AsyncLoopThread syncSupEventThread = new AsyncLoopThread(syncSupEventManager);
threads.add(syncSupEventThread);
SyncSupervisorEvent syncSupervisorEvent = new SyncSupervisorEvent(
supervisorId, conf, syncSupEventManager, stormClusterState, localState, syncProcessEvent, hb);
int syncFrequency = JStormUtils.parseInt(conf.get(Config.SUPERVISOR_MONITOR_FREQUENCY_SECS));
EventManagerPusher syncSupervisorPusher = new EventManagerPusher(
syncSupEventManager, syncSupervisorEvent, syncFrequency);
AsyncLoopThread syncSupervisorThread = new AsyncLoopThread(syncSupervisorPusher);
threads.add(syncSupervisorThread);
// Step 6 start httpserver
Httpserver httpserver = null;
if (!StormConfig.local_mode(conf)) {
int port = ConfigExtension.getSupervisorDeamonHttpserverPort(conf);
httpserver = new Httpserver(port, conf);
httpserver.start();
}
//Step 7 check supervisor
if (!StormConfig.local_mode(conf)) {
if (ConfigExtension.isEnableCheckSupervisor(conf)) {
SupervisorHealth supervisorHealth = new SupervisorHealth(conf, checkStatus, supervisorId);
AsyncLoopThread healthThread = new AsyncLoopThread(supervisorHealth, false, null, Thread.MIN_PRIORITY, true);
threads.add(healthThread);
}
// init refresh config thread
AsyncLoopThread refreshConfigThread = new AsyncLoopThread(new SupervisorRefreshConfig(conf));
threads.add(refreshConfigThread);
}
// create SupervisorManger which can shutdown all supervisor and workers
return new SupervisorManger(
conf, supervisorId, threads, syncSupEventManager, httpserver, stormClusterState, workerThreadPids);
}
/**
* shutdown
*/
public void killSupervisor(SupervisorManger supervisor) {
supervisor.shutdown();
}
private void initShutdownHook(SupervisorManger supervisor) {
Runtime.getRuntime().addShutdownHook(new Thread(supervisor));
//JStormUtils.registerJStormSignalHandler();
}
private void createPid(Map conf) throws Exception {
String pidDir = StormConfig.supervisorPids(conf);
JStormServerUtils.createPid(pidDir);
}
/**
* start supervisor
*/
public void run() {
SupervisorManger supervisorManager;
try {
Map<Object, Object> conf = Utils.readStormConfig();
StormConfig.validate_distributed_mode(conf);
createPid(conf);
supervisorManager = mkSupervisor(conf, null);
JStormUtils.redirectOutput("/dev/null");
initShutdownHook(supervisorManager);
while (!supervisorManager.isFinishShutdown()) {
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
} catch (Throwable e) {
if (e instanceof OutOfMemoryError) {
LOG.error("Halting due to Out Of Memory Error...");
}
LOG.error("Fail to run supervisor ", e);
System.exit(1);
} finally {
LOG.info("Shutdown supervisor!!!");
}
}
/**
* start supervisor daemon
*/
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler());
JStormServerUtils.startTaobaoJvmMonitor();
Supervisor instance = new Supervisor();
instance.run();
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.protocolPB;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import com.google.common.collect.Lists;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.crypto.CryptoProtocolVersion;
import org.apache.hadoop.fs.BatchedRemoteIterator.BatchedEntries;
import org.apache.hadoop.fs.CacheFlag;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.CreateFlag;
import org.apache.hadoop.fs.FileAlreadyExistsException;
import org.apache.hadoop.fs.FsServerDefaults;
import org.apache.hadoop.fs.Options.Rename;
import org.apache.hadoop.fs.ParentNotDirectoryException;
import org.apache.hadoop.fs.UnresolvedLinkException;
import org.apache.hadoop.fs.XAttr;
import org.apache.hadoop.fs.XAttrSetFlag;
import org.apache.hadoop.fs.permission.AclEntry;
import org.apache.hadoop.fs.permission.AclStatus;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.inotify.EventBatchList;
import org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException;
import org.apache.hadoop.hdfs.protocol.BlockStoragePolicy;
import org.apache.hadoop.hdfs.protocol.CacheDirectiveEntry;
import org.apache.hadoop.hdfs.protocol.CacheDirectiveInfo;
import org.apache.hadoop.hdfs.protocol.CachePoolEntry;
import org.apache.hadoop.hdfs.protocol.CachePoolInfo;
import org.apache.hadoop.hdfs.protocol.ClientProtocol;
import org.apache.hadoop.hdfs.protocol.CorruptFileBlocks;
import org.apache.hadoop.hdfs.protocol.DSQuotaExceededException;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.DirectoryListing;
import org.apache.hadoop.hdfs.protocol.EncryptionZone;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.DatanodeReportType;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.RollingUpgradeAction;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.protocol.LastBlockWithStatus;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.protocol.NSQuotaExceededException;
import org.apache.hadoop.hdfs.protocol.RollingUpgradeInfo;
import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport;
import org.apache.hadoop.hdfs.protocol.SnapshottableDirectoryStatus;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.GetAclStatusRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.ModifyAclEntriesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.RemoveAclEntriesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.RemoveAclRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.RemoveDefaultAclRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.SetAclRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AbandonBlockRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AddBlockRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AddCacheDirectiveRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AddCachePoolRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AllowSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AppendRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AppendResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CachePoolEntryProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CheckAccessRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CompleteRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ConcatRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateSymlinkRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DeleteRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DeleteSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DisallowSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.FinalizeUpgradeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.FsyncRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetAdditionalDatanodeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetBlockLocationsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetBlockLocationsResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetContentSummaryRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetCurrentEditLogTxidRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDataEncryptionKeyRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDataEncryptionKeyResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDatanodeReportRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDatanodeStorageReportRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetEditsFromTxidRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFileInfoRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFileInfoResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFileLinkInfoRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFileLinkInfoResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFsStatusRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetLinkTargetRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetLinkTargetResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetListingRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetListingResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetPreferredBlockSizeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetServerDefaultsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetSnapshotDiffReportRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetSnapshotDiffReportResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetSnapshottableDirListingRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetSnapshottableDirListingResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetStoragePoliciesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetStoragePoliciesResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.IsFileClosedRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCacheDirectivesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCacheDirectivesResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCachePoolsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCachePoolsResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCorruptFileBlocksRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.MetaSaveRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.MkdirsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ModifyCacheDirectiveRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ModifyCachePoolRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RecoverLeaseRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RefreshNodesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RemoveCacheDirectiveRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RemoveCachePoolRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.Rename2RequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RenameRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RenameSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RenewLeaseRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ReportBadBlocksRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RestoreFailedStorageRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollEditsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollEditsResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollingUpgradeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollingUpgradeResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SaveNamespaceRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetBalancerBandwidthRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetOwnerRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetPermissionRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetQuotaRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetReplicationRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetSafeModeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetTimesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.TruncateRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.UpdateBlockForPipelineRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.UpdatePipelineRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetStoragePolicyRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos.CreateEncryptionZoneRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos.GetEZForPathRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos.ListEncryptionZonesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.GetXAttrsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.ListXAttrsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.RemoveXAttrRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.SetXAttrRequestProto;
import org.apache.hadoop.hdfs.security.token.block.DataEncryptionKey;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.hdfs.server.namenode.NotReplicatedYetException;
import org.apache.hadoop.hdfs.server.namenode.SafeModeException;
import org.apache.hadoop.hdfs.server.protocol.DatanodeStorageReport;
import org.apache.hadoop.hdfs.StorageType;
import org.apache.hadoop.io.EnumSetWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc.ProtobufHelper;
import org.apache.hadoop.ipc.ProtocolMetaInterface;
import org.apache.hadoop.ipc.ProtocolTranslator;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RpcClientUtil;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.proto.SecurityProtos.CancelDelegationTokenRequestProto;
import org.apache.hadoop.security.proto.SecurityProtos.GetDelegationTokenRequestProto;
import org.apache.hadoop.security.proto.SecurityProtos.GetDelegationTokenResponseProto;
import org.apache.hadoop.security.proto.SecurityProtos.RenewDelegationTokenRequestProto;
import org.apache.hadoop.security.token.Token;
import com.google.protobuf.ByteString;
import com.google.protobuf.ServiceException;
import static org.apache.hadoop.fs.BatchedRemoteIterator.BatchedListEntries;
import static org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos
.EncryptionZoneProto;
/**
* This class forwards NN's ClientProtocol calls as RPC calls to the NN server
* while translating from the parameter types used in ClientProtocol to the
* new PB types.
*/
@InterfaceAudience.Private
@InterfaceStability.Stable
public class ClientNamenodeProtocolTranslatorPB implements
ProtocolMetaInterface, ClientProtocol, Closeable, ProtocolTranslator {
final private ClientNamenodeProtocolPB rpcProxy;
static final GetServerDefaultsRequestProto VOID_GET_SERVER_DEFAULT_REQUEST =
GetServerDefaultsRequestProto.newBuilder().build();
private final static GetFsStatusRequestProto VOID_GET_FSSTATUS_REQUEST =
GetFsStatusRequestProto.newBuilder().build();
private final static SaveNamespaceRequestProto VOID_SAVE_NAMESPACE_REQUEST =
SaveNamespaceRequestProto.newBuilder().build();
private final static RollEditsRequestProto VOID_ROLLEDITS_REQUEST =
RollEditsRequestProto.getDefaultInstance();
private final static RefreshNodesRequestProto VOID_REFRESH_NODES_REQUEST =
RefreshNodesRequestProto.newBuilder().build();
private final static FinalizeUpgradeRequestProto
VOID_FINALIZE_UPGRADE_REQUEST =
FinalizeUpgradeRequestProto.newBuilder().build();
private final static GetDataEncryptionKeyRequestProto
VOID_GET_DATA_ENCRYPTIONKEY_REQUEST =
GetDataEncryptionKeyRequestProto.newBuilder().build();
private final static GetStoragePoliciesRequestProto
VOID_GET_STORAGE_POLICIES_REQUEST =
GetStoragePoliciesRequestProto.newBuilder().build();
public ClientNamenodeProtocolTranslatorPB(ClientNamenodeProtocolPB proxy) {
rpcProxy = proxy;
}
@Override
public void close() {
RPC.stopProxy(rpcProxy);
}
@Override
public LocatedBlocks getBlockLocations(String src, long offset, long length)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
GetBlockLocationsRequestProto req = GetBlockLocationsRequestProto
.newBuilder()
.setSrc(src)
.setOffset(offset)
.setLength(length)
.build();
try {
GetBlockLocationsResponseProto resp = rpcProxy.getBlockLocations(null,
req);
return resp.hasLocations() ?
PBHelper.convert(resp.getLocations()) : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public FsServerDefaults getServerDefaults() throws IOException {
GetServerDefaultsRequestProto req = VOID_GET_SERVER_DEFAULT_REQUEST;
try {
return PBHelper
.convert(rpcProxy.getServerDefaults(null, req).getServerDefaults());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public HdfsFileStatus create(String src, FsPermission masked,
String clientName, EnumSetWritable<CreateFlag> flag,
boolean createParent, short replication, long blockSize,
CryptoProtocolVersion[] supportedVersions)
throws AccessControlException, AlreadyBeingCreatedException,
DSQuotaExceededException, FileAlreadyExistsException,
FileNotFoundException, NSQuotaExceededException,
ParentNotDirectoryException, SafeModeException, UnresolvedLinkException,
IOException {
CreateRequestProto.Builder builder = CreateRequestProto.newBuilder()
.setSrc(src)
.setMasked(PBHelper.convert(masked))
.setClientName(clientName)
.setCreateFlag(PBHelper.convertCreateFlag(flag))
.setCreateParent(createParent)
.setReplication(replication)
.setBlockSize(blockSize);
builder.addAllCryptoProtocolVersion(PBHelper.convert(supportedVersions));
CreateRequestProto req = builder.build();
try {
CreateResponseProto res = rpcProxy.create(null, req);
return res.hasFs() ? PBHelper.convert(res.getFs()) : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean truncate(String src, long newLength, String clientName)
throws IOException, UnresolvedLinkException {
TruncateRequestProto req = TruncateRequestProto.newBuilder()
.setSrc(src)
.setNewLength(newLength)
.setClientName(clientName)
.build();
try {
return rpcProxy.truncate(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public LastBlockWithStatus append(String src, String clientName,
EnumSetWritable<CreateFlag> flag) throws AccessControlException,
DSQuotaExceededException, FileNotFoundException, SafeModeException,
UnresolvedLinkException, IOException {
AppendRequestProto req = AppendRequestProto.newBuilder().setSrc(src)
.setClientName(clientName).setFlag(PBHelper.convertCreateFlag(flag))
.build();
try {
AppendResponseProto res = rpcProxy.append(null, req);
LocatedBlock lastBlock = res.hasBlock() ? PBHelper
.convert(res.getBlock()) : null;
HdfsFileStatus stat = (res.hasStat()) ? PBHelper.convert(res.getStat())
: null;
return new LastBlockWithStatus(lastBlock, stat);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean setReplication(String src, short replication)
throws AccessControlException, DSQuotaExceededException,
FileNotFoundException, SafeModeException, UnresolvedLinkException,
IOException {
SetReplicationRequestProto req = SetReplicationRequestProto.newBuilder()
.setSrc(src)
.setReplication(replication)
.build();
try {
return rpcProxy.setReplication(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setPermission(String src, FsPermission permission)
throws AccessControlException, FileNotFoundException, SafeModeException,
UnresolvedLinkException, IOException {
SetPermissionRequestProto req = SetPermissionRequestProto.newBuilder()
.setSrc(src)
.setPermission(PBHelper.convert(permission))
.build();
try {
rpcProxy.setPermission(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setOwner(String src, String username, String groupname)
throws AccessControlException, FileNotFoundException, SafeModeException,
UnresolvedLinkException, IOException {
SetOwnerRequestProto.Builder req = SetOwnerRequestProto.newBuilder()
.setSrc(src);
if (username != null)
req.setUsername(username);
if (groupname != null)
req.setGroupname(groupname);
try {
rpcProxy.setOwner(null, req.build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void abandonBlock(ExtendedBlock b, long fileId, String src,
String holder) throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
AbandonBlockRequestProto req = AbandonBlockRequestProto.newBuilder()
.setB(PBHelper.convert(b)).setSrc(src).setHolder(holder)
.setFileId(fileId).build();
try {
rpcProxy.abandonBlock(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public LocatedBlock addBlock(String src, String clientName,
ExtendedBlock previous, DatanodeInfo[] excludeNodes, long fileId,
String[] favoredNodes)
throws AccessControlException, FileNotFoundException,
NotReplicatedYetException, SafeModeException, UnresolvedLinkException,
IOException {
AddBlockRequestProto.Builder req = AddBlockRequestProto.newBuilder()
.setSrc(src).setClientName(clientName).setFileId(fileId);
if (previous != null)
req.setPrevious(PBHelper.convert(previous));
if (excludeNodes != null)
req.addAllExcludeNodes(PBHelper.convert(excludeNodes));
if (favoredNodes != null) {
req.addAllFavoredNodes(Arrays.asList(favoredNodes));
}
try {
return PBHelper.convert(rpcProxy.addBlock(null, req.build()).getBlock());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public LocatedBlock getAdditionalDatanode(String src, long fileId,
ExtendedBlock blk, DatanodeInfo[] existings, String[] existingStorageIDs,
DatanodeInfo[] excludes,
int numAdditionalNodes, String clientName) throws AccessControlException,
FileNotFoundException, SafeModeException, UnresolvedLinkException,
IOException {
GetAdditionalDatanodeRequestProto req = GetAdditionalDatanodeRequestProto
.newBuilder()
.setSrc(src)
.setFileId(fileId)
.setBlk(PBHelper.convert(blk))
.addAllExistings(PBHelper.convert(existings))
.addAllExistingStorageUuids(Arrays.asList(existingStorageIDs))
.addAllExcludes(PBHelper.convert(excludes))
.setNumAdditionalNodes(numAdditionalNodes)
.setClientName(clientName)
.build();
try {
return PBHelper.convert(rpcProxy.getAdditionalDatanode(null, req)
.getBlock());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean complete(String src, String clientName,
ExtendedBlock last, long fileId)
throws AccessControlException, FileNotFoundException, SafeModeException,
UnresolvedLinkException, IOException {
CompleteRequestProto.Builder req = CompleteRequestProto.newBuilder()
.setSrc(src)
.setClientName(clientName)
.setFileId(fileId);
if (last != null)
req.setLast(PBHelper.convert(last));
try {
return rpcProxy.complete(null, req.build()).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void reportBadBlocks(LocatedBlock[] blocks) throws IOException {
ReportBadBlocksRequestProto req = ReportBadBlocksRequestProto.newBuilder()
.addAllBlocks(Arrays.asList(PBHelper.convertLocatedBlock(blocks)))
.build();
try {
rpcProxy.reportBadBlocks(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean rename(String src, String dst) throws UnresolvedLinkException,
IOException {
RenameRequestProto req = RenameRequestProto.newBuilder()
.setSrc(src)
.setDst(dst).build();
try {
return rpcProxy.rename(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void rename2(String src, String dst, Rename... options)
throws AccessControlException, DSQuotaExceededException,
FileAlreadyExistsException, FileNotFoundException,
NSQuotaExceededException, ParentNotDirectoryException, SafeModeException,
UnresolvedLinkException, IOException {
boolean overwrite = false;
if (options != null) {
for (Rename option : options) {
if (option == Rename.OVERWRITE) {
overwrite = true;
}
}
}
Rename2RequestProto req = Rename2RequestProto.newBuilder().
setSrc(src).
setDst(dst).setOverwriteDest(overwrite).
build();
try {
rpcProxy.rename2(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void concat(String trg, String[] srcs) throws IOException,
UnresolvedLinkException {
ConcatRequestProto req = ConcatRequestProto.newBuilder().
setTrg(trg).
addAllSrcs(Arrays.asList(srcs)).build();
try {
rpcProxy.concat(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean delete(String src, boolean recursive)
throws AccessControlException, FileNotFoundException, SafeModeException,
UnresolvedLinkException, IOException {
DeleteRequestProto req = DeleteRequestProto.newBuilder().setSrc(src).setRecursive(recursive).build();
try {
return rpcProxy.delete(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean mkdirs(String src, FsPermission masked, boolean createParent)
throws AccessControlException, FileAlreadyExistsException,
FileNotFoundException, NSQuotaExceededException,
ParentNotDirectoryException, SafeModeException, UnresolvedLinkException,
IOException {
MkdirsRequestProto req = MkdirsRequestProto.newBuilder()
.setSrc(src)
.setMasked(PBHelper.convert(masked))
.setCreateParent(createParent).build();
try {
return rpcProxy.mkdirs(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public DirectoryListing getListing(String src, byte[] startAfter,
boolean needLocation) throws AccessControlException,
FileNotFoundException, UnresolvedLinkException, IOException {
GetListingRequestProto req = GetListingRequestProto.newBuilder()
.setSrc(src)
.setStartAfter(ByteString.copyFrom(startAfter))
.setNeedLocation(needLocation).build();
try {
GetListingResponseProto result = rpcProxy.getListing(null, req);
if (result.hasDirList()) {
return PBHelper.convert(result.getDirList());
}
return null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void renewLease(String clientName) throws AccessControlException,
IOException {
RenewLeaseRequestProto req = RenewLeaseRequestProto.newBuilder()
.setClientName(clientName).build();
try {
rpcProxy.renewLease(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean recoverLease(String src, String clientName)
throws IOException {
RecoverLeaseRequestProto req = RecoverLeaseRequestProto.newBuilder()
.setSrc(src)
.setClientName(clientName).build();
try {
return rpcProxy.recoverLease(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public long[] getStats() throws IOException {
try {
return PBHelper.convert(rpcProxy.getFsStats(null,
VOID_GET_FSSTATUS_REQUEST));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public DatanodeInfo[] getDatanodeReport(DatanodeReportType type)
throws IOException {
GetDatanodeReportRequestProto req = GetDatanodeReportRequestProto
.newBuilder()
.setType(PBHelper.convert(type)).build();
try {
return PBHelper.convert(
rpcProxy.getDatanodeReport(null, req).getDiList());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public DatanodeStorageReport[] getDatanodeStorageReport(DatanodeReportType type)
throws IOException {
final GetDatanodeStorageReportRequestProto req
= GetDatanodeStorageReportRequestProto.newBuilder()
.setType(PBHelper.convert(type)).build();
try {
return PBHelper.convertDatanodeStorageReports(
rpcProxy.getDatanodeStorageReport(null, req).getDatanodeStorageReportsList());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public long getPreferredBlockSize(String filename) throws IOException,
UnresolvedLinkException {
GetPreferredBlockSizeRequestProto req = GetPreferredBlockSizeRequestProto
.newBuilder()
.setFilename(filename)
.build();
try {
return rpcProxy.getPreferredBlockSize(null, req).getBsize();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean setSafeMode(SafeModeAction action, boolean isChecked) throws IOException {
SetSafeModeRequestProto req = SetSafeModeRequestProto.newBuilder()
.setAction(PBHelper.convert(action)).setChecked(isChecked).build();
try {
return rpcProxy.setSafeMode(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void saveNamespace() throws AccessControlException, IOException {
try {
rpcProxy.saveNamespace(null, VOID_SAVE_NAMESPACE_REQUEST);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public long rollEdits() throws AccessControlException, IOException {
try {
RollEditsResponseProto resp = rpcProxy.rollEdits(null,
VOID_ROLLEDITS_REQUEST);
return resp.getNewSegmentTxId();
} catch (ServiceException se) {
throw ProtobufHelper.getRemoteException(se);
}
}
@Override
public boolean restoreFailedStorage(String arg)
throws AccessControlException, IOException{
RestoreFailedStorageRequestProto req = RestoreFailedStorageRequestProto
.newBuilder()
.setArg(arg).build();
try {
return rpcProxy.restoreFailedStorage(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void refreshNodes() throws IOException {
try {
rpcProxy.refreshNodes(null, VOID_REFRESH_NODES_REQUEST);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void finalizeUpgrade() throws IOException {
try {
rpcProxy.finalizeUpgrade(null, VOID_FINALIZE_UPGRADE_REQUEST);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public RollingUpgradeInfo rollingUpgrade(RollingUpgradeAction action) throws IOException {
final RollingUpgradeRequestProto r = RollingUpgradeRequestProto.newBuilder()
.setAction(PBHelper.convert(action)).build();
try {
final RollingUpgradeResponseProto proto = rpcProxy.rollingUpgrade(null, r);
if (proto.hasRollingUpgradeInfo()) {
return PBHelper.convert(proto.getRollingUpgradeInfo());
}
return null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public CorruptFileBlocks listCorruptFileBlocks(String path, String cookie)
throws IOException {
ListCorruptFileBlocksRequestProto.Builder req =
ListCorruptFileBlocksRequestProto.newBuilder().setPath(path);
if (cookie != null)
req.setCookie(cookie);
try {
return PBHelper.convert(
rpcProxy.listCorruptFileBlocks(null, req.build()).getCorrupt());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void metaSave(String filename) throws IOException {
MetaSaveRequestProto req = MetaSaveRequestProto.newBuilder()
.setFilename(filename).build();
try {
rpcProxy.metaSave(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public HdfsFileStatus getFileInfo(String src) throws AccessControlException,
FileNotFoundException, UnresolvedLinkException, IOException {
GetFileInfoRequestProto req = GetFileInfoRequestProto.newBuilder()
.setSrc(src).build();
try {
GetFileInfoResponseProto res = rpcProxy.getFileInfo(null, req);
return res.hasFs() ? PBHelper.convert(res.getFs()) : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public HdfsFileStatus getFileLinkInfo(String src)
throws AccessControlException, UnresolvedLinkException, IOException {
GetFileLinkInfoRequestProto req = GetFileLinkInfoRequestProto.newBuilder()
.setSrc(src).build();
try {
GetFileLinkInfoResponseProto result = rpcProxy.getFileLinkInfo(null, req);
return result.hasFs() ?
PBHelper.convert(rpcProxy.getFileLinkInfo(null, req).getFs()) : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public ContentSummary getContentSummary(String path)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
GetContentSummaryRequestProto req = GetContentSummaryRequestProto
.newBuilder()
.setPath(path)
.build();
try {
return PBHelper.convert(rpcProxy.getContentSummary(null, req)
.getSummary());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setQuota(String path, long namespaceQuota, long diskspaceQuota,
StorageType type)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
final SetQuotaRequestProto.Builder builder
= SetQuotaRequestProto.newBuilder()
.setPath(path)
.setNamespaceQuota(namespaceQuota)
.setDiskspaceQuota(diskspaceQuota);
if (type != null) {
builder.setStorageType(PBHelper.convertStorageType(type));
}
final SetQuotaRequestProto req = builder.build();
try {
rpcProxy.setQuota(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void fsync(String src, long fileId, String client,
long lastBlockLength)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
FsyncRequestProto req = FsyncRequestProto.newBuilder().setSrc(src)
.setClient(client).setLastBlockLength(lastBlockLength)
.setFileId(fileId).build();
try {
rpcProxy.fsync(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setTimes(String src, long mtime, long atime)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
SetTimesRequestProto req = SetTimesRequestProto.newBuilder()
.setSrc(src)
.setMtime(mtime)
.setAtime(atime)
.build();
try {
rpcProxy.setTimes(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void createSymlink(String target, String link, FsPermission dirPerm,
boolean createParent) throws AccessControlException,
FileAlreadyExistsException, FileNotFoundException,
ParentNotDirectoryException, SafeModeException, UnresolvedLinkException,
IOException {
CreateSymlinkRequestProto req = CreateSymlinkRequestProto.newBuilder()
.setTarget(target)
.setLink(link)
.setDirPerm(PBHelper.convert(dirPerm))
.setCreateParent(createParent)
.build();
try {
rpcProxy.createSymlink(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public String getLinkTarget(String path) throws AccessControlException,
FileNotFoundException, IOException {
GetLinkTargetRequestProto req = GetLinkTargetRequestProto.newBuilder()
.setPath(path).build();
try {
GetLinkTargetResponseProto rsp = rpcProxy.getLinkTarget(null, req);
return rsp.hasTargetPath() ? rsp.getTargetPath() : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public LocatedBlock updateBlockForPipeline(ExtendedBlock block,
String clientName) throws IOException {
UpdateBlockForPipelineRequestProto req = UpdateBlockForPipelineRequestProto
.newBuilder()
.setBlock(PBHelper.convert(block))
.setClientName(clientName)
.build();
try {
return PBHelper.convert(
rpcProxy.updateBlockForPipeline(null, req).getBlock());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void updatePipeline(String clientName, ExtendedBlock oldBlock,
ExtendedBlock newBlock, DatanodeID[] newNodes, String[] storageIDs) throws IOException {
UpdatePipelineRequestProto req = UpdatePipelineRequestProto.newBuilder()
.setClientName(clientName)
.setOldBlock(PBHelper.convert(oldBlock))
.setNewBlock(PBHelper.convert(newBlock))
.addAllNewNodes(Arrays.asList(PBHelper.convert(newNodes)))
.addAllStorageIDs(storageIDs == null ? null : Arrays.asList(storageIDs))
.build();
try {
rpcProxy.updatePipeline(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public Token<DelegationTokenIdentifier> getDelegationToken(Text renewer)
throws IOException {
GetDelegationTokenRequestProto req = GetDelegationTokenRequestProto
.newBuilder()
.setRenewer(renewer.toString())
.build();
try {
GetDelegationTokenResponseProto resp = rpcProxy.getDelegationToken(null, req);
return resp.hasToken() ? PBHelper.convertDelegationToken(resp.getToken())
: null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public long renewDelegationToken(Token<DelegationTokenIdentifier> token)
throws IOException {
RenewDelegationTokenRequestProto req = RenewDelegationTokenRequestProto.newBuilder().
setToken(PBHelper.convert(token)).
build();
try {
return rpcProxy.renewDelegationToken(null, req).getNewExpiryTime();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void cancelDelegationToken(Token<DelegationTokenIdentifier> token)
throws IOException {
CancelDelegationTokenRequestProto req = CancelDelegationTokenRequestProto
.newBuilder()
.setToken(PBHelper.convert(token))
.build();
try {
rpcProxy.cancelDelegationToken(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setBalancerBandwidth(long bandwidth) throws IOException {
SetBalancerBandwidthRequestProto req = SetBalancerBandwidthRequestProto.newBuilder()
.setBandwidth(bandwidth)
.build();
try {
rpcProxy.setBalancerBandwidth(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean isMethodSupported(String methodName) throws IOException {
return RpcClientUtil.isMethodSupported(rpcProxy,
ClientNamenodeProtocolPB.class, RPC.RpcKind.RPC_PROTOCOL_BUFFER,
RPC.getProtocolVersion(ClientNamenodeProtocolPB.class), methodName);
}
@Override
public DataEncryptionKey getDataEncryptionKey() throws IOException {
try {
GetDataEncryptionKeyResponseProto rsp = rpcProxy.getDataEncryptionKey(
null, VOID_GET_DATA_ENCRYPTIONKEY_REQUEST);
return rsp.hasDataEncryptionKey() ?
PBHelper.convert(rsp.getDataEncryptionKey()) : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean isFileClosed(String src) throws AccessControlException,
FileNotFoundException, UnresolvedLinkException, IOException {
IsFileClosedRequestProto req = IsFileClosedRequestProto.newBuilder()
.setSrc(src).build();
try {
return rpcProxy.isFileClosed(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public Object getUnderlyingProxyObject() {
return rpcProxy;
}
@Override
public String createSnapshot(String snapshotRoot, String snapshotName)
throws IOException {
final CreateSnapshotRequestProto.Builder builder
= CreateSnapshotRequestProto.newBuilder().setSnapshotRoot(snapshotRoot);
if (snapshotName != null) {
builder.setSnapshotName(snapshotName);
}
final CreateSnapshotRequestProto req = builder.build();
try {
return rpcProxy.createSnapshot(null, req).getSnapshotPath();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void deleteSnapshot(String snapshotRoot, String snapshotName)
throws IOException {
DeleteSnapshotRequestProto req = DeleteSnapshotRequestProto.newBuilder()
.setSnapshotRoot(snapshotRoot).setSnapshotName(snapshotName).build();
try {
rpcProxy.deleteSnapshot(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void allowSnapshot(String snapshotRoot) throws IOException {
AllowSnapshotRequestProto req = AllowSnapshotRequestProto.newBuilder()
.setSnapshotRoot(snapshotRoot).build();
try {
rpcProxy.allowSnapshot(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void disallowSnapshot(String snapshotRoot) throws IOException {
DisallowSnapshotRequestProto req = DisallowSnapshotRequestProto
.newBuilder().setSnapshotRoot(snapshotRoot).build();
try {
rpcProxy.disallowSnapshot(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void renameSnapshot(String snapshotRoot, String snapshotOldName,
String snapshotNewName) throws IOException {
RenameSnapshotRequestProto req = RenameSnapshotRequestProto.newBuilder()
.setSnapshotRoot(snapshotRoot).setSnapshotOldName(snapshotOldName)
.setSnapshotNewName(snapshotNewName).build();
try {
rpcProxy.renameSnapshot(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public SnapshottableDirectoryStatus[] getSnapshottableDirListing()
throws IOException {
GetSnapshottableDirListingRequestProto req =
GetSnapshottableDirListingRequestProto.newBuilder().build();
try {
GetSnapshottableDirListingResponseProto result = rpcProxy
.getSnapshottableDirListing(null, req);
if (result.hasSnapshottableDirList()) {
return PBHelper.convert(result.getSnapshottableDirList());
}
return null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public SnapshotDiffReport getSnapshotDiffReport(String snapshotRoot,
String fromSnapshot, String toSnapshot) throws IOException {
GetSnapshotDiffReportRequestProto req = GetSnapshotDiffReportRequestProto
.newBuilder().setSnapshotRoot(snapshotRoot)
.setFromSnapshot(fromSnapshot).setToSnapshot(toSnapshot).build();
try {
GetSnapshotDiffReportResponseProto result =
rpcProxy.getSnapshotDiffReport(null, req);
return PBHelper.convert(result.getDiffReport());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public long addCacheDirective(CacheDirectiveInfo directive,
EnumSet<CacheFlag> flags) throws IOException {
try {
AddCacheDirectiveRequestProto.Builder builder =
AddCacheDirectiveRequestProto.newBuilder().
setInfo(PBHelper.convert(directive));
if (!flags.isEmpty()) {
builder.setCacheFlags(PBHelper.convertCacheFlags(flags));
}
return rpcProxy.addCacheDirective(null, builder.build()).getId();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void modifyCacheDirective(CacheDirectiveInfo directive,
EnumSet<CacheFlag> flags) throws IOException {
try {
ModifyCacheDirectiveRequestProto.Builder builder =
ModifyCacheDirectiveRequestProto.newBuilder().
setInfo(PBHelper.convert(directive));
if (!flags.isEmpty()) {
builder.setCacheFlags(PBHelper.convertCacheFlags(flags));
}
rpcProxy.modifyCacheDirective(null, builder.build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeCacheDirective(long id)
throws IOException {
try {
rpcProxy.removeCacheDirective(null,
RemoveCacheDirectiveRequestProto.newBuilder().
setId(id).build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
private static class BatchedCacheEntries
implements BatchedEntries<CacheDirectiveEntry> {
private final ListCacheDirectivesResponseProto response;
BatchedCacheEntries(
ListCacheDirectivesResponseProto response) {
this.response = response;
}
@Override
public CacheDirectiveEntry get(int i) {
return PBHelper.convert(response.getElements(i));
}
@Override
public int size() {
return response.getElementsCount();
}
@Override
public boolean hasMore() {
return response.getHasMore();
}
}
@Override
public BatchedEntries<CacheDirectiveEntry>
listCacheDirectives(long prevId,
CacheDirectiveInfo filter) throws IOException {
if (filter == null) {
filter = new CacheDirectiveInfo.Builder().build();
}
try {
return new BatchedCacheEntries(
rpcProxy.listCacheDirectives(null,
ListCacheDirectivesRequestProto.newBuilder().
setPrevId(prevId).
setFilter(PBHelper.convert(filter)).
build()));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void addCachePool(CachePoolInfo info) throws IOException {
AddCachePoolRequestProto.Builder builder =
AddCachePoolRequestProto.newBuilder();
builder.setInfo(PBHelper.convert(info));
try {
rpcProxy.addCachePool(null, builder.build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void modifyCachePool(CachePoolInfo req) throws IOException {
ModifyCachePoolRequestProto.Builder builder =
ModifyCachePoolRequestProto.newBuilder();
builder.setInfo(PBHelper.convert(req));
try {
rpcProxy.modifyCachePool(null, builder.build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeCachePool(String cachePoolName) throws IOException {
try {
rpcProxy.removeCachePool(null,
RemoveCachePoolRequestProto.newBuilder().
setPoolName(cachePoolName).build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
private static class BatchedCachePoolEntries
implements BatchedEntries<CachePoolEntry> {
private final ListCachePoolsResponseProto proto;
public BatchedCachePoolEntries(ListCachePoolsResponseProto proto) {
this.proto = proto;
}
@Override
public CachePoolEntry get(int i) {
CachePoolEntryProto elem = proto.getEntries(i);
return PBHelper.convert(elem);
}
@Override
public int size() {
return proto.getEntriesCount();
}
@Override
public boolean hasMore() {
return proto.getHasMore();
}
}
@Override
public BatchedEntries<CachePoolEntry> listCachePools(String prevKey)
throws IOException {
try {
return new BatchedCachePoolEntries(
rpcProxy.listCachePools(null,
ListCachePoolsRequestProto.newBuilder().
setPrevPoolName(prevKey).build()));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void modifyAclEntries(String src, List<AclEntry> aclSpec)
throws IOException {
ModifyAclEntriesRequestProto req = ModifyAclEntriesRequestProto
.newBuilder().setSrc(src)
.addAllAclSpec(PBHelper.convertAclEntryProto(aclSpec)).build();
try {
rpcProxy.modifyAclEntries(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeAclEntries(String src, List<AclEntry> aclSpec)
throws IOException {
RemoveAclEntriesRequestProto req = RemoveAclEntriesRequestProto
.newBuilder().setSrc(src)
.addAllAclSpec(PBHelper.convertAclEntryProto(aclSpec)).build();
try {
rpcProxy.removeAclEntries(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeDefaultAcl(String src) throws IOException {
RemoveDefaultAclRequestProto req = RemoveDefaultAclRequestProto
.newBuilder().setSrc(src).build();
try {
rpcProxy.removeDefaultAcl(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeAcl(String src) throws IOException {
RemoveAclRequestProto req = RemoveAclRequestProto.newBuilder()
.setSrc(src).build();
try {
rpcProxy.removeAcl(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setAcl(String src, List<AclEntry> aclSpec) throws IOException {
SetAclRequestProto req = SetAclRequestProto.newBuilder()
.setSrc(src)
.addAllAclSpec(PBHelper.convertAclEntryProto(aclSpec))
.build();
try {
rpcProxy.setAcl(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public AclStatus getAclStatus(String src) throws IOException {
GetAclStatusRequestProto req = GetAclStatusRequestProto.newBuilder()
.setSrc(src).build();
try {
return PBHelper.convert(rpcProxy.getAclStatus(null, req));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void createEncryptionZone(String src, String keyName)
throws IOException {
final CreateEncryptionZoneRequestProto.Builder builder =
CreateEncryptionZoneRequestProto.newBuilder();
builder.setSrc(src);
if (keyName != null && !keyName.isEmpty()) {
builder.setKeyName(keyName);
}
CreateEncryptionZoneRequestProto req = builder.build();
try {
rpcProxy.createEncryptionZone(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public EncryptionZone getEZForPath(String src)
throws IOException {
final GetEZForPathRequestProto.Builder builder =
GetEZForPathRequestProto.newBuilder();
builder.setSrc(src);
final GetEZForPathRequestProto req = builder.build();
try {
final EncryptionZonesProtos.GetEZForPathResponseProto response =
rpcProxy.getEZForPath(null, req);
if (response.hasZone()) {
return PBHelper.convert(response.getZone());
} else {
return null;
}
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public BatchedEntries<EncryptionZone> listEncryptionZones(long id)
throws IOException {
final ListEncryptionZonesRequestProto req =
ListEncryptionZonesRequestProto.newBuilder()
.setId(id)
.build();
try {
EncryptionZonesProtos.ListEncryptionZonesResponseProto response =
rpcProxy.listEncryptionZones(null, req);
List<EncryptionZone> elements =
Lists.newArrayListWithCapacity(response.getZonesCount());
for (EncryptionZoneProto p : response.getZonesList()) {
elements.add(PBHelper.convert(p));
}
return new BatchedListEntries<EncryptionZone>(elements,
response.getHasMore());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setXAttr(String src, XAttr xAttr, EnumSet<XAttrSetFlag> flag)
throws IOException {
SetXAttrRequestProto req = SetXAttrRequestProto.newBuilder()
.setSrc(src)
.setXAttr(PBHelper.convertXAttrProto(xAttr))
.setFlag(PBHelper.convert(flag))
.build();
try {
rpcProxy.setXAttr(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public List<XAttr> getXAttrs(String src, List<XAttr> xAttrs)
throws IOException {
GetXAttrsRequestProto.Builder builder = GetXAttrsRequestProto.newBuilder();
builder.setSrc(src);
if (xAttrs != null) {
builder.addAllXAttrs(PBHelper.convertXAttrProto(xAttrs));
}
GetXAttrsRequestProto req = builder.build();
try {
return PBHelper.convert(rpcProxy.getXAttrs(null, req));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public List<XAttr> listXAttrs(String src)
throws IOException {
ListXAttrsRequestProto.Builder builder = ListXAttrsRequestProto.newBuilder();
builder.setSrc(src);
ListXAttrsRequestProto req = builder.build();
try {
return PBHelper.convert(rpcProxy.listXAttrs(null, req));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeXAttr(String src, XAttr xAttr) throws IOException {
RemoveXAttrRequestProto req = RemoveXAttrRequestProto
.newBuilder().setSrc(src)
.setXAttr(PBHelper.convertXAttrProto(xAttr)).build();
try {
rpcProxy.removeXAttr(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void checkAccess(String path, FsAction mode) throws IOException {
CheckAccessRequestProto req = CheckAccessRequestProto.newBuilder()
.setPath(path).setMode(PBHelper.convert(mode)).build();
try {
rpcProxy.checkAccess(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setStoragePolicy(String src, String policyName)
throws IOException {
SetStoragePolicyRequestProto req = SetStoragePolicyRequestProto
.newBuilder().setSrc(src).setPolicyName(policyName).build();
try {
rpcProxy.setStoragePolicy(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public BlockStoragePolicy[] getStoragePolicies() throws IOException {
try {
GetStoragePoliciesResponseProto response = rpcProxy
.getStoragePolicies(null, VOID_GET_STORAGE_POLICIES_REQUEST);
return PBHelper.convertStoragePolicies(response.getPoliciesList());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
public long getCurrentEditLogTxid() throws IOException {
GetCurrentEditLogTxidRequestProto req = GetCurrentEditLogTxidRequestProto
.getDefaultInstance();
try {
return rpcProxy.getCurrentEditLogTxid(null, req).getTxid();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public EventBatchList getEditsFromTxid(long txid) throws IOException {
GetEditsFromTxidRequestProto req = GetEditsFromTxidRequestProto.newBuilder()
.setTxid(txid).build();
try {
return PBHelper.convert(rpcProxy.getEditsFromTxid(null, req));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
}
| |
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.jssrc.internal;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.google.template.soy.jssrc.SoyJsSrcOptions;
import com.google.template.soy.jssrc.SoyJsSrcOptions.CodeStyle;
import com.google.template.soy.shared.internal.ApiCallScope;
import com.google.template.soy.soytree.AbstractReturningSoyNodeVisitor;
import com.google.template.soy.soytree.CallNode;
import com.google.template.soy.soytree.CallParamContentNode;
import com.google.template.soy.soytree.CallParamValueNode;
import com.google.template.soy.soytree.CssNode;
import com.google.template.soy.soytree.ForNode;
import com.google.template.soy.soytree.ForeachNode;
import com.google.template.soy.soytree.IfCondNode;
import com.google.template.soy.soytree.IfElseNode;
import com.google.template.soy.soytree.IfNode;
import com.google.template.soy.soytree.LetNode;
import com.google.template.soy.soytree.MsgHtmlTagNode;
import com.google.template.soy.soytree.MsgPlaceholderNode;
import com.google.template.soy.soytree.PrintNode;
import com.google.template.soy.soytree.RawTextNode;
import com.google.template.soy.soytree.SoyNode;
import com.google.template.soy.soytree.SoyNode.ParentSoyNode;
import com.google.template.soy.soytree.SwitchNode;
import com.google.template.soy.soytree.TemplateNode;
import com.google.template.soy.soytree.jssrc.GoogMsgNode;
import com.google.template.soy.soytree.jssrc.GoogMsgRefNode;
import java.util.Map;
/**
* Visitor to determine whether the output string for the subtree rooted at a given node is
* computable as the concatenation of one or more JS expressions. If this is false, it means the
* generated code for computing the node's output must include one or more full JS statements.
*
* <p> Precondition: MsgNode should not exist in the tree.
*
* <p> Important: This class is in {@link ApiCallScope} because it memoizes results that are
* reusable for the same parse tree. If we change the parse tree between uses of the scoped
* instance, then the results may not be correct. (In that case, we would need to take this class
* out of {@code ApiCallScope} and rewrite the code somehow to still take advantage of the
* memoized results to the extent that they remain correct.)
*
*/
@ApiCallScope
class IsComputableAsJsExprsVisitor extends AbstractReturningSoyNodeVisitor<Boolean> {
/** The options for generating JS source code. */
private final SoyJsSrcOptions jsSrcOptions;
/** The memoized results of past visits to nodes. */
private final Map<SoyNode, Boolean> memoizedResults;
/**
* @param jsSrcOptions The options for generating JS source code.
*/
@Inject
IsComputableAsJsExprsVisitor(SoyJsSrcOptions jsSrcOptions) {
this.jsSrcOptions = jsSrcOptions;
memoizedResults = Maps.newHashMap();
}
@Override protected Boolean visit(SoyNode node) {
if (memoizedResults.containsKey(node)) {
return memoizedResults.get(node);
} else {
Boolean result = super.visit(node);
memoizedResults.put(node, result);
return result;
}
}
// -----------------------------------------------------------------------------------------------
// Implementations for specific nodes.
@Override protected Boolean visitTemplateNode(TemplateNode node) {
return areChildrenComputableAsJsExprs(node);
}
@Override protected Boolean visitRawTextNode(RawTextNode node) {
return true;
}
@Override protected Boolean visitGoogMsgNode(GoogMsgNode node) {
return false;
}
@Override protected Boolean visitMsgPlaceholderNode(MsgPlaceholderNode node) {
return areChildrenComputableAsJsExprs(node);
}
@Override protected Boolean visitGoogMsgRefNode(GoogMsgRefNode node) {
return true;
}
@Override protected Boolean visitMsgHtmlTagNode(MsgHtmlTagNode node) {
return areChildrenComputableAsJsExprs(node);
}
@Override protected Boolean visitPrintNode(PrintNode node) {
return true;
}
@Override protected Boolean visitCssNode(CssNode node) {
return true;
}
@Override protected Boolean visitLetNode(LetNode node) {
return false;
}
@Override protected Boolean visitIfNode(IfNode node) {
// If all children are computable as JS expressions, then this 'if' statement can be written
// as an expression as well, using the ternary conditional operator ("? :").
return areChildrenComputableAsJsExprs(node);
}
@Override protected Boolean visitIfCondNode(IfCondNode node) {
return areChildrenComputableAsJsExprs(node);
}
@Override protected Boolean visitIfElseNode(IfElseNode node) {
return areChildrenComputableAsJsExprs(node);
}
@Override protected Boolean visitSwitchNode(SwitchNode node) {
return false;
}
@Override protected Boolean visitForeachNode(ForeachNode node) {
return false;
}
@Override protected Boolean visitForNode(ForNode node) {
return false;
}
@Override protected Boolean visitCallNode(CallNode node) {
return jsSrcOptions.getCodeStyle() == CodeStyle.CONCAT && areChildrenComputableAsJsExprs(node);
}
@Override protected Boolean visitCallParamValueNode(CallParamValueNode node) {
return true;
}
@Override protected Boolean visitCallParamContentNode(CallParamContentNode node) {
return areChildrenComputableAsJsExprs(node);
}
// -----------------------------------------------------------------------------------------------
// Private helpers.
/**
* Private helper to check whether all children of a given parent node satisfy
* IsComputableAsJsExprsVisitor.
* @param node The parent node whose children to check.
* @return True if all children satisfy IsComputableAsJsExprsVisitor.
*/
private boolean areChildrenComputableAsJsExprs(ParentSoyNode<?> node) {
for (SoyNode child : node.getChildren()) {
// Note: Save time by not visiting RawTextNode and PrintNode children.
if (! (child instanceof RawTextNode) && ! (child instanceof PrintNode)) {
if (! visit(child)) {
return false;
}
}
}
return true;
}
}
| |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react.views.image;
import javax.annotation.Nullable;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.os.SystemClock;
import com.facebook.common.util.UriUtil;
import com.facebook.drawee.controller.AbstractDraweeControllerBuilder;
import com.facebook.drawee.drawable.AutoRotateDrawable;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.controller.ForwardingControllerListener;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.GenericDraweeView;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.imagepipeline.request.BasePostprocessor;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.facebook.imagepipeline.request.Postprocessor;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.events.EventDispatcher;
/**
* Wrapper class around Fresco's GenericDraweeView, enabling persisting props across multiple view
* update and consistent processing of both static and network images.
*/
public class ReactImageView extends GenericDraweeView {
private static final int REMOTE_IMAGE_FADE_DURATION_MS = 300;
/*
* Implementation note re rounded corners:
*
* Fresco's built-in rounded corners only work for 'cover' resize mode -
* this is a limitation in Android itself. Fresco has a workaround for this, but
* it requires knowing the background color.
*
* So for the other modes, we use a postprocessor.
* Because the postprocessor uses a modified bitmap, that would just get cropped in
* 'cover' mode, so we fall back to Fresco's normal implementation.
*/
private static final Matrix sMatrix = new Matrix();
private static final Matrix sInverse = new Matrix();
private class RoundedCornerPostprocessor extends BasePostprocessor {
float getRadius(Bitmap source) {
ScalingUtils.getTransform(
sMatrix,
new Rect(0, 0, source.getWidth(), source.getHeight()),
source.getWidth(),
source.getHeight(),
0.0f,
0.0f,
mScaleType);
sMatrix.invert(sInverse);
return sInverse.mapRadius(mBorderRadius);
}
@Override
public void process(Bitmap output, Bitmap source) {
output.setHasAlpha(true);
if (mBorderRadius < 0.01f) {
super.process(output, source);
return;
}
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
Canvas canvas = new Canvas(output);
float radius = getRadius(source);
canvas.drawRoundRect(
new RectF(0, 0, source.getWidth(), source.getHeight()),
radius,
radius,
paint);
}
}
private @Nullable Uri mUri;
private @Nullable Drawable mLoadingImageDrawable;
private int mBorderColor;
private float mBorderWidth;
private float mBorderRadius;
private ScalingUtils.ScaleType mScaleType;
private boolean mIsDirty;
private boolean mIsLocalImage;
private final AbstractDraweeControllerBuilder mDraweeControllerBuilder;
private final RoundedCornerPostprocessor mRoundedCornerPostprocessor;
private @Nullable ControllerListener mControllerListener;
private @Nullable ControllerListener mControllerForTesting;
private final @Nullable Object mCallerContext;
private int mFadeDurationMs = -1;
private boolean mProgressiveRenderingEnabled;
// We can't specify rounding in XML, so have to do so here
private static GenericDraweeHierarchy buildHierarchy(Context context) {
return new GenericDraweeHierarchyBuilder(context.getResources())
.setRoundingParams(RoundingParams.fromCornersRadius(0))
.build();
}
public ReactImageView(
Context context,
AbstractDraweeControllerBuilder draweeControllerBuilder,
@Nullable Object callerContext) {
super(context, buildHierarchy(context));
mScaleType = ImageResizeMode.defaultValue();
mDraweeControllerBuilder = draweeControllerBuilder;
mRoundedCornerPostprocessor = new RoundedCornerPostprocessor();
mCallerContext = callerContext;
}
public void setShouldNotifyLoadEvents(boolean shouldNotify) {
if (!shouldNotify) {
mControllerListener = null;
} else {
final EventDispatcher mEventDispatcher = ((ReactContext) getContext()).
getNativeModule(UIManagerModule.class).getEventDispatcher();
mControllerListener = new BaseControllerListener<ImageInfo>() {
@Override
public void onSubmit(String id, Object callerContext) {
mEventDispatcher.dispatchEvent(
new ImageLoadEvent(getId(), SystemClock.uptimeMillis(), ImageLoadEvent.ON_LOAD_START)
);
}
@Override
public void onFinalImageSet(
String id,
@Nullable final ImageInfo imageInfo,
@Nullable Animatable animatable) {
if (imageInfo != null) {
mEventDispatcher.dispatchEvent(
new ImageLoadEvent(getId(), SystemClock.uptimeMillis(), ImageLoadEvent.ON_LOAD_END)
);
mEventDispatcher.dispatchEvent(
new ImageLoadEvent(getId(), SystemClock.uptimeMillis(), ImageLoadEvent.ON_LOAD)
);
}
}
@Override
public void onFailure(String id, Throwable throwable) {
mEventDispatcher.dispatchEvent(
new ImageLoadEvent(getId(), SystemClock.uptimeMillis(), ImageLoadEvent.ON_LOAD_END)
);
}
};
}
mIsDirty = true;
}
public void setBorderColor(int borderColor) {
mBorderColor = borderColor;
mIsDirty = true;
}
public void setBorderWidth(float borderWidth) {
mBorderWidth = PixelUtil.toPixelFromDIP(borderWidth);
mIsDirty = true;
}
public void setBorderRadius(float borderRadius) {
mBorderRadius = PixelUtil.toPixelFromDIP(borderRadius);
mIsDirty = true;
}
public void setScaleType(ScalingUtils.ScaleType scaleType) {
mScaleType = scaleType;
mIsDirty = true;
}
public void setSource(@Nullable String source) {
mUri = null;
if (source != null) {
try {
mUri = Uri.parse(source);
// Verify scheme is set, so that relative uri (used by static resources) are not handled.
if (mUri.getScheme() == null) {
mUri = null;
}
} catch (Exception e) {
// ignore malformed uri, then attempt to extract resource ID.
}
if (mUri == null) {
mUri = getResourceDrawableUri(getContext(), source);
mIsLocalImage = true;
} else {
mIsLocalImage = false;
}
}
mIsDirty = true;
}
public void setLoadingIndicatorSource(@Nullable String name) {
Drawable drawable = getResourceDrawable(getContext(), name);
mLoadingImageDrawable =
drawable != null ? (Drawable) new AutoRotateDrawable(drawable, 1000) : null;
mIsDirty = true;
}
public void setProgressiveRenderingEnabled(boolean enabled) {
mProgressiveRenderingEnabled = enabled;
// no worth marking as dirty if it already rendered..
}
public void setFadeDuration(int durationMs) {
mFadeDurationMs = durationMs;
// no worth marking as dirty if it already rendered..
}
public void maybeUpdateView() {
if (!mIsDirty) {
return;
}
boolean doResize = shouldResize(mUri);
if (doResize && (getWidth() <= 0 || getHeight() <=0)) {
// If need a resize and the size is not yet set, wait until the layout pass provides one
return;
}
GenericDraweeHierarchy hierarchy = getHierarchy();
hierarchy.setActualImageScaleType(mScaleType);
if (mLoadingImageDrawable != null) {
hierarchy.setPlaceholderImage(mLoadingImageDrawable, ScalingUtils.ScaleType.CENTER);
}
boolean usePostprocessorScaling =
mScaleType != ScalingUtils.ScaleType.CENTER_CROP &&
mScaleType != ScalingUtils.ScaleType.FOCUS_CROP;
float hierarchyRadius = usePostprocessorScaling ? 0 : mBorderRadius;
RoundingParams roundingParams = hierarchy.getRoundingParams();
roundingParams.setCornersRadius(hierarchyRadius);
roundingParams.setBorder(mBorderColor, mBorderWidth);
hierarchy.setRoundingParams(roundingParams);
hierarchy.setFadeDuration(
mFadeDurationMs >= 0
? mFadeDurationMs
: mIsLocalImage ? 0 : REMOTE_IMAGE_FADE_DURATION_MS);
Postprocessor postprocessor = usePostprocessorScaling ? mRoundedCornerPostprocessor : null;
ResizeOptions resizeOptions = doResize ? new ResizeOptions(getWidth(), getHeight()) : null;
ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(mUri)
.setPostprocessor(postprocessor)
.setResizeOptions(resizeOptions)
.setProgressiveRenderingEnabled(mProgressiveRenderingEnabled)
.build();
// This builder is reused
mDraweeControllerBuilder.reset();
mDraweeControllerBuilder
.setAutoPlayAnimations(true)
.setCallerContext(mCallerContext)
.setOldController(getController())
.setImageRequest(imageRequest);
if (mControllerListener != null && mControllerForTesting != null) {
ForwardingControllerListener combinedListener = new ForwardingControllerListener();
combinedListener.addListener(mControllerListener);
combinedListener.addListener(mControllerForTesting);
mDraweeControllerBuilder.setControllerListener(combinedListener);
} else if (mControllerForTesting != null) {
mDraweeControllerBuilder.setControllerListener(mControllerForTesting);
} else if (mControllerListener != null) {
mDraweeControllerBuilder.setControllerListener(mControllerListener);
}
setController(mDraweeControllerBuilder.build());
mIsDirty = false;
}
// VisibleForTesting
public void setControllerListener(ControllerListener controllerListener) {
mControllerForTesting = controllerListener;
mIsDirty = true;
maybeUpdateView();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (w > 0 && h > 0) {
maybeUpdateView();
}
}
/**
* ReactImageViews only render a single image.
*/
@Override
public boolean hasOverlappingRendering() {
return false;
}
private static boolean shouldResize(@Nullable Uri uri) {
// Resizing is inferior to scaling. See http://frescolib.org/docs/resizing-rotating.html#_
// We resize here only for images likely to be from the device's camera, where the app developer
// has no control over the original size
return uri != null && (UriUtil.isLocalContentUri(uri) || UriUtil.isLocalFileUri(uri));
}
private static int getResourceDrawableId(Context context, @Nullable String name) {
if (name == null || name.isEmpty()) {
return 0;
}
return context.getResources().getIdentifier(
name.toLowerCase().replace("-", "_"),
"drawable",
context.getPackageName());
}
private static @Nullable Drawable getResourceDrawable(Context context, @Nullable String name) {
int resId = getResourceDrawableId(context, name);
return resId > 0 ? context.getResources().getDrawable(resId) : null;
}
private static @Nullable Uri getResourceDrawableUri(Context context, @Nullable String name) {
int resId = getResourceDrawableId(context, name);
return resId > 0 ? new Uri.Builder()
.scheme(UriUtil.LOCAL_RESOURCE_SCHEME)
.path(String.valueOf(resId))
.build() : null;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.namespace;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.container.NamespaceHandlerRegistry;
import org.apache.aries.blueprint.parser.NamespaceHandlerSet;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.SAXException;
/**
* Default implementation of the NamespaceHandlerRegistry.
*
* This registry will track NamespaceHandler objects in the OSGi registry and make
* them available, calling listeners when handlers are registered or unregistered.
*
* @version $Rev$, $Date$
*/
public class NamespaceHandlerRegistryImpl implements NamespaceHandlerRegistry, ServiceTrackerCustomizer {
public static final URI BLUEPRINT_NAMESPACE = URI.create("http://www.osgi.org/xmlns/blueprint/v1.0.0");
public static final String NAMESPACE = "osgi.service.blueprint.namespace";
private static final Logger LOGGER = LoggerFactory.getLogger(NamespaceHandlerRegistryImpl.class);
// The bundle context is thread safe
private final BundleContext bundleContext;
// The service tracker is thread safe
private final ServiceTracker tracker;
// The handlers map is concurrent
private final ConcurrentHashMap<URI, CopyOnWriteArraySet<NamespaceHandler>> handlers =
new ConcurrentHashMap<URI, CopyOnWriteArraySet<NamespaceHandler>>();
// Access to the LRU schemas map is synchronized on itself
private final LRUMap<Map<URI, NamespaceHandler>, Reference<Schema>> schemas =
new LRUMap<Map<URI, NamespaceHandler>, Reference<Schema>>(10);
// Access to this factory is synchronized on itself
private final SchemaFactory schemaFactory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// Access to this variable is must be synchronized on itself
private final ArrayList<NamespaceHandlerSetImpl> sets =
new ArrayList<NamespaceHandlerSetImpl>();
public NamespaceHandlerRegistryImpl(BundleContext bundleContext) {
this.bundleContext = bundleContext;
tracker = new ServiceTracker(bundleContext, NamespaceHandler.class.getName(), this);
tracker.open();
}
public Object addingService(ServiceReference reference) {
LOGGER.debug("Adding NamespaceHandler " + reference.toString());
NamespaceHandler handler = (NamespaceHandler) bundleContext.getService(reference);
if (handler != null) {
try {
Map<String, Object> props = new HashMap<String, Object>();
for (String name : reference.getPropertyKeys()) {
props.put(name, reference.getProperty(name));
}
registerHandler(handler, props);
} catch (Exception e) {
LOGGER.warn("Error registering NamespaceHandler", e);
}
} else {
LOGGER.warn("Error resolving NamespaceHandler, null Service obtained from tracked ServiceReference {} for bundle {}/{}",
reference.toString(), reference.getBundle().getSymbolicName(), reference.getBundle().getVersion());
}
return handler;
}
public void modifiedService(ServiceReference reference, Object service) {
removedService(reference, service);
addingService(reference);
}
public void removedService(ServiceReference reference, Object service) {
try {
LOGGER.debug("Removing NamespaceHandler " + reference.toString());
NamespaceHandler handler = (NamespaceHandler) service;
Map<String, Object> props = new HashMap<String, Object>();
for (String name : reference.getPropertyKeys()) {
props.put(name, reference.getProperty(name));
}
unregisterHandler(handler, props);
} catch (Exception e) {
LOGGER.warn("Error unregistering NamespaceHandler", e);
}
}
public void registerHandler(NamespaceHandler handler, Map properties) {
List<URI> namespaces = getNamespaces(properties);
for (URI uri : namespaces) {
CopyOnWriteArraySet<NamespaceHandler> h = handlers.putIfAbsent(uri, new CopyOnWriteArraySet<NamespaceHandler>());
if (h == null) {
h = handlers.get(uri);
}
if (h.add(handler)) {
List<NamespaceHandlerSetImpl> sets;
synchronized (this.sets) {
sets = new ArrayList<NamespaceHandlerSetImpl>(this.sets);
}
for (NamespaceHandlerSetImpl s : sets) {
s.registerHandler(uri, handler);
}
}
}
}
public void unregisterHandler(NamespaceHandler handler, Map properties) {
List<URI> namespaces = getNamespaces(properties);
for (URI uri : namespaces) {
CopyOnWriteArraySet<NamespaceHandler> h = handlers.get(uri);
if (!h.remove(handler)) {
continue;
}
List<NamespaceHandlerSetImpl> sets;
synchronized (this.sets) {
sets = new ArrayList<NamespaceHandlerSetImpl>(this.sets);
}
for (NamespaceHandlerSetImpl s : sets) {
s.unregisterHandler(uri, handler);
}
}
removeSchemasFor(handler);
}
private static List<URI> getNamespaces(Map properties) {
Object ns = properties != null ? properties.get(NAMESPACE) : null;
if (ns == null) {
throw new IllegalArgumentException("NamespaceHandler service does not have an associated "
+ NAMESPACE + " property defined");
} else if (ns instanceof URI[]) {
return Arrays.asList((URI[]) ns);
} else if (ns instanceof URI) {
return Collections.singletonList((URI) ns);
} else if (ns instanceof String) {
return Collections.singletonList(URI.create((String) ns));
} else if (ns instanceof String[]) {
String[] strings = (String[]) ns;
List<URI> namespaces = new ArrayList<URI>(strings.length);
for (String string : strings) {
namespaces.add(URI.create(string));
}
return namespaces;
} else if (ns instanceof Collection) {
Collection col = (Collection) ns;
List<URI> namespaces = new ArrayList<URI>(col.size());
for (Object o : col) {
namespaces.add(toURI(o));
}
return namespaces;
} else if (ns instanceof Object[]) {
Object[] array = (Object[]) ns;
List<URI> namespaces = new ArrayList<URI>(array.length);
for (Object o : array) {
namespaces.add(toURI(o));
}
return namespaces;
} else {
throw new IllegalArgumentException("NamespaceHandler service has an associated "
+ NAMESPACE + " property defined which can not be converted to an array of URI");
}
}
private static URI toURI(Object o) {
if (o instanceof URI) {
return (URI) o;
} else if (o instanceof String) {
return URI.create((String) o);
} else {
throw new IllegalArgumentException("NamespaceHandler service has an associated "
+ NAMESPACE + " property defined which can not be converted to an array of URI");
}
}
public NamespaceHandlerSet getNamespaceHandlers(Set<URI> uris, Bundle bundle) {
NamespaceHandlerSetImpl s;
synchronized (sets) {
s = new NamespaceHandlerSetImpl(uris, bundle);
sets.add(s);
}
return s;
}
public void destroy() {
tracker.close();
}
private Schema getSchema(Map<URI, NamespaceHandler> handlers,
final Bundle bundle,
final Properties schemaMap) throws IOException, SAXException {
if (schemaMap != null && !schemaMap.isEmpty()) {
return createSchema(handlers, bundle, schemaMap);
}
// Find a schema that can handle all the requested namespaces
// If it contains additional namespaces, it should not be a problem since
// they won't be used at all
Schema schema = getExistingSchema(handlers);
if (schema == null) {
// Create schema
schema = createSchema(handlers, bundle, schemaMap);
cacheSchema(handlers, schema);
}
return schema;
}
private Schema getExistingSchema(Map<URI, NamespaceHandler> handlers) {
synchronized (schemas) {
for (Map<URI, NamespaceHandler> key : schemas.keySet()) {
boolean found = true;
for (URI uri : handlers.keySet()) {
if (!handlers.get(uri).equals(key.get(uri))) {
found = false;
break;
}
}
if (found) {
return schemas.get(key).get();
}
}
return null;
}
}
private void removeSchemasFor(NamespaceHandler handler) {
synchronized (schemas) {
List<Map<URI, NamespaceHandler>> keys = new ArrayList<Map<URI, NamespaceHandler>>();
for (Map<URI, NamespaceHandler> key : schemas.keySet()) {
if (key.values().contains(handler)) {
keys.add(key);
}
}
for (Map<URI, NamespaceHandler> key : keys) {
schemas.remove(key);
}
}
}
private void cacheSchema(Map<URI, NamespaceHandler> handlers, Schema schema) {
synchronized (schemas) {
// Remove schemas that are fully included
for (Iterator<Map<URI, NamespaceHandler>> iterator = schemas.keySet().iterator(); iterator.hasNext();) {
Map<URI, NamespaceHandler> key = iterator.next();
boolean found = true;
for (URI uri : key.keySet()) {
if (!key.get(uri).equals(handlers.get(uri))) {
found = false;
break;
}
}
if (found) {
iterator.remove();
break;
}
}
// Add our new schema
schemas.put(handlers, new SoftReference<Schema>(schema));
}
}
private Schema createSchema(Map<URI, NamespaceHandler> handlers,
Bundle bundle,
Properties schemaMap) throws IOException, SAXException {
final List<StreamSource> schemaSources = new ArrayList<StreamSource>();
try {
schemaSources.add(new StreamSource(getClass().getResourceAsStream("/org/apache/aries/blueprint/blueprint.xsd")));
// Create a schema for all namespaces known at this point
// It will speed things as it can be reused for all other blueprint containers
for (URI ns : handlers.keySet()) {
URL url = handlers.get(ns).getSchemaLocation(ns.toString());
if (url == null) {
LOGGER.warn("No URL is defined for schema " + ns + ". This schema will not be validated");
} else {
schemaSources.add(new StreamSource(url.openStream(), url.toExternalForm()));
}
}
for (Object ns : schemaMap.values()) {
URL url = bundle.getResource(ns.toString());
if (url == null) {
LOGGER.warn("No URL is defined for schema " + ns + ". This schema will not be validated");
} else {
schemaSources.add(new StreamSource(url.openStream(), url.toExternalForm()));
}
}
synchronized (schemaFactory) {
schemaFactory.setResourceResolver(new BundleResourceResolver(schemaMap, bundle, schemaSources));
return schemaFactory.newSchema(schemaSources.toArray(new Source[schemaSources.size()]));
}
} finally {
for (StreamSource s : schemaSources) {
closeQuietly(s.getInputStream());
}
}
}
private static void closeQuietly(Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException e) {
// Ignore
}
}
private class BundleResourceResolver implements LSResourceResolver {
private final Properties schemaMap;
private final Bundle bundle;
private final List<StreamSource> schemaSources;
public BundleResourceResolver(Properties schemaMap, Bundle bundle, List<StreamSource> schemaSources) {
this.schemaMap = schemaMap;
this.bundle = bundle;
this.schemaSources = schemaSources;
}
public LSInput resolveResource(String type,
final String namespaceURI,
final String publicId,
String systemId, String baseURI) {
String loc = null;
if (namespaceURI != null) {
loc = schemaMap.getProperty(namespaceURI);
}
if (loc == null && publicId != null) {
loc = schemaMap.getProperty(publicId);
}
if (loc == null && systemId != null) {
loc = schemaMap.getProperty(systemId);
}
if (loc != null) {
URL url = bundle.getResource(loc);
if (url != null) {
try {
StreamSource source
= new StreamSource(url.openStream(), url.toExternalForm());
schemaSources.add(source);
return new SourceLSInput(source, publicId, url);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
URI uri = URI.create(namespaceURI);
Set<NamespaceHandler> hs = NamespaceHandlerRegistryImpl.this.handlers.get(uri);
if (hs == null) {
return null;
}
for (NamespaceHandler h : hs) {
URL url = h.getSchemaLocation(namespaceURI);
if (url != null) {
// handling include-relative-path case
if (systemId != null && !systemId.matches("^[a-z][-+.0-9a-z]*:.*")) {
try {
url = new URL(url, systemId);
} catch (Exception e) {
// ignore and use the given systemId
}
}
try {
final StreamSource source = new StreamSource(url.openStream(), url.toExternalForm());
schemaSources.add(source);
return new SourceLSInput(source, publicId, url);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return null;
}
}
private class SourceLSInput implements LSInput {
private final StreamSource source;
private final URL systemId;
private final String publicId;
public SourceLSInput(StreamSource source, String publicId, URL systemId) {
this.source = source;
this.publicId = publicId;
this.systemId = systemId;
}
public Reader getCharacterStream() {
return null;
}
public void setCharacterStream(Reader characterStream) {
}
public InputStream getByteStream() {
return source.getInputStream();
}
public void setByteStream(InputStream byteStream) {
}
public String getStringData() {
return null;
}
public void setStringData(String stringData) {
}
public String getSystemId() {
return systemId.toExternalForm();
}
public void setSystemId(String systemId) {
}
public String getPublicId() {
return publicId;
}
public void setPublicId(String publicId) {
}
public String getBaseURI() {
return null;
}
public void setBaseURI(String baseURI) {
}
public String getEncoding() {
return null;
}
public void setEncoding(String encoding) {
}
public boolean getCertifiedText() {
return false;
}
public void setCertifiedText(boolean certifiedText) {
}
}
protected class NamespaceHandlerSetImpl implements NamespaceHandlerSet {
private final List<Listener> listeners;
private final Bundle bundle;
private final Set<URI> namespaces;
private final Map<URI, NamespaceHandler> handlers;
private final Properties schemaMap = new Properties();
private Schema schema;
public NamespaceHandlerSetImpl(Set<URI> namespaces, Bundle bundle) {
this.listeners = new CopyOnWriteArrayList<Listener>();
this.namespaces = namespaces;
this.bundle = bundle;
handlers = new ConcurrentHashMap<URI, NamespaceHandler>();
for (URI ns : namespaces) {
findCompatibleNamespaceHandler(ns);
}
URL url = bundle.getResource("OSGI-INF/blueprint/schema.map");
if (url != null) {
InputStream ins = null;
try {
ins = url.openStream();
schemaMap.load(ins);
} catch (IOException ex) {
ex.printStackTrace();
//ignore
} finally {
closeQuietly(ins);
}
}
for (Object ns : schemaMap.keySet()) {
try {
this.namespaces.remove(new URI(ns.toString()));
} catch (URISyntaxException e) {
//ignore
}
}
}
public boolean isComplete() {
return handlers.size() == namespaces.size();
}
public Set<URI> getNamespaces() {
return namespaces;
}
public NamespaceHandler getNamespaceHandler(URI namespace) {
return handlers.get(namespace);
}
public Schema getSchema() throws SAXException, IOException {
if (!isComplete()) {
throw new IllegalStateException("NamespaceHandlerSet is not complete");
}
if (schema == null) {
schema = NamespaceHandlerRegistryImpl.this.getSchema(handlers, bundle, schemaMap);
}
return schema;
}
public void addListener(Listener listener) {
listeners.add(listener);
}
public void removeListener(Listener listener) {
listeners.remove(listener);
}
public void destroy() {
synchronized (NamespaceHandlerRegistryImpl.this.sets) {
NamespaceHandlerRegistryImpl.this.sets.remove(this);
}
}
public void registerHandler(URI uri, NamespaceHandler handler) {
if (namespaces.contains(uri) && handlers.get(uri) == null) {
if (findCompatibleNamespaceHandler(uri) != null) {
for (Listener listener : listeners) {
try {
listener.namespaceHandlerRegistered(uri);
} catch (Throwable t) {
LOGGER.debug("Unexpected exception when notifying a NamespaceHandler listener", t);
}
}
}
}
}
public void unregisterHandler(URI uri, NamespaceHandler handler) {
if (handlers.get(uri) == handler) {
handlers.remove(uri);
for (Listener listener : listeners) {
try {
listener.namespaceHandlerUnregistered(uri);
} catch (Throwable t) {
LOGGER.debug("Unexpected exception when notifying a NamespaceHandler listener", t);
}
}
}
}
private NamespaceHandler findCompatibleNamespaceHandler(URI ns) {
Set<NamespaceHandler> candidates = NamespaceHandlerRegistryImpl.this.handlers.get(ns);
if (candidates != null) {
for (NamespaceHandler h : candidates) {
Set<Class> classes = h.getManagedClasses();
boolean compat = true;
if (classes != null) {
Set<Class> allClasses = new HashSet<Class>();
for (Class cl : classes) {
for (Class c = cl; c != null; c = c.getSuperclass()) {
allClasses.add(c);
for (Class i : c.getInterfaces()) {
allClasses.add(i);
}
}
}
for (Class cl : allClasses) {
Class clb;
try {
clb = bundle.loadClass(cl.getName());
if (clb != cl) {
compat = false;
break;
}
} catch (ClassNotFoundException e) {
// Ignore
} catch (NoClassDefFoundError e) {
// Ignore
}
}
}
if (compat) {
handlers.put(ns, h);
return h;
}
}
}
return null;
}
}
public static class LRUMap<K,V> extends AbstractMap<K,V> {
private final int bound;
private final LinkedList<Entry<K,V>> entries = new LinkedList<Entry<K,V>>();
private static class LRUEntry<K,V> implements Entry<K,V> {
private final K key;
private final V value;
private LRUEntry(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public V setValue(V value) {
throw new UnsupportedOperationException();
}
}
private LRUMap(int bound) {
this.bound = bound;
}
public V get(Object key) {
if (key == null) {
throw new NullPointerException();
}
for (Entry<K,V> e : entries) {
if (e.getKey().equals(key)) {
entries.remove(e);
entries.addFirst(e);
return e.getValue();
}
}
return null;
}
public V put(K key, V value) {
if (key == null) {
throw new NullPointerException();
}
V old = null;
for (Entry<K,V> e : entries) {
if (e.getKey().equals(key)) {
entries.remove(e);
old = e.getValue();
break;
}
}
if (value != null) {
entries.addFirst(new LRUEntry<K,V>(key, value));
while (entries.size() > bound) {
entries.removeLast();
}
}
return old;
}
public Set<Entry<K, V>> entrySet() {
return new AbstractSet<Entry<K,V>>() {
public Iterator<Entry<K, V>> iterator() {
return entries.iterator();
}
public int size() {
return entries.size();
}
};
}
}
}
| |
// ========================================================================
// $Id: ServletHttpRequest.java,v 1.65 2005/08/13 00:01:27 gregwilkins Exp $
// Copyright 200-2004 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
package org.openqa.jetty.jetty.servlet;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestWrapper;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.openqa.jetty.log.LogFactory;
import org.openqa.jetty.http.HttpConnection;
import org.openqa.jetty.http.HttpFields;
import org.openqa.jetty.http.HttpInputStream;
import org.openqa.jetty.http.HttpRequest;
import org.openqa.jetty.http.SecurityConstraint;
import org.openqa.jetty.util.LazyList;
import org.openqa.jetty.util.LogSupport;
import org.openqa.jetty.util.Resource;
import org.openqa.jetty.util.StringUtil;
import org.openqa.jetty.util.URI;
/* ------------------------------------------------------------ */
/** Servlet Request Wrapper.
* This class wraps a Jetty HTTP request as a 2.2 Servlet
* request.
* <P>
* Note that this wrapper is not synchronized and if a request is to
* be operated on by multiple threads, then higher level
* synchronizations may be required.
*
* @version $Id: ServletHttpRequest.java,v 1.65 2005/08/13 00:01:27 gregwilkins Exp $
* @author Greg Wilkins (gregw)
*/
public class ServletHttpRequest
implements HttpServletRequest
{
private static Log log = LogFactory.getLog(ServletHttpRequest.class);
/* -------------------------------------------------------------- */
public static final String
__SESSIONID_NOT_CHECKED = "not checked",
__SESSIONID_URL = "url",
__SESSIONID_COOKIE = "cookie",
__SESSIONID_NONE = "none";
private static final Enumeration __emptyEnum =
Collections.enumeration(Collections.EMPTY_LIST);
private static final Collection __defaultLocale =
Collections.singleton(Locale.getDefault());
private ServletHandler _servletHandler;
private HttpRequest _httpRequest;
private ServletHttpResponse _servletHttpResponse;
private String _contextPath=null;
private String _servletPath=null;
private String _pathInfo=null;
private String _query=null;
private String _pathTranslated=null;
private String _requestedSessionId=null;
private HttpSession _session=null;
private String _sessionIdState=__SESSIONID_NOT_CHECKED;
private ServletIn _in =null;
private BufferedReader _reader=null;
private int _inputState=0;
private ServletHolder _servletHolder;
private String _pathInContext;
/* ------------------------------------------------------------ */
/** Constructor.
*/
public ServletHttpRequest(ServletHandler servletHandler,
String pathInContext,
HttpRequest request)
{
_servletHandler=servletHandler;
_pathInContext=pathInContext;
_contextPath=_servletHandler.getHttpContext().getContextPath();
if (_contextPath.length()<=1)
_contextPath="";
_httpRequest=request;
}
/* ------------------------------------------------------------ */
void recycle(ServletHandler servletHandler,String pathInContext)
{
_servletHandler=servletHandler;
_pathInContext=pathInContext;
_servletPath=null;
_pathInfo=null;
_query=null;
_pathTranslated=null;
_requestedSessionId=null;
_session=null;
_sessionIdState=__SESSIONID_NOT_CHECKED;
_in=null;
_reader=null;
_inputState=0;
_servletHolder=null;
if (servletHandler!=null)
_contextPath=_servletHandler.getHttpContext().getContextPath();
if (_contextPath!=null&&_contextPath.length()<=1)
_contextPath="";
}
/* ------------------------------------------------------------ */
ServletHandler getServletHandler()
{
return _servletHandler;
}
/* ------------------------------------------------------------ */
void setServletHandler(ServletHandler servletHandler)
{
_servletHandler=servletHandler;
}
/* ------------------------------------------------------------ */
/** Set servletpath and pathInfo.
* Called by the RestishHandler before passing a request to a particular
* holder to split the context path into a servlet path and path info.
* @param servletPath
* @param pathInfo
*/
void setServletPaths(String servletPath,
String pathInfo,
ServletHolder holder)
{
_servletPath=servletPath;
_pathInfo=pathInfo;
_servletHolder=holder;
}
/* ------------------------------------------------------------ */
ServletHolder getServletHolder()
{
return _servletHolder;
}
/* ------------------------------------------------------------ */
String getPathInContext()
{
return _pathInContext;
}
/* ------------------------------------------------------------ */
HttpRequest getHttpRequest()
{
return _httpRequest;
}
/* ------------------------------------------------------------ */
public ServletHttpResponse getServletHttpResponse()
{
return _servletHttpResponse;
}
/* ------------------------------------------------------------ */
void setServletHttpResponse(ServletHttpResponse response)
{
_servletHttpResponse = response;
}
/* ------------------------------------------------------------ */
public Locale getLocale()
{
Enumeration enm = _httpRequest.getFieldValues(HttpFields.__AcceptLanguage,
HttpFields.__separators);
// handle no locale
if (enm == null || !enm.hasMoreElements())
return Locale.getDefault();
// sort the list in quality order
List acceptLanguage = HttpFields.qualityList(enm);
if (acceptLanguage.size()==0)
return Locale.getDefault();
int size=acceptLanguage.size();
// convert to locals
for (int i=0; i<size; i++)
{
String language = (String)acceptLanguage.get(i);
language=HttpFields.valueParameters(language,null);
String country = "";
int dash = language.indexOf('-');
if (dash > -1)
{
country = language.substring(dash + 1).trim();
language = language.substring(0,dash).trim();
}
return new Locale(language,country);
}
return Locale.getDefault();
}
/* ------------------------------------------------------------ */
public Enumeration getLocales()
{
Enumeration enm = _httpRequest.getFieldValues(HttpFields.__AcceptLanguage,
HttpFields.__separators);
// handle no locale
if (enm == null || !enm.hasMoreElements())
return Collections.enumeration(__defaultLocale);
// sort the list in quality order
List acceptLanguage = HttpFields.qualityList(enm);
if (acceptLanguage.size()==0)
return
Collections.enumeration(__defaultLocale);
Object langs = null;
int size=acceptLanguage.size();
// convert to locals
for (int i=0; i<size; i++)
{
String language = (String)acceptLanguage.get(i);
language=HttpFields.valueParameters(language,null);
String country = "";
int dash = language.indexOf('-');
if (dash > -1)
{
country = language.substring(dash + 1).trim();
language = language.substring(0,dash).trim();
}
langs=LazyList.ensureSize(langs,size);
langs=LazyList.add(langs,new Locale(language,country));
}
if (LazyList.size(langs)==0)
return Collections.enumeration(__defaultLocale);
return Collections.enumeration(LazyList.getList(langs));
}
/* ------------------------------------------------------------ */
public boolean isSecure()
{
return _httpRequest.isConfidential();
}
/* ------------------------------------------------------------ */
public Cookie[] getCookies()
{
Cookie[] cookies = _httpRequest.getCookies();
if (cookies.length==0)
return null;
return cookies;
}
/* ------------------------------------------------------------ */
public long getDateHeader(String name)
{
return _httpRequest.getDateField(name);
}
/* ------------------------------------------------------------ */
public Enumeration getHeaderNames()
{
return _httpRequest.getFieldNames();
}
/* ------------------------------------------------------------ */
public String getHeader(String name)
{
return _httpRequest.getField(name);
}
/* ------------------------------------------------------------ */
public Enumeration getHeaders(String s)
{
Enumeration enm=_httpRequest.getFieldValues(s);
if (enm==null)
return __emptyEnum;
return enm;
}
/* ------------------------------------------------------------ */
public int getIntHeader(String name)
throws NumberFormatException
{
return _httpRequest.getIntField(name);
}
/* ------------------------------------------------------------ */
public String getMethod()
{
return _httpRequest.getMethod();
}
/* ------------------------------------------------------------ */
public String getContextPath()
{
return _contextPath;
}
/* ------------------------------------------------------------ */
public String getPathInfo()
{
if (_servletPath==null)
return null;
return _pathInfo;
}
/* ------------------------------------------------------------ */
public String getPathTranslated()
{
if (_pathInfo==null || _pathInfo.length()==0)
return null;
if (_pathTranslated==null)
{
Resource resource =
_servletHandler.getHttpContext().getBaseResource();
if (resource==null)
return null;
try
{
resource=resource.addPath(_pathInfo);
File file = resource.getFile();
if (file==null)
return null;
_pathTranslated=file.getAbsolutePath();
}
catch(Exception e)
{
log.debug(LogSupport.EXCEPTION,e);
}
}
return _pathTranslated;
}
/* ------------------------------------------------------------ */
public String getQueryString()
{
if (_query==null)
_query =_httpRequest.getQuery();
return _query;
}
/* ------------------------------------------------------------ */
public String getAuthType()
{
String at= _httpRequest.getAuthType();
if (at==SecurityConstraint.__BASIC_AUTH)
return HttpServletRequest.BASIC_AUTH;
if (at==SecurityConstraint.__FORM_AUTH)
return HttpServletRequest.FORM_AUTH;
if (at==SecurityConstraint.__DIGEST_AUTH)
return HttpServletRequest.DIGEST_AUTH;
if (at==SecurityConstraint.__CERT_AUTH)
return HttpServletRequest.CLIENT_CERT_AUTH;
if (at==SecurityConstraint.__CERT_AUTH2)
return HttpServletRequest.CLIENT_CERT_AUTH;
return at;
}
/* ------------------------------------------------------------ */
public String getRemoteUser()
{
return _httpRequest.getAuthUser();
}
/* ------------------------------------------------------------ */
public boolean isUserInRole(String role)
{
if (_servletHolder!=null)
role=_servletHolder.getUserRoleLink(role);
return _httpRequest.isUserInRole(role);
}
/* ------------------------------------------------------------ */
public Principal getUserPrincipal()
{
return _httpRequest.getUserPrincipal();
}
/* ------------------------------------------------------------ */
void setRequestedSessionId(String pathParams)
{
_requestedSessionId=null;
// try cookies first
if (_servletHandler.isUsingCookies())
{
Cookie[] cookies=_httpRequest.getCookies();
if (cookies!=null && cookies.length>0)
{
for (int i=0;i<cookies.length;i++)
{
if (SessionManager.__SessionCookie.equalsIgnoreCase(cookies[i].getName()))
{
if (_requestedSessionId!=null)
{
// Multiple jsessionid cookies. Probably due to
// multiple paths and/or domains. Pick the first
// known session or the last defined cookie.
SessionManager manager = _servletHandler.getSessionManager();
if (manager!=null && manager.getHttpSession(_requestedSessionId)!=null)
break;
log.debug("multiple session cookies");
}
_requestedSessionId=cookies[i].getValue();
_sessionIdState = __SESSIONID_COOKIE;
if(log.isDebugEnabled())log.debug("Got Session "+_requestedSessionId+" from cookie");
}
}
}
}
// check if there is a url encoded session param.
if (pathParams!=null && pathParams.startsWith(SessionManager.__SessionURL))
{
String id =
pathParams.substring(SessionManager.__SessionURL.length()+1);
if(log.isDebugEnabled())log.debug("Got Session "+id+" from URL");
if (_requestedSessionId==null)
{
_requestedSessionId=id;
_sessionIdState = __SESSIONID_URL;
}
else if (!id.equals(_requestedSessionId))
log.debug("Mismatched session IDs");
}
if (_requestedSessionId == null)
_sessionIdState = __SESSIONID_NONE;
}
/* ------------------------------------------------------------ */
public String getRequestedSessionId()
{
return _requestedSessionId;
}
/* ------------------------------------------------------------ */
public String getRequestURI()
{
return _httpRequest.getEncodedPath();
}
/* ------------------------------------------------------------ */
public StringBuffer getRequestURL()
{
StringBuffer buf = _httpRequest.getRootURL();
buf.append(getRequestURI());
return buf;
}
/* ------------------------------------------------------------ */
public String getServletPath()
{
if (_servletPath==null)
return _pathInContext;
return _servletPath;
}
/* ------------------------------------------------------------ */
public HttpSession getSession(boolean create)
{
if (_session != null && ((SessionManager.Session)_session).isValid())
return _session;
_session=null;
String id = getRequestedSessionId();
if (id != null)
{
_session=_servletHandler.getHttpSession(id);
if (_session == null && !create)
return null;
}
if (_session == null && create)
{
_session=newSession();
}
return _session;
}
/* ------------------------------------------------------------ */
/* Create a new HttpSession.
* If cookies are being used a set cookie is added to the response.
*/
HttpSession newSession()
{
HttpSession session=_servletHandler.newHttpSession(this);
Cookie cookie=_servletHandler.getSessionManager().getSessionCookie(session,isSecure());
if (cookie!=null)
_servletHttpResponse.getHttpResponse().addSetCookie(cookie);
return session;
}
/* ------------------------------------------------------------ */
public HttpSession getSession()
{
HttpSession session = getSession(true);
return session;
}
/* ------------------------------------------------------------ */
public boolean isRequestedSessionIdValid()
{
return _requestedSessionId != null && getSession(false) != null;
}
/* -------------------------------------------------------------- */
public boolean isRequestedSessionIdFromCookie()
{
return _sessionIdState == __SESSIONID_COOKIE;
}
/* -------------------------------------------------------------- */
public boolean isRequestedSessionIdFromURL()
{
return _sessionIdState == __SESSIONID_URL;
}
/* -------------------------------------------------------------- */
/**
* @deprecated
*/
@Deprecated
public boolean isRequestedSessionIdFromUrl()
{
return isRequestedSessionIdFromURL();
}
/* -------------------------------------------------------------- */
public Enumeration getAttributeNames()
{
return _httpRequest.getAttributeNames();
}
/* -------------------------------------------------------------- */
public Object getAttribute(String name)
{
return _httpRequest.getAttribute(name);
}
/* -------------------------------------------------------------- */
public void setAttribute(String name, Object value)
{
_httpRequest.setAttribute(name,value);
}
/* -------------------------------------------------------------- */
public void removeAttribute(String name)
{
_httpRequest.removeAttribute(name);
}
/* -------------------------------------------------------------- */
public void setCharacterEncoding(String encoding)
throws UnsupportedEncodingException
{
if (_inputState!=0)
throw new IllegalStateException("getReader() or getInputStream() called");
"".getBytes(encoding);
_httpRequest.setCharacterEncoding(encoding,false);
}
/* -------------------------------------------------------------- */
public String getCharacterEncoding()
{
return _httpRequest.getCharacterEncoding();
}
/* -------------------------------------------------------------- */
public int getContentLength()
{
return _httpRequest.getContentLength();
}
/* -------------------------------------------------------------- */
public String getContentType()
{
return _httpRequest.getContentType();
}
/* -------------------------------------------------------------- */
public ServletInputStream getInputStream()
{
if (_inputState!=0 && _inputState!=1)
throw new IllegalStateException();
if (_in==null)
_in = new ServletIn((HttpInputStream)_httpRequest.getInputStream());
_inputState=1;
_reader=null;
return _in;
}
/* -------------------------------------------------------------- */
/**
* This method is not recommended as it forces the generation of a
* non-optimal data structure.
*/
public Map getParameterMap()
{
return Collections.unmodifiableMap(_httpRequest.getParameterStringArrayMap());
}
/* -------------------------------------------------------------- */
public String getParameter(String name)
{
return _httpRequest.getParameter(name);
}
/* -------------------------------------------------------------- */
public Enumeration getParameterNames()
{
return Collections.enumeration(_httpRequest.getParameterNames());
}
/* -------------------------------------------------------------- */
public String[] getParameterValues(String name)
{
List v=_httpRequest.getParameterValues(name);
if (v==null)
return null;
String[]a=new String[v.size()];
return (String[])v.toArray(a);
}
/* -------------------------------------------------------------- */
public String getProtocol()
{
return _httpRequest.getVersion();
}
/* -------------------------------------------------------------- */
public String getScheme()
{
return _httpRequest.getScheme();
}
/* -------------------------------------------------------------- */
public String getServerName()
{
return _httpRequest.getHost();
}
/* -------------------------------------------------------------- */
public int getServerPort()
{
int port = _httpRequest.getPort();
if (port==0)
{
if (getScheme().equalsIgnoreCase("https"))
return 443;
return 80;
}
return port;
}
/* -------------------------------------------------------------- */
public int getRemotePort()
{
HttpConnection connection= _httpRequest.getHttpConnection();
if (connection!=null)
return connection.getRemotePort();
return 0;
}
/* -------------------------------------------------------------- */
public String getLocalName()
{
HttpConnection connection= _httpRequest.getHttpConnection();
if (connection!=null)
return connection.getServerName();
return null;
}
/* -------------------------------------------------------------- */
public String getLocalAddr()
{
HttpConnection connection= _httpRequest.getHttpConnection();
if (connection!=null)
return connection.getServerAddr();
return null;
}
/* -------------------------------------------------------------- */
public int getLocalPort()
{
HttpConnection connection= _httpRequest.getHttpConnection();
if (connection!=null)
return connection.getServerPort();
return 0;
}
/* -------------------------------------------------------------- */
public BufferedReader getReader()
throws UnsupportedEncodingException
{
if (_inputState!=0 && _inputState!=2)
throw new IllegalStateException();
if (_reader==null)
{
String encoding=getCharacterEncoding();
if (encoding==null)
encoding=StringUtil.__ISO_8859_1;
_reader=new BufferedReader(new InputStreamReader(getInputStream(),encoding));
}
_inputState=2;
return _reader;
}
/* -------------------------------------------------------------- */
public String getRemoteAddr()
{
return _httpRequest.getRemoteAddr();
}
/* -------------------------------------------------------------- */
public String getRemoteHost()
{
if (_httpRequest.getHttpConnection()==null)
return null;
return _httpRequest.getRemoteHost();
}
/* -------------------------------------------------------------- */
/**
* @deprecated As of Version 2.1 of the Java Servlet API,
* use {@link javax.servlet.ServletContext#getRealPath} instead.
*/
@Deprecated
public String getRealPath(String path)
{
return _servletHandler.getServletContext().getRealPath(path);
}
/* ------------------------------------------------------------ */
public RequestDispatcher getRequestDispatcher(String url)
{
if (url == null)
return null;
if (!url.startsWith("/"))
{
String relTo=URI.addPaths(_servletPath,_pathInfo);
int slash=relTo.lastIndexOf("/");
if (slash>1)
relTo=relTo.substring(0,slash+1);
else
relTo="/";
url=URI.addPaths(relTo,url);
}
return _servletHandler.getServletContext().getRequestDispatcher(url);
}
/* ------------------------------------------------------------ */
public String toString()
{
return
getContextPath()+"+"+getServletPath()+"+"+getPathInfo()+"\n"+
_httpRequest.toString();
}
/* ------------------------------------------------------------ */
/** Unwrap a ServletRequest.
*
* @see javax.servlet.ServletRequestWrapper
* @see javax.servlet.http.HttpServletRequestWrapper
* @param request
* @return The core ServletHttpRequest which must be the
* underlying request object
*/
public static ServletHttpRequest unwrap(ServletRequest request)
{
while (!(request instanceof ServletHttpRequest))
{
if (request instanceof ServletRequestWrapper)
{
ServletRequestWrapper wrapper =
(ServletRequestWrapper)request;
request=wrapper.getRequest();
}
else
throw new IllegalArgumentException("Does not wrap ServletHttpRequest");
}
return (ServletHttpRequest)request;
}
}
| |
package com.swrve.sdk;
import android.app.Activity;
import android.content.Context;
import com.swrve.sdk.config.SwrveConfigBase;
import com.swrve.sdk.messaging.ISwrveCustomButtonListener;
import com.swrve.sdk.messaging.ISwrveDialogListener;
import com.swrve.sdk.messaging.ISwrveInstallButtonListener;
import com.swrve.sdk.messaging.ISwrveMessageListener;
import com.swrve.sdk.messaging.SwrveButton;
import com.swrve.sdk.messaging.SwrveMessage;
import com.swrve.sdk.messaging.SwrveMessageFormat;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
/**
* SwrveSDK interface. You can obtain an instance of this class using the SwrveFactory or
* SwrveInstance that creates a singleton Swrve object.
*/
public interface ISwrveBase<T, C extends SwrveConfigBase> {
/**
* Create or bind to a Swrve object. Typically this function is called in your main
* activity's onCreate function.
*
* @param activity your activity
* @param appId your app id in the Swrve dashboard
* @param apiKey your app api_key in the Swrve dashboard
* @throws IllegalArgumentException
*/
T onCreate(final Activity activity, final int appId, final String apiKey) throws IllegalArgumentException;
/**
* Create or bind to a Swrve object. Typically this function is called in your main
* activity's onCreate function.
*
* @param activity your activity
* @param appId your app id in the Swrve dashboard
* @param apiKey your app api_key in the Swrve dashboard
* @param config your SwrveConfig options
* @throws IllegalArgumentException
*/
T onCreate(final Activity activity, final int appId, final String apiKey, final C config) throws IllegalArgumentException;
/**
* Add a Swrve.session.start event to the event queue. This event should
* typically be added in your main activity's onStart method.
*/
void sessionStart();
/**
* Add a Swrve.session.end event to the event queue. This event should
* typically be added in your main activity's onStop method.
*/
void sessionEnd();
/**
* Add a generic named event to the event queue.
*
* @param name the name of the event in question. The character '.' is used
* as grouping syntax.
*/
void event(String name);
/**
* Add a generic named event to the event queue.
*
* @param name the name of the event in question. The character '.' is used
* as grouping syntax.
* @param payload a dictionary of key-value pairs to be supplied with this named
* event. Typically this would be information about the event
* rather than about the user. Compare with the userUpdate
* function for properties of the user.
*/
void event(String name, Map<String, String> payload);
/**
* Add a Swrve.user_purchase event to the event queue. This event should be
* added on virtual goods purchase in your app.
*
* @param item unique name of the purchased item
* @param currency currency in Swrve to be used for this purchase. This currency
* must be declared in the Swrve dashboard before calling this
* function. If this currency is not declared this event will be
* rejected.
* @param cost cost of the item in units of 'currency'
* @param quantity number of the item purchased
*/
void purchase(String item, String currency, int cost, int quantity);
/**
* Add a Swrve.currency_given event to the event queue. This event should be
* added on award of virtual currency in the app.
*
* @param givenCurrency currency in Swrve to be used for this gift. This currency must
* be declared in the Swrve dashboard before calling this
* function. If this currency is not declared this event will be
* rejected.
* @param givenAmount amount of currency given to the user.
*/
void currencyGiven(String givenCurrency, double givenAmount);
/**
* Add a Swrve.user event to the event queue. This event would typically be
* added to the queue after session_start and at points where properties of
* your users change - for example, levelUp.
*
* @param attributes key-value pairs of properties of the user. Typical values
* would be level => number, referrer => channel, coin balance =>
* number.
*/
void userUpdate(Map<String, String> attributes);
/**
* Add a Swrve.iap event to the event queue. This event should be added for
* unvalidated real money transactions where a single item was purchased.
* (i.e where no in-app currency or bundle was purchased)
*
* @param quantity Quantity purchased. Must be greater than zero.
* @param productId Unique product identifier for the item bought. This should
* match the Swrve resource name. Required, cannot be empty.
* @param productPrice The price (in real money) of the product that was purchased.
* Note: this is not the price of the total transaction, but the
* per-product price. Must be greater than or equal to zero.
* @param currency real world currency used for this transaction. This must be an
* ISO currency code. A typical value would be "USD". Required,
* cannot be empty.
*/
void iap(int quantity, String productId, double productPrice, String currency);
/**
* Add a Swrve.iap event to the event queue. This event should be added for
* unvalidated real money transactions where in-app currency was purchased
* or where multiple items and/or currencies were purchased.
* <p/>
* To create the rewards object, create an instance of SwrveIAPRewards and
* use addItem() and addCurrency() to add the individual rewards
*
* @param quantity Quantity purchased. Must be greater than zero.
* @param productId Unique product identifier for the item bought. This should
* match the Swrve resource name. Required, cannot be empty.
* @param productPrice price of the product in real money. Note that this is the
* price per product, not the total price of the transaction
* (when quantity > 1) A typical value would be 0.99. Must be
* greater than or equal to zero.
* @param currency real world currency used for this transaction. This must be an
* ISO currency code. A typical value would be "USD". Required,
* cannot be empty.
* @param rewards SwrveIAPRewards object containing any in-app currency and/or
* additional items included in this purchase that need to be
* recorded.
*/
void iap(int quantity, String productId, double productPrice, String currency, SwrveIAPRewards rewards);
/**
* Get the SwrveResourceManager, which can be queried for up-to-date resource attribute values
*/
SwrveResourceManager getResourceManager();
/**
* The resourcesListener onResourcesUpdated() method is invoked when user resources in the SwrveResourceManager
* have been initially loaded and each time user resources are updated.
*/
void setResourcesListener(ISwrveResourcesListener resourcesListener);
/**
* Request the list of resources for the user with full attribute data after
* any applicable AB Tests have been applied. This request is executed on a
* background thread, which will call methods on the user-provided listener
* parameter.
* <p/>
* If no user id has been specified this function raises a
* NoUserIdSwrveException exception to the listener object.
*
* @param listener
*/
void getUserResources(final ISwrveUserResourcesListener listener);
/**
* Request all applicable AB-Tested resources for the user. This request is
* executed on a background thread, which will call methods on the
* user-provided listener parameter.
* <p/>
* If no user id has been specified this function raises a
* NoUserIdSwrveException exception to the listener object.
*
* @param listener
*/
void getUserResourcesDiff(final ISwrveUserResourcesDiffListener listener);
/**
* Send events to Swrve servers.
*/
void sendQueuedEvents();
/**
* Flush events and others to the device's disk.
*/
void flushToDisk();
/**
* Default SDK behavior for activity onPause(). Flush data to disk.
* Notify the SDK that the binded activity may be finishing.
*/
void onPause();
/**
* Default SDK behavior for activity onResume(). Send events to Swrve.
*
* @param ctx Activity that called this method
*/
void onResume(Activity ctx);
/**
* Notify that the app is low on memory.
*/
void onLowMemory();
/**
* Notify that the app has closed.
*
* @param ctx Activity that called this method
*/
void onDestroy(Activity ctx);
/**
* Shutdown the SDK. This instance will be unusable after shutdown.
* <p/>
* Note: All the background jobs will try to stop when this happens.
*/
void shutdown();
/**
* Set the current language
*/
void setLanguage(Locale locale);
/**
* Get the current language
*/
String getLanguage();
/**
* Set the current language
*
* @deprecated use {@link #setLanguage(Locale)} instead
*/
@Deprecated
void setLanguage(String language);
/**
* Get the current api key
*/
String getApiKey();
/**
* Get the current user id
*/
String getUserId();
/**
* Collect device information
*
* @throws JSONException
*/
JSONObject getDeviceInfo() throws JSONException;
/**
* Update campaign and resources values
* This function will be called automatically to keep campaigns and resources up-to-date.
* You should only call this function manually if you have changed the value of
* config.autoDownloadCampaignsAndResources to false.
*/
void refreshCampaignsAndResources();
/**
* Returns a message for a given trigger event. There may be messages for
* the trigger but the rules avoid a message from being displayed at some
* point.
*
* @param event trigger event
* @return SwrveMessage supported message from a campaign set up for the
* given trigger
*/
SwrveMessage getMessageForEvent(String event);
/**
* Returns a message for a given id. This function should be used for
* retrieving a known message that is being displayed when the device's
* orientation changes.
*
* @param messageId id of the message
* @return SwrveMessage message with the given id
*/
SwrveMessage getMessageForId(int messageId);
/**
* Process a message button event. This function should be called by your
* implementation of the message renderer to inform Swrve of a button event.
*
* @param button button that was pressed.
*/
void buttonWasPressedByUser(SwrveButton button);
/**
* Inform that a message has been shown. This function should be called by
* your implementation of the message renderer to update the campaign
* information and send the appropriate data to Swrve.
*
* @param messageFormat message that was shown to the user for the first time in this
* session.
*/
void messageWasShownToUser(SwrveMessageFormat messageFormat);
/**
* Get app store link configured in the dashboard for a given app id.
*
* @param appId id of the app
* @return String App store link for the app
*/
String getAppStoreURLForApp(int appId);
/**
* Get location of the chosen cache folder where the resources will be
* downloaded.
*
* @return File path to the chosen cache folder
*/
File getCacheDir();
/**
* Set a message listener to process Talk messages.
*
* @param messageListener logic to listen for messages
*/
void setMessageListener(ISwrveMessageListener messageListener);
/**
* Get the time when the SDK was initialized.
*
* @return the time the SDK was initialized
*/
Date getInitialisedTime();
/**
* Get the custom listener to process Talk message install button clicks
*
* @return custom install button listener
*/
ISwrveInstallButtonListener getInstallButtonListener();
/**
* Set the custom listener to process Talk message install button clicks
*
* @param installButtonListener
*/
void setInstallButtonListener(ISwrveInstallButtonListener installButtonListener);
/**
* Get the custom listener to process Talk message custom button clicks
*
* @return custom button listener
*/
ISwrveCustomButtonListener getCustomButtonListener();
/**
* Set the custom listener to process Talk message custom button clicks
*
* @param customButtonListener
*/
void setCustomButtonListener(ISwrveCustomButtonListener customButtonListener);
/**
* Get the custom dialog listener for Talk message dialogs
*
* @return dialog listener
*/
ISwrveDialogListener getDialogListener();
/**
* Set the custom dialog listener for Talk message dialogs
*
* @param dialogListener
*/
void setDialogListener(ISwrveDialogListener dialogListener);
/**
* Get the context where the SDK is attached.
*
* @return activity or application context
*/
Context getContext();
/**
* Returns the Swrve configuration that was used to initialize the SDK.
*
* @return configuration used to context the SDK
*/
C getConfig();
}
| |
package ttaomae.connectn.network.server;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ttaomae.connectn.ArrayBoard;
import ttaomae.connectn.Board;
import ttaomae.connectn.IllegalMoveException;
import ttaomae.connectn.Piece;
import ttaomae.connectn.network.LostConnectionException;
import ttaomae.connectn.network.ProtocolEvent.Message;
import ttaomae.connectn.network.ProtocolException;
/**
* Manages a game between two {@linkplain ClientHandler clients}.
*
* @author Todd Taomae
*/
public class NetworkGameManager implements Callable<Void>
{
private final Logger logger = LoggerFactory.getLogger(NetworkGameManager.class);
private final ClientManager clientManager;
private final ClientHandler playerOneHandler;
private final ClientHandler playerTwoHandler;
/**
* A thread pool used to send messages to both clients simultaneously. It
* should contain only two threads and should reject anything beyond two
* simultaneous tasks.
*/
private final ExecutorService clientRequestThreadPool;
public NetworkGameManager(ClientManager clientManager,
ClientHandler playerOneHandler, ClientHandler playerTwoHandler)
{
checkNotNull(clientManager, "clientManager must not be null");
checkNotNull(playerOneHandler, "playerOneHandler must not be null");
checkNotNull(playerTwoHandler, "playerTwoHandler must not be null");
this.clientManager = clientManager;
this.playerOneHandler = playerOneHandler;
this.playerTwoHandler = playerTwoHandler;
this.clientRequestThreadPool = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS,
new SynchronousQueue<>());
}
ClientHandler getPlayerOne()
{
return this.playerOneHandler;
}
ClientHandler getPlayerTwo()
{
return this.playerTwoHandler;
}
@Override
public Void call() throws NetworkGameException
{
// this will be used to asynchronously get responses from both players
CompletionService<Boolean> completionService
= new ExecutorCompletionService<>(clientRequestThreadPool);
boolean playerOneFirst = true;
boolean rematch = true;
while (rematch) {
try {
startMatch();
} catch (LostConnectionException e) {
String message = "A player disconnected while starting match.";
logger.info(message);
throw new ClientDisconnectedException(message, e, this);
}
Board board = new ArrayBoard();
try {
playMatch(board, playerOneFirst);
} catch (LostConnectionException e) {
String message = "A player disconnected while playing match.";
logger.info(message);
throw new ClientDisconnectedException(message, e, this);
}
completionService.submit(() -> handleRematchRequest(playerOneHandler));
completionService.submit(() -> handleRematchRequest(playerTwoHandler));
try {
boolean firstResponse = completionService.take().get();
boolean secondResponse = completionService.take().get();
// only rematch if both accept
rematch = firstResponse && secondResponse;
}
catch (ExecutionException | InterruptedException e) {
if (e.getCause() instanceof LostConnectionException) {
String message = "A player disconnected while waiting for rematch response.";
logger.info(message);
throw new ClientDisconnectedException(message, e.getCause(), this);
}
else {
String errorMessage = "Error occurred while waiting for rematch response";
logger.error(errorMessage, e);
throw new NetworkGameException(errorMessage, e, this);
}
}
if (!rematch) {
this.clientManager.playerMatchEnded(playerOneHandler);
this.clientManager.playerMatchEnded(playerTwoHandler);
}
// switch player order for next game
playerOneFirst = !playerOneFirst;
}
return null;
}
private void startMatch() throws LostConnectionException
{
logger.info("Starting match between {} and {}", playerOneHandler, playerTwoHandler);
playerOneHandler.sendMessage(Message.START_GAME);
playerTwoHandler.sendMessage(Message.START_GAME);
}
private void playMatch(Board board, boolean playerOneFirst) throws LostConnectionException
{
assert board.getCurrentTurn() == 0 : "board must be empty";
while (board.getWinner() == Piece.NONE) {
// determine which is the current / next player
ClientHandler currentPlayer;
if (playerOneFirst) {
currentPlayer = board.getNextPiece() == Piece.BLACK
? playerOneHandler : playerTwoHandler;
}
else {
currentPlayer = board.getNextPiece() == Piece.BLACK
? playerTwoHandler : playerOneHandler;
}
ClientHandler nextPlayer = getOpponent(currentPlayer);
Optional<Integer> optionalMove = getMove(currentPlayer);
if (!optionalMove.isPresent()) {
throw new ProtocolException("Received empty move");
}
int move = optionalMove.get();
if (!board.isValidMove(move)) {
throw new IllegalMoveException("Client sent illegal move: " + move);
}
board.play(move);
nextPlayer.sendOpponentMove(move);
}
}
private ClientHandler getOpponent(ClientHandler player)
{
assert managerOwnsPlayer(player) : "player does not belong to this game manager";
if (player == this.playerOneHandler) {
return this.playerTwoHandler;
}
else {
return this.playerOneHandler;
}
}
private Optional<Integer> getMove(ClientHandler player) throws LostConnectionException
{
assert managerOwnsPlayer(player) : "player does not belong to this game manager";
try {
return player.getMove(null);
}
catch (RuntimeException e) {
if (e.getCause().getClass() == LostConnectionException.class) {
throw (LostConnectionException)(e.getCause());
}
else {
throw e;
}
}
}
private boolean handleRematchRequest(ClientHandler player) throws LostConnectionException
{
assert managerOwnsPlayer(player) : "player does not belong to this game manager";
ClientHandler opponent = getOpponent(player);
boolean acceptRematch = player.requestRematch();
if (acceptRematch) {
opponent.sendMessage(Message.ACCEPT_REMATCH);
}
else {
opponent.sendMessage(Message.DENY_REMATCH);
}
return acceptRematch;
}
private boolean managerOwnsPlayer(ClientHandler player)
{
return player == playerOneHandler || player == playerTwoHandler;
}
}
| |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.simpleemail.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* The content of the email, composed of a subject line, an HTML part, and a text-only part.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/Template" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class Template implements Serializable, Cloneable {
/**
* <p>
* The name of the template. You will refer to this name when you send email using the
* <code>SendTemplatedEmail</code> or <code>SendBulkTemplatedEmail</code> operations.
* </p>
*/
private String templateName;
/**
* <p>
* The subject line of the email.
* </p>
*/
private String subjectPart;
/**
* <p>
* The email body that will be visible to recipients whose email clients do not display HTML.
* </p>
*/
private String textPart;
/**
* <p>
* The HTML body of the email.
* </p>
*/
private String htmlPart;
/**
* <p>
* The name of the template. You will refer to this name when you send email using the
* <code>SendTemplatedEmail</code> or <code>SendBulkTemplatedEmail</code> operations.
* </p>
*
* @param templateName
* The name of the template. You will refer to this name when you send email using the
* <code>SendTemplatedEmail</code> or <code>SendBulkTemplatedEmail</code> operations.
*/
public void setTemplateName(String templateName) {
this.templateName = templateName;
}
/**
* <p>
* The name of the template. You will refer to this name when you send email using the
* <code>SendTemplatedEmail</code> or <code>SendBulkTemplatedEmail</code> operations.
* </p>
*
* @return The name of the template. You will refer to this name when you send email using the
* <code>SendTemplatedEmail</code> or <code>SendBulkTemplatedEmail</code> operations.
*/
public String getTemplateName() {
return this.templateName;
}
/**
* <p>
* The name of the template. You will refer to this name when you send email using the
* <code>SendTemplatedEmail</code> or <code>SendBulkTemplatedEmail</code> operations.
* </p>
*
* @param templateName
* The name of the template. You will refer to this name when you send email using the
* <code>SendTemplatedEmail</code> or <code>SendBulkTemplatedEmail</code> operations.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Template withTemplateName(String templateName) {
setTemplateName(templateName);
return this;
}
/**
* <p>
* The subject line of the email.
* </p>
*
* @param subjectPart
* The subject line of the email.
*/
public void setSubjectPart(String subjectPart) {
this.subjectPart = subjectPart;
}
/**
* <p>
* The subject line of the email.
* </p>
*
* @return The subject line of the email.
*/
public String getSubjectPart() {
return this.subjectPart;
}
/**
* <p>
* The subject line of the email.
* </p>
*
* @param subjectPart
* The subject line of the email.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Template withSubjectPart(String subjectPart) {
setSubjectPart(subjectPart);
return this;
}
/**
* <p>
* The email body that will be visible to recipients whose email clients do not display HTML.
* </p>
*
* @param textPart
* The email body that will be visible to recipients whose email clients do not display HTML.
*/
public void setTextPart(String textPart) {
this.textPart = textPart;
}
/**
* <p>
* The email body that will be visible to recipients whose email clients do not display HTML.
* </p>
*
* @return The email body that will be visible to recipients whose email clients do not display HTML.
*/
public String getTextPart() {
return this.textPart;
}
/**
* <p>
* The email body that will be visible to recipients whose email clients do not display HTML.
* </p>
*
* @param textPart
* The email body that will be visible to recipients whose email clients do not display HTML.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Template withTextPart(String textPart) {
setTextPart(textPart);
return this;
}
/**
* <p>
* The HTML body of the email.
* </p>
*
* @param htmlPart
* The HTML body of the email.
*/
public void setHtmlPart(String htmlPart) {
this.htmlPart = htmlPart;
}
/**
* <p>
* The HTML body of the email.
* </p>
*
* @return The HTML body of the email.
*/
public String getHtmlPart() {
return this.htmlPart;
}
/**
* <p>
* The HTML body of the email.
* </p>
*
* @param htmlPart
* The HTML body of the email.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Template withHtmlPart(String htmlPart) {
setHtmlPart(htmlPart);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getTemplateName() != null)
sb.append("TemplateName: ").append(getTemplateName()).append(",");
if (getSubjectPart() != null)
sb.append("SubjectPart: ").append(getSubjectPart()).append(",");
if (getTextPart() != null)
sb.append("TextPart: ").append(getTextPart()).append(",");
if (getHtmlPart() != null)
sb.append("HtmlPart: ").append(getHtmlPart());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Template == false)
return false;
Template other = (Template) obj;
if (other.getTemplateName() == null ^ this.getTemplateName() == null)
return false;
if (other.getTemplateName() != null && other.getTemplateName().equals(this.getTemplateName()) == false)
return false;
if (other.getSubjectPart() == null ^ this.getSubjectPart() == null)
return false;
if (other.getSubjectPart() != null && other.getSubjectPart().equals(this.getSubjectPart()) == false)
return false;
if (other.getTextPart() == null ^ this.getTextPart() == null)
return false;
if (other.getTextPart() != null && other.getTextPart().equals(this.getTextPart()) == false)
return false;
if (other.getHtmlPart() == null ^ this.getHtmlPart() == null)
return false;
if (other.getHtmlPart() != null && other.getHtmlPart().equals(this.getHtmlPart()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getTemplateName() == null) ? 0 : getTemplateName().hashCode());
hashCode = prime * hashCode + ((getSubjectPart() == null) ? 0 : getSubjectPart().hashCode());
hashCode = prime * hashCode + ((getTextPart() == null) ? 0 : getTextPart().hashCode());
hashCode = prime * hashCode + ((getHtmlPart() == null) ? 0 : getHtmlPart().hashCode());
return hashCode;
}
@Override
public Template clone() {
try {
return (Template) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.ec2.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* Describes the status of a client connection.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ClientVpnConnectionStatus" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ClientVpnConnectionStatus implements Serializable, Cloneable {
/**
* <p>
* The state of the client connection.
* </p>
*/
private String code;
/**
* <p>
* A message about the status of the client connection, if applicable.
* </p>
*/
private String message;
/**
* <p>
* The state of the client connection.
* </p>
*
* @param code
* The state of the client connection.
* @see ClientVpnConnectionStatusCode
*/
public void setCode(String code) {
this.code = code;
}
/**
* <p>
* The state of the client connection.
* </p>
*
* @return The state of the client connection.
* @see ClientVpnConnectionStatusCode
*/
public String getCode() {
return this.code;
}
/**
* <p>
* The state of the client connection.
* </p>
*
* @param code
* The state of the client connection.
* @return Returns a reference to this object so that method calls can be chained together.
* @see ClientVpnConnectionStatusCode
*/
public ClientVpnConnectionStatus withCode(String code) {
setCode(code);
return this;
}
/**
* <p>
* The state of the client connection.
* </p>
*
* @param code
* The state of the client connection.
* @return Returns a reference to this object so that method calls can be chained together.
* @see ClientVpnConnectionStatusCode
*/
public ClientVpnConnectionStatus withCode(ClientVpnConnectionStatusCode code) {
this.code = code.toString();
return this;
}
/**
* <p>
* A message about the status of the client connection, if applicable.
* </p>
*
* @param message
* A message about the status of the client connection, if applicable.
*/
public void setMessage(String message) {
this.message = message;
}
/**
* <p>
* A message about the status of the client connection, if applicable.
* </p>
*
* @return A message about the status of the client connection, if applicable.
*/
public String getMessage() {
return this.message;
}
/**
* <p>
* A message about the status of the client connection, if applicable.
* </p>
*
* @param message
* A message about the status of the client connection, if applicable.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ClientVpnConnectionStatus withMessage(String message) {
setMessage(message);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getCode() != null)
sb.append("Code: ").append(getCode()).append(",");
if (getMessage() != null)
sb.append("Message: ").append(getMessage());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ClientVpnConnectionStatus == false)
return false;
ClientVpnConnectionStatus other = (ClientVpnConnectionStatus) obj;
if (other.getCode() == null ^ this.getCode() == null)
return false;
if (other.getCode() != null && other.getCode().equals(this.getCode()) == false)
return false;
if (other.getMessage() == null ^ this.getMessage() == null)
return false;
if (other.getMessage() != null && other.getMessage().equals(this.getMessage()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getCode() == null) ? 0 : getCode().hashCode());
hashCode = prime * hashCode + ((getMessage() == null) ? 0 : getMessage().hashCode());
return hashCode;
}
@Override
public ClientVpnConnectionStatus clone() {
try {
return (ClientVpnConnectionStatus) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| |
/*
* Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.dynamodb.model;
/**
* Scan Result
*/
public class ScanResult {
private java.util.List<java.util.Map<String,AttributeValue>> items;
/**
* Number of items in the response.
*/
private Integer count;
/**
* Number of items in the complete scan before any filters are applied. A
* high <code>ScannedCount</code> value with few, or no,
* <code>Count</code> results indicates an inefficient <code>Scan</code>
* operation.
*/
private Integer scannedCount;
/**
* Primary key of the item where the scan operation stopped. Provide this
* value in a subsequent scan operation to continue the operation from
* that point. The <code>LastEvaluatedKey</code> is null when the entire
* scan result set is complete (i.e. the operation processed the "last
* page").
*/
private Key lastEvaluatedKey;
/**
* The number of Capacity Units of the provisioned throughput of the
* table consumed during the operation. <code>GetItem</code>,
* <code>BatchGetItem</code>, <code>BatchWriteItem</code>,
* <code>Query</code>, and <code>Scan</code> operations consume
* <code>ReadCapacityUnits</code>, while <code>PutItem</code>,
* <code>UpdateItem</code>, and <code>DeleteItem</code> operations
* consume <code>WriteCapacityUnits</code>.
*/
private Double consumedCapacityUnits;
/**
* Returns the value of the Items property for this object.
*
* @return The value of the Items property for this object.
*/
public java.util.List<java.util.Map<String,AttributeValue>> getItems() {
return items;
}
/**
* Sets the value of the Items property for this object.
*
* @param items The new value for the Items property for this object.
*/
public void setItems(java.util.Collection<java.util.Map<String,AttributeValue>> items) {
if (items == null) {
this.items = null;
return;
}
java.util.List<java.util.Map<String,AttributeValue>> itemsCopy = new java.util.ArrayList<java.util.Map<String,AttributeValue>>(items.size());
itemsCopy.addAll(items);
this.items = itemsCopy;
}
/**
* Sets the value of the Items property for this object.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param items The new value for the Items property for this object.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public ScanResult withItems(java.util.Map<String,AttributeValue>... items) {
if (getItems() == null) setItems(new java.util.ArrayList<java.util.Map<String,AttributeValue>>(items.length));
for (java.util.Map<String,AttributeValue> value : items) {
getItems().add(value);
}
return this;
}
/**
* Sets the value of the Items property for this object.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param items The new value for the Items property for this object.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public ScanResult withItems(java.util.Collection<java.util.Map<String,AttributeValue>> items) {
if (items == null) {
this.items = null;
} else {
java.util.List<java.util.Map<String,AttributeValue>> itemsCopy = new java.util.ArrayList<java.util.Map<String,AttributeValue>>(items.size());
itemsCopy.addAll(items);
this.items = itemsCopy;
}
return this;
}
/**
* Number of items in the response.
*
* @return Number of items in the response.
*/
public Integer getCount() {
return count;
}
/**
* Number of items in the response.
*
* @param count Number of items in the response.
*/
public void setCount(Integer count) {
this.count = count;
}
/**
* Number of items in the response.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param count Number of items in the response.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public ScanResult withCount(Integer count) {
this.count = count;
return this;
}
/**
* Number of items in the complete scan before any filters are applied. A
* high <code>ScannedCount</code> value with few, or no,
* <code>Count</code> results indicates an inefficient <code>Scan</code>
* operation.
*
* @return Number of items in the complete scan before any filters are applied. A
* high <code>ScannedCount</code> value with few, or no,
* <code>Count</code> results indicates an inefficient <code>Scan</code>
* operation.
*/
public Integer getScannedCount() {
return scannedCount;
}
/**
* Number of items in the complete scan before any filters are applied. A
* high <code>ScannedCount</code> value with few, or no,
* <code>Count</code> results indicates an inefficient <code>Scan</code>
* operation.
*
* @param scannedCount Number of items in the complete scan before any filters are applied. A
* high <code>ScannedCount</code> value with few, or no,
* <code>Count</code> results indicates an inefficient <code>Scan</code>
* operation.
*/
public void setScannedCount(Integer scannedCount) {
this.scannedCount = scannedCount;
}
/**
* Number of items in the complete scan before any filters are applied. A
* high <code>ScannedCount</code> value with few, or no,
* <code>Count</code> results indicates an inefficient <code>Scan</code>
* operation.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param scannedCount Number of items in the complete scan before any filters are applied. A
* high <code>ScannedCount</code> value with few, or no,
* <code>Count</code> results indicates an inefficient <code>Scan</code>
* operation.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public ScanResult withScannedCount(Integer scannedCount) {
this.scannedCount = scannedCount;
return this;
}
/**
* Primary key of the item where the scan operation stopped. Provide this
* value in a subsequent scan operation to continue the operation from
* that point. The <code>LastEvaluatedKey</code> is null when the entire
* scan result set is complete (i.e. the operation processed the "last
* page").
*
* @return Primary key of the item where the scan operation stopped. Provide this
* value in a subsequent scan operation to continue the operation from
* that point. The <code>LastEvaluatedKey</code> is null when the entire
* scan result set is complete (i.e. the operation processed the "last
* page").
*/
public Key getLastEvaluatedKey() {
return lastEvaluatedKey;
}
/**
* Primary key of the item where the scan operation stopped. Provide this
* value in a subsequent scan operation to continue the operation from
* that point. The <code>LastEvaluatedKey</code> is null when the entire
* scan result set is complete (i.e. the operation processed the "last
* page").
*
* @param lastEvaluatedKey Primary key of the item where the scan operation stopped. Provide this
* value in a subsequent scan operation to continue the operation from
* that point. The <code>LastEvaluatedKey</code> is null when the entire
* scan result set is complete (i.e. the operation processed the "last
* page").
*/
public void setLastEvaluatedKey(Key lastEvaluatedKey) {
this.lastEvaluatedKey = lastEvaluatedKey;
}
/**
* Primary key of the item where the scan operation stopped. Provide this
* value in a subsequent scan operation to continue the operation from
* that point. The <code>LastEvaluatedKey</code> is null when the entire
* scan result set is complete (i.e. the operation processed the "last
* page").
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param lastEvaluatedKey Primary key of the item where the scan operation stopped. Provide this
* value in a subsequent scan operation to continue the operation from
* that point. The <code>LastEvaluatedKey</code> is null when the entire
* scan result set is complete (i.e. the operation processed the "last
* page").
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public ScanResult withLastEvaluatedKey(Key lastEvaluatedKey) {
this.lastEvaluatedKey = lastEvaluatedKey;
return this;
}
/**
* The number of Capacity Units of the provisioned throughput of the
* table consumed during the operation. <code>GetItem</code>,
* <code>BatchGetItem</code>, <code>BatchWriteItem</code>,
* <code>Query</code>, and <code>Scan</code> operations consume
* <code>ReadCapacityUnits</code>, while <code>PutItem</code>,
* <code>UpdateItem</code>, and <code>DeleteItem</code> operations
* consume <code>WriteCapacityUnits</code>.
*
* @return The number of Capacity Units of the provisioned throughput of the
* table consumed during the operation. <code>GetItem</code>,
* <code>BatchGetItem</code>, <code>BatchWriteItem</code>,
* <code>Query</code>, and <code>Scan</code> operations consume
* <code>ReadCapacityUnits</code>, while <code>PutItem</code>,
* <code>UpdateItem</code>, and <code>DeleteItem</code> operations
* consume <code>WriteCapacityUnits</code>.
*/
public Double getConsumedCapacityUnits() {
return consumedCapacityUnits;
}
/**
* The number of Capacity Units of the provisioned throughput of the
* table consumed during the operation. <code>GetItem</code>,
* <code>BatchGetItem</code>, <code>BatchWriteItem</code>,
* <code>Query</code>, and <code>Scan</code> operations consume
* <code>ReadCapacityUnits</code>, while <code>PutItem</code>,
* <code>UpdateItem</code>, and <code>DeleteItem</code> operations
* consume <code>WriteCapacityUnits</code>.
*
* @param consumedCapacityUnits The number of Capacity Units of the provisioned throughput of the
* table consumed during the operation. <code>GetItem</code>,
* <code>BatchGetItem</code>, <code>BatchWriteItem</code>,
* <code>Query</code>, and <code>Scan</code> operations consume
* <code>ReadCapacityUnits</code>, while <code>PutItem</code>,
* <code>UpdateItem</code>, and <code>DeleteItem</code> operations
* consume <code>WriteCapacityUnits</code>.
*/
public void setConsumedCapacityUnits(Double consumedCapacityUnits) {
this.consumedCapacityUnits = consumedCapacityUnits;
}
/**
* The number of Capacity Units of the provisioned throughput of the
* table consumed during the operation. <code>GetItem</code>,
* <code>BatchGetItem</code>, <code>BatchWriteItem</code>,
* <code>Query</code>, and <code>Scan</code> operations consume
* <code>ReadCapacityUnits</code>, while <code>PutItem</code>,
* <code>UpdateItem</code>, and <code>DeleteItem</code> operations
* consume <code>WriteCapacityUnits</code>.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param consumedCapacityUnits The number of Capacity Units of the provisioned throughput of the
* table consumed during the operation. <code>GetItem</code>,
* <code>BatchGetItem</code>, <code>BatchWriteItem</code>,
* <code>Query</code>, and <code>Scan</code> operations consume
* <code>ReadCapacityUnits</code>, while <code>PutItem</code>,
* <code>UpdateItem</code>, and <code>DeleteItem</code> operations
* consume <code>WriteCapacityUnits</code>.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public ScanResult withConsumedCapacityUnits(Double consumedCapacityUnits) {
this.consumedCapacityUnits = consumedCapacityUnits;
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (items != null) sb.append("Items: " + items + ", ");
if (count != null) sb.append("Count: " + count + ", ");
if (scannedCount != null) sb.append("ScannedCount: " + scannedCount + ", ");
if (lastEvaluatedKey != null) sb.append("LastEvaluatedKey: " + lastEvaluatedKey + ", ");
if (consumedCapacityUnits != null) sb.append("ConsumedCapacityUnits: " + consumedCapacityUnits + ", ");
sb.append("}");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getItems() == null) ? 0 : getItems().hashCode());
hashCode = prime * hashCode + ((getCount() == null) ? 0 : getCount().hashCode());
hashCode = prime * hashCode + ((getScannedCount() == null) ? 0 : getScannedCount().hashCode());
hashCode = prime * hashCode + ((getLastEvaluatedKey() == null) ? 0 : getLastEvaluatedKey().hashCode());
hashCode = prime * hashCode + ((getConsumedCapacityUnits() == null) ? 0 : getConsumedCapacityUnits().hashCode());
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj instanceof ScanResult == false) return false;
ScanResult other = (ScanResult)obj;
if (other.getItems() == null ^ this.getItems() == null) return false;
if (other.getItems() != null && other.getItems().equals(this.getItems()) == false) return false;
if (other.getCount() == null ^ this.getCount() == null) return false;
if (other.getCount() != null && other.getCount().equals(this.getCount()) == false) return false;
if (other.getScannedCount() == null ^ this.getScannedCount() == null) return false;
if (other.getScannedCount() != null && other.getScannedCount().equals(this.getScannedCount()) == false) return false;
if (other.getLastEvaluatedKey() == null ^ this.getLastEvaluatedKey() == null) return false;
if (other.getLastEvaluatedKey() != null && other.getLastEvaluatedKey().equals(this.getLastEvaluatedKey()) == false) return false;
if (other.getConsumedCapacityUnits() == null ^ this.getConsumedCapacityUnits() == null) return false;
if (other.getConsumedCapacityUnits() != null && other.getConsumedCapacityUnits().equals(this.getConsumedCapacityUnits()) == false) return false;
return true;
}
}
| |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.trans.steps.blockingstep;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.annotations.PluginDialog;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.steps.blockingstep.BlockingStepMeta;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
@PluginDialog( id = "BlockingStep", image = "BLK.svg", pluginType = PluginDialog.PluginType.STEP,
documentationUrl = "http://wiki.pentaho.com/display/EAI/Blocking+step" )
public class BlockingStepDialog extends BaseStepDialog implements StepDialogInterface {
private static Class<?> PKG = BlockingStepDialog.class; // for i18n purposes, needed by Translator2!!
private BlockingStepMeta input;
private Label wlPassAllRows;
private Button wPassAllRows;
private Label wlSpoolDir;
private Button wbSpoolDir;
private TextVar wSpoolDir;
private FormData fdlSpoolDir, fdbSpoolDir, fdSpoolDir;
private Label wlPrefix;
private Text wPrefix;
private FormData fdlPrefix, fdPrefix;
private Label wlCacheSize;
private Text wCacheSize;
private FormData fdlCacheSize, fdCacheSize;
private Label wlCompress;
private Button wCompress;
private FormData fdlCompress, fdCompress;
public BlockingStepDialog( Shell parent, Object in, TransMeta transMeta, String sname ) {
super( parent, (BaseStepMeta) in, transMeta, sname );
input = (BlockingStepMeta) in;
}
public String open() {
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX );
props.setLook( shell );
setShellImage( shell, input );
ModifyListener lsMod = new ModifyListener() {
public void modifyText( ModifyEvent e ) {
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout( formLayout );
shell.setText( BaseMessages.getString( PKG, "BlockingStepDialog.Shell.Title" ) );
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Stepname line
wlStepname = new Label( shell, SWT.RIGHT );
wlStepname.setText( BaseMessages.getString( PKG, "BlockingStepDialog.Stepname.Label" ) );
props.setLook( wlStepname );
fdlStepname = new FormData();
fdlStepname.left = new FormAttachment( 0, 0 );
fdlStepname.right = new FormAttachment( middle, -margin );
fdlStepname.top = new FormAttachment( 0, margin );
wlStepname.setLayoutData( fdlStepname );
wStepname = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wStepname.setText( stepname );
props.setLook( wStepname );
wStepname.addModifyListener( lsMod );
fdStepname = new FormData();
fdStepname.left = new FormAttachment( middle, 0 );
fdStepname.top = new FormAttachment( 0, margin );
fdStepname.right = new FormAttachment( 100, 0 );
wStepname.setLayoutData( fdStepname );
// Update the dimension?
wlPassAllRows = new Label( shell, SWT.RIGHT );
wlPassAllRows.setText( BaseMessages.getString( PKG, "BlockingStepDialog.PassAllRows.Label" ) );
props.setLook( wlPassAllRows );
FormData fdlUpdate = new FormData();
fdlUpdate.left = new FormAttachment( 0, 0 );
fdlUpdate.right = new FormAttachment( middle, -margin );
fdlUpdate.top = new FormAttachment( wStepname, margin );
wlPassAllRows.setLayoutData( fdlUpdate );
wPassAllRows = new Button( shell, SWT.CHECK );
props.setLook( wPassAllRows );
FormData fdUpdate = new FormData();
fdUpdate.left = new FormAttachment( middle, 0 );
fdUpdate.top = new FormAttachment( wStepname, margin );
fdUpdate.right = new FormAttachment( 100, 0 );
wPassAllRows.setLayoutData( fdUpdate );
// Clicking on update changes the options in the update combo boxes!
wPassAllRows.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent e ) {
input.setChanged();
setEnableDialog();
}
} );
// Temp directory for sorting
wlSpoolDir = new Label( shell, SWT.RIGHT );
wlSpoolDir.setText( BaseMessages.getString( PKG, "BlockingStepDialog.SpoolDir.Label" ) );
props.setLook( wlSpoolDir );
fdlSpoolDir = new FormData();
fdlSpoolDir.left = new FormAttachment( 0, 0 );
fdlSpoolDir.right = new FormAttachment( middle, -margin );
fdlSpoolDir.top = new FormAttachment( wPassAllRows, margin );
wlSpoolDir.setLayoutData( fdlSpoolDir );
wbSpoolDir = new Button( shell, SWT.PUSH | SWT.CENTER );
props.setLook( wbSpoolDir );
wbSpoolDir.setText( BaseMessages.getString( PKG, "System.Button.Browse" ) );
fdbSpoolDir = new FormData();
fdbSpoolDir.right = new FormAttachment( 100, 0 );
fdbSpoolDir.top = new FormAttachment( wPassAllRows, margin );
wbSpoolDir.setLayoutData( fdbSpoolDir );
wSpoolDir = new TextVar( transMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wSpoolDir );
wSpoolDir.addModifyListener( lsMod );
fdSpoolDir = new FormData();
fdSpoolDir.left = new FormAttachment( middle, 0 );
fdSpoolDir.top = new FormAttachment( wPassAllRows, margin );
fdSpoolDir.right = new FormAttachment( wbSpoolDir, -margin );
wSpoolDir.setLayoutData( fdSpoolDir );
wbSpoolDir.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent arg0 ) {
DirectoryDialog dd = new DirectoryDialog( shell, SWT.NONE );
dd.setFilterPath( wSpoolDir.getText() );
String dir = dd.open();
if ( dir != null ) {
wSpoolDir.setText( dir );
}
}
} );
// Whenever something changes, set the tooltip to the expanded version:
wSpoolDir.addModifyListener( new ModifyListener() {
public void modifyText( ModifyEvent e ) {
wSpoolDir.setToolTipText( transMeta.environmentSubstitute( wSpoolDir.getText() ) );
}
} );
// Prefix of temporary file
wlPrefix = new Label( shell, SWT.RIGHT );
wlPrefix.setText( BaseMessages.getString( PKG, "BlockingStepDialog.Prefix.Label" ) );
props.setLook( wlPrefix );
fdlPrefix = new FormData();
fdlPrefix.left = new FormAttachment( 0, 0 );
fdlPrefix.right = new FormAttachment( middle, -margin );
fdlPrefix.top = new FormAttachment( wbSpoolDir, margin * 2 );
wlPrefix.setLayoutData( fdlPrefix );
wPrefix = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wPrefix );
wPrefix.addModifyListener( lsMod );
fdPrefix = new FormData();
fdPrefix.left = new FormAttachment( middle, 0 );
fdPrefix.top = new FormAttachment( wbSpoolDir, margin * 2 );
fdPrefix.right = new FormAttachment( 100, 0 );
wPrefix.setLayoutData( fdPrefix );
// Maximum number of lines to keep in memory before using temporary files
wlCacheSize = new Label( shell, SWT.RIGHT );
wlCacheSize.setText( BaseMessages.getString( PKG, "BlockingStepDialog.CacheSize.Label" ) );
props.setLook( wlCacheSize );
fdlCacheSize = new FormData();
fdlCacheSize.left = new FormAttachment( 0, 0 );
fdlCacheSize.right = new FormAttachment( middle, -margin );
fdlCacheSize.top = new FormAttachment( wPrefix, margin * 2 );
wlCacheSize.setLayoutData( fdlCacheSize );
wCacheSize = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wCacheSize );
wCacheSize.addModifyListener( lsMod );
fdCacheSize = new FormData();
fdCacheSize.left = new FormAttachment( middle, 0 );
fdCacheSize.top = new FormAttachment( wPrefix, margin * 2 );
fdCacheSize.right = new FormAttachment( 100, 0 );
wCacheSize.setLayoutData( fdCacheSize );
// Using compression for temporary files?
wlCompress = new Label( shell, SWT.RIGHT );
wlCompress.setText( BaseMessages.getString( PKG, "BlockingStepDialog.Compress.Label" ) );
props.setLook( wlCompress );
fdlCompress = new FormData();
fdlCompress.left = new FormAttachment( 0, 0 );
fdlCompress.right = new FormAttachment( middle, -margin );
fdlCompress.top = new FormAttachment( wCacheSize, margin * 2 );
wlCompress.setLayoutData( fdlCompress );
wCompress = new Button( shell, SWT.CHECK );
props.setLook( wCompress );
fdCompress = new FormData();
fdCompress.left = new FormAttachment( middle, 0 );
fdCompress.top = new FormAttachment( wCacheSize, margin * 2 );
fdCompress.right = new FormAttachment( 100, 0 );
wCompress.setLayoutData( fdCompress );
wCompress.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent e ) {
input.setChanged();
}
} );
// Some buttons
wOK = new Button( shell, SWT.PUSH );
wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) );
wCancel = new Button( shell, SWT.PUSH );
wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) );
setButtonPositions( new Button[] {
wOK, wCancel }, margin, wCompress );
// Add listeners
lsCancel = new Listener() {
public void handleEvent( Event e ) {
cancel();
}
};
lsOK = new Listener() {
public void handleEvent( Event e ) {
ok();
}
};
wCancel.addListener( SWT.Selection, lsCancel );
wOK.addListener( SWT.Selection, lsOK );
lsDef = new SelectionAdapter() {
public void widgetDefaultSelected( SelectionEvent e ) {
ok();
}
};
wStepname.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() {
public void shellClosed( ShellEvent e ) {
cancel();
}
} );
// Set the shell size, based upon previous time...
setSize();
getData();
input.setChanged( changed );
// Set the enablement of the dialog widgets
setEnableDialog();
shell.open();
while ( !shell.isDisposed() ) {
if ( !display.readAndDispatch() ) {
display.sleep();
}
}
return stepname;
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData() {
wPassAllRows.setSelection( input.isPassAllRows() );
if ( input.getPrefix() != null ) {
wPrefix.setText( input.getPrefix() );
}
if ( input.getDirectory() != null ) {
wSpoolDir.setText( input.getDirectory() );
}
wCacheSize.setText( "" + input.getCacheSize() );
wCompress.setSelection( input.getCompress() );
wStepname.selectAll();
wStepname.setFocus();
}
private void cancel() {
stepname = null;
input.setChanged( changed );
dispose();
}
private void ok() {
if ( Utils.isEmpty( wStepname.getText() ) ) {
return;
}
stepname = wStepname.getText(); // return value
input.setPrefix( wPrefix.getText() );
input.setDirectory( wSpoolDir.getText() );
input.setCacheSize( Const.toInt( wCacheSize.getText(), BlockingStepMeta.CACHE_SIZE ) );
if ( isDetailed() ) {
logDetailed( "Compression is set to " + wCompress.getSelection() );
}
input.setCompress( wCompress.getSelection() );
input.setPassAllRows( wPassAllRows.getSelection() );
dispose();
}
/**
* Set the correct state "enabled or not" of the dialog widgets.
*/
private void setEnableDialog() {
wlSpoolDir.setEnabled( wPassAllRows.getSelection() );
wbSpoolDir.setEnabled( wPassAllRows.getSelection() );
wSpoolDir.setEnabled( wPassAllRows.getSelection() );
wlPrefix.setEnabled( wPassAllRows.getSelection() );
wPrefix.setEnabled( wPassAllRows.getSelection() );
wlCacheSize.setEnabled( wPassAllRows.getSelection() );
wCacheSize.setEnabled( wPassAllRows.getSelection() );
wlCompress.setEnabled( wPassAllRows.getSelection() );
wCompress.setEnabled( wPassAllRows.getSelection() );
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/iot/v1/resources.proto
package com.google.cloud.iot.v1;
/**
*
*
* <pre>
* The configuration of MQTT for a device registry.
* </pre>
*
* Protobuf type {@code google.cloud.iot.v1.MqttConfig}
*/
public final class MqttConfig extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.iot.v1.MqttConfig)
MqttConfigOrBuilder {
private static final long serialVersionUID = 0L;
// Use MqttConfig.newBuilder() to construct.
private MqttConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private MqttConfig() {
mqttEnabledState_ = 0;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private MqttConfig(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 8:
{
int rawValue = input.readEnum();
mqttEnabledState_ = rawValue;
break;
}
default:
{
if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.iot.v1.ResourcesProto
.internal_static_google_cloud_iot_v1_MqttConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.iot.v1.ResourcesProto
.internal_static_google_cloud_iot_v1_MqttConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.iot.v1.MqttConfig.class,
com.google.cloud.iot.v1.MqttConfig.Builder.class);
}
public static final int MQTT_ENABLED_STATE_FIELD_NUMBER = 1;
private int mqttEnabledState_;
/**
*
*
* <pre>
* If enabled, allows connections using the MQTT protocol. Otherwise, MQTT
* connections to this registry will fail.
* </pre>
*
* <code>.google.cloud.iot.v1.MqttState mqtt_enabled_state = 1;</code>
*/
public int getMqttEnabledStateValue() {
return mqttEnabledState_;
}
/**
*
*
* <pre>
* If enabled, allows connections using the MQTT protocol. Otherwise, MQTT
* connections to this registry will fail.
* </pre>
*
* <code>.google.cloud.iot.v1.MqttState mqtt_enabled_state = 1;</code>
*/
public com.google.cloud.iot.v1.MqttState getMqttEnabledState() {
@SuppressWarnings("deprecation")
com.google.cloud.iot.v1.MqttState result =
com.google.cloud.iot.v1.MqttState.valueOf(mqttEnabledState_);
return result == null ? com.google.cloud.iot.v1.MqttState.UNRECOGNIZED : result;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (mqttEnabledState_ != com.google.cloud.iot.v1.MqttState.MQTT_STATE_UNSPECIFIED.getNumber()) {
output.writeEnum(1, mqttEnabledState_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (mqttEnabledState_ != com.google.cloud.iot.v1.MqttState.MQTT_STATE_UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, mqttEnabledState_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.iot.v1.MqttConfig)) {
return super.equals(obj);
}
com.google.cloud.iot.v1.MqttConfig other = (com.google.cloud.iot.v1.MqttConfig) obj;
boolean result = true;
result = result && mqttEnabledState_ == other.mqttEnabledState_;
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + MQTT_ENABLED_STATE_FIELD_NUMBER;
hash = (53 * hash) + mqttEnabledState_;
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.iot.v1.MqttConfig parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iot.v1.MqttConfig parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.iot.v1.MqttConfig parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iot.v1.MqttConfig parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.iot.v1.MqttConfig parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iot.v1.MqttConfig parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.iot.v1.MqttConfig parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.iot.v1.MqttConfig parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.iot.v1.MqttConfig parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.iot.v1.MqttConfig parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.iot.v1.MqttConfig parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.iot.v1.MqttConfig parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.iot.v1.MqttConfig prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The configuration of MQTT for a device registry.
* </pre>
*
* Protobuf type {@code google.cloud.iot.v1.MqttConfig}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.iot.v1.MqttConfig)
com.google.cloud.iot.v1.MqttConfigOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.iot.v1.ResourcesProto
.internal_static_google_cloud_iot_v1_MqttConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.iot.v1.ResourcesProto
.internal_static_google_cloud_iot_v1_MqttConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.iot.v1.MqttConfig.class,
com.google.cloud.iot.v1.MqttConfig.Builder.class);
}
// Construct using com.google.cloud.iot.v1.MqttConfig.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
mqttEnabledState_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.iot.v1.ResourcesProto
.internal_static_google_cloud_iot_v1_MqttConfig_descriptor;
}
@java.lang.Override
public com.google.cloud.iot.v1.MqttConfig getDefaultInstanceForType() {
return com.google.cloud.iot.v1.MqttConfig.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.iot.v1.MqttConfig build() {
com.google.cloud.iot.v1.MqttConfig result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.iot.v1.MqttConfig buildPartial() {
com.google.cloud.iot.v1.MqttConfig result = new com.google.cloud.iot.v1.MqttConfig(this);
result.mqttEnabledState_ = mqttEnabledState_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return (Builder) super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return (Builder) super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.iot.v1.MqttConfig) {
return mergeFrom((com.google.cloud.iot.v1.MqttConfig) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.iot.v1.MqttConfig other) {
if (other == com.google.cloud.iot.v1.MqttConfig.getDefaultInstance()) return this;
if (other.mqttEnabledState_ != 0) {
setMqttEnabledStateValue(other.getMqttEnabledStateValue());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.iot.v1.MqttConfig parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.iot.v1.MqttConfig) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int mqttEnabledState_ = 0;
/**
*
*
* <pre>
* If enabled, allows connections using the MQTT protocol. Otherwise, MQTT
* connections to this registry will fail.
* </pre>
*
* <code>.google.cloud.iot.v1.MqttState mqtt_enabled_state = 1;</code>
*/
public int getMqttEnabledStateValue() {
return mqttEnabledState_;
}
/**
*
*
* <pre>
* If enabled, allows connections using the MQTT protocol. Otherwise, MQTT
* connections to this registry will fail.
* </pre>
*
* <code>.google.cloud.iot.v1.MqttState mqtt_enabled_state = 1;</code>
*/
public Builder setMqttEnabledStateValue(int value) {
mqttEnabledState_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* If enabled, allows connections using the MQTT protocol. Otherwise, MQTT
* connections to this registry will fail.
* </pre>
*
* <code>.google.cloud.iot.v1.MqttState mqtt_enabled_state = 1;</code>
*/
public com.google.cloud.iot.v1.MqttState getMqttEnabledState() {
@SuppressWarnings("deprecation")
com.google.cloud.iot.v1.MqttState result =
com.google.cloud.iot.v1.MqttState.valueOf(mqttEnabledState_);
return result == null ? com.google.cloud.iot.v1.MqttState.UNRECOGNIZED : result;
}
/**
*
*
* <pre>
* If enabled, allows connections using the MQTT protocol. Otherwise, MQTT
* connections to this registry will fail.
* </pre>
*
* <code>.google.cloud.iot.v1.MqttState mqtt_enabled_state = 1;</code>
*/
public Builder setMqttEnabledState(com.google.cloud.iot.v1.MqttState value) {
if (value == null) {
throw new NullPointerException();
}
mqttEnabledState_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* If enabled, allows connections using the MQTT protocol. Otherwise, MQTT
* connections to this registry will fail.
* </pre>
*
* <code>.google.cloud.iot.v1.MqttState mqtt_enabled_state = 1;</code>
*/
public Builder clearMqttEnabledState() {
mqttEnabledState_ = 0;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.iot.v1.MqttConfig)
}
// @@protoc_insertion_point(class_scope:google.cloud.iot.v1.MqttConfig)
private static final com.google.cloud.iot.v1.MqttConfig DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.iot.v1.MqttConfig();
}
public static com.google.cloud.iot.v1.MqttConfig getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<MqttConfig> PARSER =
new com.google.protobuf.AbstractParser<MqttConfig>() {
@java.lang.Override
public MqttConfig parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new MqttConfig(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<MqttConfig> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<MqttConfig> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.iot.v1.MqttConfig getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.appstream.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Describes a user in the user pool and the associated stack.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/UserStackAssociation" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UserStackAssociation implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The name of the stack that is associated with the user.
* </p>
*/
private String stackName;
/**
* <p>
* The email address of the user who is associated with the stack.
* </p>
* <note>
* <p>
* Users' email addresses are case-sensitive.
* </p>
* </note>
*/
private String userName;
/**
* <p>
* The authentication type for the user.
* </p>
*/
private String authenticationType;
/**
* <p>
* Specifies whether a welcome email is sent to a user after the user is created in the user pool.
* </p>
*/
private Boolean sendEmailNotification;
/**
* <p>
* The name of the stack that is associated with the user.
* </p>
*
* @param stackName
* The name of the stack that is associated with the user.
*/
public void setStackName(String stackName) {
this.stackName = stackName;
}
/**
* <p>
* The name of the stack that is associated with the user.
* </p>
*
* @return The name of the stack that is associated with the user.
*/
public String getStackName() {
return this.stackName;
}
/**
* <p>
* The name of the stack that is associated with the user.
* </p>
*
* @param stackName
* The name of the stack that is associated with the user.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UserStackAssociation withStackName(String stackName) {
setStackName(stackName);
return this;
}
/**
* <p>
* The email address of the user who is associated with the stack.
* </p>
* <note>
* <p>
* Users' email addresses are case-sensitive.
* </p>
* </note>
*
* @param userName
* The email address of the user who is associated with the stack.</p> <note>
* <p>
* Users' email addresses are case-sensitive.
* </p>
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* <p>
* The email address of the user who is associated with the stack.
* </p>
* <note>
* <p>
* Users' email addresses are case-sensitive.
* </p>
* </note>
*
* @return The email address of the user who is associated with the stack.</p> <note>
* <p>
* Users' email addresses are case-sensitive.
* </p>
*/
public String getUserName() {
return this.userName;
}
/**
* <p>
* The email address of the user who is associated with the stack.
* </p>
* <note>
* <p>
* Users' email addresses are case-sensitive.
* </p>
* </note>
*
* @param userName
* The email address of the user who is associated with the stack.</p> <note>
* <p>
* Users' email addresses are case-sensitive.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UserStackAssociation withUserName(String userName) {
setUserName(userName);
return this;
}
/**
* <p>
* The authentication type for the user.
* </p>
*
* @param authenticationType
* The authentication type for the user.
* @see AuthenticationType
*/
public void setAuthenticationType(String authenticationType) {
this.authenticationType = authenticationType;
}
/**
* <p>
* The authentication type for the user.
* </p>
*
* @return The authentication type for the user.
* @see AuthenticationType
*/
public String getAuthenticationType() {
return this.authenticationType;
}
/**
* <p>
* The authentication type for the user.
* </p>
*
* @param authenticationType
* The authentication type for the user.
* @return Returns a reference to this object so that method calls can be chained together.
* @see AuthenticationType
*/
public UserStackAssociation withAuthenticationType(String authenticationType) {
setAuthenticationType(authenticationType);
return this;
}
/**
* <p>
* The authentication type for the user.
* </p>
*
* @param authenticationType
* The authentication type for the user.
* @return Returns a reference to this object so that method calls can be chained together.
* @see AuthenticationType
*/
public UserStackAssociation withAuthenticationType(AuthenticationType authenticationType) {
this.authenticationType = authenticationType.toString();
return this;
}
/**
* <p>
* Specifies whether a welcome email is sent to a user after the user is created in the user pool.
* </p>
*
* @param sendEmailNotification
* Specifies whether a welcome email is sent to a user after the user is created in the user pool.
*/
public void setSendEmailNotification(Boolean sendEmailNotification) {
this.sendEmailNotification = sendEmailNotification;
}
/**
* <p>
* Specifies whether a welcome email is sent to a user after the user is created in the user pool.
* </p>
*
* @return Specifies whether a welcome email is sent to a user after the user is created in the user pool.
*/
public Boolean getSendEmailNotification() {
return this.sendEmailNotification;
}
/**
* <p>
* Specifies whether a welcome email is sent to a user after the user is created in the user pool.
* </p>
*
* @param sendEmailNotification
* Specifies whether a welcome email is sent to a user after the user is created in the user pool.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UserStackAssociation withSendEmailNotification(Boolean sendEmailNotification) {
setSendEmailNotification(sendEmailNotification);
return this;
}
/**
* <p>
* Specifies whether a welcome email is sent to a user after the user is created in the user pool.
* </p>
*
* @return Specifies whether a welcome email is sent to a user after the user is created in the user pool.
*/
public Boolean isSendEmailNotification() {
return this.sendEmailNotification;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getStackName() != null)
sb.append("StackName: ").append(getStackName()).append(",");
if (getUserName() != null)
sb.append("UserName: ").append("***Sensitive Data Redacted***").append(",");
if (getAuthenticationType() != null)
sb.append("AuthenticationType: ").append(getAuthenticationType()).append(",");
if (getSendEmailNotification() != null)
sb.append("SendEmailNotification: ").append(getSendEmailNotification());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof UserStackAssociation == false)
return false;
UserStackAssociation other = (UserStackAssociation) obj;
if (other.getStackName() == null ^ this.getStackName() == null)
return false;
if (other.getStackName() != null && other.getStackName().equals(this.getStackName()) == false)
return false;
if (other.getUserName() == null ^ this.getUserName() == null)
return false;
if (other.getUserName() != null && other.getUserName().equals(this.getUserName()) == false)
return false;
if (other.getAuthenticationType() == null ^ this.getAuthenticationType() == null)
return false;
if (other.getAuthenticationType() != null && other.getAuthenticationType().equals(this.getAuthenticationType()) == false)
return false;
if (other.getSendEmailNotification() == null ^ this.getSendEmailNotification() == null)
return false;
if (other.getSendEmailNotification() != null && other.getSendEmailNotification().equals(this.getSendEmailNotification()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getStackName() == null) ? 0 : getStackName().hashCode());
hashCode = prime * hashCode + ((getUserName() == null) ? 0 : getUserName().hashCode());
hashCode = prime * hashCode + ((getAuthenticationType() == null) ? 0 : getAuthenticationType().hashCode());
hashCode = prime * hashCode + ((getSendEmailNotification() == null) ? 0 : getSendEmailNotification().hashCode());
return hashCode;
}
@Override
public UserStackAssociation clone() {
try {
return (UserStackAssociation) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.appstream.model.transform.UserStackAssociationMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.compute.v1;
import com.google.api.core.BetaApi;
import com.google.api.gax.httpjson.ApiMessage;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import javax.annotation.Generated;
import javax.annotation.Nullable;
@Generated("by GAPIC")
@BetaApi
public final class SecurityPolicyList implements ApiMessage {
private final String id;
private final List<SecurityPolicy> items;
private final String kind;
private final String nextPageToken;
private final Warning warning;
private SecurityPolicyList() {
this.id = null;
this.items = null;
this.kind = null;
this.nextPageToken = null;
this.warning = null;
}
private SecurityPolicyList(
String id, List<SecurityPolicy> items, String kind, String nextPageToken, Warning warning) {
this.id = id;
this.items = items;
this.kind = kind;
this.nextPageToken = nextPageToken;
this.warning = warning;
}
@Override
public Object getFieldValue(String fieldName) {
if ("id".equals(fieldName)) {
return id;
}
if ("items".equals(fieldName)) {
return items;
}
if ("kind".equals(fieldName)) {
return kind;
}
if ("nextPageToken".equals(fieldName)) {
return nextPageToken;
}
if ("warning".equals(fieldName)) {
return warning;
}
return null;
}
@Nullable
@Override
public ApiMessage getApiMessageRequestBody() {
return null;
}
@Nullable
@Override
/**
* The fields that should be serialized (even if they have empty values). If the containing
* message object has a non-null fieldmask, then all the fields in the field mask (and only those
* fields in the field mask) will be serialized. If the containing object does not have a
* fieldmask, then only non-empty fields will be serialized.
*/
public List<String> getFieldMask() {
return null;
}
/** [Output Only] Unique identifier for the resource; defined by the server. */
public String getId() {
return id;
}
/** A list of SecurityPolicy resources. */
public List<SecurityPolicy> getItemsList() {
return items;
}
/**
* [Output Only] Type of resource. Always compute#securityPolicyList for listsof securityPolicies
*/
public String getKind() {
return kind;
}
/**
* [Output Only] This token allows you to get the next page of results for list requests. If the
* number of results is larger than maxResults, use the nextPageToken as a value for the query
* parameter pageToken in the next list request. Subsequent list requests will have their own
* nextPageToken to continue paging through the results.
*/
public String getNextPageToken() {
return nextPageToken;
}
/** [Output Only] Informational warning message. */
public Warning getWarning() {
return warning;
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(SecurityPolicyList prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
public static SecurityPolicyList getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final SecurityPolicyList DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new SecurityPolicyList();
}
public static class Builder {
private String id;
private List<SecurityPolicy> items;
private String kind;
private String nextPageToken;
private Warning warning;
Builder() {}
public Builder mergeFrom(SecurityPolicyList other) {
if (other == SecurityPolicyList.getDefaultInstance()) return this;
if (other.getId() != null) {
this.id = other.id;
}
if (other.getItemsList() != null) {
this.items = other.items;
}
if (other.getKind() != null) {
this.kind = other.kind;
}
if (other.getNextPageToken() != null) {
this.nextPageToken = other.nextPageToken;
}
if (other.getWarning() != null) {
this.warning = other.warning;
}
return this;
}
Builder(SecurityPolicyList source) {
this.id = source.id;
this.items = source.items;
this.kind = source.kind;
this.nextPageToken = source.nextPageToken;
this.warning = source.warning;
}
/** [Output Only] Unique identifier for the resource; defined by the server. */
public String getId() {
return id;
}
/** [Output Only] Unique identifier for the resource; defined by the server. */
public Builder setId(String id) {
this.id = id;
return this;
}
/** A list of SecurityPolicy resources. */
public List<SecurityPolicy> getItemsList() {
return items;
}
/** A list of SecurityPolicy resources. */
public Builder addAllItems(List<SecurityPolicy> items) {
if (this.items == null) {
this.items = new LinkedList<>();
}
this.items.addAll(items);
return this;
}
/** A list of SecurityPolicy resources. */
public Builder addItems(SecurityPolicy items) {
if (this.items == null) {
this.items = new LinkedList<>();
}
this.items.add(items);
return this;
}
/**
* [Output Only] Type of resource. Always compute#securityPolicyList for listsof
* securityPolicies
*/
public String getKind() {
return kind;
}
/**
* [Output Only] Type of resource. Always compute#securityPolicyList for listsof
* securityPolicies
*/
public Builder setKind(String kind) {
this.kind = kind;
return this;
}
/**
* [Output Only] This token allows you to get the next page of results for list requests. If the
* number of results is larger than maxResults, use the nextPageToken as a value for the query
* parameter pageToken in the next list request. Subsequent list requests will have their own
* nextPageToken to continue paging through the results.
*/
public String getNextPageToken() {
return nextPageToken;
}
/**
* [Output Only] This token allows you to get the next page of results for list requests. If the
* number of results is larger than maxResults, use the nextPageToken as a value for the query
* parameter pageToken in the next list request. Subsequent list requests will have their own
* nextPageToken to continue paging through the results.
*/
public Builder setNextPageToken(String nextPageToken) {
this.nextPageToken = nextPageToken;
return this;
}
/** [Output Only] Informational warning message. */
public Warning getWarning() {
return warning;
}
/** [Output Only] Informational warning message. */
public Builder setWarning(Warning warning) {
this.warning = warning;
return this;
}
public SecurityPolicyList build() {
return new SecurityPolicyList(id, items, kind, nextPageToken, warning);
}
public Builder clone() {
Builder newBuilder = new Builder();
newBuilder.setId(this.id);
newBuilder.addAllItems(this.items);
newBuilder.setKind(this.kind);
newBuilder.setNextPageToken(this.nextPageToken);
newBuilder.setWarning(this.warning);
return newBuilder;
}
}
@Override
public String toString() {
return "SecurityPolicyList{"
+ "id="
+ id
+ ", "
+ "items="
+ items
+ ", "
+ "kind="
+ kind
+ ", "
+ "nextPageToken="
+ nextPageToken
+ ", "
+ "warning="
+ warning
+ "}";
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof SecurityPolicyList) {
SecurityPolicyList that = (SecurityPolicyList) o;
return Objects.equals(this.id, that.getId())
&& Objects.equals(this.items, that.getItemsList())
&& Objects.equals(this.kind, that.getKind())
&& Objects.equals(this.nextPageToken, that.getNextPageToken())
&& Objects.equals(this.warning, that.getWarning());
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(id, items, kind, nextPageToken, warning);
}
}
| |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.omnibox.suggestions.base;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.res.Resources;
import android.view.View;
import android.widget.ImageView;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.annotation.Config;
import org.chromium.chrome.R;
import org.chromium.components.browser_ui.widget.RoundedCornerImageView;
import org.chromium.testing.local.LocalRobolectricTestRunner;
import org.chromium.ui.modelutil.PropertyModel;
import org.chromium.ui.modelutil.PropertyModelChangeProcessor;
/**
* Tests for {@link BaseSuggestionViewBinder}.
*/
@RunWith(LocalRobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class BaseSuggestionViewBinderUnitTest {
@Mock
BaseSuggestionView mBaseView;
@Mock
DecoratedSuggestionView mDecoratedView;
@Mock
RoundedCornerImageView mIconView;
@Mock
ImageView mActionView;
@Mock
ImageView mContentView;
private Activity mActivity;
private Resources mResources;
private PropertyModel mModel;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mActivity = Robolectric.buildActivity(Activity.class).setup().get();
mResources = mActivity.getResources();
when(mBaseView.getContext()).thenReturn(mActivity);
when(mIconView.getContext()).thenReturn(mActivity);
when(mActionView.getContext()).thenReturn(mActivity);
when(mBaseView.getDecoratedSuggestionView()).thenReturn(mDecoratedView);
when(mBaseView.getSuggestionImageView()).thenReturn(mIconView);
when(mBaseView.getActionImageView()).thenReturn(mActionView);
when(mDecoratedView.getContentView()).thenReturn(mContentView);
when(mBaseView.getContentView()).thenReturn(mContentView);
when(mDecoratedView.getResources()).thenReturn(mResources);
mModel = new PropertyModel(BaseSuggestionViewProperties.ALL_KEYS);
PropertyModelChangeProcessor.create(mModel, mBaseView,
new BaseSuggestionViewBinder(
(m, v, p) -> { Assert.assertEquals(mContentView, v); }));
}
@Test
public void decorIcon_showSquareIcon() {
SuggestionDrawableState state = SuggestionDrawableState.Builder.forColor(0).build();
mModel.set(BaseSuggestionViewProperties.ICON, state);
// Expect a single call to setRoundedCorners, and make sure this call sets all radii to 0.
verify(mIconView).setRoundedCorners(0, 0, 0, 0);
verify(mIconView).setRoundedCorners(anyInt(), anyInt(), anyInt(), anyInt());
verify(mIconView).setVisibility(View.VISIBLE);
verify(mIconView).setImageDrawable(state.drawable);
}
@Test
public void decorIcon_showRoundedIcon() {
SuggestionDrawableState state =
SuggestionDrawableState.Builder.forColor(0).setUseRoundedCorners(true).build();
mModel.set(BaseSuggestionViewProperties.ICON, state);
// Expect a single call to setRoundedCorners, and make sure this call sets radii to non-0.
verify(mIconView, never()).setRoundedCorners(0, 0, 0, 0);
verify(mIconView).setRoundedCorners(anyInt(), anyInt(), anyInt(), anyInt());
verify(mIconView).setVisibility(View.VISIBLE);
verify(mIconView).setImageDrawable(state.drawable);
}
@Test
public void decorIcon_hideIcon() {
InOrder ordered = inOrder(mIconView);
SuggestionDrawableState state = SuggestionDrawableState.Builder.forColor(0).build();
mModel.set(BaseSuggestionViewProperties.ICON, state);
mModel.set(BaseSuggestionViewProperties.ICON, null);
ordered.verify(mIconView).setVisibility(View.VISIBLE);
ordered.verify(mIconView).setImageDrawable(state.drawable);
ordered.verify(mIconView).setVisibility(View.GONE);
// Ensure we're releasing drawable to free memory.
ordered.verify(mIconView).setImageDrawable(null);
}
@Test
public void actionIcon_showSquareIcon() {
SuggestionDrawableState state = SuggestionDrawableState.Builder.forColor(0).build();
mModel.set(BaseSuggestionViewProperties.ACTION_ICON, state);
verify(mActionView).setVisibility(View.VISIBLE);
verify(mActionView).setImageDrawable(state.drawable);
}
@Test
public void actionIcon_hideIcon() {
InOrder ordered = inOrder(mActionView);
SuggestionDrawableState state = SuggestionDrawableState.Builder.forColor(0).build();
mModel.set(BaseSuggestionViewProperties.ACTION_ICON, state);
mModel.set(BaseSuggestionViewProperties.ACTION_ICON, null);
ordered.verify(mActionView).setVisibility(View.VISIBLE);
ordered.verify(mActionView).setImageDrawable(state.drawable);
ordered.verify(mActionView).setVisibility(View.GONE);
// Ensure we're releasing drawable to free memory.
ordered.verify(mActionView).setImageDrawable(null);
}
@Test
public void suggestionPadding_decorIconPresent() {
final int startSpace = 0;
final int endSpace = mResources.getDimensionPixelSize(
R.dimen.omnibox_suggestion_refine_view_modern_end_padding);
SuggestionDrawableState state = SuggestionDrawableState.Builder.forColor(0).build();
mModel.set(BaseSuggestionViewProperties.ICON, state);
verify(mDecoratedView).setPaddingRelative(startSpace, 0, endSpace, 0);
verify(mBaseView, never()).setPaddingRelative(anyInt(), anyInt(), anyInt(), anyInt());
}
@Test
public void suggestionPadding_decorIconAbsent() {
final int startSpace = mResources.getDimensionPixelSize(
R.dimen.omnibox_suggestion_start_offset_without_icon);
final int endSpace = mResources.getDimensionPixelSize(
R.dimen.omnibox_suggestion_refine_view_modern_end_padding);
mModel.set(BaseSuggestionViewProperties.ICON, null);
verify(mDecoratedView).setPaddingRelative(startSpace, 0, endSpace, 0);
verify(mBaseView, never()).setPaddingRelative(anyInt(), anyInt(), anyInt(), anyInt());
}
@Test
public void suggestionDensity_comfortableMode() {
mModel.set(BaseSuggestionViewProperties.DENSITY,
BaseSuggestionViewProperties.Density.COMFORTABLE);
final int expectedPadding =
mResources.getDimensionPixelSize(R.dimen.omnibox_suggestion_comfortable_padding);
final int expectedHeight =
mResources.getDimensionPixelSize(R.dimen.omnibox_suggestion_comfortable_height);
verify(mContentView).setPaddingRelative(0, expectedPadding, 0, expectedPadding);
verify(mContentView).setMinimumHeight(expectedHeight);
}
@Test
public void suggestionDensity_semiCompactMode() {
mModel.set(BaseSuggestionViewProperties.DENSITY,
BaseSuggestionViewProperties.Density.SEMICOMPACT);
final int expectedPadding =
mResources.getDimensionPixelSize(R.dimen.omnibox_suggestion_semicompact_padding);
final int expectedHeight =
mResources.getDimensionPixelSize(R.dimen.omnibox_suggestion_semicompact_height);
verify(mContentView).setPaddingRelative(0, expectedPadding, 0, expectedPadding);
verify(mContentView).setMinimumHeight(expectedHeight);
}
@Test
public void suggestionDensity_compactMode() {
mModel.set(
BaseSuggestionViewProperties.DENSITY, BaseSuggestionViewProperties.Density.COMPACT);
final int expectedPadding =
mResources.getDimensionPixelSize(R.dimen.omnibox_suggestion_compact_padding);
final int expectedHeight =
mResources.getDimensionPixelSize(R.dimen.omnibox_suggestion_compact_height);
verify(mContentView).setPaddingRelative(0, expectedPadding, 0, expectedPadding);
verify(mContentView).setMinimumHeight(expectedHeight);
}
@Test
public void actionCallback_installedWhenSet() {
ArgumentCaptor<View.OnClickListener> callback =
ArgumentCaptor.forClass(View.OnClickListener.class);
Runnable mockCallback = mock(Runnable.class);
mModel.set(BaseSuggestionViewProperties.ACTION_CALLBACK, mockCallback);
verify(mActionView, times(1)).setOnClickListener(callback.capture());
callback.getValue().onClick(null);
verify(mockCallback, times(1)).run();
}
@Test
public void actionCallback_subsequentUpdatesReplaceCallback() {
ArgumentCaptor<View.OnClickListener> callback =
ArgumentCaptor.forClass(View.OnClickListener.class);
Runnable mockCallback1 = mock(Runnable.class);
Runnable mockCallback2 = mock(Runnable.class);
mModel.set(BaseSuggestionViewProperties.ACTION_CALLBACK, mockCallback1);
mModel.set(BaseSuggestionViewProperties.ACTION_CALLBACK, mockCallback2);
verify(mActionView, times(2)).setOnClickListener(callback.capture());
callback.getValue().onClick(null);
verify(mockCallback1, never()).run();
verify(mockCallback2, times(1)).run();
}
@Test
public void actionCallback_clearedWhenUnset() {
mModel.set(BaseSuggestionViewProperties.ACTION_CALLBACK, () -> {});
verify(mActionView, times(1)).setOnClickListener(any(View.OnClickListener.class));
mModel.set(BaseSuggestionViewProperties.ACTION_CALLBACK, null);
verify(mActionView, times(1)).setOnClickListener(null);
}
}
| |
package com.liferay.support.tools.utils;
import com.liferay.petra.string.StringPool;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.model.Layout;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.service.ServiceContextFactory;
import com.liferay.portal.kernel.theme.ThemeDisplay;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
import com.liferay.wiki.configuration.WikiGroupServiceConfiguration;
import com.liferay.wiki.engine.WikiEngine;
import com.liferay.wiki.engine.WikiEngineRenderer;
import com.liferay.wiki.model.WikiNode;
import com.liferay.wiki.model.WikiPage;
import com.liferay.wiki.model.WikiPageConstants;
import com.liferay.wiki.service.WikiNodeLocalService;
import com.liferay.wiki.service.WikiNodeLocalServiceUtil;
import com.liferay.wiki.service.WikiPageLocalService;
import com.liferay.wiki.service.WikiPageLocalServiceUtil;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import javax.portlet.PortletRequest;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
/**
* Utilities for Wiki
*
* @author Yasuyuki Takeo
*/
@Component(immediate = true, service = WikiCommons.class)
public class WikiCommons {
private static final Log _log = LogFactoryUtil.getLog(WikiCommons.class);
private WikiEngineRenderer _wikiEngineRenderer;
private WikiGroupServiceConfiguration _wikiGroupServiceConfiguration;
private WikiNodeLocalService _wikiNodeLocalService;
private WikiPageLocalService _wikiPageLocalService;
@Reference(unbind = "-")
protected void setWikiEngineRenderer(
WikiEngineRenderer wikiEngineRenderer) {
_wikiEngineRenderer = wikiEngineRenderer;
}
@Reference(unbind = "-")
protected void setWikiGroupServiceConfiguration(
WikiGroupServiceConfiguration wikiGroupServiceConfiguration) {
_wikiGroupServiceConfiguration = wikiGroupServiceConfiguration;
}
@Reference(unbind = "-")
protected void setWikiNodeLocalService(WikiNodeLocalService wikiNodeLocalService) {
_wikiNodeLocalService = wikiNodeLocalService;
}
@Reference(unbind = "-")
protected void setWikiPageLocalService(WikiPageLocalService wikiPageLocalService) {
_wikiPageLocalService = wikiPageLocalService;
}
/**
* Get Wiki format list
*
* @param locale
* @return available Wiki format list
*/
public Map<String, String> getFormats(Locale locale) {
Collection<String> formats = _wikiEngineRenderer.getFormats();
Map<String, String> fmt = new LinkedHashMap<>();
for (String format : formats) {
fmt.put(format, getFormatLabel(_wikiEngineRenderer, format, locale));
}
return fmt;
}
public String getFormatLabel(
WikiEngineRenderer wikiEngineRenderer, String format, Locale locale) {
WikiEngine wikiEngine = wikiEngineRenderer.fetchWikiEngine(format);
if (wikiEngine != null) {
return wikiEngine.getFormatLabel(locale);
}
return StringPool.BLANK;
}
/**
* Initialize Wiki
* <p>
* When the first time access the wiki on the vanilla bundle, Wiki page gets exception due to no
* data created. This method simulate the initial access to the Wiki.
*
* @param portletRequest
*/
public void initWiki(PortletRequest portletRequest, long scopeGroupId) {
try {
if(!isNodeExist(scopeGroupId)) {
return;
}
WikiNode node = getFirstVisibleNode(portletRequest, scopeGroupId);
long nodeId = (node == null) ? 0 : node.getNodeId();
getFirstVisiblePage(nodeId, portletRequest);
} catch (PortalException e) {
_log.error(e.getMessage());
}
}
/**
* Initialize Page
*
* @param nodeId
* @param portletRequest
* @throws PortalException
*/
public void getFirstVisiblePage(
long nodeId, PortletRequest portletRequest)
throws PortalException {
ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest.getAttribute(
WebKeys.THEME_DISPLAY);
WikiPage page = _wikiPageLocalService.fetchPage(
nodeId, _wikiGroupServiceConfiguration.frontPageName(), 0);
if (page != null) {
return;
}
ServiceContext serviceContext = ServiceContextFactory.getInstance(
WikiPage.class.getName(), portletRequest);
serviceContext.setAddGuestPermissions(true);
serviceContext.setAddGroupPermissions(true);
boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
try {
WorkflowThreadLocal.setEnabled(false);
WikiPageLocalServiceUtil.addPage(
themeDisplay.getDefaultUserId(), nodeId,
_wikiGroupServiceConfiguration.frontPageName(), null,
WikiPageConstants.NEW, true, serviceContext);
} catch (Exception e) {
_log.error(e.getMessage());
} finally {
WorkflowThreadLocal.setEnabled(workflowEnabled);
}
}
/**
* Validate a Node exist
*
* @param scopeGroupId
* @return true if a node exist or false
*/
public boolean isNodeExist(long scopeGroupId) {
int nodesCount = _wikiNodeLocalService.getNodesCount(
scopeGroupId);
if (nodesCount != 0) {
_log.info("Wiki Node has already been initialized.");
return false;
}
return true;
}
/**
* Initialize Node
*
* @param portletRequest
* @param scopeGroupId
* @return
* @throws PortalException
*/
public WikiNode getFirstVisibleNode(PortletRequest portletRequest, long scopeGroupId)
throws PortalException {
ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest.getAttribute(
WebKeys.THEME_DISPLAY);
WikiNode node = null;
Layout layout = themeDisplay.getLayout();
ServiceContext serviceContext = ServiceContextFactory.getInstance(
WikiNode.class.getName(), portletRequest);
serviceContext.setAddGroupPermissions(true);
if (layout.isPublicLayout() || layout.isTypeControlPanel()) {
serviceContext.setAddGuestPermissions(true);
} else {
serviceContext.setAddGuestPermissions(false);
}
serviceContext.setScopeGroupId(scopeGroupId);
node = _wikiNodeLocalService.addDefaultNode(
themeDisplay.getDefaultUserId(), serviceContext);
_log.info("Wiki Node has been initialized");
return node;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jena.sparql.algebra;
import java.util.* ;
import org.apache.jena.atlas.logging.Log ;
import org.apache.jena.query.SortCondition ;
import org.apache.jena.sparql.algebra.OpWalker.WalkerVisitor ;
import org.apache.jena.sparql.algebra.op.* ;
import org.apache.jena.sparql.algebra.optimize.ExprTransformApplyTransform ;
import org.apache.jena.sparql.core.Var ;
import org.apache.jena.sparql.core.VarExprList ;
import org.apache.jena.sparql.expr.* ;
import org.apache.jena.sparql.expr.aggregate.Aggregator ;
/** A bottom-top application of a transformation of SPARQL algebra */
public class Transformer
{
private static Transformer singleton = new Transformer();
// TopQuadrant extend Transformer for use in their SPARQL debugger.
/** Get the current transformer */
public static Transformer get() { return singleton; }
/** Set the current transformer - use with care */
public static void set(Transformer value) { Transformer.singleton = value; }
/** Transform an algebra expression */
public static Op transform(Transform transform, Op op)
{ return get().transformation(transform, op, null, null) ; }
/** Transform an algebra expression and the expressions */
public static Op transform(Transform transform, ExprTransform exprTransform, Op op)
{ return get().transformation(transform, exprTransform, op, null, null) ; }
/** Transformation with specific Transform and default ExprTransform (apply transform inside pattern expressions like NOT EXISTS) */
public static Op transform(Transform transform, Op op, OpVisitor beforeVisitor, OpVisitor afterVisitor)
{
return get().transformation(transform, op, beforeVisitor, afterVisitor) ;
}
/** Transformation with specific Transform and ExprTransform applied */
public static Op transform(Transform transform, ExprTransform exprTransform, Op op, OpVisitor beforeVisitor, OpVisitor afterVisitor)
{
return get().transformation(transform, exprTransform, op, beforeVisitor, afterVisitor) ;
}
/** Transform an algebra expression except skip (leave alone) any OpService nodes */
public static Op transformSkipService(Transform transform, Op op)
{
return transformSkipService(transform, op, null, null) ;
}
/** Transform an algebra expression except skip (leave alone) any OpService nodes */
public static Op transformSkipService(Transform transform, ExprTransform exprTransform, Op op)
{
return transformSkipService(transform, exprTransform, op, null, null) ;
}
/** Transform an algebra expression except skip (leave alone) any OpService nodes */
public static Op transformSkipService(Transform transform, Op op, OpVisitor beforeVisitor, OpVisitor afterVisitor)
{
// Skip SERVICE
if ( true )
{
// Simplest way but still walks the OpService subtree (and throws away the transformation).
Transform walker = new TransformSkipService(transform) ;
return Transformer.transform(walker, op, beforeVisitor, afterVisitor) ;
}
else
{
// Don't transform OpService and don't walk the sub-op
ExprTransform exprTransform = new ExprTransformApplyTransform(transform, beforeVisitor, afterVisitor) ;
ApplyTransformVisitorServiceAsLeaf v = new ApplyTransformVisitorServiceAsLeaf(transform, exprTransform) ;
WalkerVisitorSkipService walker = new WalkerVisitorSkipService(v, beforeVisitor, afterVisitor) ;
OpWalker.walk(walker, op) ;
return v.result() ;
}
}
/** Transform an algebra expression except skip (leave alone) any OpService nodes */
public static Op transformSkipService(Transform transform, ExprTransform exprTransform, Op op, OpVisitor beforeVisitor, OpVisitor afterVisitor)
{
// Skip SERVICE
if ( true )
{
// Simplest way but still walks the OpService subtree (and throws away the transformation).
Transform walker = new TransformSkipService(transform) ;
return Transformer.transform(walker, exprTransform, op, beforeVisitor, afterVisitor) ;
}
else
{
ApplyTransformVisitorServiceAsLeaf v = new ApplyTransformVisitorServiceAsLeaf(transform, exprTransform) ;
WalkerVisitorSkipService walker = new WalkerVisitorSkipService(v, beforeVisitor, afterVisitor) ;
OpWalker.walk(walker, op) ;
return v.result() ;
}
}
// To allow subclassing this class, we use a singleton pattern
// and theses protected methods.
protected Op transformation(Transform transform, Op op, OpVisitor beforeVisitor, OpVisitor afterVisitor)
{
ExprTransform exprTransform = new ExprTransformApplyTransform(transform, beforeVisitor, afterVisitor) ;
return transformation(transform, exprTransform, op, beforeVisitor, afterVisitor) ;
}
protected Op transformation(Transform transform, ExprTransform exprTransform, Op op, OpVisitor beforeVisitor, OpVisitor afterVisitor)
{
ApplyTransformVisitor v = new ApplyTransformVisitor(transform, exprTransform) ;
return transformation(v, op, beforeVisitor, afterVisitor) ;
}
protected Op transformation(ApplyTransformVisitor transformApply,
Op op, OpVisitor beforeVisitor, OpVisitor afterVisitor)
{
if ( op == null )
{
Log.warn(this, "Attempt to transform a null Op - ignored") ;
return op ;
}
return applyTransformation(transformApply, op, beforeVisitor, afterVisitor) ;
}
/** The primitive operation to apply a transformation to an Op */
protected Op applyTransformation(ApplyTransformVisitor transformApply,
Op op, OpVisitor beforeVisitor, OpVisitor afterVisitor)
{
OpWalker.walk(op, transformApply, beforeVisitor, afterVisitor) ;
Op r = transformApply.result() ;
return r ;
}
protected Transformer() { }
public static
class ApplyTransformVisitor extends OpVisitorByType
{
protected final Transform transform ;
private final ExprTransform exprTransform ;
private final Deque<Op> stack = new ArrayDeque<>() ;
protected final Op pop()
{ return stack.pop(); }
protected final void push(Op op)
{
// Including nulls
stack.push(op) ;
}
public ApplyTransformVisitor(Transform transform, ExprTransform exprTransform)
{
this.transform = transform ;
this.exprTransform = exprTransform ;
}
final Op result()
{
if ( stack.size() != 1 )
Log.warn(this, "Stack is not aligned") ;
return pop() ;
}
private static ExprList transform(ExprList exprList, ExprTransform exprTransform)
{
if ( exprList == null || exprTransform == null )
return exprList ;
return ExprTransformer.transform(exprTransform, exprList) ;
}
private static Expr transform(Expr expr, ExprTransform exprTransform)
{
if ( expr == null || exprTransform == null )
return expr ;
return ExprTransformer.transform(exprTransform, expr) ;
}
// ----
// Algebra operations that involve an Expr, and so might include NOT EXISTS
@Override
public void visit(OpOrder opOrder)
{
List<SortCondition> conditions = opOrder.getConditions() ;
List<SortCondition> conditions2 = new ArrayList<>() ;
boolean changed = false ;
for ( SortCondition sc : conditions )
{
Expr e = sc.getExpression() ;
Expr e2 = transform(e, exprTransform) ;
conditions2.add(new SortCondition(e2, sc.getDirection())) ;
if ( e != e2 )
changed = true ;
}
OpOrder x = opOrder ;
if ( changed )
x = new OpOrder(opOrder.getSubOp(), conditions2) ;
visit1(x) ;
}
@Override
public void visit(OpAssign opAssign)
{
VarExprList varExpr = opAssign.getVarExprList() ;
VarExprList varExpr2 = process(varExpr, exprTransform) ;
OpAssign opAssign2 = opAssign ;
if ( varExpr != varExpr2 )
opAssign2 = OpAssign.create(opAssign.getSubOp(), varExpr2) ;
visit1(opAssign2) ;
}
@Override
public void visit(OpExtend opExtend)
{
VarExprList varExpr = opExtend.getVarExprList() ;
VarExprList varExpr2 = process(varExpr, exprTransform) ;
OpExtend opExtend2 = opExtend ;
if ( varExpr != varExpr2 )
opExtend2 = OpExtend.create(opExtend.getSubOp(), varExpr2) ;
visit1(opExtend2) ;
}
private static VarExprList process(VarExprList varExpr, ExprTransform exprTransform)
{
List<Var> vars = varExpr.getVars() ;
VarExprList varExpr2 = new VarExprList() ;
boolean changed = false ;
for ( Var v : vars )
{
Expr e = varExpr.getExpr(v) ;
Expr e2 = e ;
if ( e != null )
e2 = transform(e, exprTransform) ;
if ( e2 == null )
varExpr2.add(v) ;
else
varExpr2.add(v, e2) ;
if ( e != e2 )
changed = true ;
}
if ( ! changed )
return varExpr ;
return varExpr2 ;
}
private static ExprList process(ExprList exprList, ExprTransform exprTransform)
{
if ( exprList == null )
return null ;
ExprList exprList2 = new ExprList() ;
boolean changed = false ;
for ( Expr e : exprList )
{
Expr e2 = process(e, exprTransform) ;
exprList2.add(e2) ;
if ( e != e2 )
changed = true ;
}
if ( ! changed )
return exprList ;
return exprList2 ;
}
private static Expr process(Expr expr, ExprTransform exprTransform)
{
Expr e = expr ;
Expr e2 = e ;
if ( e != null )
e2 = transform(e, exprTransform) ;
if ( e == e2 )
return expr ;
return e2 ;
}
@Override
public void visit(OpGroup opGroup)
{
boolean changed = false ;
VarExprList varExpr = opGroup.getGroupVars() ;
VarExprList varExpr2 = process(varExpr, exprTransform) ;
if ( varExpr != varExpr2 )
changed = true ;
List<ExprAggregator> aggs = opGroup.getAggregators() ;
List<ExprAggregator> aggs2 = aggs ;
//And the aggregators...
aggs2 = new ArrayList<>() ;
for ( ExprAggregator agg : aggs )
{
Aggregator aggregator = agg.getAggregator() ;
Var v = agg.getVar() ;
// Variable associated with the aggregate
Expr eVar = agg.getAggVar() ; // Not .getExprVar()
Expr eVar2 = transform(eVar, exprTransform) ;
if ( eVar != eVar2 )
changed = true ;
// The Aggregator expression
ExprList e = aggregator.getExprList() ;
ExprList e2 = e ;
if ( e != null ) // Null means "no relevant expression" e.g. COUNT(*)
e2 = transform(e, exprTransform) ;
if ( e != e2 )
changed = true ;
Aggregator a2 = aggregator.copy(e2) ;
aggs2.add(new ExprAggregator(eVar2.asVar(), a2)) ;
}
OpGroup opGroup2 = opGroup ;
if ( changed )
opGroup2 = new OpGroup(opGroup.getSubOp(), varExpr2, aggs2) ;
visit1(opGroup2) ;
}
// ----
@Override
protected void visit0(Op0 op)
{
push(op.apply(transform)) ;
}
@Override
protected void visit1(Op1 op)
{
Op subOp = null ;
if ( op.getSubOp() != null )
subOp = pop() ;
push(op.apply(transform, subOp)) ;
}
@Override
protected void visit2(Op2 op)
{
Op left = null ;
Op right = null ;
// Must do right-left because the pushes onto the stack were left-right.
if ( op.getRight() != null )
right = pop() ;
if ( op.getLeft() != null )
left = pop() ;
Op opX = op.apply(transform, left, right) ;
push(opX) ;
}
@Override
protected void visitN(OpN op)
{
List<Op> x = new ArrayList<>(op.size()) ;
for ( Iterator<Op> iter = op.iterator() ; iter.hasNext() ; )
{
Op sub = iter.next() ;
Op r = pop() ;
// Skip nulls.
if ( r != null )
// Add in reverse.
x.add(0, r) ;
}
Op opX = op.apply(transform, x) ;
push(opX) ;
}
@Override
protected void visitFilter(OpFilter opFilter)
{
Op subOp = null ;
if ( opFilter.getSubOp() != null )
subOp = pop() ;
boolean changed = ( opFilter.getSubOp() != subOp ) ;
ExprList ex = opFilter.getExprs() ;
ExprList ex2 = process(ex, exprTransform) ;
OpFilter f = opFilter ;
if ( ex != ex2 )
f = (OpFilter)OpFilter.filter(ex2, subOp) ;
push(f.apply(transform, subOp)) ;
}
@Override
protected void visitLeftJoin(OpLeftJoin op) {
Op left = null ;
Op right = null ;
// Must do right-left because the pushes onto the stack were left-right.
if ( op.getRight() != null )
right = pop() ;
if ( op.getLeft() != null )
left = pop() ;
ExprList exprs = op.getExprs() ;
ExprList exprs2 = process(exprs, exprTransform) ;
OpLeftJoin x = op ;
if ( exprs != exprs2 )
x = OpLeftJoin.createLeftJoin(left, right, exprs2) ;
Op opX = x.apply(transform, left, right) ;
push(opX) ;
}
@Override
protected void visitExt(OpExt op)
{
push(transform.transform(op)) ;
}
}
// --------------------------------
// Transformations that avoid touching SERVICE.
// Modified classes to avoid transforming SERVICE/OpService.
// Plan A: In the application of the transform, skip OpService.
/** Treat OpService as a leaf of the tree */
static class ApplyTransformVisitorServiceAsLeaf extends ApplyTransformVisitor
{
public ApplyTransformVisitorServiceAsLeaf(Transform transform, ExprTransform exprTransform)
{
super(transform, exprTransform) ;
}
@Override
public void visit(OpService op)
{
// Treat as a leaf that does not change.
push(op) ;
}
}
// Plan B: The walker skips walking into OpService nodes.
/** Don't walk down an OpService sub-operation */
static class WalkerVisitorSkipService extends WalkerVisitor
{
public WalkerVisitorSkipService(OpVisitor visitor, OpVisitor beforeVisitor, OpVisitor afterVisitor)
{
super(visitor, beforeVisitor, afterVisitor) ;
}
public WalkerVisitorSkipService(OpVisitor visitor)
{
super(visitor) ;
}
@Override
public void visit(OpService op)
{
before(op) ;
// visit1 code from WalkerVisitor
// if ( op.getSubOp() != null ) op.getSubOp().visit(this) ;
// Just visit the OpService node itself.
// The transformer needs to push the code as a result (see ApplyTransformVisitorSkipService)
if ( visitor != null ) op.visit(visitor) ;
after(op) ;
}
}
// --------------------------------
// Safe: ignore transformation of OpService and return the original.
// Still walks the sub-op of OpService
static class TransformSkipService extends TransformWrapper
{
public TransformSkipService(Transform transform)
{
super(transform) ;
}
@Override
public Op transform(OpService opService, Op subOp)
{ return opService ; }
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.pipeline.lib.util;
import com.google.common.annotations.VisibleForTesting;
import com.streamsets.pipeline.api.Field;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.impl.Utils;
import org.apache.avro.Schema;
import org.apache.avro.UnresolvedUnionException;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericFixed;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.util.Utf8;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class AvroTypeUtil {
@VisibleForTesting
static final String AVRO_UNION_TYPE_INDEX_PREFIX = "avro.union.typeIndex.";
private static final String FORWARD_SLASH = "/";
public static Field avroToSdcField(Record record, Schema schema, Object value) {
return avroToSdcField(record, "", schema, value);
}
private static Field avroToSdcField(Record record, String fieldPath, Schema schema, Object value) {
if(schema.getType() == Schema.Type.UNION) {
int typeIndex = GenericData.get().resolveUnion(schema, value);
schema = schema.getTypes().get(typeIndex);
record.getHeader().setAttribute(AVRO_UNION_TYPE_INDEX_PREFIX + fieldPath, String.valueOf(typeIndex));
}
if(value == null) {
return Field.create(getFieldType(schema.getType()), value);
}
Field f = null;
switch(schema.getType()) {
case ARRAY:
List<?> objectList = (List<?>) value;
List<Field> list = new ArrayList<>(objectList.size());
for (int i = 0; i < objectList.size(); i++) {
list.add(avroToSdcField(record, fieldPath + "[" + i + "]", schema.getElementType(), objectList.get(i)));
}
f = Field.create(list);
break;
case BOOLEAN:
f = Field.create(Field.Type.BOOLEAN, value);
break;
case BYTES:
f = Field.create(Field.Type.BYTE_ARRAY, ((ByteBuffer)value).array());
break;
case DOUBLE:
f = Field.create(Field.Type.DOUBLE, value);
break;
case ENUM:
f = Field.create(Field.Type.STRING, value);
break;
case FIXED:
f = Field.create(Field.Type.BYTE_ARRAY, ((GenericFixed)value).bytes());
break;
case FLOAT:
f = Field.create(Field.Type.FLOAT, value);
break;
case INT:
f = Field.create(Field.Type.INTEGER, value);
break;
case LONG:
f = Field.create(Field.Type.LONG, value);
break;
case MAP:
Map<Object, Object> avroMap = (Map<Object, Object>) value;
Map<String, Field> map = new LinkedHashMap<>();
for (Map.Entry<Object, Object> entry : avroMap.entrySet()) {
String key;
if (entry.getKey() instanceof Utf8) {
key = entry.getKey().toString();
} else if (entry.getKey() instanceof String) {
key = (String) entry.getKey();
} else {
throw new IllegalStateException(Utils.format("Unrecognized type for avro value: {}", entry.getKey()
.getClass().getName()));
}
map.put(key, avroToSdcField(record, fieldPath + FORWARD_SLASH + key,
schema.getValueType(), entry.getValue()));
}
f = Field.create(map);
break;
case NULL:
f = Field.create(Field.Type.MAP, null);
break;
case RECORD:
GenericRecord avroRecord = (GenericRecord) value;
Map<String, Field> recordMap = new HashMap<>();
for(Schema.Field field : schema.getFields()) {
Field temp = avroToSdcField(record, fieldPath + FORWARD_SLASH + field.name(), field.schema(),
avroRecord.get(field.name()));
if(temp != null) {
recordMap.put(field.name(), temp);
}
}
f = Field.create(recordMap);
break;
case STRING:
f = Field.create(Field.Type.STRING, value.toString());
break;
}
return f;
}
public static Object sdcRecordToAvro(Record record, Schema schema) throws StageException {
return sdcRecordToAvro(record, "", schema);
}
@VisibleForTesting
static Object sdcRecordToAvro(Record record, String avroFieldPath, Schema schema ) throws StageException {
String fieldPath = avroFieldPath;
if(fieldPath != null) {
Field field = record.get(fieldPath);
if(field == null) {
return null;
}
Object obj;
if (schema.getType() == Schema.Type.UNION) {
String fieldPathAttribute = record.getHeader().getAttribute(AVRO_UNION_TYPE_INDEX_PREFIX + fieldPath);
if (fieldPathAttribute != null && !fieldPathAttribute.isEmpty()) {
int typeIndex = Integer.parseInt(fieldPathAttribute);
schema = schema.getTypes().get(typeIndex);
} else {
//Record does not have the avro union type index which means this record was not created from avro data.
//try our best to resolve the union type.
Field field1 = record.get(fieldPath);
Object object = JsonUtil.fieldToJsonObject(record, field1);
try {
int typeIndex = GenericData.get().resolveUnion(schema, object);
schema = schema.getTypes().get(typeIndex);
} catch (UnresolvedUnionException e) {
String objectType = object == null ? "null" : object.getClass().getName();
throw new StageException(CommonError.CMN_0106, objectType, field1.getType().name(), e.toString(),
e);
}
}
}
switch(schema.getType()) {
case ARRAY:
List<Field> valueAsList = field.getValueAsList();
List<Object> toReturn = new ArrayList<>(valueAsList.size());
for(int i = 0; i < valueAsList.size(); i++) {
toReturn.add(sdcRecordToAvro(record, avroFieldPath + "[" + i + "]", schema.getElementType()));
}
obj = toReturn;
break;
case BOOLEAN:
obj = field.getValueAsBoolean();
break;
case BYTES:
obj = ByteBuffer.wrap(field.getValueAsByteArray());
break;
case DOUBLE:
obj = field.getValueAsDouble();
break;
case ENUM:
obj = new GenericData.EnumSymbol(schema, field.getValueAsString());
break;
case FIXED:
obj = new GenericData.Fixed(schema, field.getValueAsByteArray());
break;
case FLOAT:
obj = field.getValueAsFloat();
break;
case INT:
obj = field.getValueAsInteger();
break;
case LONG:
obj = field.getValueAsLong();
break;
case MAP:
Map<String, Field> map = field.getValueAsMap();
Map<String, Object> toReturnMap = new LinkedHashMap<>();
if(map != null) {
for (Map.Entry<String, Field> e : map.entrySet()) {
if (map.containsKey(e.getKey())) {
toReturnMap.put(e.getKey(), sdcRecordToAvro(record, avroFieldPath + FORWARD_SLASH + e.getKey(),
schema.getValueType()));
}
}
}
obj = toReturnMap;
break;
case NULL:
obj = null;
break;
case RECORD:
Map<String, Field> valueAsMap = field.getValueAsMap();
GenericRecord genericRecord = new GenericData.Record(schema);
for (Schema.Field f : schema.getFields()) {
if (valueAsMap.containsKey(f.name())) {
genericRecord.put(f.name(), sdcRecordToAvro(record, avroFieldPath + FORWARD_SLASH + f.name(),
f.schema()));
}
}
obj = genericRecord;
break;
case STRING:
obj = field.getValueAsString();
break;
default :
obj = null;
}
return obj;
}
return null;
}
private static Field.Type getFieldType(Schema.Type type) {
switch(type) {
case ARRAY:
return Field.Type.LIST;
case BOOLEAN:
return Field.Type.BOOLEAN;
case BYTES:
return Field.Type.BYTE_ARRAY;
case DOUBLE:
return Field.Type.DOUBLE;
case ENUM:
return Field.Type.STRING;
case FIXED:
return Field.Type.BYTE_ARRAY;
case FLOAT:
return Field.Type.FLOAT;
case INT:
return Field.Type.INTEGER;
case LONG:
return Field.Type.LONG;
case MAP:
return Field.Type.MAP;
case NULL:
return Field.Type.MAP;
case RECORD:
return Field.Type.MAP;
case STRING:
return Field.Type.STRING;
default:
throw new IllegalStateException(Utils.format("Unexpected schema type {}", type.getName()));
}
}
}
| |
/*
* Copyright 2005 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.core.common;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.drools.core.concurrent.RuleEvaluator;
import org.drools.core.concurrent.SequentialRuleEvaluator;
import org.drools.core.definitions.rule.impl.RuleImpl;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.phreak.ExecutableEntry;
import org.drools.core.phreak.PropagationEntry;
import org.drools.core.phreak.PropagationList;
import org.drools.core.phreak.RuleAgendaItem;
import org.drools.core.phreak.RuleExecutor;
import org.drools.core.phreak.SynchronizedBypassPropagationList;
import org.drools.core.phreak.SynchronizedPropagationList;
import org.drools.core.phreak.ThreadUnsafePropagationList;
import org.drools.core.reteoo.LeftTuple;
import org.drools.core.reteoo.ObjectTypeConf;
import org.drools.core.reteoo.ObjectTypeNode;
import org.drools.core.reteoo.PathMemory;
import org.drools.core.reteoo.RuleTerminalNodeLeftTuple;
import org.drools.core.reteoo.TerminalNode;
import org.drools.core.rule.Declaration;
import org.drools.core.rule.EntryPointId;
import org.drools.core.rule.QueryImpl;
import org.drools.core.spi.Activation;
import org.drools.core.spi.AgendaGroup;
import org.drools.core.spi.ConsequenceException;
import org.drools.core.spi.ConsequenceExceptionHandler;
import org.drools.core.spi.InternalActivationGroup;
import org.drools.core.spi.KnowledgeHelper;
import org.drools.core.spi.PropagationContext;
import org.drools.core.spi.RuleFlowGroup;
import org.drools.core.spi.Tuple;
import org.drools.core.util.StringUtils;
import org.drools.core.util.index.TupleList;
import org.drools.reflective.ComponentsFactory;
import org.kie.api.conf.EventProcessingOption;
import org.kie.api.event.rule.MatchCancelledCause;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.rule.AgendaFilter;
import org.kie.api.runtime.rule.Match;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Rule-firing Agenda.
*
* <p>
* Since many rules may be matched by a single assertObject(...) all scheduled
* actions are placed into the <code>Agenda</code>.
* </p>
*
* <p>
* While processing a scheduled action, it may update or retract objects in
* other scheduled actions, which must then be removed from the agenda.
* Non-invalidated actions are left on the agenda, and are executed in turn.
* </p>
*/
public class DefaultAgenda
implements
Externalizable,
InternalAgenda {
public static final String ON_BEFORE_ALL_FIRES_CONSEQUENCE_NAME = "$onBeforeAllFire$";
public static final String ON_AFTER_ALL_FIRES_CONSEQUENCE_NAME = "$onAfterAllFire$";
public static final String ON_DELETE_MATCH_CONSEQUENCE_NAME = "$onDeleteMatch$";
protected static final transient Logger log = LoggerFactory.getLogger( DefaultAgenda.class );
private static final long serialVersionUID = 510l;
/** Working memory of this Agenda. */
protected InternalWorkingMemory workingMemory;
/** Items time-delayed. */
private Map<String, InternalActivationGroup> activationGroups;
private final org.drools.core.util.LinkedList<RuleAgendaItem> eager = new org.drools.core.util.LinkedList<>();
private final Map<QueryImpl, RuleAgendaItem> queries = new ConcurrentHashMap<>();
private ConsequenceExceptionHandler legacyConsequenceExceptionHandler;
private org.kie.api.runtime.rule.ConsequenceExceptionHandler consequenceExceptionHandler;
protected int activationCounter;
private boolean declarativeAgenda;
private boolean sequential;
private ObjectTypeConf activationObjectTypeConf;
private ActivationsFilter activationsFilter;
private volatile List<PropagationContext> expirationContexts;
private RuleEvaluator ruleEvaluator;
private PropagationList propagationList;
private ExecutionStateMachine executionStateMachine;
private AgendaGroupsManager agendaGroupsManager;
// ------------------------------------------------------------
// Constructors
// ------------------------------------------------------------
public DefaultAgenda() { }
public DefaultAgenda(InternalKnowledgeBase kBase) {
this( kBase, true );
}
public DefaultAgenda(InternalKnowledgeBase kBase, boolean initMain) {
this(kBase, initMain, new ConcurrentExecutionStateMachine());
}
DefaultAgenda(InternalKnowledgeBase kBase,
boolean initMain,
ExecutionStateMachine executionStateMachine) {
this.agendaGroupsManager = AgendaGroupsManager.create(kBase, initMain);
this.activationGroups = new HashMap<>();
this.executionStateMachine = executionStateMachine;
Object object = ComponentsFactory.createConsequenceExceptionHandler( kBase.getConfiguration().getConsequenceExceptionHandler(),
kBase.getConfiguration().getClassLoader() );
if ( object instanceof ConsequenceExceptionHandler ) {
this.legacyConsequenceExceptionHandler = (ConsequenceExceptionHandler) object;
} else {
this.consequenceExceptionHandler = (org.kie.api.runtime.rule.ConsequenceExceptionHandler) object;
}
this.declarativeAgenda = kBase.getConfiguration().isDeclarativeAgenda();
this.sequential = kBase.getConfiguration().isSequential();
if (kBase.getConfiguration().getEventProcessingMode() == EventProcessingOption.STREAM) {
expirationContexts = new ArrayList<>();
}
}
@Override
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
setWorkingMemory( (InternalWorkingMemory) in.readObject() );
agendaGroupsManager = (AgendaGroupsManager) in.readObject();
activationGroups = (Map) in.readObject();
legacyConsequenceExceptionHandler = (ConsequenceExceptionHandler) in.readObject();
declarativeAgenda = in.readBoolean();
sequential = in.readBoolean();
this.executionStateMachine = new ConcurrentExecutionStateMachine();
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject( workingMemory );
out.writeObject( agendaGroupsManager );
out.writeObject( activationGroups );
out.writeObject( legacyConsequenceExceptionHandler );
out.writeBoolean( declarativeAgenda );
out.writeBoolean( sequential );
}
@Override
public RuleAgendaItem createRuleAgendaItem(final int salience,
final PathMemory rs,
final TerminalNode rtn ) {
String ruleFlowGroupName = rtn.getRule().getRuleFlowGroup();
return new RuleAgendaItem( activationCounter++, null, salience, null, rs, rtn, isDeclarativeAgenda(),
(InternalAgendaGroup) getAgendaGroup( !StringUtils.isEmpty(ruleFlowGroupName) ? ruleFlowGroupName : rtn.getRule().getAgendaGroup() ));
}
@Override
public AgendaItem createAgendaItem(RuleTerminalNodeLeftTuple rtnLeftTuple,
final int salience,
final PropagationContext context,
RuleAgendaItem ruleAgendaItem,
InternalAgendaGroup agendaGroup) {
rtnLeftTuple.init(activationCounter++,
salience,
context,
ruleAgendaItem, agendaGroup);
return rtnLeftTuple;
}
@Override
public void setWorkingMemory(final InternalWorkingMemory workingMemory) {
this.workingMemory = workingMemory;
this.agendaGroupsManager.setWorkingMemory( workingMemory );
if ( !workingMemory.getSessionConfiguration().isThreadSafe() ) {
executionStateMachine = new UnsafeExecutionStateMachine();
}
this.ruleEvaluator = new SequentialRuleEvaluator( this );
this.propagationList = createPropagationList();
}
private PropagationList createPropagationList() {
if (!workingMemory.getSessionConfiguration().isThreadSafe()) {
return new ThreadUnsafePropagationList( workingMemory );
}
return workingMemory.getSessionConfiguration().hasForceEagerActivationFilter() ?
new SynchronizedBypassPropagationList( workingMemory ) :
new SynchronizedPropagationList( workingMemory );
}
@Override
public PropagationList getPropagationList() {
return propagationList;
}
@Override
public InternalWorkingMemory getWorkingMemory() {
return this.workingMemory;
}
@Override
public void addEagerRuleAgendaItem(RuleAgendaItem item) {
if ( sequential ) {
return;
}
if ( item.isInList(eager) ) {
return;
}
if ( log.isTraceEnabled() ) {
log.trace("Added {} to eager evaluation list.", item.getRule().getName() );
}
eager.add( item );
}
@Override
public void removeEagerRuleAgendaItem(RuleAgendaItem item) {
if ( !item.isInList(eager) ) {
return;
}
if ( log.isTraceEnabled() ) {
log.trace( "Removed {} from eager evaluation list.", item.getRule().getName() );
}
eager.remove( item );
}
@Override
public void addQueryAgendaItem(RuleAgendaItem item) {
queries.put( (QueryImpl) item.getRule(), item );
if ( log.isTraceEnabled() ) {
log.trace( "Added {} to query evaluation list.", item.getRule().getName() );
}
}
@Override
public void removeQueryAgendaItem(RuleAgendaItem item) {
queries.remove( (QueryImpl) item.getRule() );
if ( log.isTraceEnabled() ) {
log.trace("Removed {} from query evaluation list.", item.getRule().getName() );
}
}
/**
* If the item belongs to an activation group, add it
*
* @param item
*/
@Override
public void addItemToActivationGroup(final AgendaItem item) {
if ( item.isRuleAgendaItem() ) {
throw new UnsupportedOperationException("defensive programming, making sure this isn't called, before removing");
}
String group = item.getRule().getActivationGroup();
if ( group != null && group.length() > 0 ) {
InternalActivationGroup actgroup = getActivationGroup( group );
// Don't allow lazy activations to activate, from before it's last trigger point
if ( actgroup.getTriggeredForRecency() != 0 &&
actgroup.getTriggeredForRecency() >= item.getPropagationContext().getFactHandle().getRecency() ) {
return;
}
actgroup.addActivation( item );
}
}
@Override
public void insertAndStageActivation(final AgendaItem activation) {
if ( activationObjectTypeConf == null ) {
EntryPointId ep = workingMemory.getEntryPoint();
activationObjectTypeConf = workingMemory.getWorkingMemoryEntryPoint( ep.getEntryPointId() ).getObjectTypeConfigurationRegistry().getObjectTypeConf(activation );
}
InternalFactHandle factHandle = workingMemory.getFactHandleFactory().newFactHandle( activation, activationObjectTypeConf, workingMemory, workingMemory );
workingMemory.getEntryPointNode().assertActivation( factHandle, activation.getPropagationContext(), workingMemory );
activation.setActivationFactHandle( factHandle );
}
@Override
public boolean isDeclarativeAgenda() {
return declarativeAgenda;
}
@Override
public void modifyActivation(final AgendaItem activation,
boolean previouslyActive) {
// in Phreak this is only called for declarative agenda, on rule instances
InternalFactHandle factHandle = activation.getActivationFactHandle();
if ( factHandle != null ) {
// removes the declarative rule instance for the real rule instance
workingMemory.getEntryPointNode().modifyActivation( factHandle, activation.getPropagationContext(), workingMemory );
}
}
@Override
public boolean isRuleActiveInRuleFlowGroup(String ruleflowGroupName, String ruleName, long processInstanceId) {
return isRuleInstanceAgendaItem(ruleflowGroupName, ruleName, processInstanceId);
}
@Override
public void cancelActivation(final Activation activation) {
AgendaItem item = (AgendaItem) activation;
item.removeAllBlockersAndBlocked( this );
workingMemory.cancelActivation( activation, isDeclarativeAgenda() );
if ( isDeclarativeAgenda() ) {
if (activation.getActivationFactHandle() == null) {
// This a control rule activation, nothing to do except update counters. As control rules are not in agenda-groups etc.
return;
}
// we are cancelling an actual Activation, so also it's handle from the WM.
if ( activation.getActivationGroupNode() != null ) {
activation.getActivationGroupNode().getActivationGroup().removeActivation( activation );
}
}
if ( activation.isQueued() ) {
if ( activation.getActivationGroupNode() != null ) {
activation.getActivationGroupNode().getActivationGroup().removeActivation( activation );
}
(( Tuple ) activation).decreaseActivationCountForEvents();
workingMemory.getAgendaEventSupport().fireActivationCancelled( activation,
workingMemory,
MatchCancelledCause.WME_MODIFY );
}
if (item.getRuleAgendaItem() != null) {
item.getRuleAgendaItem().getRuleExecutor().fireConsequenceEvent( this.workingMemory, this, item, ON_DELETE_MATCH_CONSEQUENCE_NAME );
}
workingMemory.getRuleEventSupport().onDeleteMatch( item );
TruthMaintenanceSystemHelper.removeLogicalDependencies( activation, ( Tuple ) activation, activation.getRule() );
}
/*
* (non-Javadoc)
*
* @see org.kie.common.AgendaI#setFocus(org.kie.spi.AgendaGroup)
*/
@Override
public boolean setFocus(final AgendaGroup agendaGroup) {
return this.agendaGroupsManager.setFocus((InternalAgendaGroup) agendaGroup);
}
/*
* (non-Javadoc)
*
* @see org.kie.common.AgendaI#setFocus(java.lang.String)
*/
@Override
public void setFocus(final String name) {
setFocus( null, name );
}
public void setFocus(final PropagationContext ctx,
final String name) {
AgendaGroup agendaGroup = getAgendaGroup( name );
agendaGroup.setAutoFocusActivator( ctx );
setFocus( agendaGroup );
}
@Override
public InternalAgendaGroup getNextFocus() {
return agendaGroupsManager.getNextFocus();
}
@Override
public RuleAgendaItem peekNextRule() {
return agendaGroupsManager.peekNextRule();
}
@Override
public AgendaGroup getAgendaGroup(final String name) {
return agendaGroupsManager.getAgendaGroup( name );
}
@Override
public void removeAgendaGroup(final String name) {
agendaGroupsManager.removeGroup( agendaGroupsManager.getAgendaGroup( name ) );
}
@Override
public AgendaGroup getAgendaGroup(String name, InternalKnowledgeBase kBase) {
return agendaGroupsManager.getAgendaGroup(name, kBase);
}
@Override
public AgendaGroup[] getAgendaGroups() {
return agendaGroupsManager.getAgendaGroups();
}
@Override
public Map<String, InternalAgendaGroup> getAgendaGroupsMap() {
return agendaGroupsManager.getAgendaGroupsMap();
}
@Override
public void putOnAgendaGroupsMap(String name, InternalAgendaGroup group) {
agendaGroupsManager.putOnAgendaGroupsMap(name, group);
}
@Override
public Collection<String> getGroupsName() {
return agendaGroupsManager.getGroupsName();
}
@Override
public void addAgendaGroupOnStack(AgendaGroup agendaGroup) {
agendaGroupsManager.addAgendaGroupOnStack((InternalAgendaGroup) agendaGroup);
}
@Override
public Map<String, InternalActivationGroup> getActivationGroupsMap() {
return this.activationGroups;
}
@Override
public InternalActivationGroup getActivationGroup(final String name) {
return this.activationGroups.computeIfAbsent(name, k -> new ActivationGroupImpl( this, k ));
}
@Override
public RuleFlowGroup getRuleFlowGroup(final String name) {
return ( RuleFlowGroup ) getAgendaGroup(name);
}
@Override
public void activateRuleFlowGroup(final String name) {
InternalRuleFlowGroup group = (InternalRuleFlowGroup) getRuleFlowGroup( name );
activateRuleFlowGroup( group, -1, null );
}
@Override
public void activateRuleFlowGroup(final String name,
long processInstanceId,
String nodeInstanceId) {
InternalRuleFlowGroup ruleFlowGroup = (InternalRuleFlowGroup) getRuleFlowGroup( name );
activateRuleFlowGroup( ruleFlowGroup, processInstanceId, nodeInstanceId );
}
public void activateRuleFlowGroup(final InternalRuleFlowGroup group, Object processInstanceId, String nodeInstanceId) {
this.workingMemory.getAgendaEventSupport().fireBeforeRuleFlowGroupActivated( group, this.workingMemory );
group.setActive( true );
group.hasRuleFlowListener(true);
if ( !StringUtils.isEmpty( nodeInstanceId ) ) {
group.addNodeInstance( processInstanceId, nodeInstanceId );
group.setActive( true );
}
group.setFocus();
this.workingMemory.getAgendaEventSupport().fireAfterRuleFlowGroupActivated( group, this.workingMemory );
propagationList.notifyWaitOnRest();
}
@Override
public void deactivateRuleFlowGroup(final String name) {
agendaGroupsManager.deactivateRuleFlowGroup(name);
}
/*
* (non-Javadoc)
*
* @see org.kie.common.AgendaI#focusStackSize()
*/
@Override
public int focusStackSize() {
return agendaGroupsManager.focusStackSize();
}
/*
* (non-Javadoc)
*
* @see org.kie.common.AgendaI#agendaSize()
*/
@Override
public int agendaSize() {
return agendaGroupsManager.agendaSize();
}
/*
* (non-Javadoc)
*
* @see org.kie.common.AgendaI#getActivations()
*/
@Override
public Activation[] getActivations() {
return agendaGroupsManager.getActivations();
}
@Override
public void clear() {
agendaGroupsManager.reset(true);
// reset all activation groups.
for ( InternalActivationGroup group : this.activationGroups.values() ) {
group.setTriggeredForRecency(this.workingMemory.getFactHandleFactory().getRecency());
group.reset();
}
propagationList.reset();
}
@Override
public void reset() {
agendaGroupsManager.reset(false);
// reset all activation groups.
for ( InternalActivationGroup group : this.activationGroups.values() ) {
group.setTriggeredForRecency( this.workingMemory.getFactHandleFactory().getRecency() );
group.reset();
}
eager.clear();
activationCounter = 0;
executionStateMachine.reset();
propagationList.reset();
}
@Override
public void clearAndCancel() {
// Cancel all items and fire a Cancelled event for each Activation
agendaGroupsManager.clearAndCancel(this);
// cancel all activation groups.
for ( InternalActivationGroup group : this.activationGroups.values() ) {
clearAndCancelActivationGroup( group );
}
}
/*
* (non-Javadoc)
*
* @see org.kie.common.AgendaI#clearAgendaGroup(java.lang.String)
*/
@Override
public void clearAndCancelAgendaGroup(final String name) {
agendaGroupsManager.clearAndCancelAgendaGroup(name, this);
}
/*
* (non-Javadoc)
*
* @see org.kie.common.AgendaI#clearActivationGroup(java.lang.String)
*/
@Override
public void clearAndCancelActivationGroup(final String name) {
final InternalActivationGroup activationGroup = this.activationGroups.get( name );
if ( activationGroup != null ) {
clearAndCancelActivationGroup( activationGroup );
}
}
/*
* (non-Javadoc)
*
* @see org.kie.common.AgendaI#clearActivationGroup(org.kie.spi.ActivationGroup)
*/
@Override
public void clearAndCancelActivationGroup(final InternalActivationGroup activationGroup) {
final EventSupport eventsupport = this.workingMemory;
activationGroup.setTriggeredForRecency( this.workingMemory.getFactHandleFactory().getRecency() );
for ( final Iterator it = activationGroup.iterator(); it.hasNext(); ) {
final ActivationGroupNode node = (ActivationGroupNode) it.next();
final Activation activation = node.getActivation();
activation.setActivationGroupNode( null );
if ( activation.isQueued() ) {
activation.setQueued(false);
activation.remove();
RuleExecutor ruleExec = ((RuleTerminalNodeLeftTuple)activation).getRuleAgendaItem().getRuleExecutor();
ruleExec.removeLeftTuple((LeftTuple) activation);
eventsupport.getAgendaEventSupport().fireActivationCancelled( activation,
this.workingMemory,
MatchCancelledCause.CLEAR );
}
}
activationGroup.reset();
}
@Override
public void clearAndCancelRuleFlowGroup(final String name) {
agendaGroupsManager.clearAndCancelAgendaGroup(name, this);
}
/**
* Fire the next scheduled <code>Agenda</code> item, skipping items
* that are not allowed by the agenda filter.
*
* @return true if an activation was fired. false if no more activations
* to fire
*
* @throws ConsequenceException
* If an error occurs while firing an agenda item.
*/
@Override
public int fireNextItem(final AgendaFilter filter,
int fireCount,
int fireLimit) {
// Because rules can be on the agenda, but after network evaluation produce no full matches, the
// engine uses tryAgain to drive a loop to find a rule that has matches, until there are no more rules left to try.
// once rule with 1..n matches is found, it'll return back to the outer loop.
boolean tryagain;
int localFireCount = 0;
do {
tryagain = false;
evaluateEagerList();
final InternalAgendaGroup group = getNextFocus();
// if there is a group with focus
if ( group != null ) {
localFireCount = ruleEvaluator.evaluateAndFire(filter, fireCount, fireLimit, group);
// it produced no full matches, so drive the search to the next rule
if ( localFireCount == 0 ) {
// nothing matched
tryagain = true;
propagationList.flush(); // There may actions to process, which create new rule matches
}
}
} while ( tryagain );
return localFireCount;
}
@Override
public void evaluateEagerList() {
while ( !eager.isEmpty() ) {
RuleAgendaItem item = eager.removeFirst();
if (item.isRuleInUse()) { // this rule could have been removed by an incremental compilation
evaluateQueriesForRule( item );
RuleExecutor ruleExecutor = item.getRuleExecutor();
ruleExecutor.evaluateNetwork( this );
}
}
}
public void evaluateQueriesForRule(RuleAgendaItem item) {
RuleImpl rule = item.getRule();
if (!rule.isQuery()) {
for (QueryImpl query : rule.getDependingQueries()) {
RuleAgendaItem queryAgendaItem = queries.remove(query);
if (queryAgendaItem != null) {
queryAgendaItem.getRuleExecutor().evaluateNetwork(this);
}
}
}
}
@Override
public int sizeOfRuleFlowGroup(String name) {
return agendaGroupsManager.sizeOfRuleFlowGroup(name);
}
@Override
public boolean isRuleInstanceAgendaItem(String ruleflowGroupName,
String ruleName,
long processInstanceId) {
return isRuleInstanceAgendaItem(ruleflowGroupName, ruleName, (Object) processInstanceId);
}
protected boolean isRuleInstanceAgendaItem(String ruleflowGroupName,
String ruleName,
Object processInstanceId) {
propagationList.flush();
RuleFlowGroup systemRuleFlowGroup = this.getRuleFlowGroup( ruleflowGroupName );
Match[] matches = ((InternalAgendaGroup)systemRuleFlowGroup).getActivations();
for ( Match match : matches ) {
Activation act = ( Activation ) match;
if ( act.isRuleAgendaItem() ) {
// The lazy RuleAgendaItem must be fully evaluated, to see if there is a rule match
RuleExecutor ruleExecutor = ((RuleAgendaItem) act).getRuleExecutor();
ruleExecutor.evaluateNetwork(this);
TupleList list = ruleExecutor.getLeftTupleList();
for (RuleTerminalNodeLeftTuple lt = (RuleTerminalNodeLeftTuple) list.getFirst(); lt != null; lt = (RuleTerminalNodeLeftTuple) lt.getNext()) {
if ( ruleName.equals( lt.getRule().getName() )
&& ( checkProcessInstance( lt, processInstanceId ) )) {
return true;
}
}
} else {
if ( ruleName.equals( act.getRule().getName() )
&& ( checkProcessInstance( act, processInstanceId ) )) {
return true;
}
}
}
return false;
}
private boolean checkProcessInstance(Activation activation,
Object processInstanceId) {
final Map<String, Declaration> declarations = activation.getSubRule().getOuterDeclarations();
for ( Declaration declaration : declarations.values() ) {
if ( "processInstance".equals( declaration.getIdentifier() )
|| "org.kie.api.runtime.process.WorkflowProcessInstance".equals(declaration.getTypeName())) {
Object value = declaration.getValue( workingMemory, activation.getTuple() );
if ( value instanceof ProcessInstance ) {
return sameProcessInstance( processInstanceId, ( ProcessInstance ) value );
}
}
}
return true;
}
protected boolean sameProcessInstance( Object processInstanceId, ProcessInstance value ) {
return processInstanceId.equals( value.getId());
}
@Override
public String getFocusName() {
return this.agendaGroupsManager.getFocusName();
}
@Override
public void stageLeftTuple(RuleAgendaItem ruleAgendaItem, AgendaItem justified) {
if (!ruleAgendaItem.isQueued()) {
ruleAgendaItem.getRuleExecutor().getPathMemory().queueRuleAgendaItem(this);
}
ruleAgendaItem.getRuleExecutor().addLeftTuple( justified.getTuple() );
}
@Override
public void fireUntilHalt() {
fireUntilHalt( null );
}
@Override
public void fireUntilHalt(final AgendaFilter agendaFilter) {
if ( log.isTraceEnabled() ) {
log.trace("Starting Fire Until Halt");
}
if (executionStateMachine.toFireUntilHalt()) {
internalFireUntilHalt( agendaFilter, true );
}
if ( log.isTraceEnabled() ) {
log.trace("Ending Fire Until Halt");
}
}
void internalFireUntilHalt( AgendaFilter agendaFilter, boolean isInternalFire ) {
propagationList.setFiringUntilHalt( true );
try {
fireLoop( agendaFilter, -1, RestHandler.FIRE_UNTIL_HALT, isInternalFire );
} finally {
propagationList.setFiringUntilHalt( false );
}
}
@Override
public int fireAllRules(AgendaFilter agendaFilter, int fireLimit) {
if (!executionStateMachine.toFireAllRules()) {
return 0;
}
if ( log.isTraceEnabled() ) {
log.trace("Starting Fire All Rules");
}
int fireCount = internalFireAllRules( agendaFilter, fireLimit, true );
if ( log.isTraceEnabled() ) {
log.trace("Ending Fire All Rules");
}
return fireCount;
}
int internalFireAllRules( AgendaFilter agendaFilter, int fireLimit, boolean isInternalFire ) {
return fireLoop( agendaFilter, fireLimit, RestHandler.FIRE_ALL_RULES, isInternalFire );
}
private int fireLoop(AgendaFilter agendaFilter, int fireLimit, RestHandler restHandler, boolean isInternalFire) {
int fireCount = 0;
try {
PropagationEntry head = propagationList.takeAll();
int returnedFireCount;
boolean limitReached = fireLimit == 0; // -1 or > 0 will return false. No reason for user to give 0, just handled for completeness.
// The engine comes to potential rest (inside the loop) when there are no propagations and no rule firings.
// It's potentially at rest, because we cannot guarantee it is at rest.
// This is because external async actions (timer rules) can populate the queue that must be executed immediately.
// A final takeAll within the sync point determines if it can safely come to rest.
// if takeAll returns null, the engine is now safely at rest. If it returns something
// the engine is not at rest and the loop continues.
//
// When FireUntilHalt comes to a safe rest, the thread is put into a wait state,
// when the queue is populated the thread is notified and the loop begins again.
//
// When FireAllRules comes to a safe rest it will put the engine into an INACTIVE state
// and the loop can exit.
//
// When a halt() command is added to the propagation queue and that queue is flushed
// the engine is put into a INACTIVE state. At this point isFiring returns false and
// no more rules can fire. However the loop will continue until rest point has been safely
// entered, i.e. the queue returns null within that sync point.
//
// The loop is susceptable to never return on extremely greedy behaviour.
//
// Note that if a halt() command is given, the engine is changed to INACTIVE,
// and isFiring returns false allowing it to exit before all rules are fired.
//
while ( isFiring() ) {
if ( head != null ) {
// it is possible that there are no action propagations, but there are rules to fire.
propagationList.flush(head);
head = null;
}
// a halt may have occurred during the flushPropagations,
// which changes the isFiring state. So a second isFiring guard is needed
if (!isFiring()) {
break;
}
evaluateEagerList();
InternalAgendaGroup group = getNextFocus();
if ( group != null && !limitReached ) {
// only fire rules while the limit has not reached.
// if halt is called, then isFiring will be false.
// The while loop may continue to loop, to keep flushing the action propagation queue
returnedFireCount = ruleEvaluator.evaluateAndFire( agendaFilter, fireCount, fireLimit, group );
fireCount += returnedFireCount;
limitReached = ( fireLimit > 0 && fireCount >= fireLimit );
head = propagationList.takeAll();
} else {
returnedFireCount = 0; // no rules fired this iteration, so we know this is 0
group = null; // set the group to null in case the fire limit has been reached
}
if ( returnedFireCount == 0 && head == null && ( group == null || ( group.isEmpty() && !group.isAutoDeactivate() ) ) && !flushExpirations() ) {
// if true, the engine is now considered potentially at rest
head = restHandler.handleRest( this, isInternalFire );
if (!isInternalFire && head == null) {
break;
}
}
}
agendaGroupsManager.deactivateMainGroupWhenEmpty();
} finally {
// makes sure the engine is inactive, if an exception is thrown.
// if it safely returns, then the engine should already be inactive
if (isInternalFire) {
executionStateMachine.immediateHalt(propagationList);
}
}
return fireCount;
}
interface RestHandler {
RestHandler FIRE_ALL_RULES = new FireAllRulesRestHandler();
RestHandler FIRE_UNTIL_HALT = new FireUntilHaltRestHandler();
PropagationEntry handleRest(DefaultAgenda agenda, boolean isInternalFire);
class FireAllRulesRestHandler implements RestHandler {
@Override
public PropagationEntry handleRest(DefaultAgenda agenda, boolean isInternalFire) {
synchronized (agenda.executionStateMachine.getStateMachineLock()) {
PropagationEntry head = agenda.propagationList.takeAll();
if (isInternalFire && head == null) {
agenda.internalHalt();
}
return head;
}
}
}
class FireUntilHaltRestHandler implements RestHandler {
@Override
public PropagationEntry handleRest(DefaultAgenda agenda, boolean isInternalFire) {
boolean deactivated = false;
if (isInternalFire && agenda.executionStateMachine.getCurrentState() == ExecutionStateMachine.ExecutionState.FIRING_UNTIL_HALT) {
agenda.executionStateMachine.inactiveOnFireUntilHalt();
deactivated = true;
}
PropagationEntry head;
// this must use the same sync target as takeAllPropagations, to ensure this entire block is atomic, up to the point of wait
synchronized (agenda.propagationList) {
head = agenda.propagationList.takeAll();
// if halt() has called, the thread should not be put into a wait state
// instead this is just a safe way to make sure the queue is flushed before exiting the loop
if (head == null && (
agenda.executionStateMachine.getCurrentState() == ExecutionStateMachine.ExecutionState.FIRING_UNTIL_HALT ||
agenda.executionStateMachine.getCurrentState() == ExecutionStateMachine.ExecutionState.INACTIVE_ON_FIRING_UNTIL_HALT )) {
agenda.propagationList.waitOnRest();
head = agenda.propagationList.takeAll();
}
}
if (deactivated) {
agenda.executionStateMachine.toFireUntilHalt();
}
return head;
}
}
}
@Override
public boolean isFiring() {
return executionStateMachine.isFiring();
}
@Override
public void executeTask( ExecutableEntry executable ) {
if ( !executionStateMachine.toExecuteTask( executable ) ) {
return;
}
try {
executable.execute();
} finally {
executionStateMachine.immediateHalt(propagationList);
}
}
@Override
public void executeFlush() {
if (!executionStateMachine.toExecuteTaskState()) {
return;
}
try {
flushPropagations();
} finally {
executionStateMachine.immediateHalt(propagationList);
}
}
@Override
public void activate() {
executionStateMachine.activate(this, propagationList);
}
@Override
public void deactivate() {
executionStateMachine.deactivate();
}
@Override
public boolean tryDeactivate() {
return executionStateMachine.tryDeactivate();
}
static class Halt extends PropagationEntry.AbstractPropagationEntry {
private final ExecutionStateMachine executionStateMachine;
protected Halt( ExecutionStateMachine executionStateMachine ) {
this.executionStateMachine = executionStateMachine;
}
@Override
public void execute( InternalWorkingMemory wm ) {
executionStateMachine.internalHalt();
}
@Override
public String toString() {
return "Halt";
}
}
@Override
public synchronized void halt() {
// only attempt halt an engine that is currently firing
// This will place a halt command on the propagation queue
// that will allow the engine to halt safely
if ( isFiring() ) {
propagationList.addEntry(new Halt(executionStateMachine));
}
}
@Override
public boolean dispose(InternalWorkingMemory wm) {
propagationList.dispose();
return executionStateMachine.dispose( wm );
}
@Override
public boolean isAlive() {
return executionStateMachine.isAlive();
}
public void internalHalt() {
executionStateMachine.internalHalt();
}
@Override
public void setActivationsFilter(ActivationsFilter filter) {
this.activationsFilter = filter;
}
@Override
public ActivationsFilter getActivationsFilter() {
return this.activationsFilter;
}
@Override
public void handleException(InternalWorkingMemory wm, Activation activation, Exception e) {
if ( this.legacyConsequenceExceptionHandler != null ) {
this.legacyConsequenceExceptionHandler.handleException( activation, wm, e );
} else if ( this.consequenceExceptionHandler != null ) {
this.consequenceExceptionHandler.handleException( activation, wm.getKnowledgeRuntime(), e );
} else {
throw new RuntimeException( e );
}
}
@Override
public KnowledgeHelper getKnowledgeHelper() {
return ruleEvaluator.getKnowledgeHelper();
}
@Override
public void addPropagation(PropagationEntry propagationEntry) {
propagationList.addEntry( propagationEntry );
}
@Override
public void flushPropagations() {
propagationList.flush();
}
@Override
public void notifyWaitOnRest() {
propagationList.notifyWaitOnRest();
}
@Override
public Iterator<PropagationEntry> getActionsIterator() {
return propagationList.iterator();
}
@Override
public boolean hasPendingPropagations() {
return !propagationList.isEmpty();
}
interface ExecutionStateMachine {
enum ExecutionState { // fireAllRule | fireUntilHalt | executeTask <-- required action
INACTIVE( false, true ), // fire | fire | exec
FIRING_ALL_RULES( true, true ), // do nothing | wait + fire | enqueue
FIRING_UNTIL_HALT( true, true ), // do nothing | do nothing | enqueue
INACTIVE_ON_FIRING_UNTIL_HALT( true, true ),
HALTING( false, true ), // wait + fire | wait + fire | enqueue
EXECUTING_TASK( false, true ), // wait + fire | wait + fire | wait + exec
DEACTIVATED( false, true ), // wait + fire | wait + fire | wait + exec
DISPOSING( false, false ), // no further action is allowed
DISPOSED( false, false ); // no further action is allowed
private final boolean firing;
private final boolean alive;
ExecutionState( boolean firing, boolean alive ) {
this.firing = firing;
this.alive = alive;
}
public boolean isFiring() {
return firing;
}
public boolean isAlive() {
return alive;
}
}
boolean isFiring();
void reset();
boolean toFireAllRules();
boolean toFireUntilHalt();
boolean toExecuteTask( ExecutableEntry executable );
boolean toExecuteTaskState();
void activate(DefaultAgenda agenda, PropagationList propagationList);
void deactivate();
boolean tryDeactivate();
void immediateHalt(PropagationList propagationList);
void inactiveOnFireUntilHalt();
void internalHalt();
boolean dispose(InternalWorkingMemory workingMemory);
boolean isAlive();
ExecutionState getCurrentState();
Object getStateMachineLock();
}
static class UnsafeExecutionStateMachine implements ExecutionStateMachine {
private final Object stateMachineLock = new Object();
private ExecutionState currentState = ExecutionState.INACTIVE;
@Override
public boolean isFiring() {
return currentState.isFiring();
}
@Override
public void reset() {
currentState = ExecutionState.INACTIVE;
}
@Override
public boolean toFireAllRules() {
currentState = ExecutionState.FIRING_ALL_RULES;
return true;
}
@Override
public boolean toFireUntilHalt() {
throw new UnsupportedOperationException( "Not permitted in non-thread-safe mode" );
}
@Override
public boolean toExecuteTask( ExecutableEntry executable ) {
throw new UnsupportedOperationException( "Not permitted in non-thread-safe mode" );
}
@Override
public boolean toExecuteTaskState() {
currentState = ExecutionState.EXECUTING_TASK;
return true;
}
@Override
public void activate( DefaultAgenda agenda, PropagationList propagationList ) {
}
@Override
public void deactivate() {
currentState = ExecutionState.DEACTIVATED;
}
@Override
public boolean tryDeactivate() {
currentState = ExecutionState.DEACTIVATED;
return true;
}
@Override
public void immediateHalt( PropagationList propagationList ) {
currentState = ExecutionState.INACTIVE;
}
@Override
public void inactiveOnFireUntilHalt() {
throw new UnsupportedOperationException( "Not permitted in non-thread-safe mode" );
}
@Override
public void internalHalt() {
if (isFiring()) {
currentState = ExecutionState.HALTING;
}
}
@Override
public boolean dispose( InternalWorkingMemory workingMemory ) {
currentState = ExecutionState.DISPOSED;
return true;
}
@Override
public boolean isAlive() {
return currentState.isAlive();
}
@Override
public ExecutionState getCurrentState() {
return currentState;
}
@Override
public Object getStateMachineLock() {
return stateMachineLock;
}
}
static class ConcurrentExecutionStateMachine implements ExecutionStateMachine {
private volatile ExecutionState currentState = ExecutionState.INACTIVE;
private volatile boolean wasFiringUntilHalt = false;
private final Object stateMachineLock = new Object();
private long fireUntilHaltThreadId = -1;
public boolean isFiring() {
return currentState.isFiring();
}
public void reset() {
currentState = ExecutionState.INACTIVE;
wasFiringUntilHalt = false;
}
public boolean toFireAllRules() {
synchronized (stateMachineLock) {
if (currentState.isFiring() || !currentState.isAlive()) {
return false;
}
waitAndEnterExecutionState( ExecutionState.FIRING_ALL_RULES );
}
return true;
}
public boolean toFireUntilHalt() {
synchronized (stateMachineLock) {
if ( currentState == ExecutionState.FIRING_UNTIL_HALT || currentState == ExecutionState.HALTING ) {
return false;
}
waitAndEnterExecutionState( ExecutionState.FIRING_UNTIL_HALT );
}
return true;
}
public boolean toExecuteTask( ExecutableEntry executable ) {
synchronized (stateMachineLock) {
// state is never changed outside of a sync block, so this is safe.
if (isFiring()) {
executable.enqueue();
return false;
}
if (currentState != ExecutionState.EXECUTING_TASK) {
waitAndEnterExecutionState( ExecutionState.EXECUTING_TASK );
}
return true;
}
}
public boolean toExecuteTaskState() {
synchronized (stateMachineLock) {
// state is never changed outside of a sync block, so this is safe.
if (!currentState.isAlive() || currentState.isFiring()) {
return false;
}
waitAndEnterExecutionState( ExecutionState.EXECUTING_TASK );
return true;
}
}
private void waitAndEnterExecutionState( ExecutionState newState ) {
waitInactive();
setCurrentState( newState );
}
private void waitInactive() {
while ( currentState != ExecutionState.INACTIVE && currentState != ExecutionState.INACTIVE_ON_FIRING_UNTIL_HALT && currentState != ExecutionState.DISPOSED ) {
try {
stateMachineLock.wait();
} catch (InterruptedException e) {
throw new RuntimeException( e );
}
}
}
private void setCurrentState(ExecutionState state) {
if ( log.isDebugEnabled() ) {
log.debug("State was {} is now {}", currentState, state);
}
if (currentState != ExecutionState.DISPOSED) {
currentState = state;
}
}
public void activate(DefaultAgenda agenda, PropagationList propagationList) {
if ( currentState.isAlive() ) {
boolean restoreFireUntilHalt = wasFiringUntilHalt;
wasFiringUntilHalt = false;
boolean restoreFiringOnSameThread = restoreFireUntilHalt && fireUntilHaltThreadId == Thread.currentThread().getId();
fireUntilHaltThreadId = -1L;
immediateHalt( propagationList );
if ( restoreFireUntilHalt ) {
// restoring a fire until halt after an incremental compilation should either happen on the same thread
// where the fireUntilHalt was running before the compilation or on a brand new thread
if (restoreFiringOnSameThread) {
agenda.fireUntilHalt();
} else {
new Thread(agenda::fireUntilHalt).start();
}
}
}
}
public void deactivate() {
synchronized (stateMachineLock) {
pauseFiringUntilHalt();
if ( currentState != ExecutionState.DEACTIVATED && currentState.isAlive() ) {
waitAndEnterExecutionState( ExecutionState.DEACTIVATED );
}
}
}
public boolean tryDeactivate() {
synchronized (stateMachineLock) {
if ( !currentState.isAlive() ) {
return true;
}
pauseFiringUntilHalt();
if ( currentState == ExecutionState.INACTIVE || currentState == ExecutionState.INACTIVE_ON_FIRING_UNTIL_HALT ) {
setCurrentState( ExecutionState.DEACTIVATED );
return true;
}
}
return false;
}
private void pauseFiringUntilHalt() {
if ( currentState == ExecutionState.FIRING_UNTIL_HALT) {
wasFiringUntilHalt = true;
setCurrentState( ExecutionState.HALTING );
waitInactive();
}
}
public void immediateHalt(PropagationList propagationList) {
synchronized (stateMachineLock) {
if (currentState != ExecutionState.INACTIVE) {
setCurrentState( ExecutionState.INACTIVE );
stateMachineLock.notifyAll();
propagationList.onEngineInactive();
if (wasFiringUntilHalt) {
// if it is halting a thread that was running a fireUntilHalt registers its id
fireUntilHaltThreadId = Thread.currentThread().getId();
}
}
}
}
public void inactiveOnFireUntilHalt() {
synchronized (stateMachineLock) {
if (currentState != ExecutionState.INACTIVE && currentState != ExecutionState.INACTIVE_ON_FIRING_UNTIL_HALT) {
setCurrentState( ExecutionState.INACTIVE_ON_FIRING_UNTIL_HALT );
stateMachineLock.notifyAll();
}
}
}
public void internalHalt() {
synchronized (stateMachineLock) {
if (isFiring()) {
setCurrentState( ExecutionState.HALTING );
}
}
}
public boolean dispose(InternalWorkingMemory workingMemory) {
synchronized (stateMachineLock) {
if (!currentState.isAlive()) {
return false;
}
if (currentState.isFiring() && currentState != ExecutionState.INACTIVE_ON_FIRING_UNTIL_HALT) {
setCurrentState( ExecutionState.DISPOSING );
workingMemory.notifyWaitOnRest();
}
waitAndEnterExecutionState( ExecutionState.DISPOSED );
stateMachineLock.notifyAll();
return true;
}
}
public boolean isAlive() {
synchronized (stateMachineLock) {
return currentState.isAlive();
}
}
public ExecutionState getCurrentState() {
return currentState;
}
public Object getStateMachineLock() {
return stateMachineLock;
}
}
@Override
public void registerExpiration(PropagationContext ectx) {
// it is safe to add into the expirationContexts list without any synchronization because
// the state machine already guarantees that only one thread at time can access it
expirationContexts.add(ectx);
}
private boolean flushExpirations() {
if (expirationContexts == null || expirationContexts.isEmpty() || propagationList.hasEntriesDeferringExpiration()) {
return false;
}
for (PropagationContext ectx : expirationContexts) {
doRetract( ectx );
}
expirationContexts.clear();
return true;
}
protected void doRetract( PropagationContext ectx ) {
InternalFactHandle factHandle = ectx.getFactHandle();
ObjectTypeNode.retractLeftTuples( factHandle, ectx, workingMemory );
ObjectTypeNode.retractRightTuples( factHandle, ectx, workingMemory );
if ( factHandle.isPendingRemoveFromStore() ) {
String epId = factHandle.getEntryPointName();
( (InternalWorkingMemoryEntryPoint) workingMemory.getEntryPoint( epId ) ).removeFromObjectStore( factHandle );
}
}
@Override
public boolean isParallelAgenda() {
return false;
}
}
| |
package org.codehaus.xfire.service.binding;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.codehaus.xfire.MessageContext;
import org.codehaus.xfire.XFireRuntimeException;
import org.codehaus.xfire.client.Client;
import org.codehaus.xfire.exchange.InMessage;
import org.codehaus.xfire.exchange.MessageSerializer;
import org.codehaus.xfire.fault.XFireFault;
import org.codehaus.xfire.service.MessageInfo;
import org.codehaus.xfire.service.MessagePartInfo;
import org.codehaus.xfire.service.OperationInfo;
import org.codehaus.xfire.soap.SoapConstants;
import org.codehaus.xfire.util.STAXUtils;
import org.codehaus.xfire.util.stax.DepthXMLStreamReader;
public abstract class AbstractBinding
implements MessageSerializer
{
private static final QName XSD_ANY = new QName(SoapConstants.XSD, "anyType", SoapConstants.XSD_PREFIX);
public void setOperation(OperationInfo operation, MessageContext context)
{
context.getExchange().setOperation(operation);
}
protected void nextEvent(XMLStreamReader dr)
{
try
{
dr.next();
}
catch (XMLStreamException e)
{
throw new XFireRuntimeException("Couldn't parse stream.", e);
}
}
protected OperationInfo findOperation(Collection operations, List parameters)
{
// first check for exact matches
for ( Iterator itr = operations.iterator(); itr.hasNext(); )
{
OperationInfo o = (OperationInfo) itr.next();
List messageParts = o.getInputMessage().getMessageParts();
if ( messageParts.size() == parameters.size() )
{
if (checkExactParameters(messageParts, parameters))
return o;
}
}
// now check for assignable matches
for ( Iterator itr = operations.iterator(); itr.hasNext(); )
{
OperationInfo o = (OperationInfo) itr.next();
List messageParts = o.getInputMessage().getMessageParts();
if ( messageParts.size() == parameters.size() )
{
if (checkParameters(messageParts, parameters))
return o;
}
}
return null;
}
/**
* Return true only if the message parts exactly match the classes of the parameters
* @param messageParts
* @param parameters
* @return
*/
private boolean checkExactParameters(List messageParts, List parameters)
{
Iterator messagePartIterator = messageParts.iterator();
for (Iterator parameterIterator = parameters.iterator(); parameterIterator.hasNext();)
{
Object param = parameterIterator.next();
MessagePartInfo mpi = (MessagePartInfo) messagePartIterator.next();
if (!mpi.getTypeClass().equals(param.getClass()))
{
return false;
}
}
return true;
}
private boolean checkParameters(List messageParts, List parameters)
{
Iterator messagePartIterator = messageParts.iterator();
for (Iterator parameterIterator = parameters.iterator(); parameterIterator.hasNext();)
{
Object param = parameterIterator.next();
MessagePartInfo mpi = (MessagePartInfo) messagePartIterator.next();
if (!mpi.getTypeClass().isAssignableFrom(param.getClass()))
{
if (!param.getClass().isPrimitive() && mpi.getTypeClass().isPrimitive())
{
return checkPrimitiveMatch(mpi.getTypeClass(), param.getClass());
}
else
{
return false;
}
}
}
return true;
}
private boolean checkPrimitiveMatch(Class clazz, Class typeClass)
{
if ((typeClass == Integer.class && clazz == int.class) ||
(typeClass == Double.class && clazz == double.class) ||
(typeClass == Long.class && clazz == long.class) ||
(typeClass == Float.class && clazz == float.class) ||
(typeClass == Short.class && clazz == short.class) ||
(typeClass == Boolean.class && clazz == boolean.class) ||
(typeClass == Byte.class && clazz == byte.class))
return true;
return false;
}
protected MessagePartInfo findMessagePart(MessageContext context,
Collection operations,
QName name,
int index)
{
// TODO: This isn't too efficient. we need to only look at non headers here
// TODO: filter out operations which aren't applicable
MessagePartInfo lastChoice = null;
for ( Iterator itr = operations.iterator(); itr.hasNext(); )
{
OperationInfo op = (OperationInfo) itr.next();
MessageInfo msgInfo = null;
if (isClientModeOn(context))
{
msgInfo = op.getOutputMessage();
}
else
{
msgInfo = op.getInputMessage();
}
Collection bodyParts = msgInfo.getMessageParts();
if (bodyParts.size() == 0 || bodyParts.size() <= index)
{
// itr.remove();
continue;
}
MessagePartInfo p = (MessagePartInfo) msgInfo.getMessageParts().get(index);
if (p.getName().equals(name)) return p;
if (p.getSchemaType().getSchemaType().equals(XSD_ANY))
lastChoice = p;
}
return lastChoice;
}
protected void read(InMessage inMessage, MessageContext context, Collection operations)
throws XFireFault
{
List parameters = new ArrayList();
OperationInfo opInfo = context.getExchange().getOperation();
DepthXMLStreamReader dr = new DepthXMLStreamReader(context.getInMessage().getXMLStreamReader());
int param = 0;
boolean clientMode = isClientModeOn(context);
while (STAXUtils.toNextElement(dr))
{
MessagePartInfo p;
if (opInfo != null && clientMode)
{
p = (MessagePartInfo) opInfo.getOutputMessage().getMessageParts().get(param);
}
else if (opInfo != null && !clientMode)
{
p = (MessagePartInfo) opInfo.getInputMessage().getMessageParts().get(param);
}
else
{
// Try to intelligently find the right part if we don't know the operation yet.
p = findMessagePart(context, operations, dr.getName(), param);
}
if (p == null)
{
throw new XFireFault("Parameter " + dr.getName() + " does not exist!",
XFireFault.SENDER);
}
param++;
parameters.add( context.getService().getBindingProvider().readParameter(p, dr, context) );
if (dr.getEventType() == XMLStreamReader.END_ELEMENT) nextEvent(dr);
}
if (opInfo == null && !clientMode)
{
opInfo = findOperation(operations, parameters);
if (opInfo == null)
{
StringBuffer sb = new StringBuffer("Could not find appropriate operation for request ");
//we know we have at least one operation, right?
sb.append(((OperationInfo)operations.iterator().next()).getName());
sb.append('(');
for(Iterator iterator = parameters.iterator(); iterator.hasNext();)
{
sb.append(iterator.next().getClass().getName());
if(iterator.hasNext())
{
sb.append(", ");
}
}
sb.append(") in service '");
sb.append(context.getService().getSimpleName());
sb.append('\'');
throw new XFireFault(sb.toString(), XFireFault.SENDER);
}
setOperation(opInfo, context);
}
context.getInMessage().setBody(parameters);
}
public static void writeParameter(XMLStreamWriter writer,
MessageContext context,
Object value,
MessagePartInfo p,
String ns)
throws XFireFault, XMLStreamException
{
// write the parameter's start element
if (p.getSchemaType().isWriteOuter())
{
if (ns.length() > 0)
{
String prefix = writer.getPrefix(ns);
boolean declare = false;
if (prefix == null || "".equals(prefix) )
{
prefix = "";
declare = true;
writer.setDefaultNamespace(ns);
}
writer.writeStartElement(prefix, p.getName().getLocalPart(), ns);
if (declare) writer.writeDefaultNamespace(ns);
}
else
{
writer.writeStartElement(p.getName().getLocalPart());
writer.writeDefaultNamespace("");
}
}
context.getService().getBindingProvider().writeParameter(p, writer, context, value);
// write the parameter's end element
if (p.getSchemaType().isWriteOuter())
{
writer.writeEndElement();
}
}
protected Object getParam(Object[] values, MessagePartInfo outParam, MessageContext context)
{
int index = outParam.getIndex();
if (index == -1) return values[0];
Object[] inParams = (Object[]) context.getInMessage().getBody();
return inParams[index];
}
protected Object getClientParam(Object[] values, MessagePartInfo outParam, MessageContext context)
throws XFireFault
{
if (outParam.getIndex() >= values.length)
{
throw new XFireFault("Not enough input parameters were supplied!", XFireFault.SENDER);
}
return values[outParam.getIndex()];
}
/**
* Get the namespace for a particular part. This will change depending on if
* we're doc/lit or rpc/lit or if the MessagePartInfo is a concrete type.
*
* @param context
* @param p
* @return
*/
protected String getBoundNamespace(MessageContext context, MessagePartInfo p)
{
if (p.isSchemaElement())
return p.getName().getNamespaceURI();
else
return context.getService().getTargetNamespace();
}
public static boolean isClientModeOn(MessageContext context)
{
Boolean on = (Boolean) context.getProperty(Client.CLIENT_MODE);
return (on != null && on.booleanValue());
}
public static MessageInfo getIncomingMessageInfo(MessageContext context)
{
MessageInfo msgInfo;
if (isClientModeOn(context))
{
msgInfo = context.getExchange().getOperation().getOutputMessage();
}
else
{
msgInfo = context.getExchange().getOperation().getInputMessage();
}
return msgInfo;
}
public static MessageInfo getOutgoingMessageInfo(MessageContext context)
{
MessageInfo msgInfo;
if (isClientModeOn(context))
{
msgInfo = context.getExchange().getOperation().getInputMessage();
}
else
{
msgInfo = context.getExchange().getOperation().getOutputMessage();
}
return msgInfo;
}
}
| |
package org.imsglobal.pox;
import java.io.ByteArrayInputStream;
import java.io.Reader;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthMessage;
import net.oauth.OAuthValidator;
import net.oauth.SimpleOAuthValidator;
import net.oauth.server.OAuthServlet;
import net.oauth.signature.OAuthSignatureMethod;
import org.apache.commons.lang.StringEscapeUtils;
import org.imsglobal.basiclti.Base64;
import org.imsglobal.basiclti.XMLMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class IMSPOXRequest {
private final static Logger Log = Logger.getLogger(IMSPOXRequest.class .getName());
public final static String MAJOR_SUCCESS = "success";
public final static String MAJOR_FAILURE = "failure";
public final static String MAJOR_UNSUPPORTED = "unsupported";
public final static String MAJOR_PROCESSING = "processing";
public final static String [] validMajor = {
MAJOR_SUCCESS, MAJOR_FAILURE, MAJOR_UNSUPPORTED, MAJOR_PROCESSING };
public final static String SEVERITY_ERROR = "error";
public final static String SEVERITY_WARNING = "warning";
public final static String SEVERITY_STATUS = "status";
public final static String [] validSeverity = {
SEVERITY_ERROR, SEVERITY_WARNING, SEVERITY_STATUS };
public final static String MINOR_FULLSUCCESS ="fullsuccess";
public final static String MINOR_NOSOURCEDIDS = "nosourcedids";
public final static String MINOR_IDALLOC = "idalloc";
public final static String MINOR_OVERFLOWFAIL = "overflowfail";
public final static String MINOR_IDALLOCINUSEFAIL = "idallocinusefail";
public final static String MINOR_INVALIDDATAFAIL = "invaliddata";
public final static String MINOR_INCOMPLETEDATA = "incompletedata";
public final static String MINOR_PARTIALSTORAGE = "partialdatastorage";
public final static String MINOR_UNKNOWNOBJECT = "unknownobject";
public final static String MINOR_DELETEFAILURE = "deletefailure";
public final static String MINOR_TARGETREADFAILURE = "targetreadfailure";
public final static String MINOR_SAVEPOINTERROR = "savepointerror";
public final static String MINOR_SAVEPOINTSYNCERROR = "savepointsyncerror";
public final static String MINOR_UNKNOWNQUERY = "unknownquery";
public final static String MINOR_UNKNOWNVOCAB = "unknownvocab";
public final static String MINOR_TARGETISBUSY = "targetisbusy";
public final static String MINOR_UNKNOWNEXTENSION = "unknownextension";
public final static String MINOR_UNAUTHORIZEDREQUEST = "unauthorizedrequest";
public final static String MINOR_LINKFAILURE = "linkfailure";
public final static String MINOR_UNSUPPORTED = "unsupported";
public final static String [] validMinor = {
MINOR_FULLSUCCESS, MINOR_NOSOURCEDIDS, MINOR_IDALLOC, MINOR_OVERFLOWFAIL,
MINOR_IDALLOCINUSEFAIL, MINOR_INVALIDDATAFAIL, MINOR_INCOMPLETEDATA,
MINOR_PARTIALSTORAGE, MINOR_UNKNOWNOBJECT, MINOR_DELETEFAILURE,
MINOR_TARGETREADFAILURE, MINOR_SAVEPOINTERROR, MINOR_SAVEPOINTSYNCERROR,
MINOR_UNKNOWNQUERY, MINOR_UNKNOWNVOCAB, MINOR_TARGETISBUSY,
MINOR_UNKNOWNEXTENSION, MINOR_UNAUTHORIZEDREQUEST, MINOR_LINKFAILURE,
MINOR_UNSUPPORTED
} ;
public Document postDom = null;
public Element bodyElement = null;
public Element headerElement = null;
public String postBody = null;
private String header = null;
private String oauth_body_hash = null;
private String oauth_consumer_key = null;
public boolean valid = false;
private String operation = null;
public String errorMessage = null;
public String base_string = null;
private Map<String,String> bodyMap = null;
private Map<String,String> headerMap = null;
public String getOperation()
{
return operation;
}
public String getOAuthConsumerKey()
{
return oauth_consumer_key;
}
public String getHeaderVersion()
{
return getHeaderItem("/imsx_version");
}
public String getHeaderMessageIdentifier()
{
return getHeaderItem("/imsx_messageIdentifier");
}
public String getHeaderItem(String path)
{
if ( getHeaderMap() == null ) return null;
return headerMap.get(path);
}
public Map<String,String> getHeaderMap()
{
if ( headerMap != null ) return headerMap;
if ( headerElement == null ) return null;
headerMap = XMLMap.getMap(headerElement);
return headerMap;
}
public Map<String,String> getBodyMap()
{
if ( bodyMap != null ) return bodyMap;
if ( bodyElement == null ) return null;
bodyMap = XMLMap.getMap(bodyElement);
return bodyMap;
}
public String getPostBody()
{
return postBody;
}
// Normal Constructor
public IMSPOXRequest(String oauth_consumer_key, String oauth_secret, HttpServletRequest request)
{
loadFromRequest(request);
if ( ! valid ) return;
validateRequest(oauth_consumer_key, oauth_secret, request);
}
// Constructor for delayed validation
public IMSPOXRequest(HttpServletRequest request)
{
loadFromRequest(request);
}
// Constructor for testing...
public IMSPOXRequest(String bodyString)
{
postBody = bodyString;
parsePostBody();
}
// Load but do not check the authentication
@SuppressWarnings("deprecation")
public void loadFromRequest(HttpServletRequest request)
{
String contentType = request.getContentType();
if ( ! "application/xml".equals(contentType) ) {
errorMessage = "Content Type must be application/xml";
Log.info(errorMessage+"\n"+contentType);
return;
}
header = request.getHeader("Authorization");
oauth_body_hash = null;
if ( header != null ) {
if (header.startsWith("OAuth ")) header = header.substring(5);
String [] parms = header.split(",");
for ( String parm : parms ) {
parm = parm.trim();
if ( parm.startsWith("oauth_body_hash=") ) {
String [] pieces = parm.split("\"");
oauth_body_hash = URLDecoder.decode(pieces[1]);
}
if ( parm.startsWith("oauth_consumer_key=") ) {
String [] pieces = parm.split("\"");
oauth_consumer_key = URLDecoder.decode(pieces[1]);
}
}
}
if ( oauth_body_hash == null ) {
errorMessage = "Did not find oauth_body_hash";
Log.info(errorMessage+"\n"+header);
return;
}
// System.out.println("OBH="+oauth_body_hash);
final char[] buffer = new char[0x10000];
try {
StringBuilder out = new StringBuilder();
Reader in = request.getReader();
int read;
do {
read = in.read(buffer, 0, buffer.length);
if (read>0) {
out.append(buffer, 0, read);
}
} while (read>=0);
postBody = out.toString();
} catch(Exception e) {
errorMessage = "Could not read message body:"+e.getMessage();
return;
}
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.update(postBody.getBytes());
byte[] output = Base64.encode(md.digest());
String hash = new String(output);
// System.out.println("HASH="+hash);
if ( ! hash.equals(oauth_body_hash) ) {
errorMessage = "Body hash does not match header";
return;
}
} catch (Exception e) {
errorMessage = "Could not compute body hash";
return;
}
parsePostBody();
}
public void parsePostBody()
{
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
DocumentBuilder db = dbf.newDocumentBuilder();
postDom = db.parse(new ByteArrayInputStream(postBody.getBytes()));
}catch(Exception e) {
errorMessage = "Could not parse XML: "+e.getMessage();
return;
}
try {
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/imsx_POXEnvelopeRequest/imsx_POXBody/*");
Object result = expr.evaluate(postDom, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
bodyElement = (Element) nodes.item(0);
operation = bodyElement.getNodeName();
expr = xpath.compile("/imsx_POXEnvelopeRequest/imsx_POXHeader/*");
result = expr.evaluate(postDom, XPathConstants.NODESET);
nodes = (NodeList) result;
headerElement = (Element) nodes.item(0);
}catch(javax.xml.xpath.XPathExpressionException e) {
errorMessage = "Could not parse XPATH: "+e.getMessage();
return;
}catch(Exception e) {
errorMessage = "Could not parse input XML: "+e.getMessage();
return;
}
if ( operation == null || bodyElement == null ) {
errorMessage = "Could not find operation";
return;
}
valid = true;
}
// Assumes data is all loaded
public void validateRequest(String oauth_consumer_key, String oauth_secret, HttpServletRequest request)
{
validateRequest(oauth_consumer_key, oauth_secret, request, null) ;
}
public void validateRequest(String oauth_consumer_key, String oauth_secret, HttpServletRequest request, String URL)
{
valid = false;
OAuthMessage oam = OAuthServlet.getMessage(request, URL);
OAuthValidator oav = new SimpleOAuthValidator();
OAuthConsumer cons = new OAuthConsumer("about:blank#OAuth+CallBack+NotUsed",
oauth_consumer_key, oauth_secret, null);
OAuthAccessor acc = new OAuthAccessor(cons);
try {
base_string = OAuthSignatureMethod.getBaseString(oam);
} catch (Exception e) {
base_string = null;
}
try {
oav.validateMessage(oam,acc);
} catch(Exception e) {
errorMessage = "Launch fails OAuth validation: "+e.getMessage();
return;
}
valid = true;
}
public static String fetchTag(org.w3c.dom.Element element, String tag)
{
try {
org.w3c.dom.NodeList elements = element.getElementsByTagName(tag);
int numElements = elements.getLength();
if (numElements > 0) {
org.w3c.dom.Element e = (org.w3c.dom.Element)elements.item(0);
if (e.hasChildNodes()) {
return e.getFirstChild().getNodeValue();
}
}
} catch (Throwable t) {
Log.warning(t.getMessage());
// t.printStackTrace();
}
return null;
}
public boolean inArray(final String [] theArray, final String theString)
{
if ( theString == null ) return false;
for ( String str : theArray ) {
if ( theString.equals(str) ) return true;
}
return false;
}
static final String fatalMessage =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<imsx_POXEnvelopeResponse xmlns = \"http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0\">\n" +
" <imsx_POXHeader>\n" +
" <imsx_POXResponseHeaderInfo>\n" +
" <imsx_version>V1.0</imsx_version>\n" +
" <imsx_messageIdentifier>%s</imsx_messageIdentifier>\n" +
" <imsx_statusInfo>\n" +
" <imsx_codeMajor>failure</imsx_codeMajor>\n" +
" <imsx_severity>error</imsx_severity>\n" +
" <imsx_description>%s</imsx_description>\n" +
" <imsx_operationRefIdentifier>%s</imsx_operationRefIdentifier>" +
" </imsx_statusInfo>\n" +
" </imsx_POXResponseHeaderInfo>\n" +
" </imsx_POXHeader>\n" +
" <imsx_POXBody/>\n" +
"</imsx_POXEnvelopeResponse>";
public static String getFatalResponse(String description)
{
return getFatalResponse(description, "unknown");
}
public static String getFatalResponse(String description, String message_id)
{
Date dt = new Date();
String messageId = ""+dt.getTime();
return String.format(fatalMessage,
StringEscapeUtils.escapeXml(messageId),
StringEscapeUtils.escapeXml(description),
StringEscapeUtils.escapeXml(message_id));
}
static final String responseMessage =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<imsx_POXEnvelopeResponse xmlns = \"http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0\">\n" +
" <imsx_POXHeader>\n" +
" <imsx_POXResponseHeaderInfo>\n" +
" <imsx_version>V1.0</imsx_version>\n" +
" <imsx_messageIdentifier>%s</imsx_messageIdentifier>\n" +
" <imsx_statusInfo>\n" +
" <imsx_codeMajor>%s</imsx_codeMajor>\n" +
" <imsx_severity>%s</imsx_severity>\n" +
" <imsx_description>%s</imsx_description>\n" +
" <imsx_messageRefIdentifier>%s</imsx_messageRefIdentifier>\n" +
" <imsx_operationRefIdentifier>%s</imsx_operationRefIdentifier>" +
"%s\n"+
" </imsx_statusInfo>\n" +
" </imsx_POXResponseHeaderInfo>\n" +
" </imsx_POXHeader>\n" +
" <imsx_POXBody>\n" +
"%s%s"+
" </imsx_POXBody>\n" +
"</imsx_POXEnvelopeResponse>";
public String getResponseUnsupported(String desc)
{
return getResponse(desc, MAJOR_UNSUPPORTED, null, null, null, null);
}
public String getResponseFailure(String desc, Properties minor)
{
return getResponse(desc, null, null, null, minor, null);
}
public String getResponseFailure(String desc, Properties minor, String bodyString)
{
return getResponse(desc, null, null, null, minor, bodyString);
}
public String getResponseSuccess(String desc, String bodyString)
{
return getResponse(desc, MAJOR_SUCCESS, null, null, null, bodyString);
}
public String getResponse(String description, String major, String severity,
String messageId, Properties minor, String bodyString)
{
StringBuffer internalError = new StringBuffer();
if ( major == null ) major = MAJOR_FAILURE;
if ( severity == null && MAJOR_PROCESSING.equals(major) ) severity = SEVERITY_STATUS;
if ( severity == null && MAJOR_SUCCESS.equals(major) ) severity = SEVERITY_STATUS;
if ( severity == null ) severity = SEVERITY_ERROR;
if ( messageId == null ) {
Date dt = new Date();
messageId = ""+dt.getTime();
}
StringBuffer sb = new StringBuffer();
if ( minor != null && minor.size() > 0 ) {
for(Object okey : minor.keySet() ) {
String key = (String) okey;
String value = minor.getProperty(key);
if ( key == null || value == null ) continue;
if ( !inArray(validMinor, value) ) {
if ( internalError.length() > 0 ) sb.append(", ");
internalError.append("Invalid imsx_codeMinorFieldValue="+major);
continue;
}
if ( sb.length() == 0 ) sb.append("\n <imsx_codeMinor>\n");
sb.append(" <imsx_codeMinorField>\n <imsx_codeMinorFieldName>");
sb.append(key);
sb.append("</imsx_codeMinorFieldName>\n <imsx_codeMinorFieldValue>");
sb.append(StringEscapeUtils.escapeXml(value));
sb.append("</imsx_codeMinorFieldValue>\n </imsx_codeMinorField>\n");
}
if ( sb.length() > 0 ) sb.append(" </imsx_codeMinor>");
}
String minorString = sb.toString();
if ( ! inArray(validMajor, major) ) {
if ( internalError.length() > 0 ) sb.append(", ");
internalError.append("Invalid imsx_codeMajor="+major);
}
if ( ! inArray(validSeverity, severity) ) {
if ( internalError.length() > 0 ) sb.append(", ");
internalError.append("Invalid imsx_severity="+major);
}
if ( internalError.length() > 0 ) {
description = description + " (Internal error: " + internalError.toString() + ")";
Log.warning(internalError.toString());
}
if ( bodyString == null ) bodyString = "";
// Trim off XML header
if ( bodyString.startsWith("<?xml") ) {
int pos = bodyString.indexOf("<",1);
if ( pos > 0 ) bodyString = bodyString.substring(pos);
}
bodyString = bodyString.trim();
String newLine = "";
if ( bodyString.length() > 0 ) newLine = "\n";
return String.format(responseMessage,
StringEscapeUtils.escapeXml(messageId),
StringEscapeUtils.escapeXml(major),
StringEscapeUtils.escapeXml(severity),
StringEscapeUtils.escapeXml(description),
StringEscapeUtils.escapeXml(getHeaderMessageIdentifier()),
StringEscapeUtils.escapeXml(operation),
StringEscapeUtils.escapeXml(minorString),
bodyString, newLine);
}
/** Unit Tests */
static final String inputTestData = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n" +
"<imsx_POXEnvelopeRequest xmlns = \"http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0\">\n" +
"<imsx_POXHeader>\n" +
"<imsx_POXRequestHeaderInfo>\n" +
"<imsx_version>V1.0</imsx_version>\n" +
"<imsx_messageIdentifier>999999123</imsx_messageIdentifier>\n" +
"</imsx_POXRequestHeaderInfo>\n" +
"</imsx_POXHeader>\n" +
"<imsx_POXBody>\n" +
"<replaceResultRequest>\n" +
"<resultRecord>\n" +
"<sourcedGUID>\n" +
"<sourcedId>3124567</sourcedId>\n" +
"</sourcedGUID>\n" +
"<result>\n" +
"<resultScore>\n" +
"<language>en-us</language>\n" +
"<textString>A</textString>\n" +
"</resultScore>\n" +
"</result>\n" +
"</resultRecord>\n" +
"</replaceResultRequest>\n" +
"</imsx_POXBody>\n" +
"</imsx_POXEnvelopeRequest>";
public static void runTest() {
System.out.println("Runnig test.");
IMSPOXRequest pox = new IMSPOXRequest(inputTestData);
System.out.println("Version = "+pox.getHeaderVersion());
System.out.println("Operation = "+pox.getOperation());
Map<String,String> bodyMap = pox.getBodyMap();
String guid = bodyMap.get("/resultRecord/sourcedGUID/sourcedId");
System.out.println("guid="+guid);
String grade = bodyMap.get("/resultRecord/result/resultScore/textString");
System.out.println("grade="+grade);
String desc = "Message received and validated operation="+pox.getOperation()+
" guid="+guid+" grade="+grade;
String output = pox.getResponseUnsupported(desc);
System.out.println("---- Unsupported ----");
System.out.println(output);
Properties props = new Properties();
props.setProperty("fred","zap");
props.setProperty("sam",IMSPOXRequest.MINOR_IDALLOC);
System.out.println("---- Generate Log Error ----");
output = pox.getResponseFailure(desc,props);
System.out.println("---- Failure ----");
System.out.println(output);
Map<String, Object> theMap = new TreeMap<String, Object> ();
theMap.put("/readMembershipResponse/membershipRecord/sourcedId", "123course456");
List<Map<String,String>> lm = new ArrayList<Map<String,String>>();
Map<String,String> mm = new TreeMap<String,String>();
mm.put("/personSourcedId","123user456");
mm.put("/role/roleType","Learner");
lm.add(mm);
mm = new TreeMap<String,String>();
mm.put("/personSourcedId","789user123");
mm.put("/role/roleType","Instructor");
lm.add(mm);
theMap.put("/readMembershipResponse/membershipRecord/membership/member", lm);
String theXml = XMLMap.getXMLFragment(theMap, true);
// System.out.println("th="+theXml);
output = pox.getResponseSuccess(desc,theXml);
System.out.println("---- Success String ----");
System.out.println(output);
}
/*
roleType:
Learner
Instructor
ContentDeveloper
Member
Manager
Mentor
Administrator
TeachingAssistant
fieldType:
Boolean
Integer
Real
String
<readMembershipResponse
xmlns="http://www.imsglobal.org/services/lis/mms2p0/wsdl11/sync/imsmms_v2p0">
<membershipRecord>
<sourcedId>GUID.TYPE</sourcedId>
<membership>
<collectionSourcedId>GUID.TYPE</collectionSourcedId>
<membershipIdType>MEMBERSHIPIDTYPE.TYPE</membershipIdType>
<member>
<personSourcedId>GUID.TYPE</personSourcedId>
<role>
<roleType>STRING</roleType>
<subRole>STRING</subRole>
<timeFrame>
<begin>DATETIME</begin>
<end>DATETIME</end>
<restrict>BOOLEAN</restrict>
<adminPeriod>
<language>LANGUAGESET.TYPE</language>
<textString>STRING</textString>
</adminPeriod>
</timeFrame>
<status>STATUS.TYPE</status>
<dateTime>DATETIME</dateTime>
<dataSource>GUID.TYPE</dataSource>
<recordInfo>
<extensionField>
<fieldName>STRING</fieldName>
<fieldType>FIELDTYPE.TYPE</fieldType>
<fieldValue>STRING</fieldValue>
</extensionField>
</recordInfo>
<extension>
<extensionField>
<fieldName>STRING</fieldName>
<fieldType>FIELDTYPE.TYPE</fieldType>
<fieldValue>STRING</fieldValue>
</extensionField>
</extension>
</role>
</member>
<creditHours>INTEGER</creditHours>
<dataSource>GUID.TYPE</dataSource>
</membership>
</membershipRecord>
</readMembershipResponse>
*/
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ambari.server.controller.internal;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.ambari.annotations.Experimental;
import org.apache.ambari.annotations.ExperimentalFeature;
import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.api.resources.RepositoryResourceDefinition;
import org.apache.ambari.server.controller.AmbariManagementController;
import org.apache.ambari.server.controller.RepositoryRequest;
import org.apache.ambari.server.controller.RepositoryResponse;
import org.apache.ambari.server.controller.spi.NoSuchParentResourceException;
import org.apache.ambari.server.controller.spi.NoSuchResourceException;
import org.apache.ambari.server.controller.spi.Predicate;
import org.apache.ambari.server.controller.spi.Request;
import org.apache.ambari.server.controller.spi.RequestStatus;
import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.controller.spi.Resource.Type;
import org.apache.ambari.server.controller.spi.ResourceAlreadyExistsException;
import org.apache.ambari.server.controller.spi.SystemException;
import org.apache.ambari.server.controller.spi.UnsupportedPropertyException;
import org.apache.ambari.server.controller.utilities.PropertyHelper;
import org.apache.commons.lang.BooleanUtils;
public class RepositoryResourceProvider extends AbstractControllerResourceProvider {
public static final String REPOSITORY_REPO_NAME_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "repo_name");
public static final String REPOSITORY_STACK_NAME_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "stack_name");
public static final String REPOSITORY_STACK_VERSION_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "stack_version");
public static final String REPOSITORY_CLUSTER_STACK_VERSION_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "cluster_version_id");
public static final String REPOSITORY_OS_TYPE_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "os_type");
public static final String REPOSITORY_BASE_URL_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "base_url");
public static final String REPOSITORY_DISTRIBUTION_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "distribution");
public static final String REPOSITORY_COMPONENTS_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "components");
public static final String REPOSITORY_REPO_ID_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "repo_id");
public static final String REPOSITORY_MIRRORS_LIST_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "mirrors_list");
public static final String REPOSITORY_DEFAULT_BASE_URL_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "default_base_url");
public static final String REPOSITORY_VERIFY_BASE_URL_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "verify_base_url");
public static final String REPOSITORY_LATEST_BASE_URL_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "latest_base_url");
public static final String REPOSITORY_REPOSITORY_VERSION_ID_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "repository_version_id");
public static final String REPOSITORY_VERSION_DEFINITION_ID_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "version_definition_id");
public static final String REPOSITORY_UNIQUE_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "unique");
public static final String REPOSITORY_TAGS_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "tags");
@Experimental(feature = ExperimentalFeature.CUSTOM_SERVICE_REPOS,
comment = "Remove logic for handling custom service repos after enabling multi-mpack cluster deployment")
public static final String REPOSITORY_APPLICABLE_SERVICES_PROPERTY_ID = PropertyHelper.getPropertyId("Repositories", "applicable_services");
@SuppressWarnings("serial")
private static Set<String> pkPropertyIds = new HashSet<String>() {
{
add(REPOSITORY_STACK_NAME_PROPERTY_ID);
add(REPOSITORY_STACK_VERSION_PROPERTY_ID);
add(REPOSITORY_OS_TYPE_PROPERTY_ID);
add(REPOSITORY_REPO_ID_PROPERTY_ID);
}
};
@SuppressWarnings("serial")
public static Set<String> propertyIds = new HashSet<String>() {
{
add(REPOSITORY_REPO_NAME_PROPERTY_ID);
add(REPOSITORY_DISTRIBUTION_PROPERTY_ID);
add(REPOSITORY_COMPONENTS_PROPERTY_ID);
add(REPOSITORY_STACK_NAME_PROPERTY_ID);
add(REPOSITORY_STACK_VERSION_PROPERTY_ID);
add(REPOSITORY_OS_TYPE_PROPERTY_ID);
add(REPOSITORY_BASE_URL_PROPERTY_ID);
add(REPOSITORY_REPO_ID_PROPERTY_ID);
add(REPOSITORY_MIRRORS_LIST_PROPERTY_ID);
add(REPOSITORY_DEFAULT_BASE_URL_PROPERTY_ID);
add(REPOSITORY_VERIFY_BASE_URL_PROPERTY_ID);
add(REPOSITORY_LATEST_BASE_URL_PROPERTY_ID);
add(REPOSITORY_REPOSITORY_VERSION_ID_PROPERTY_ID);
add(REPOSITORY_VERSION_DEFINITION_ID_PROPERTY_ID);
add(REPOSITORY_CLUSTER_STACK_VERSION_PROPERTY_ID);
add(REPOSITORY_UNIQUE_PROPERTY_ID);
add(REPOSITORY_APPLICABLE_SERVICES_PROPERTY_ID);
add(REPOSITORY_TAGS_PROPERTY_ID);
}
};
@SuppressWarnings("serial")
public static Map<Type, String> keyPropertyIds = new HashMap<Type, String>() {
{
put(Resource.Type.Stack, REPOSITORY_STACK_NAME_PROPERTY_ID);
put(Resource.Type.StackVersion, REPOSITORY_STACK_VERSION_PROPERTY_ID);
put(Resource.Type.ClusterStackVersion, REPOSITORY_CLUSTER_STACK_VERSION_PROPERTY_ID);
put(Resource.Type.OperatingSystem, REPOSITORY_OS_TYPE_PROPERTY_ID);
put(Resource.Type.Repository, REPOSITORY_REPO_ID_PROPERTY_ID);
put(Resource.Type.RepositoryVersion, REPOSITORY_REPOSITORY_VERSION_ID_PROPERTY_ID);
put(Resource.Type.VersionDefinition, REPOSITORY_VERSION_DEFINITION_ID_PROPERTY_ID);
}
};
public RepositoryResourceProvider(AmbariManagementController managementController) {
super(propertyIds, keyPropertyIds, managementController);
}
@Override
public RequestStatus updateResources(Request request, Predicate predicate)
throws SystemException, UnsupportedPropertyException,
NoSuchResourceException, NoSuchParentResourceException {
final Set<RepositoryRequest> requests = new HashSet<>();
Iterator<Map<String,Object>> iterator = request.getProperties().iterator();
if (iterator.hasNext()) {
for (Map<String, Object> propertyMap : getPropertyMaps(iterator.next(), predicate)) {
requests.add(getRequest(propertyMap));
}
}
modifyResources(new Command<Void>() {
@Override
public Void invoke() throws AmbariException {
getManagementController().updateRepositories(requests);
return null;
}
});
return getRequestStatus(null);
}
@Override
public Set<Resource> getResources(Request request, Predicate predicate)
throws SystemException, UnsupportedPropertyException,
NoSuchResourceException, NoSuchParentResourceException {
final Set<RepositoryRequest> requests = new HashSet<>();
if (predicate == null) {
requests.add(getRequest(Collections.<String, Object>emptyMap()));
} else {
for (Map<String, Object> propertyMap : getPropertyMaps(predicate)) {
requests.add(getRequest(propertyMap));
}
}
Set<String> requestedIds = getRequestPropertyIds(request, predicate);
Set<RepositoryResponse> responses = getResources(new Command<Set<RepositoryResponse>>() {
@Override
public Set<RepositoryResponse> invoke() throws AmbariException {
return getManagementController().getRepositories(requests);
}
});
Set<Resource> resources = new HashSet<>();
for (RepositoryResponse response : responses) {
Resource resource = new ResourceImpl(Resource.Type.Repository);
setResourceProperty(resource, REPOSITORY_STACK_NAME_PROPERTY_ID, response.getStackName(), requestedIds);
setResourceProperty(resource, REPOSITORY_STACK_VERSION_PROPERTY_ID, response.getStackVersion(), requestedIds);
setResourceProperty(resource, REPOSITORY_REPO_NAME_PROPERTY_ID, response.getRepoName(), requestedIds);
setResourceProperty(resource, REPOSITORY_DISTRIBUTION_PROPERTY_ID, response.getDistribution(), requestedIds);
setResourceProperty(resource, REPOSITORY_COMPONENTS_PROPERTY_ID, response.getComponents(), requestedIds);
setResourceProperty(resource, REPOSITORY_BASE_URL_PROPERTY_ID, response.getBaseUrl(), requestedIds);
setResourceProperty(resource, REPOSITORY_OS_TYPE_PROPERTY_ID, response.getOsType(), requestedIds);
setResourceProperty(resource, REPOSITORY_REPO_ID_PROPERTY_ID, response.getRepoId(), requestedIds);
setResourceProperty(resource, REPOSITORY_MIRRORS_LIST_PROPERTY_ID, response.getMirrorsList(), requestedIds);
setResourceProperty(resource, REPOSITORY_DEFAULT_BASE_URL_PROPERTY_ID, response.getDefaultBaseUrl(), requestedIds);
setResourceProperty(resource, REPOSITORY_LATEST_BASE_URL_PROPERTY_ID, response.getLatestBaseUrl(), requestedIds);
setResourceProperty(resource, REPOSITORY_UNIQUE_PROPERTY_ID, response.isUnique(), requestedIds);
setResourceProperty(resource, REPOSITORY_APPLICABLE_SERVICES_PROPERTY_ID, response.getApplicableServices(), requestedIds);
setResourceProperty(resource, REPOSITORY_TAGS_PROPERTY_ID, response.getTags(), requestedIds);
if (null != response.getClusterVersionId()) {
setResourceProperty(resource, REPOSITORY_CLUSTER_STACK_VERSION_PROPERTY_ID, response.getClusterVersionId(), requestedIds);
}
if (null != response.getRepositoryVersionId()) {
setResourceProperty(resource, REPOSITORY_REPOSITORY_VERSION_ID_PROPERTY_ID, response.getRepositoryVersionId(), requestedIds);
}
if (null != response.getVersionDefinitionId()) {
setResourceProperty(resource, REPOSITORY_VERSION_DEFINITION_ID_PROPERTY_ID,
response.getVersionDefinitionId(), requestedIds);
}
resources.add(resource);
}
return resources;
}
@Override
public RequestStatus createResources(Request request) throws SystemException, UnsupportedPropertyException, ResourceAlreadyExistsException, NoSuchParentResourceException {
final String validateOnlyProperty = request.getRequestInfoProperties().get(RepositoryResourceDefinition.VALIDATE_ONLY_DIRECTIVE);
if (BooleanUtils.toBoolean(validateOnlyProperty)) {
final Set<RepositoryRequest> requests = new HashSet<>();
final Iterator<Map<String,Object>> iterator = request.getProperties().iterator();
if (iterator.hasNext()) {
for (Map<String, Object> propertyMap : request.getProperties()) {
requests.add(getRequest(propertyMap));
}
}
createResources(new Command<Void>() {
@Override
public Void invoke() throws AmbariException {
getManagementController().verifyRepositories(requests);
return null;
}
});
return getRequestStatus(null);
} else {
throw new SystemException("Cannot create repositories.", null);
}
}
@Override
public RequestStatus deleteResources(Request request, Predicate predicate)
throws SystemException, UnsupportedPropertyException,
NoSuchResourceException, NoSuchParentResourceException {
throw new SystemException("Cannot delete repositories.", null);
}
private RepositoryRequest getRequest(Map<String, Object> properties) {
RepositoryRequest request = new RepositoryRequest(
(String) properties.get(REPOSITORY_STACK_NAME_PROPERTY_ID),
(String) properties.get(REPOSITORY_STACK_VERSION_PROPERTY_ID),
(String) properties.get(REPOSITORY_OS_TYPE_PROPERTY_ID),
(String) properties.get(REPOSITORY_REPO_ID_PROPERTY_ID),
(String) properties.get(REPOSITORY_REPO_NAME_PROPERTY_ID));
if (properties.containsKey(REPOSITORY_REPOSITORY_VERSION_ID_PROPERTY_ID)) {
request.setRepositoryVersionId(Long.parseLong(properties.get(REPOSITORY_REPOSITORY_VERSION_ID_PROPERTY_ID).toString()));
}
if (properties.containsKey(REPOSITORY_VERSION_DEFINITION_ID_PROPERTY_ID)) {
request.setVersionDefinitionId(properties.get(REPOSITORY_VERSION_DEFINITION_ID_PROPERTY_ID).toString());
}
if (properties.containsKey(REPOSITORY_CLUSTER_STACK_VERSION_PROPERTY_ID)) {
request.setClusterVersionId(Long.parseLong(properties.get(REPOSITORY_CLUSTER_STACK_VERSION_PROPERTY_ID).toString()));
}
if (properties.containsKey(REPOSITORY_BASE_URL_PROPERTY_ID)) {
request.setBaseUrl((String) properties.get(REPOSITORY_BASE_URL_PROPERTY_ID));
if (properties.containsKey(REPOSITORY_VERIFY_BASE_URL_PROPERTY_ID)) {
request.setVerifyBaseUrl("true".equalsIgnoreCase(properties.get(REPOSITORY_VERIFY_BASE_URL_PROPERTY_ID).toString()));
}
}
return request;
}
@Override
public Set<String> getPKPropertyIds() {
return pkPropertyIds;
}
}
| |
/**
* MIT License
*
* Copyright (c) 2017 Thomas Cashman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.mini2Dx.yarn.parser;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BufferedTokenStream;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.mini2Dx.yarn.YarnNode;
import org.mini2Dx.yarn.operation.YarnAssign;
import org.mini2Dx.yarn.operation.YarnCommand;
import org.mini2Dx.yarn.operation.YarnCondition;
import org.mini2Dx.yarn.operation.YarnEndIfBlock;
import org.mini2Dx.yarn.operation.YarnIfStatement;
import org.mini2Dx.yarn.operation.YarnIfStatement.IfStatementType;
import org.mini2Dx.yarn.operation.YarnLine;
import org.mini2Dx.yarn.operation.YarnOption;
import org.mini2Dx.yarn.operation.YarnOptionGroup;
import org.mini2Dx.yarn.parser.YarnParser.CommandStatementContext;
import org.mini2Dx.yarn.parser.YarnParser.ElseStatementContext;
import org.mini2Dx.yarn.parser.YarnParser.ElseifExpressionContext;
import org.mini2Dx.yarn.parser.YarnParser.EndifStatementContext;
import org.mini2Dx.yarn.parser.YarnParser.IfExpressionContext;
import org.mini2Dx.yarn.parser.YarnParser.LineStatementContext;
import org.mini2Dx.yarn.parser.YarnParser.NodeContext;
import org.mini2Dx.yarn.parser.YarnParser.OptionGroupContext;
import org.mini2Dx.yarn.parser.YarnParser.OptionStatementContext;
/**
* A parser for an entire Yarn tree
*/
public class YarnTreeParser extends YarnBaseListener {
private final Stack<YarnIfStatement> ifStack = new Stack<YarnIfStatement>();
private YarnNode currentNode;
/**
* Reads .yarn.txt content, parses and returns the resulting list of {@link YarnNode} instances
* @param reader The {@link Reader} to read the file from
* @return The {@link List} of {@link YarnNode}
* @throws IOException Thrown if an error occurs during parsing
*/
public List<YarnNode> read(Reader reader) throws IOException {
List<YarnNode> result = new ArrayList<YarnNode>();
Scanner scanner = new Scanner(reader);
while (scanner.hasNextLine()) {
currentNode = readNodeHeader(scanner);
parseNodeContent(currentNode.getNodeContent());
result.add(currentNode);
}
scanner.close();
return result;
}
private YarnNode readNodeHeader(Scanner scanner) {
String title = scanner.nextLine().replace("title:", "").trim();
String[] tags = scanner.nextLine().replace("tags:", "").split(" ");
// Skip color
scanner.nextLine();
// Skip position
scanner.nextLine();
// Skip header end
scanner.nextLine();
StringBuilder nodeContent = new StringBuilder();
while (scanner.hasNextLine()) {
String nextLine = scanner.nextLine();
if (nextLine.startsWith("===")) {
break;
}
if (nextLine.equals("\r\n")) {
continue;
}
if (nextLine.equals("\n")) {
continue;
}
nodeContent.append(nextLine);
nodeContent.append(System.lineSeparator());
}
return new YarnNode(title, tags, nodeContent.toString());
}
private void parseNodeContent(String nodeContent) throws IOException {
YarnLexer yarnLexer = new YarnLexer(new ANTLRInputStream(nodeContent));
YarnParser yarnParser = new YarnParser(new BufferedTokenStream(yarnLexer));
NodeContext nodeContext = yarnParser.node();
ParseTreeWalker parseTreeWalker = new ParseTreeWalker();
parseTreeWalker.walk(this, nodeContext);
if(!ifStack.isEmpty()) {
throw new YarnParserException("<<if>> statement was not closed with an <<endif>> statement");
}
}
@Override
public void exitLineStatement(LineStatementContext ctx) {
YarnLine line = null;
if (ctx.characterExpression() != null) {
line = new YarnLine(currentNode.getTotalOperations(), ctx.getStart().getLine(),
ctx.characterExpression().getText().trim(), ctx.textExpression().getText().trim());
} else {
line = new YarnLine(currentNode.getTotalOperations(), ctx.getStart().getLine(),
ctx.textExpression().getText().trim());
}
currentNode.appendOperation(line);
}
@Override
public void exitIfExpression(IfExpressionContext ctx) {
YarnIfStatement ifStatement = new YarnIfStatement(currentNode.getTotalOperations(), ctx.getStart().getLine(), IfStatementType.IF);
for(int i = 0; i < ctx.conditionExpression().size(); i++) {
ifStatement.appendCondition(new YarnCondition(ctx.getStart().getLine(), ctx.conditionExpression().get(i)));
if(i > 0) {
ifStatement.appendOperator(ctx.boolOperator(i - 1));
}
}
currentNode.appendOperation(ifStatement);
ifStack.push(ifStatement);
}
@Override
public void exitElseifExpression(ElseifExpressionContext ctx) {
currentNode.appendOperation(new YarnEndIfBlock(currentNode.getTotalOperations(), ifStack.peek()));
YarnIfStatement ifStatement = ifStack.peek();
ifStatement.setFailureOperationIndex(currentNode.getTotalOperations());
ifStatement = new YarnIfStatement(currentNode.getTotalOperations(), ctx.getStart().getLine(), IfStatementType.ELSEIF);
for(int i = 0; i < ctx.conditionExpression().size(); i++) {
ifStatement.appendCondition(new YarnCondition(ctx.getStart().getLine(), ctx.conditionExpression().get(i)));
if(i > 0) {
ifStatement.appendOperator(ctx.boolOperator(i - 1));
}
}
currentNode.appendOperation(ifStatement);
ifStack.push(ifStatement);
}
@Override
public void exitElseStatement(ElseStatementContext ctx) {
currentNode.appendOperation(new YarnEndIfBlock(currentNode.getTotalOperations(), ifStack.peek()));
YarnIfStatement ifStatement = ifStack.peek();
ifStatement.setFailureOperationIndex(currentNode.getTotalOperations());
ifStatement = new YarnIfStatement(currentNode.getTotalOperations(), ctx.getStart().getLine(), IfStatementType.ELSE);
currentNode.appendOperation(ifStatement);
ifStack.push(ifStatement);
}
@Override
public void exitEndifStatement(EndifStatementContext ctx) {
YarnIfStatement ifStatement = ifStack.pop();
ifStatement.setFailureOperationIndex(currentNode.getTotalOperations());
ifStatement.setEndBlockOperationindex(currentNode.getTotalOperations());
while(ifStatement.getStatementType() != IfStatementType.IF) {
ifStatement = ifStack.pop();
ifStatement.setEndBlockOperationindex(currentNode.getTotalOperations());
}
}
@Override
public void exitCommandStatement(CommandStatementContext ctx) {
if (ctx.assignExpression() != null) {
String variableName = ctx.assignExpression().VariableLiteral().getText().trim();
YarnAssign assign = new YarnAssign(currentNode.getTotalOperations(), ctx.getStart().getLine(), variableName, ctx.assignExpression().valueExpression());
currentNode.appendOperation(assign);
} else {
YarnCommand command = new YarnCommand(currentNode.getTotalOperations(), ctx.getStart().getLine(),
ctx.textExpression().getText().trim());
currentNode.appendOperation(command);
}
}
@Override
public void exitOptionGroup(OptionGroupContext ctx) {
YarnOptionGroup optionGroup = new YarnOptionGroup(currentNode.getTotalOperations(), ctx.getStart().getLine());
for (int i = 0; i < ctx.optionStatement().size(); i++) {
OptionStatementContext optionContext = ctx.optionStatement().get(i);
YarnOption option = null;
if (optionContext.textExpression() != null) {
option = new YarnOption(i, optionContext.textExpression().getText().trim(),
optionContext.TARGETNAME().getText().trim());
} else {
option = new YarnOption(i, optionContext.TARGETNAME().getText().trim());
}
optionGroup.getOptions().add(option);
}
currentNode.appendOperation(optionGroup);
}
}
| |
package by.vorokhobko.generalization.tracker.abstractclass;
import by.vorokhobko.generalization.tracker.encapsulation.models.Item;
import by.vorokhobko.generalization.tracker.encapsulation.start.Tracker;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test.
*
* @author Evgeny Vorokhobko (vorokhobko2011@yandex.ru).
* @version 1.
* @since 19.04.2017.
*/
public class StartUITest {
/**
* Test Add.
*/
@Test
public void whenAddItemsWithMenuTracker() {
Tracker tracker = new Tracker();
Input inputAdd = new StubInput(new String[]{"0", "testName", "testDesc", "45", "y"});
new StartUI(inputAdd).init(tracker);
assertThat(tracker.findAll().get(0).getName(), is("testName"));
}
/**
* Test Show.
*/
@Test
public void whenShowItemsWithMenuTracker() {
Tracker tracker = new Tracker();
int key = 0;
int keyMaster = 1;
String select = "y";
String name = "testName";
String desc = "testDesc";
String time = "45";
Input inputAdd = new StubInput(new String[]{String.valueOf(key), name, desc, time, select});
new StartUI(inputAdd).init(tracker);
String name1 = "updateName";
String desc1 = "updateDesc";
String time1 = "60";
Input inputUpdate = new StubInput(new String[]{String.valueOf(key), name1, desc1, time1, select});
new StartUI(inputUpdate).init(tracker);
Input input = new StubInput(new String[]{String.valueOf(keyMaster), select});
new StartUI(input).init(tracker);
List<Item> list = tracker.findAll();
assertThat(list.get(0).getName(), is("testName"));
assertThat(list.get(1).getName(), is("updateName"));
}
/**
* Test Show Null.
*/
@Test
public void whenShowNullItemsWithMenuTracker() {
Tracker tracker = new Tracker();
int keyMaster = 1;
String select = "y";
Item item = new Item();
Input input = new StubInput(new String[]{String.valueOf(keyMaster), select});
new StartUI(input).init(tracker);
Assert.assertNull(item.getName());
}
/**
* Test Edit.
*/
@Test
public void whenEditItemsWithMenuTracker() {
Tracker tracker = new Tracker();
int key = 0;
int keyMaster = 2;
String select = "y";
String name = "testName";
String desc = "testDesc";
String time = "45";
Input inputAdd = new StubInput(new String[]{String.valueOf(key), name, desc, time, select});
new StartUI(inputAdd).init(tracker);
List<Item> list = tracker.findAll();
String id = list.get(0).getId();
String name1 = "updateName";
String desc1 = "updateDesc";
String time1 = "60";
Input inputUpdate = new StubInput(new String[]{String.valueOf(keyMaster), id, name1, desc1, time1, select});
new StartUI(inputUpdate).init(tracker);
assertThat(list.get(0).getName(), is("updateName"));
}
/**
* Test Edit Null.
*/
@Test
public void whenEditNullItemsWithMenuTracker() {
Tracker tracker = new Tracker();
int key = 0;
int keyMaster = 2;
String select = "y";
String name = "testName";
String desc = "testDesc";
String time = "45";
Input inputAdd = new StubInput(new String[]{String.valueOf(key), name, desc, time, select});
new StartUI(inputAdd).init(tracker);
String id = null;
String name1 = "updateName";
String desc1 = "updateDesc";
String time1 = "60";
Input inputUpdate = new StubInput(new String[]{String.valueOf(keyMaster), id, name1, desc1, time1, select});
new StartUI(inputUpdate).init(tracker);
List<Item> list = tracker.findAll();
assertThat(list.get(0).getName(), is("testName"));
}
/**
* Test Delete.
*/
@Test
public void whenUserDeleteWithMenuTracker() {
Tracker tracker = new Tracker();
int key = 0;
int keyMaster = 3;
String select = "y";
String name = "testName";
String desc = "testDesc";
String time = "45";
Input inputAdd = new StubInput(new String[]{String.valueOf(key), name, desc, time, select});
new StartUI(inputAdd).init(tracker);
String name1 = "updateName";
String desc1 = "updateDesc";
String time1 = "60";
Input inputUpdate = new StubInput(new String[]{String.valueOf(key), name1, desc1, time1, select});
new StartUI(inputUpdate).init(tracker);
List<Item> list = tracker.findAll();
String id = list.get(0).getId();
Input inputDelete = new StubInput(new String[]{String.valueOf(keyMaster), id, select});
new StartUI(inputDelete).init(tracker);
Assert.assertNull(tracker.findById(id));
}
/**
* Test Delete null.
*/
@Test
public void whenUserDeleteNullWithMenuTracker() {
Tracker tracker = new Tracker();
int key = 0;
int keyMaster = 3;
String select = "y";
String name = "testName";
String desc = "testDesc";
String time = "45";
Input inputAdd = new StubInput(new String[]{String.valueOf(key), name, desc, time, select});
new StartUI(inputAdd).init(tracker);
String name1 = "updateName";
String desc1 = "updateDesc";
String time1 = "60";
Input inputUpdate = new StubInput(new String[]{String.valueOf(key), name1, desc1, time1, select});
new StartUI(inputUpdate).init(tracker);
String id = null;
Input inputDelete = new StubInput(new String[]{String.valueOf(keyMaster), id, select});
new StartUI(inputDelete).init(tracker);
Assert.assertNull(tracker.findById(id));
}
/**
* Test Find by NAME.
*/
@Test
public void whenUserFindItemByNameWithMenuTracker() {
Tracker tracker = new Tracker();
int key = 0;
int keyMaster = 4;
String select = "y";
String name = "testName";
String desc = "testDesc";
String time = "45";
Input inputAdd = new StubInput(new String[]{String.valueOf(key), name, desc, time, select});
new StartUI(inputAdd).init(tracker);
Input inputName = new StubInput(new String[]{String.valueOf(keyMaster), name, select});
new StartUI(inputName).init(tracker);
List<Item> list = tracker.findAll();
assertThat(list.get(0).getName(), is("testName"));
}
/**
* Test Find by NAME null.
*/
@Test
public void whenUserFindItemByNameNullWithMenuTracker() {
Tracker tracker = new Tracker();
int key = 0;
int keyMaster = 4;
String select = "y";
String name = "testName";
String desc = "testDesc";
String time = "45";
Input inputAdd = new StubInput(new String[]{String.valueOf(key), name, desc, time, select});
new StartUI(inputAdd).init(tracker);
String nameTest = "ee";
Input inputName = new StubInput(new String[]{String.valueOf(keyMaster), nameTest, select});
new StartUI(inputName).init(tracker);
List<Item> list = tracker.findAll();
assertThat(list.get(0).getName(), is("testName"));
}
/**
* Test Find by NAME null.
*/
@Test
public void whenUserDoNotCloseMenuTracker() {
Tracker tracker = new Tracker();
int key = 0;
int keyMaster = 1;
String select = "n";
String exit = "y";
String name = "testName";
String desc = "testDesc";
String time = "45";
Input inputAdd = new StubInput(new String[]{String.valueOf(key), name, desc, time, select, String.valueOf(keyMaster), exit});
new StartUI(inputAdd).init(tracker);
List<Item> list = tracker.findAll();
Assert.assertNotNull(list.get(0).getId());
}
/**
* Test by exception(StubInputTest).
* @throws MenuOutException tag.
*/
@Test(expected = MenuOutException.class)
public void testException() throws MenuOutException {
Tracker tracker = new Tracker();
int keyMaster = 11;
Input input = new StubInput(new String[]{String.valueOf(keyMaster)});
new StartUI(input).init(tracker);
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.elasticsearch.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Specifies the connection status of an outbound cross-cluster search connection.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class OutboundCrossClusterSearchConnectionStatus implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The state code for outbound connection. This can be one of the following:
* </p>
* <ul>
* <li>VALIDATING: The outbound connection request is being validated.</li>
* <li>VALIDATION_FAILED: Validation failed for the connection request.</li>
* <li>PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by destination domain
* owner.</li>
* <li>PROVISIONING: Outbound connection request is in process.</li>
* <li>ACTIVE: Outbound connection is active and ready to use.</li>
* <li>REJECTED: Outbound connection request is rejected by destination domain owner.</li>
* <li>DELETING: Outbound connection deletion is in progress.</li>
* <li>DELETED: Outbound connection is deleted and cannot be used further.</li>
* </ul>
*/
private String statusCode;
/**
* <p>
* Specifies verbose information for the outbound connection status.
* </p>
*/
private String message;
/**
* <p>
* The state code for outbound connection. This can be one of the following:
* </p>
* <ul>
* <li>VALIDATING: The outbound connection request is being validated.</li>
* <li>VALIDATION_FAILED: Validation failed for the connection request.</li>
* <li>PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by destination domain
* owner.</li>
* <li>PROVISIONING: Outbound connection request is in process.</li>
* <li>ACTIVE: Outbound connection is active and ready to use.</li>
* <li>REJECTED: Outbound connection request is rejected by destination domain owner.</li>
* <li>DELETING: Outbound connection deletion is in progress.</li>
* <li>DELETED: Outbound connection is deleted and cannot be used further.</li>
* </ul>
*
* @param statusCode
* The state code for outbound connection. This can be one of the following:</p>
* <ul>
* <li>VALIDATING: The outbound connection request is being validated.</li>
* <li>VALIDATION_FAILED: Validation failed for the connection request.</li>
* <li>PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by destination
* domain owner.</li>
* <li>PROVISIONING: Outbound connection request is in process.</li>
* <li>ACTIVE: Outbound connection is active and ready to use.</li>
* <li>REJECTED: Outbound connection request is rejected by destination domain owner.</li>
* <li>DELETING: Outbound connection deletion is in progress.</li>
* <li>DELETED: Outbound connection is deleted and cannot be used further.</li>
* @see OutboundCrossClusterSearchConnectionStatusCode
*/
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
/**
* <p>
* The state code for outbound connection. This can be one of the following:
* </p>
* <ul>
* <li>VALIDATING: The outbound connection request is being validated.</li>
* <li>VALIDATION_FAILED: Validation failed for the connection request.</li>
* <li>PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by destination domain
* owner.</li>
* <li>PROVISIONING: Outbound connection request is in process.</li>
* <li>ACTIVE: Outbound connection is active and ready to use.</li>
* <li>REJECTED: Outbound connection request is rejected by destination domain owner.</li>
* <li>DELETING: Outbound connection deletion is in progress.</li>
* <li>DELETED: Outbound connection is deleted and cannot be used further.</li>
* </ul>
*
* @return The state code for outbound connection. This can be one of the following:</p>
* <ul>
* <li>VALIDATING: The outbound connection request is being validated.</li>
* <li>VALIDATION_FAILED: Validation failed for the connection request.</li>
* <li>PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by destination
* domain owner.</li>
* <li>PROVISIONING: Outbound connection request is in process.</li>
* <li>ACTIVE: Outbound connection is active and ready to use.</li>
* <li>REJECTED: Outbound connection request is rejected by destination domain owner.</li>
* <li>DELETING: Outbound connection deletion is in progress.</li>
* <li>DELETED: Outbound connection is deleted and cannot be used further.</li>
* @see OutboundCrossClusterSearchConnectionStatusCode
*/
public String getStatusCode() {
return this.statusCode;
}
/**
* <p>
* The state code for outbound connection. This can be one of the following:
* </p>
* <ul>
* <li>VALIDATING: The outbound connection request is being validated.</li>
* <li>VALIDATION_FAILED: Validation failed for the connection request.</li>
* <li>PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by destination domain
* owner.</li>
* <li>PROVISIONING: Outbound connection request is in process.</li>
* <li>ACTIVE: Outbound connection is active and ready to use.</li>
* <li>REJECTED: Outbound connection request is rejected by destination domain owner.</li>
* <li>DELETING: Outbound connection deletion is in progress.</li>
* <li>DELETED: Outbound connection is deleted and cannot be used further.</li>
* </ul>
*
* @param statusCode
* The state code for outbound connection. This can be one of the following:</p>
* <ul>
* <li>VALIDATING: The outbound connection request is being validated.</li>
* <li>VALIDATION_FAILED: Validation failed for the connection request.</li>
* <li>PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by destination
* domain owner.</li>
* <li>PROVISIONING: Outbound connection request is in process.</li>
* <li>ACTIVE: Outbound connection is active and ready to use.</li>
* <li>REJECTED: Outbound connection request is rejected by destination domain owner.</li>
* <li>DELETING: Outbound connection deletion is in progress.</li>
* <li>DELETED: Outbound connection is deleted and cannot be used further.</li>
* @return Returns a reference to this object so that method calls can be chained together.
* @see OutboundCrossClusterSearchConnectionStatusCode
*/
public OutboundCrossClusterSearchConnectionStatus withStatusCode(String statusCode) {
setStatusCode(statusCode);
return this;
}
/**
* <p>
* The state code for outbound connection. This can be one of the following:
* </p>
* <ul>
* <li>VALIDATING: The outbound connection request is being validated.</li>
* <li>VALIDATION_FAILED: Validation failed for the connection request.</li>
* <li>PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by destination domain
* owner.</li>
* <li>PROVISIONING: Outbound connection request is in process.</li>
* <li>ACTIVE: Outbound connection is active and ready to use.</li>
* <li>REJECTED: Outbound connection request is rejected by destination domain owner.</li>
* <li>DELETING: Outbound connection deletion is in progress.</li>
* <li>DELETED: Outbound connection is deleted and cannot be used further.</li>
* </ul>
*
* @param statusCode
* The state code for outbound connection. This can be one of the following:</p>
* <ul>
* <li>VALIDATING: The outbound connection request is being validated.</li>
* <li>VALIDATION_FAILED: Validation failed for the connection request.</li>
* <li>PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by destination
* domain owner.</li>
* <li>PROVISIONING: Outbound connection request is in process.</li>
* <li>ACTIVE: Outbound connection is active and ready to use.</li>
* <li>REJECTED: Outbound connection request is rejected by destination domain owner.</li>
* <li>DELETING: Outbound connection deletion is in progress.</li>
* <li>DELETED: Outbound connection is deleted and cannot be used further.</li>
* @return Returns a reference to this object so that method calls can be chained together.
* @see OutboundCrossClusterSearchConnectionStatusCode
*/
public OutboundCrossClusterSearchConnectionStatus withStatusCode(OutboundCrossClusterSearchConnectionStatusCode statusCode) {
this.statusCode = statusCode.toString();
return this;
}
/**
* <p>
* Specifies verbose information for the outbound connection status.
* </p>
*
* @param message
* Specifies verbose information for the outbound connection status.
*/
public void setMessage(String message) {
this.message = message;
}
/**
* <p>
* Specifies verbose information for the outbound connection status.
* </p>
*
* @return Specifies verbose information for the outbound connection status.
*/
public String getMessage() {
return this.message;
}
/**
* <p>
* Specifies verbose information for the outbound connection status.
* </p>
*
* @param message
* Specifies verbose information for the outbound connection status.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public OutboundCrossClusterSearchConnectionStatus withMessage(String message) {
setMessage(message);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getStatusCode() != null)
sb.append("StatusCode: ").append(getStatusCode()).append(",");
if (getMessage() != null)
sb.append("Message: ").append(getMessage());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof OutboundCrossClusterSearchConnectionStatus == false)
return false;
OutboundCrossClusterSearchConnectionStatus other = (OutboundCrossClusterSearchConnectionStatus) obj;
if (other.getStatusCode() == null ^ this.getStatusCode() == null)
return false;
if (other.getStatusCode() != null && other.getStatusCode().equals(this.getStatusCode()) == false)
return false;
if (other.getMessage() == null ^ this.getMessage() == null)
return false;
if (other.getMessage() != null && other.getMessage().equals(this.getMessage()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getStatusCode() == null) ? 0 : getStatusCode().hashCode());
hashCode = prime * hashCode + ((getMessage() == null) ? 0 : getMessage().hashCode());
return hashCode;
}
@Override
public OutboundCrossClusterSearchConnectionStatus clone() {
try {
return (OutboundCrossClusterSearchConnectionStatus) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.elasticsearch.model.transform.OutboundCrossClusterSearchConnectionStatusMarshaller.getInstance().marshall(this,
protocolMarshaller);
}
}
| |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.core.util;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaBoolean;
import org.pentaho.di.core.row.value.ValueMetaDate;
import org.pentaho.di.core.row.value.ValueMetaInteger;
import org.pentaho.di.core.row.value.ValueMetaNumber;
import org.pentaho.di.core.row.value.ValueMetaString;
/**
* This class evaluates strings and extracts a data type. It allows you to criteria after which the analysis should be
* completed.
*
* @author matt
*/
public class StringEvaluator {
private Set<String> values;
private List<StringEvaluationResult> evaluationResults;
private int maxLength;
private int maxPrecision;
private int count;
private boolean tryTrimming;
private ValueMetaInterface stringMeta;
private String[] dateFormats;
private String[] numberFormats;
private static final String[] DEFAULT_NUMBER_FORMATS = new String[]
{
"#,###,###.#",
"#.#",
"#",
"#.0",
"#.00",
"#.000",
"#.0000",
"#.00000",
"#.000000",
" #.0#"
};
protected static final Pattern PRECISION_PATTERN = Pattern.compile( "[^0-9#]" );
public StringEvaluator() {
this( true );
}
public StringEvaluator( boolean tryTrimming ) {
this( tryTrimming, DEFAULT_NUMBER_FORMATS, Const.getDateFormats() );
}
public StringEvaluator( boolean tryTrimming, List<String> numberFormats, List<String> dateFormats ) {
this( tryTrimming, numberFormats.toArray( new String[ numberFormats.size() ] ), dateFormats
.toArray( new String[ dateFormats.size() ] ) );
}
public StringEvaluator( boolean tryTrimming, String[] numberFormats, String[] dateFormats ) {
this.tryTrimming = tryTrimming;
values = new HashSet<String>();
evaluationResults = new ArrayList<StringEvaluationResult>();
count = 0;
stringMeta = new ValueMetaString( "string" );
this.numberFormats = numberFormats;
this.dateFormats = dateFormats;
populateConversionMetaList();
}
public void evaluateString( String value ) {
count++;
if ( !values.contains( value ) ) {
values.add( value );
if ( value != null ) {
evaluateLength( value );
evaluatePrecision( value );
challengeConversions( value );
}
}
}
private void challengeConversions( String value ) {
List<StringEvaluationResult> all = new ArrayList<StringEvaluationResult>( evaluationResults );
ValueMetaInterface stringMetaClone = null;
for ( StringEvaluationResult cmm : all ) {
if ( cmm.getConversionMeta().isBoolean() ) {
// Boolean conversion never fails.
// If it's a Y, N, true, false it's a boolean otherwise it ain't.
//
String string;
if ( tryTrimming ) {
string = Const.trim( value );
} else {
string = value;
}
if ( StringUtils.isEmpty( value ) ) {
cmm.incrementNrNull();
} else if ( !( "Y".equalsIgnoreCase( string ) || "N".equalsIgnoreCase( string ) || "TRUE".equalsIgnoreCase(
string ) || "FALSE".equalsIgnoreCase( string ) ) ) {
evaluationResults.remove( cmm );
} else {
cmm.incrementSuccesses();
}
} else if ( cmm.getConversionMeta().isDate() ) {
String dateFormat = cmm.getConversionMeta().getConversionMask();
if ( !DateDetector.isValidDateFormatToStringDate( dateFormat, value, "en_US" ) ) {
evaluationResults.remove( cmm );
} else {
try {
Object object = DateDetector.getDateFromStringByFormat( value, dateFormat );
cmm.incrementSuccesses();
if ( cmm.getMin() == null || cmm.getConversionMeta().compare( cmm.getMin(), object ) > 0 ) {
cmm.setMin( object );
}
if ( cmm.getMax() == null || cmm.getConversionMeta().compare( cmm.getMax(), object ) < 0 ) {
cmm.setMax( object );
}
} catch ( ParseException e ) {
evaluationResults.remove( cmm );
} catch ( KettleValueException e ) {
evaluationResults.remove( cmm );
}
}
} else {
try {
if ( cmm.getConversionMeta().isNumeric() ) {
boolean stop = false;
int nrDots = 0;
int nrCommas = 0;
int pos = 0;
for ( char c : value.toCharArray() ) {
boolean currencySymbolMatch = !String.valueOf( c ).equals( cmm.getConversionMeta().getCurrencySymbol() )
&& c != '('
&& c != ')';
if ( !Character.isDigit( c )
&& c != '.'
&& c != ','
&& !Character.isSpaceChar( c )
&& currencySymbolMatch
&& ( pos > 0 && ( c == '+' || c == '-' ) ) // allow + & - at the 1st position
) {
evaluationResults.remove( cmm );
stop = true;
break;
}
// If the value contains a decimal or grouping symbol or some sort, it's not an integer
//
if ( ( c == '.' && cmm.getConversionMeta().isInteger() )
|| ( c == ',' && cmm.getConversionMeta().isInteger() ) ) {
evaluationResults.remove( cmm );
stop = true;
break;
}
if ( c == '.' ) {
nrDots++;
}
if ( c == ',' ) {
nrCommas++;
}
pos++;
}
if ( nrDots > 1 && nrCommas > 1 ) {
evaluationResults.remove( cmm );
stop = true;
}
if ( stop ) {
continue;
}
}
if ( stringMetaClone == null ) {
// avoid cloning each time
stringMetaClone = stringMeta.clone();
}
stringMetaClone.setConversionMetadata( cmm.getConversionMeta() );
stringMetaClone.setTrimType( cmm.getConversionMeta().getTrimType() );
Object object = stringMetaClone.convertDataUsingConversionMetaData( value );
// Still here? Evaluate the data...
// Keep track of null values, min, max, etc.
//
if ( cmm.getConversionMeta().isNull( object ) ) {
cmm.incrementNrNull();
} else {
cmm.incrementSuccesses();
}
if ( cmm.getMin() == null || cmm.getConversionMeta().compare( cmm.getMin(), object ) > 0 ) {
cmm.setMin( object );
}
if ( cmm.getMax() == null || cmm.getConversionMeta().compare( cmm.getMax(), object ) < 0 ) {
cmm.setMax( object );
}
} catch ( KettleValueException e ) {
// This one doesn't work, remove it from the list!
//
evaluationResults.remove( cmm );
}
}
}
}
private void evaluateLength( String value ) {
if ( value.length() > maxLength ) {
maxLength = value.length();
}
}
private void evaluatePrecision( String value ) {
int p = determinePrecision( value );
if ( p > maxPrecision ) {
maxPrecision = p;
}
}
private boolean containsInteger() {
for ( StringEvaluationResult result : evaluationResults ) {
if ( result.getConversionMeta().isInteger() && result.getNrSuccesses() > 0 ) {
return true;
}
}
return false;
}
private boolean containsNumber() {
for ( StringEvaluationResult result : evaluationResults ) {
if ( result.getConversionMeta().isNumber() && result.getNrSuccesses() > 0 ) {
return true;
}
}
return false;
}
private boolean containsDate() {
for ( StringEvaluationResult result : evaluationResults ) {
if ( result.getConversionMeta().isDate() && result.getNrSuccesses() > 0 ) {
return true;
}
}
return false;
}
public StringEvaluationResult getAdvicedResult() {
if ( evaluationResults.isEmpty() ) {
ValueMetaInterface adviced = new ValueMetaString( "adviced" );
adviced.setLength( maxLength );
int nrNulls = 0;
String min = null;
String max = null;
for ( String string : values ) {
if ( string != null ) {
if ( min == null || min.compareTo( string ) > 0 ) {
min = string;
}
if ( max == null || max.compareTo( string ) < 0 ) {
max = string;
}
} else {
nrNulls++;
}
}
StringEvaluationResult result = new StringEvaluationResult( adviced );
result.setNrNull( nrNulls );
result.setMin( min );
result.setMax( max );
return result;
} else {
// If there are Numbers and Integers, pick the integers...
//
if ( containsInteger() && containsNumber() ) {
for ( Iterator<StringEvaluationResult> iterator = evaluationResults.iterator(); iterator.hasNext(); ) {
StringEvaluationResult result = iterator.next();
if ( maxPrecision == 0 && result.getConversionMeta().isNumber() ) {
// no precision, don't bother with a number
iterator.remove();
} else if ( maxPrecision > 0 && result.getConversionMeta().isInteger() ) {
// precision is needed, can't use integer
iterator.remove();
}
}
}
// If there are Dates and Integers, pick the dates...
//
if ( containsInteger() && containsDate() ) {
for ( Iterator<StringEvaluationResult> iterator = evaluationResults.iterator(); iterator.hasNext(); ) {
StringEvaluationResult result = iterator.next();
if ( result.getConversionMeta().isInteger() ) {
iterator.remove();
}
}
}
Comparator<StringEvaluationResult> compare = null;
if ( containsDate() ) {
// want the longest format for dates
compare = new Comparator<StringEvaluationResult>() {
@Override
public int compare( StringEvaluationResult r1, StringEvaluationResult r2 ) {
Integer length1 =
r1.getConversionMeta().getConversionMask() == null ? 0 : r1
.getConversionMeta().getConversionMask().length();
Integer length2 =
r2.getConversionMeta().getConversionMask() == null ? 0 : r2
.getConversionMeta().getConversionMask().length();
return length2.compareTo( length1 );
}
};
} else {
// want the shortest format mask for numerics & integers
compare = new Comparator<StringEvaluationResult>() {
@Override
public int compare( StringEvaluationResult r1, StringEvaluationResult r2 ) {
Integer length1 =
r1.getConversionMeta().getConversionMask() == null ? 0 : r1
.getConversionMeta().getConversionMask().length();
Integer length2 =
r2.getConversionMeta().getConversionMask() == null ? 0 : r2
.getConversionMeta().getConversionMask().length();
return length1.compareTo( length2 );
}
};
}
Collections.sort( evaluationResults, compare );
StringEvaluationResult result = evaluationResults.get( 0 );
ValueMetaInterface conversionMeta = result.getConversionMeta();
if ( conversionMeta.isNumber() && conversionMeta.getCurrencySymbol() == null ) {
conversionMeta.setPrecision( maxPrecision );
if ( maxPrecision > 0 && maxLength > 0 ) {
conversionMeta.setLength( maxLength );
}
}
return result;
}
}
public String[] getDateFormats() {
return dateFormats;
}
public String[] getNumberFormats() {
return numberFormats;
}
private void populateConversionMetaList() {
int[] trimTypes;
if ( tryTrimming ) {
trimTypes = new int[] { ValueMetaInterface.TRIM_TYPE_NONE, ValueMetaInterface.TRIM_TYPE_BOTH, };
} else {
trimTypes = new int[] { ValueMetaInterface.TRIM_TYPE_NONE, };
}
for ( int trimType : trimTypes ) {
for ( String format : getDateFormats() ) {
ValueMetaInterface conversionMeta = new ValueMetaDate( "date" );
conversionMeta.setConversionMask( format );
conversionMeta.setTrimType( trimType );
conversionMeta.setDateFormatLenient( false );
evaluationResults.add( new StringEvaluationResult( conversionMeta ) );
}
EvalResultBuilder numberUsBuilder = new EvalResultBuilder( "number-us", ValueMetaInterface.TYPE_NUMBER, 15, trimType, ".", "," );
EvalResultBuilder numberEuBuilder = new EvalResultBuilder( "number-eu", ValueMetaInterface.TYPE_NUMBER, 15, trimType, ",", "." );
for ( String format : getNumberFormats() ) {
if ( format.equals( "#" ) || format.equals( "0" ) ) {
// skip the integer ones. we'll get those later
continue;
}
int precision = determinePrecision( format );
evaluationResults.add( numberUsBuilder.format( format, precision ).build() );
evaluationResults.add( numberEuBuilder.format( format, precision ).build() );
}
// Try the locale's Currency
DecimalFormat currencyFormat = ( (DecimalFormat) NumberFormat.getCurrencyInstance() );
ValueMetaInterface conversionMeta = new ValueMetaNumber( "number-currency" );
// replace the universal currency symbol with the locale's currency symbol for user recognition
String currencyMask = currencyFormat.toLocalizedPattern().replace( "\u00A4", currencyFormat.getCurrency().getSymbol() );
conversionMeta.setConversionMask( currencyMask );
conversionMeta.setTrimType( trimType );
conversionMeta.setDecimalSymbol( String.valueOf( currencyFormat.getDecimalFormatSymbols().getDecimalSeparator() ) );
conversionMeta.setGroupingSymbol( String.valueOf( currencyFormat.getDecimalFormatSymbols().getGroupingSeparator() ) );
conversionMeta.setCurrencySymbol( currencyFormat.getCurrency().getSymbol() );
conversionMeta.setLength( 15 );
int currencyPrecision = currencyFormat.getCurrency().getDefaultFractionDigits();
conversionMeta.setPrecision( currencyPrecision );
evaluationResults.add( new StringEvaluationResult( conversionMeta ) );
// add same mask w/o currency symbol
String currencyMaskAsNumeric = currencyMask.replaceAll( Pattern.quote( currencyFormat.getCurrency().getSymbol() ), "" );
evaluationResults.add( numberUsBuilder.format( currencyMaskAsNumeric, currencyPrecision ).build() );
evaluationResults.add( numberEuBuilder.format( currencyMaskAsNumeric, currencyPrecision ).build() );
// Integer
//
conversionMeta = new ValueMetaInteger( "integer" );
conversionMeta.setConversionMask( "#" );
conversionMeta.setLength( 15 );
evaluationResults.add( new StringEvaluationResult( conversionMeta ) );
conversionMeta = new ValueMetaInteger( "integer" );
conversionMeta.setConversionMask( " #" );
conversionMeta.setLength( 15 );
evaluationResults.add( new StringEvaluationResult( conversionMeta ) );
// Add support for left zero padded integers
//
for ( int i = 1; i <= 15; i++ ) {
String mask = " ";
for ( int x = 0; x < i; x++ ) {
mask += "0";
}
mask += ";-";
for ( int x = 0; x < i; x++ ) {
mask += "0";
}
conversionMeta = new ValueMetaInteger( "integer-zero-padded-" + i );
conversionMeta.setConversionMask( mask );
conversionMeta.setLength( i );
evaluationResults.add( new StringEvaluationResult( conversionMeta ) );
}
// Boolean
//
conversionMeta = new ValueMetaBoolean( "boolean" );
evaluationResults.add( new StringEvaluationResult( conversionMeta ) );
}
}
protected static int determinePrecision( String numericFormat ) {
if ( numericFormat != null ) {
char decimalSymbol = ( (DecimalFormat) NumberFormat.getInstance() ).getDecimalFormatSymbols().getDecimalSeparator();
int loc = numericFormat.lastIndexOf( decimalSymbol );
if ( loc >= 0 && loc < numericFormat.length() ) {
Matcher m = PRECISION_PATTERN.matcher( numericFormat.substring( loc + 1 ) );
int nonDigitLoc = numericFormat.length();
if ( m.find() ) {
nonDigitLoc = loc + 1 + m.start();
}
return numericFormat.substring( loc + 1, nonDigitLoc ).length();
} else {
return 0;
}
} else {
return 0;
}
}
/**
* @return The distinct set of string values
*/
public Set<String> getValues() {
return values;
}
/**
* PDI-7736: Only list of successful evaluations returned.
*
* @return The list of string evaluation results
*/
public List<StringEvaluationResult> getStringEvaluationResults() {
List<StringEvaluationResult> result = new ArrayList<>();
for ( StringEvaluationResult ev : evaluationResults ) {
if ( ev.getNrSuccesses() > 0 ) {
result.add( ev );
}
}
return result;
}
/**
* @return the number of values analyzed
*/
public int getCount() {
return count;
}
/**
* @return The maximum string length encountered
*/
public int getMaxLength() {
return maxLength;
}
private static class EvalResultBuilder {
private final String name;
private final int type;
private final int length;
private final int trimType;
private final String decimalSymbol;
private final String groupingSymbol;
private String format;
private int precision;
public StringEvaluationResult build() {
ValueMetaInterface meta = new ValueMeta( name, type );
meta.setConversionMask( format );
meta.setTrimType( trimType );
meta.setDecimalSymbol( decimalSymbol );
meta.setGroupingSymbol( groupingSymbol );
meta.setLength( length );
meta.setPrecision( precision );
return new StringEvaluationResult( meta );
}
public EvalResultBuilder( String name, int type, int length, int trimType, String decimalSymbol,
String groupingSymbol ) {
this.name = name;
this.type = type;
this.length = length;
this.trimType = trimType;
this.decimalSymbol = decimalSymbol;
this.groupingSymbol = groupingSymbol;
}
public EvalResultBuilder format( String format, int precision ) {
this.format = format;
this.precision = precision;
return this;
}
}
}
| |
package net.cybersoft.visitorinfo.db;
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.config.EmbeddedConfiguration;
import com.db4o.query.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class DbService {
private static ObjectContainer objectContainer = null;
private static EmbeddedConfiguration configuration = null;
public static final int GLOBAL_QUERY_DEPTH = 7;
private static String dbPath;
/*
* static and synchronized to ensure that file locked
* exceptions will not occur when multiple threads from the same process
* attempt to access this class at near the same time.
*/
private static synchronized ObjectContainer getDb() {
objectContainer = objectContainer == null ? Db4oEmbedded.openFile(DbService.getConfig(), DbAdapter.createDbFile(getDbPath())) : objectContainer;
return objectContainer;
}
private static EmbeddedConfiguration getConfig() {
configuration = new DbConfigurationBuilder().getConfiguration();
return configuration;
}
/**
* This is used by tests only. Do not use this method for any other reason.
*/
public void closeDb() {
objectContainer.close();
objectContainer = null;
}
public void setActivationDepth(int depth) {
getDb();
configuration.common().activationDepth(depth);
configuration.common().updateDepth(depth);
}
public ObjectContainer ObjectContainer() {
return getDb();
}
/**
* Save an entity to the DB. Entity must be marked with
* {@code IDomainEntity}. Remember to set the appropriate rules in the
* {@code DbConfigurationBuilder} class so that the data is persisted
* properly in child objects.
*/
public <T> void save(DbEntity<T> entity) {
try {
ObjectContainer db = getDb();
db.store(entity);
db.commit();
}
catch (Exception e) {
System.out.println(""+e);
}
}
/**
* Save List of entities of type T to DB. Each entity must be marked with
* {@code IDomainEntity}. Remember to set the appropriate rules in the
* {@code DbConfigurationBuilder} class so that the data is persisted
* properly in child objects.
*/
public <T> void save(List<T> entity) {
try {
ObjectContainer db = getDb();
for (T iDomainEntity : entity) {
db.store(iDomainEntity);
}
db.commit();
}
catch (Exception e) {
System.out.println(""+e);
}
}
/**
* Save List of entities of type T to DB Each entity must be marked with
* {@code IDomainEntity}. Remember to set the appropriate rules in the
* {@code DbConfigurationBuilder} class so that the data is persisted
* properly in child objects.
*/
public <T> void delete(Class<T> entity) {
try {
ObjectContainer db = getDb();
List<T> results = db.query(entity);
for (T iDomainEntity : results) {
db.delete(iDomainEntity);
}
db.commit();
}
catch (Exception e) {
System.out.println(""+e);
}
}
/**
* Delete entity of type T containing id from DB. Make sure to use {@link
* DbService.setActivationDepth()} so that the appropriate depth is applied
* to the query. Otherwise, cascade deletion will not happen. Don't use this
* method to delete items in lists. Doing so will cause the record to be
* deleted from the DB while the item remains in the list. To delete items
* from lists, use {@code DeleteFromList}
*/
public <T> void deleteById(Class<T> entity, String fieldName, String id) {
try {
ObjectContainer db = getDb();
Query query = db.query();
query.constrain(entity);
query.descend(fieldName).constrain(id);
ObjectSet<T> result = query.execute();
for (T item : result) {
db.delete(item);
}
db.commit();
}
catch (Exception e) {
System.out.println(""+e);
}
}
/**
* Get List of entities of type T from DB. Make sure to use {@link
* DbService.setActivationDepth()} so that the appropriate depth is applied
* to the query. Otherwise, the data that is returned may not be hydrated
* down to the depth that is needed.
*/
public <T> List<T> getResults(Class<T> entity) {
try {
ObjectContainer db = getDb();
return db.query(entity);
}
catch (Exception e) {
System.out.println(""+e);
return new ArrayList<T>();
}
}
/**
* Get entity of type T containing id from DB. Make sure to use {@link
* DbService.setActivationDepth()} so that the appropriate depth is applied
* to the query. Otherwise, the data that is returned may not be hydrated
* down to the depth that is needed.
*/
public <T> T getResultById(Class<T> entity, String fieldName, String value) {
try {
ObjectContainer db = getDb();
Query query = db.query();
query.constrain(entity);
query.descend(fieldName).constrain(value);
ObjectSet<T> result = query.execute();
if (result == null || result.size() == 0) { return null; }
return result.get(0);
}
catch (Exception e) {
System.out.println(""+e);
return null;
}
}
public <T> T getResultByIds(Class<T> entity, Map<String, String> constraints) {
try {
ObjectContainer db = getDb();
Query query = db.query();
query.constrain(entity);
for (Entry<String, String> constraint : constraints.entrySet()) {
query.descend(constraint.getKey()).constrain(constraint.getValue());
}
ObjectSet<T> result = query.execute();
if (result == null || result.size() == 0) { return null; }
return result.get(0);
}
catch (Exception e) {
System.out.println(""+e);
return null;
}
}
public <T> List<T> getResultsByIds(Class<T> entity, Map<String, String> constraints) {
try {
ObjectContainer db = getDb();
Query query = db.query();
query.constrain(entity);
for (Entry<String, String> constraint : constraints.entrySet()) {
query.descend(constraint.getKey()).constrain(constraint.getValue());
}
ObjectSet<T> result = query.execute();
if (result == null || result.size() == 0) { return null; }
List<T> finalResults = new ArrayList<T>();
for (T t : result) {
finalResults.add(t);
}
return finalResults;
}
catch (Exception e) {
System.out.println(""+e);
return null;
}
}
public <T> List<T> getResultsById(Class<T> entity, String fieldName, String value) {
try {
ObjectContainer db = getDb();
Query query = db.query();
query.constrain(entity);
query.descend(fieldName).constrain(value);
ObjectSet<T> result = query.execute();
if (result == null || result.size() == 0) { return null; }
List<T> finalResults = new ArrayList<T>();
for (T t : result) {
finalResults.add(t);
}
return finalResults;
}
catch (Exception e) {
System.out.println(""+e);
return null;
}
}
public <T> List<T> getResultsById(Class<T> entity, String fieldName, int value) {
try {
ObjectContainer db = getDb();
Query query = db.query();
query.constrain(entity);
query.descend(fieldName).constrain(value);
ObjectSet<T> result = query.execute();
if (result == null || result.size() == 0) { return null; }
List<T> finalResults = new ArrayList<T>();
for (T t : result) {
finalResults.add(t);
}
return finalResults;
}
catch (Exception e) {
System.out.println(""+e);
return null;
}
}
/**
* Remove the list @param toDelete from @param childList and then save @param
* parent. The parent and the two lists must be associated with each other.
* The removal does NOT delete the objects from the DB; instead, they are
* orphaned. If the developer wishes for the the objects to also be deleted
* from the DB, then set @param shouldDeleteChildFromDb to true. All
* entities MUST implement {@link DbEntity}. To ensure that child
* objects are updated and deleted, make sure to modify
* {@link DbConfigurationBuilder} so that it properly handles each entity.
* Remember to set the appropriate rules in the
* {@code DbConfigurationBuilder} class so that the data is deleted in child
* objects properly.
*/
public <T, U> void deleteFromList(DbEntity<T> parent, List<U> childList, List<U> toDelete, boolean shouldDeleteChildFromDb) {
try {
childList.removeAll(toDelete);
ObjectContainer db = getDb();
save(parent);
if (shouldDeleteChildFromDb) {
for (U iDomainEntity : toDelete) {
db.delete(iDomainEntity);
}
}
db.commit();
}
catch (Exception e) {
System.out.println(""+e);
}
}
public <T> void deleteObject(DbEntity<T> object){
try{
ObjectContainer db = getDb();
db.delete(object);
db.commit();
}catch(Exception e){
System.out.println(""+e);
}
}
public void setPath(String path) {
setDbPath(path);
}
public static String getDbPath() {
return dbPath;
}
public static void setDbPath(String dbPath) {
DbService.dbPath = dbPath;
}
}
| |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is part of dcm4che, an implementation of DICOM(TM) in
* Java(TM), hosted at http://sourceforge.net/projects/dcm4che.
*
* The Initial Developer of the Original Code is
* Agfa-Gevaert AG.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* See listed authors below.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.dcm4chee.web.war.tc.keywords;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.extensions.ajax.markup.html.autocomplete.AutoCompleteSettings;
import org.apache.wicket.extensions.ajax.markup.html.autocomplete.AutoCompleteTextField;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.ListChoice;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.convert.IConverter;
import org.dcm4chee.icons.ImageManager;
import org.dcm4chee.web.war.common.AutoSelectInputTextBehaviour;
import org.dcm4chee.web.war.tc.TCPopupManager.AbstractTCPopup;
import org.dcm4chee.web.war.tc.TCPopupManager.TCPopupPosition;
import org.dcm4chee.web.war.tc.TCPopupManager.TCPopupPosition.PopupAlign;
import org.dcm4chee.web.war.tc.TCUtilities;
/**
* @author Bernhard Ableitinger <bernhard.ableitinger@agfa.com>
* @version $Revision$ $Date$
* @since June 20, 2011
*/
public class TCKeywordListInput extends AbstractTCKeywordInput {
private static final long serialVersionUID = 1L;
private AutoCompleteTextField<TCKeyword> text;
public TCKeywordListInput(final String id, List<TCKeyword> keywords) {
this(id, null, keywords);
}
public TCKeywordListInput(final String id, TCKeyword selectedKeyword,
final List<TCKeyword> keywords) {
super(id);
setDefaultModel(new Model<TCKeyword>(selectedKeyword) {
@Override
public void setObject(TCKeyword keyword)
{
if (!TCUtilities.equals(getObject(),keyword))
{
super.setObject(keyword);
fireValueChanged();
}
}
});
text = new AutoCompleteTextField<TCKeyword>(
"text", getModel(), TCKeyword.class, new AutoCompleteSettings()) {
private static final long serialVersionUID = 1L;
final Map<String, TCKeyword> keywordMap = new HashMap<String, TCKeyword>();
@Override
public IConverter getConverter(Class<?> type) {
if (TCKeyword.class.equals(type)) {
if (keywordMap.isEmpty() && keywords != null
&& !keywords.isEmpty()) {
for (TCKeyword keyword : keywords) {
keywordMap.put(keyword.toString(), keyword);
}
}
return new IConverter() {
private static final long serialVersionUID = 1L;
@Override
public String convertToString(Object o, Locale locale) {
return o != null ? o.toString() : null;
}
@Override
public TCKeyword convertToObject(String s, Locale locale) {
if (s != null) {
TCKeyword keyword = keywordMap.get(s);
if (keyword == null) {
keyword = new TCKeyword(s, null, false);
}
return keyword;
}
return null;
}
};
}
return getConverter(type);
}
@Override
protected Iterator<TCKeyword> getChoices(String s) {
List<TCKeyword> match = new ArrayList<TCKeyword>();
if (s.length() >= 3) {
for (TCKeyword keyword : keywords) {
if (keyword.toString().toUpperCase()
.contains(s.toUpperCase())) {
match.add(keyword);
}
}
}
return match.iterator();
}
};
text.setOutputMarkupId(true);
text.add(new AutoSelectInputTextBehaviour());
text.add(new AjaxFormComponentUpdatingBehavior("onchange") {
@Override
public void onUpdate(AjaxRequestTarget target)
{
text.updateModel();
}
});
final ListChoice<TCKeyword> keywordList = new ListChoice<TCKeyword>(
"keyword-list", new Model<TCKeyword>(selectedKeyword), keywords) {
private static final long serialVersionUID = 1L;
@Override
protected String getNullValidKey() {
return "tc.search.null.text";
}
};
keywordList.setOutputMarkupId(true);
keywordList.setNullValid(true);
final Button chooserBtn = new Button("chooser-button", new Model<String>("..."));
chooserBtn.add(new Image("chooser-button-img", ImageManager.IMAGE_TC_ARROW_DOWN)
.setOutputMarkupId(true));
final KeywordListPopup popup = new KeywordListPopup(keywordList, text);
popup.installPopupTrigger(chooserBtn, new TCPopupPosition(
chooserBtn.getMarkupId(),
popup.getMarkupId(),
PopupAlign.BottomLeft, PopupAlign.TopLeft));
keywordList.add(new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
@Override
public void onUpdate(AjaxRequestTarget target) {
popup.hide(target);
}
});
add(text);
add(popup);
add(chooserBtn);
}
@Override
public TCKeyword getKeyword() {
TCKeyword keyword = getModel().getObject();
return keyword == null || keyword.isAllKeywordsPlaceholder() ? null
: keyword;
}
@Override
public void resetKeyword() {
getModel().setObject(null);
}
@Override
public boolean isExclusive()
{
return text.isEnabled();
}
@Override
public void setExclusive(boolean exclusive)
{
text.setEnabled(!exclusive);
}
@SuppressWarnings({ "unchecked" })
private Model<TCKeyword> getModel() {
return (Model) getDefaultModel();
}
private class KeywordListPopup extends AbstractTCPopup
{
private ListChoice<TCKeyword> list;
private TextField<TCKeyword> text;
public KeywordListPopup(ListChoice<TCKeyword> list,
TextField<TCKeyword> text)
{
super("list-keyword-popup", true, true, true, true);
this.list = list;
this.text = text;
add(list);
}
@Override
public void afterShowing(AjaxRequestTarget target)
{
list.setModelObject(TCKeywordListInput.this.getKeyword());
if (target!=null)
{
target.addComponent(list);
}
}
@Override
public void beforeHiding(AjaxRequestTarget target)
{
TCKeyword keyword = list.getModelObject();
TCKeywordListInput.this.getModel().setObject(
keyword != null&&keyword.isAllKeywordsPlaceholder() ? null
: keyword);
if (target!=null)
{
target.addComponent(text);
}
}
}
}
| |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.ui;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.Weighted;
import com.intellij.openapi.wm.IdeGlassPane;
import com.intellij.openapi.wm.IdeGlassPaneUtil;
import com.intellij.ui.Gray;
import com.intellij.ui.JBColor;
import com.intellij.ui.OnePixelSplitter;
import com.intellij.util.Producer;
import com.intellij.util.ui.JBUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* @author Konstantin Bulenkov
*/
public class OnePixelDivider extends Divider {
public static final Color BACKGROUND = new JBColor(() -> {
final Color bg = UIManager.getColor("OnePixelDivider.background");
return bg != null ? bg : new JBColor(Gray.xC5, Gray.x51);
});
private boolean myVertical;
private Splittable mySplitter;
private boolean myResizeEnabled;
private boolean mySwitchOrientationEnabled;
protected Point myPoint;
private IdeGlassPane myGlassPane;
private final MouseAdapter myListener = new MyMouseAdapter();
private Disposable myDisposable;
public OnePixelDivider(boolean vertical, Splittable splitter) {
super(new GridBagLayout());
mySplitter = splitter;
myResizeEnabled = true;
mySwitchOrientationEnabled = false;
setFocusable(false);
enableEvents(AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
setOrientation(vertical);
setBackground(BACKGROUND);
}
@Override
public void paint(Graphics g) {
final Rectangle bounds = g.getClipBounds();
if (mySplitter instanceof OnePixelSplitter) {
final Producer<Insets> blindZone = ((OnePixelSplitter)mySplitter).getBlindZone();
if (blindZone != null) {
final Insets insets = blindZone.produce();
if (insets != null) {
bounds.x += insets.left;
bounds.y += insets.top;
bounds.width -= insets.left + insets.right;
bounds.height -= insets.top + insets.bottom;
g.setColor(getBackground());
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
return;
}
}
}
super.paint(g);
}
@Override
public void addNotify() {
super.addNotify();
init();
}
@Override
public void removeNotify() {
super.removeNotify();
if (myDisposable != null && !Disposer.isDisposed(myDisposable)) {
Disposer.dispose(myDisposable);
}
}
private boolean myDragging = false;
private void setDragging(boolean dragging) {
if (myDragging != dragging) {
myDragging = dragging;
mySplitter.setDragging(dragging);
}
}
private class MyMouseAdapter extends MouseAdapter implements Weighted {
@Override
public void mousePressed(MouseEvent e) {
setDragging(isInDragZone(e));
_processMouseEvent(e);
if (myDragging) {
e.consume();
}
}
boolean isInDragZone(MouseEvent e) {
MouseEvent event = getTargetEvent(e);
Point p = event.getPoint();
boolean vertical = isVertical();
OnePixelDivider d = OnePixelDivider.this;
if ((vertical ? p.x : p.y) < 0 || vertical && p.x > d.getWidth() || !vertical && p.y > d.getHeight()) return false;
int r = Math.abs(vertical ? p.y : p.x);
return r < JBUI.scale(6);
}
@Override
public void mouseReleased(MouseEvent e) {
_processMouseEvent(e);
setDragging(false);
}
@Override
public void mouseMoved(MouseEvent e) {
final OnePixelDivider divider = OnePixelDivider.this;
if (isInDragZone(e)) {
myGlassPane.setCursor(divider.getCursor(), divider);
} else {
myGlassPane.setCursor(null, divider);
}
_processMouseMotionEvent(e);
}
@Override
public void mouseDragged(MouseEvent e) {
_processMouseMotionEvent(e);
}
@Override
public double getWeight() {
return 1;
}
private void _processMouseMotionEvent(MouseEvent e) {
MouseEvent event = getTargetEvent(e);
if (event == null) {
myGlassPane.setCursor(null, myListener);
return;
}
processMouseMotionEvent(event);
if (event.isConsumed()) {
e.consume();
}
}
private void _processMouseEvent(MouseEvent e) {
MouseEvent event = getTargetEvent(e);
if (event == null) {
myGlassPane.setCursor(null, myListener);
return;
}
processMouseEvent(event);
if (event.isConsumed()) {
e.consume();
}
}
}
private MouseEvent getTargetEvent(MouseEvent e) {
return SwingUtilities.convertMouseEvent(e.getComponent(), e, this);
}
private void init() {
myGlassPane = IdeGlassPaneUtil.find(this);
myDisposable = Disposer.newDisposable();
myGlassPane.addMouseMotionPreprocessor(myListener, myDisposable);
myGlassPane.addMousePreprocessor(myListener, myDisposable);
}
public void setOrientation(boolean vertical) {
removeAll();
myVertical = vertical;
final int cursorType = isVertical() ? Cursor.N_RESIZE_CURSOR : Cursor.W_RESIZE_CURSOR;
setCursor(Cursor.getPredefinedCursor(cursorType));
}
@Override
protected void processMouseMotionEvent(MouseEvent e) {
super.processMouseMotionEvent(e);
if (!myResizeEnabled) return;
if (MouseEvent.MOUSE_DRAGGED == e.getID() && myDragging) {
myPoint = SwingUtilities.convertPoint(this, e.getPoint(), mySplitter.asComponent());
float proportion;
final float firstMinProportion = mySplitter.getMinProportion(true);
final float secondMinProportion = mySplitter.getMinProportion(false);
if (isVertical()) {
if (getHeight() > 0) {
proportion = Math.min(1.0f, Math
.max(.0f, Math.min(Math.max(firstMinProportion, (float)myPoint.y / (float)mySplitter.asComponent().getHeight()), 1 - secondMinProportion)));
mySplitter.setProportion(proportion);
}
}
else {
if (getWidth() > 0) {
proportion = Math.min(1.0f, Math.max(.0f, Math.min(
Math.max(firstMinProportion, (float)myPoint.x / (float)mySplitter.asComponent().getWidth()), 1 - secondMinProportion)));
mySplitter.setProportion(proportion);
}
}
e.consume();
}
}
@Override
protected void processMouseEvent(MouseEvent e) {
super.processMouseEvent(e);
if (e.getID() == MouseEvent.MOUSE_CLICKED) {
if (mySwitchOrientationEnabled
&& e.getClickCount() == 1
&& SwingUtilities.isLeftMouseButton(e) && (SystemInfo.isMac ? e.isMetaDown() : e.isControlDown())) {
mySplitter.setOrientation(!mySplitter.getOrientation());
}
if (myResizeEnabled && e.getClickCount() == 2) {
mySplitter.setProportion(.5f);
}
}
}
public void setResizeEnabled(boolean resizeEnabled) {
myResizeEnabled = resizeEnabled;
if (!myResizeEnabled) {
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
else {
setCursor(isVertical() ?
Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR) :
Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR));
}
}
public void setSwitchOrientationEnabled(boolean switchOrientationEnabled) {
mySwitchOrientationEnabled = switchOrientationEnabled;
}
public boolean isVertical() {
return myVertical;
}
}
| |
/*
* Copyright 2006-2010 Virtual Laboratory for e-Science (www.vl-e.nl)
* Copyright 2012-2013 Netherlands eScience Center.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For the full license, see: LICENSE.txt (located in the root folder of this distribution).
* ---
*/
// source:
package nl.esciencecenter.vlet.vfs.gftp;
import java.util.Vector;
import nl.esciencecenter.ptk.data.StringList;
import nl.esciencecenter.ptk.net.URIFactory;
import nl.esciencecenter.ptk.task.ITaskMonitor;
import nl.esciencecenter.vbrowser.vrs.data.Attribute;
import nl.esciencecenter.vbrowser.vrs.exceptions.VrsException;
import nl.esciencecenter.vbrowser.vrs.vrl.VRL;
import nl.esciencecenter.vlet.vrs.vfs.VDir;
import nl.esciencecenter.vlet.vrs.vfs.VFSNode;
import org.globus.ftp.MlsxEntry;
/**
* Implementation of GftpDir
*
* @author P.T. de Boer
*/
public class GftpDir extends VDir
{
// private GFTP handler object to this resource.
// private GridFTPClient gftpClient = null;
private MlsxEntry _entry = null;
// Package protected !:
private GftpFileSystem server = null;
/**
* @param client
* @throws VrsException
*/
protected GftpDir(GftpFileSystem server, String path, MlsxEntry entry) throws VrsException
{
super(server, server.getServerVRL().replacePath(path));
init(server, path, entry);
}
protected GftpDir(GftpFileSystem server, String path) throws VrsException
{
this(server, path, null);
}
private void init(GftpFileSystem server, String path, MlsxEntry entry) throws VrsException
{
this._entry = entry;
this.server = server;
}
@Override
public boolean exists()
{
return server.existsDir(this.getPath());
}
public boolean create(boolean force) throws VrsException
{
VDir dir = this.server.createDir(getPath(), force);
updateEntry();
return (dir != null);
}
/**
* Reload MLST entry
*
* @throws VrsException
*/
private MlsxEntry updateEntry() throws VrsException
{
this._entry = this.server.mlst(getPath());
return _entry;
}
@Override
public boolean isReadable() throws VrsException
{
return GftpFileSystem._isReadable(getMlsxEntry());
}
@Override
public boolean isAccessable() throws VrsException
{
return GftpFileSystem._isAccessable(getMlsxEntry());
}
@Override
public boolean isWritable() throws VrsException
{
return GftpFileSystem._isWritable(getMlsxEntry());
}
@Override
public VRL rename(String newName, boolean nameIsPath) throws VrsException
{
String path = server.rename(this.getPath(), newName, nameIsPath);
return this.resolvePath(path);
}
public VDir getParentDir() throws VrsException
{
return server.getParentDir(this.getPath());
}
public long getNrOfNodes()
{
try
{
Object list[] = list();
if (list != null)
return list.length;
}
catch (VrsException e)
{
;
}
return 0;
}
public VFSNode[] list() throws VrsException
{
Vector<?> list = null;
String path = this.getPath();
list = server.mlsd(path);
if (list == null)
return null;
Vector<VFSNode> nodes = new Vector<VFSNode>();
for (Object o : list)
{
MlsxEntry entry = ((MlsxEntry) o);
String name = entry.getFileName();
name = URIFactory.basename(name);
// Debug("fileOnfo=" + fileInfo);
String remotePath = path + "/" + name;
if (GftpFileSystem._isFile(entry))
nodes.add(new GftpFile(server, remotePath, entry));
else if (GftpFileSystem._isXDir(entry))
{
// Skip '.' and '..'
// nodes[j] = null; // new GftpDir(server,remotePath,entry);
;
}
else if (GftpFileSystem._isDir(entry))
nodes.add(new GftpDir(server, remotePath, entry));
/*
* else if (fileInfo.isSoftLink()) nodes[i] = new GftpFile(server,remotePath,fileInfo);
*/
else
{
// DEFAULT: add as file could be anything (link?)
nodes.add(new GftpFile(server, remotePath, entry));
// ; // nodes[j] = null;
}
}
VFSNode nodeArray[] = new VFSNode[nodes.size()];
nodeArray = nodes.toArray(nodeArray);
return nodeArray;
}
public boolean delete(boolean recurse) throws VrsException
{
ITaskMonitor monitor = getVRSContext().getTaskWatcher().getCurrentThreadTaskMonitor("Deleting (GFTP) directory:" + this.getPath(),
1);
// Delete children first:
if (recurse == true)
this.getVRSContext().getTransferManager().recursiveDeleteDirContents(monitor, this, true);
return server.delete(true, this.getPath());
}
/** Check if directory has child */
public boolean existsFile(String name) throws VrsException
{
String newPath = resolvePathString(name);
return server.existsFile(newPath);
}
public boolean existsDir(String dirName) throws VrsException
{
String newPath = resolvePathString(dirName);
return server.existsDir(newPath);
}
public long getModificationTime() throws VrsException
{
// doesnot work for directories: return
// server.getModificationTime(this.getPath());
return -1;
}
public String[] getAttributeNames()
{
String superNames[] = super.getAttributeNames();
if (this.server.protocol_v1)
return superNames;
return StringList.merge(superNames, GftpFSFactory.gftpAttributeNames);
}
@Override
public Attribute[] getAttributes(String names[]) throws VrsException
{
if (names == null)
return null;
Attribute attrs[] = new Attribute[names.length];
// Optimized getAttribute: use single entry for all
MlsxEntry entry = this.getMlsxEntry();
for (int i = 0; i < names.length; i++)
{
attrs[i] = getAttribute(entry, names[i]);
}
return attrs;
}
@Override
public Attribute getAttribute(String name) throws VrsException
{
return getAttribute(this.getMlsxEntry(), name);
}
/**
* Optimized method. When fetching multiple attributes, do not refetch the mlsxentry for each attribute.
*
* @param name
* @param update
* @return
* @throws VrsException
*/
public Attribute getAttribute(MlsxEntry entry, String name) throws VrsException
{
// is possible due to optimization:
if (name == null)
return null;
// get Gftp specific attribute and update
// the mslxEntry if needed
Attribute attr = GftpFileSystem.getAttribute(entry, name);
if (attr != null)
return attr;
return super.getAttribute(name);
}
public MlsxEntry getMlsxEntry() throws VrsException
{
if (_entry == null)
_entry = updateEntry();
return _entry;
}
}
| |
/*
* Copyright 2015-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.incubator.net.meter.impl;
import com.google.common.collect.Maps;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onlab.util.TriConsumer;
import org.onosproject.net.DeviceId;
import org.onosproject.net.behaviour.MeterQuery;
import org.onosproject.net.driver.DriverHandler;
import org.onosproject.net.driver.DriverService;
import org.onosproject.net.meter.DefaultMeter;
import org.onosproject.net.meter.Meter;
import org.onosproject.net.meter.MeterEvent;
import org.onosproject.net.meter.MeterFailReason;
import org.onosproject.net.meter.MeterFeatures;
import org.onosproject.net.meter.MeterFeaturesKey;
import org.onosproject.net.meter.MeterId;
import org.onosproject.net.meter.MeterKey;
import org.onosproject.net.meter.MeterListener;
import org.onosproject.net.meter.MeterOperation;
import org.onosproject.net.meter.MeterProvider;
import org.onosproject.net.meter.MeterProviderRegistry;
import org.onosproject.net.meter.MeterProviderService;
import org.onosproject.net.meter.MeterRequest;
import org.onosproject.net.meter.MeterService;
import org.onosproject.net.meter.MeterState;
import org.onosproject.net.meter.MeterStore;
import org.onosproject.net.meter.MeterStoreDelegate;
import org.onosproject.net.meter.MeterStoreResult;
import org.onosproject.net.provider.AbstractListenerProviderRegistry;
import org.onosproject.net.provider.AbstractProviderService;
import org.onosproject.store.service.AtomicCounter;
import org.onosproject.store.service.StorageService;
import org.slf4j.Logger;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Provides implementation of the meter service APIs.
*/
@Component(immediate = true)
@Service
public class MeterManager
extends AbstractListenerProviderRegistry<MeterEvent, MeterListener, MeterProvider, MeterProviderService>
implements MeterService, MeterProviderRegistry {
private static final String METERCOUNTERIDENTIFIER = "meter-id-counter-%s";
private final Logger log = getLogger(getClass());
private final MeterStoreDelegate delegate = new InternalMeterStoreDelegate();
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected StorageService storageService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected MeterStore store;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected DriverService driverService;
private Map<DeviceId, AtomicCounter> meterIdCounters
= Maps.newConcurrentMap();
private TriConsumer<MeterRequest, MeterStoreResult, Throwable> onComplete;
@Activate
public void activate() {
store.setDelegate(delegate);
eventDispatcher.addSink(MeterEvent.class, listenerRegistry);
onComplete = (request, result, error) -> {
request.context().ifPresent(c -> {
if (error != null) {
c.onError(request, MeterFailReason.UNKNOWN);
} else {
if (result.reason().isPresent()) {
c.onError(request, result.reason().get());
} else {
c.onSuccess(request);
}
}
});
};
log.info("Started");
}
@Deactivate
public void deactivate() {
store.unsetDelegate(delegate);
eventDispatcher.removeSink(MeterEvent.class);
log.info("Stopped");
}
@Override
protected MeterProviderService createProviderService(MeterProvider provider) {
return new InternalMeterProviderService(provider);
}
@Override
public Meter submit(MeterRequest request) {
MeterId id = allocateMeterId(request.deviceId());
Meter.Builder mBuilder = DefaultMeter.builder()
.forDevice(request.deviceId())
.fromApp(request.appId())
.withBands(request.bands())
.withId(id)
.withUnit(request.unit());
if (request.isBurst()) {
mBuilder.burst();
}
DefaultMeter m = (DefaultMeter) mBuilder.build();
m.setState(MeterState.PENDING_ADD);
store.storeMeter(m).whenComplete((result, error) ->
onComplete.accept(request, result, error));
return m;
}
@Override
public void withdraw(MeterRequest request, MeterId meterId) {
Meter.Builder mBuilder = DefaultMeter.builder()
.forDevice(request.deviceId())
.fromApp(request.appId())
.withBands(request.bands())
.withId(meterId)
.withUnit(request.unit());
if (request.isBurst()) {
mBuilder.burst();
}
DefaultMeter m = (DefaultMeter) mBuilder.build();
m.setState(MeterState.PENDING_REMOVE);
store.deleteMeter(m).whenComplete((result, error) ->
onComplete.accept(request, result, error));
}
@Override
public Meter getMeter(DeviceId deviceId, MeterId id) {
MeterKey key = MeterKey.key(deviceId, id);
return store.getMeter(key);
}
@Override
public Collection<Meter> getMeters(DeviceId deviceId) {
return store.getAllMeters().stream().filter(m ->
m.deviceId().equals(deviceId)).collect(Collectors.toList());
}
@Override
public Collection<Meter> getAllMeters() {
return store.getAllMeters();
}
private long queryMeters(DeviceId device) {
DriverHandler handler = driverService.createHandler(device);
if (handler == null || !handler.hasBehaviour(MeterQuery.class)) {
return 0L;
}
MeterQuery query = handler.behaviour(MeterQuery.class);
return query.getMaxMeters();
}
private MeterId allocateMeterId(DeviceId deviceId) {
// We first query the store for any previously removed meterId that could
// be reused. Receiving a value (not null) already means that meters
// are available for the device.
MeterId meterid = store.firstReusableMeterId(deviceId);
if (meterid != null) {
return meterid;
}
// If there was no reusable MeterId we have to generate a new value
// with an upper limit in maxMeters.
long maxMeters = store.getMaxMeters(MeterFeaturesKey.key(deviceId));
if (maxMeters == 0L) {
// MeterFeatures couldn't be retrieved, trying with queryMeters.
// queryMeters is implemented in FullMetersAvailable behaviour.
maxMeters = queryMeters(deviceId);
}
if (maxMeters == 0L) {
throw new IllegalStateException("Meters not supported by device " + deviceId);
}
final long mmeters = maxMeters;
long id = meterIdCounters.compute(deviceId, (k, v) -> {
if (v == null) {
return allocateCounter(k);
}
if (v.get() >= mmeters) {
throw new IllegalStateException("Maximum number of meters " +
meterIdCounters.get(deviceId).get() +
" reached for device " + deviceId);
}
return v;
}).incrementAndGet();
return MeterId.meterId(id);
}
private AtomicCounter allocateCounter(DeviceId deviceId) {
return storageService.getAtomicCounter(String.format(METERCOUNTERIDENTIFIER, deviceId));
}
private class InternalMeterProviderService
extends AbstractProviderService<MeterProvider>
implements MeterProviderService {
/**
* Creates a provider service on behalf of the specified provider.
*
* @param provider provider to which this service is being issued
*/
protected InternalMeterProviderService(MeterProvider provider) {
super(provider);
}
@Override
public void meterOperationFailed(MeterOperation operation,
MeterFailReason reason) {
store.failedMeter(operation, reason);
}
@Override
public void pushMeterMetrics(DeviceId deviceId, Collection<Meter> meterEntries) {
Collection<Meter> allMeters = store.getAllMeters(deviceId);
Map<MeterId, Meter> meterEntriesMap = meterEntries.stream()
.collect(Collectors.toMap(Meter::id, Meter -> Meter));
// Look for meters defined in onos and missing in the device (restore)
allMeters.stream().forEach(m -> {
if ((m.state().equals(MeterState.PENDING_ADD) ||
m.state().equals(MeterState.ADDED)) &&
!meterEntriesMap.containsKey(m.id())) {
// The meter is missing in the device. Reinstall!
log.debug("Adding meter missing in device {} {}", deviceId, m);
provider().performMeterOperation(deviceId,
new MeterOperation(m, MeterOperation.Type.ADD));
}
});
// Look for meters defined in the device and not in onos (remove)
meterEntriesMap.entrySet().stream()
.filter(md -> !allMeters.stream().anyMatch(m -> m.id().equals(md.getKey())))
.forEach(mio -> {
// The meter is missin in onos. Uninstall!
log.debug("Remove meter in device not in onos {} {}", deviceId, mio.getKey());
Meter meter = mio.getValue();
provider().performMeterOperation(deviceId,
new MeterOperation(meter, MeterOperation.Type.REMOVE));
});
meterEntries.stream()
.filter(m -> allMeters.stream()
.anyMatch(sm -> sm.deviceId().equals(deviceId) && sm.id().equals(m.id())))
.forEach(m -> store.updateMeterState(m));
allMeters.forEach(m -> {
if (m.state() == MeterState.PENDING_ADD) {
provider().performMeterOperation(m.deviceId(),
new MeterOperation(m,
MeterOperation.Type.MODIFY));
} else if (m.state() == MeterState.PENDING_REMOVE) {
store.deleteMeterNow(m);
}
});
}
@Override
public void pushMeterFeatures(DeviceId deviceId, MeterFeatures meterfeatures) {
store.storeMeterFeatures(meterfeatures);
}
@Override
public void deleteMeterFeatures(DeviceId deviceId) {
store.deleteMeterFeatures(deviceId);
}
}
private class InternalMeterStoreDelegate implements MeterStoreDelegate {
@Override
public void notify(MeterEvent event) {
DeviceId deviceId = event.subject().deviceId();
MeterProvider p = getProvider(event.subject().deviceId());
switch (event.type()) {
case METER_ADD_REQ:
p.performMeterOperation(deviceId, new MeterOperation(event.subject(),
MeterOperation.Type.ADD));
break;
case METER_REM_REQ:
p.performMeterOperation(deviceId, new MeterOperation(event.subject(),
MeterOperation.Type.REMOVE));
break;
case METER_ADDED:
log.info("Meter added {}", event.subject());
break;
case METER_REMOVED:
log.info("Meter removed {}", event.subject());
break;
default:
log.warn("Unknown meter event {}", event.type());
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.