text
stringlengths 7
1.01M
|
|---|
/*
* Copyright © 2021 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.cdap.internal.tethering;
/**
* Status of a tether.
*/
public enum TetheringStatus {
PENDING,
ACCEPTED,
REJECTED
}
|
/*
* 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.linkis.jobhistory.cache.impl;
import org.apache.linkis.jobhistory.cache.QueryCacheManager;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ScheduledCleanJob extends QuartzJobBean {
private static Logger logger = LoggerFactory.getLogger(ScheduledCleanJob.class);
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext)
throws JobExecutionException {
logger.info("Started cache cleaning job.");
QueryCacheManager queryCacheManager =
(QueryCacheManager)
jobExecutionContext
.getJobDetail()
.getJobDataMap()
.get(QueryCacheManager.class.getName());
queryCacheManager.cleanAll();
logger.info("Finished cache cleaning job.");
}
}
|
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.objc;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder;
import com.google.devtools.build.lib.analysis.RuleContext;
/**
* Implementation for {@code ios_application}.
*/
public class IosApplication extends ReleaseBundlingTargetFactory {
private static final ImmutableSet<Attribute> DEPENDENCY_ATTRIBUTES =
ImmutableSet.of(
new Attribute("binary", Mode.SPLIT),
new Attribute("extensions", Mode.TARGET));
public IosApplication() {
super(ReleaseBundlingSupport.APP_BUNDLE_DIR_FORMAT, XcodeProductType.APPLICATION,
ExposeAsNestedBundle.NO, DEPENDENCY_ATTRIBUTES);
}
@Override
protected OptionsProvider optionsProvider(RuleContext ruleContext) {
return new OptionsProvider.Builder()
.addInfoplists(ruleContext.getPrerequisiteArtifacts("infoplist", Mode.TARGET).list())
.addTransitive(
Optional.fromNullable(
ruleContext.getPrerequisite("options", Mode.TARGET, OptionsProvider.class)))
.build();
}
@Override
protected void configureTarget(RuleConfiguredTargetBuilder target, RuleContext ruleContext,
ReleaseBundlingSupport releaseBundlingSupport) {
// If this is an application built for the simulator, make it runnable.
if (ObjcRuleClasses.objcConfiguration(ruleContext).getPlatform() == Platform.SIMULATOR) {
Artifact runnerScript = ObjcRuleClasses.intermediateArtifacts(ruleContext).runnerScript();
Artifact ipaFile = ruleContext.getImplicitOutputArtifact(ReleaseBundlingSupport.IPA);
releaseBundlingSupport.registerGenerateRunnerScriptAction(runnerScript, ipaFile);
target.setRunfilesSupport(releaseBundlingSupport.runfilesSupport(runnerScript), runnerScript);
}
}
}
|
package com.example.gdg_fluter;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
}
}
|
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Converter;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.RetainedWith;
import com.google.j2objc.annotations.Weak;
import com.google.j2objc.annotations.WeakOuter;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Properties;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.stream.Collector;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.jpatterns.core.ValidationErrorLevel;
import org.jpatterns.gof.behavioral.IteratorPattern;
import org.jpatterns.gof.structural.DecoratorPattern;
/**
* Static utility methods pertaining to {@link Map} instances (including instances of {@link
* SortedMap}, {@link BiMap}, etc.). Also see this class's counterparts {@link Lists}, {@link Sets}
* and {@link Queues}.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#maps"> {@code Maps}</a>.
*
* @author Kevin Bourrillion
* @author Mike Bostock
* @author Isaac Shum
* @author Louis Wasserman
* @since 2.0
*/
@GwtCompatible(emulated = true)
public final class Maps {
private Maps() {}
private enum EntryFunction implements Function<Entry<?, ?>, Object> {
KEY {
@Override
public @Nullable Object apply(Entry<?, ?> entry) {
return entry.getKey();
}
},
VALUE {
@Override
public @Nullable Object apply(Entry<?, ?> entry) {
return entry.getValue();
}
};
}
@SuppressWarnings("unchecked")
static <K> Function<Entry<K, ?>, K> keyFunction() {
return (Function) EntryFunction.KEY;
}
@SuppressWarnings("unchecked")
static <V> Function<Entry<?, V>, V> valueFunction() {
return (Function) EntryFunction.VALUE;
}
static <K, V> Iterator<K> keyIterator(Iterator<Entry<K, V>> entryIterator) {
return new TransformedIterator<Entry<K, V>, K>(entryIterator) {
@Override
K transform(Entry<K, V> entry) {
return entry.getKey();
}
};
}
static <K, V> Iterator<V> valueIterator(Iterator<Entry<K, V>> entryIterator) {
return new TransformedIterator<Entry<K, V>, V>(entryIterator) {
@Override
V transform(Entry<K, V> entry) {
return entry.getValue();
}
};
}
/**
* Returns an immutable map instance containing the given entries. Internally, the returned map
* will be backed by an {@link EnumMap}.
*
* <p>The iteration order of the returned map follows the enum's iteration order, not the order in
* which the elements appear in the given map.
*
* @param map the map to make an immutable copy of
* @return an immutable map containing those entries
* @since 14.0
*/
@GwtCompatible(serializable = true)
public static <K extends Enum<K>, V> ImmutableMap<K, V> immutableEnumMap(
Map<K, ? extends V> map) {
if (map instanceof ImmutableEnumMap) {
@SuppressWarnings("unchecked") // safe covariant cast
ImmutableEnumMap<K, V> result = (ImmutableEnumMap<K, V>) map;
return result;
}
Iterator<? extends Entry<K, ? extends V>> entryItr = map.entrySet().iterator();
if (!entryItr.hasNext()) {
return ImmutableMap.of();
}
Entry<K, ? extends V> entry1 = entryItr.next();
K key1 = entry1.getKey();
V value1 = entry1.getValue();
checkEntryNotNull(key1, value1);
Class<K> clazz = key1.getDeclaringClass();
EnumMap<K, V> enumMap = new EnumMap<>(clazz);
enumMap.put(key1, value1);
while (entryItr.hasNext()) {
Entry<K, ? extends V> entry = entryItr.next();
K key = entry.getKey();
V value = entry.getValue();
checkEntryNotNull(key, value);
enumMap.put(key, value);
}
return ImmutableEnumMap.asImmutable(enumMap);
}
private static class Accumulator<K extends Enum<K>, V> {
private final BinaryOperator<V> mergeFunction;
private EnumMap<K, V> map = null;
Accumulator(BinaryOperator<V> mergeFunction) {
this.mergeFunction = mergeFunction;
}
void put(K key, V value) {
if (map == null) {
map = new EnumMap<>(key.getDeclaringClass());
}
map.merge(key, value, mergeFunction);
}
Accumulator<K, V> combine(Accumulator<K, V> other) {
if (this.map == null) {
return other;
} else if (other.map == null) {
return this;
} else {
other.map.forEach(this::put);
return this;
}
}
ImmutableMap<K, V> toImmutableMap() {
return (map == null) ? ImmutableMap.<K, V>of() : ImmutableEnumMap.asImmutable(map);
}
}
/**
* Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys
* and values are the result of applying the provided mapping functions to the input elements. The
* resulting implementation is specialized for enum key types. The returned map and its views will
* iterate over keys in their enum definition order, not encounter order.
*
* <p>If the mapped keys contain duplicates, an {@code IllegalArgumentException} is thrown when
* the collection operation is performed. (This differs from the {@code Collector} returned by
* {@link java.util.stream.Collectors#toMap(java.util.function.Function,
* java.util.function.Function) Collectors.toMap(Function, Function)}, which throws an {@code
* IllegalStateException}.)
*
* @since 21.0
*/
public static <T, K extends Enum<K>, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap(
java.util.function.Function<? super T, ? extends K> keyFunction,
java.util.function.Function<? super T, ? extends V> valueFunction) {
checkNotNull(keyFunction);
checkNotNull(valueFunction);
return Collector.of(
() ->
new Accumulator<K, V>(
(v1, v2) -> {
throw new IllegalArgumentException("Multiple values for key: " + v1 + ", " + v2);
}),
(accum, t) -> {
K key = checkNotNull(keyFunction.apply(t), "Null key for input %s", t);
V newValue = checkNotNull(valueFunction.apply(t), "Null value for input %s", t);
accum.put(key, newValue);
},
Accumulator::combine,
Accumulator::toImmutableMap,
Collector.Characteristics.UNORDERED);
}
/**
* Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys
* and values are the result of applying the provided mapping functions to the input elements. The
* resulting implementation is specialized for enum key types. The returned map and its views will
* iterate over keys in their enum definition order, not encounter order.
*
* <p>If the mapped keys contain duplicates, the values are merged using the specified merging
* function.
*
* @since 21.0
*/
public static <T, K extends Enum<K>, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap(
java.util.function.Function<? super T, ? extends K> keyFunction,
java.util.function.Function<? super T, ? extends V> valueFunction,
BinaryOperator<V> mergeFunction) {
checkNotNull(keyFunction);
checkNotNull(valueFunction);
checkNotNull(mergeFunction);
// not UNORDERED because we don't know if mergeFunction is commutative
return Collector.of(
() -> new Accumulator<K, V>(mergeFunction),
(accum, t) -> {
K key = checkNotNull(keyFunction.apply(t), "Null key for input %s", t);
V newValue = checkNotNull(valueFunction.apply(t), "Null value for input %s", t);
accum.put(key, newValue);
},
Accumulator::combine,
Accumulator::toImmutableMap);
}
/**
* Creates a <i>mutable</i>, empty {@code HashMap} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#of()} instead.
*
* <p><b>Note:</b> if {@code K} is an {@code enum} type, use {@link #newEnumMap} instead.
*
* <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
* deprecated. Instead, use the {@code HashMap} constructor directly, taking advantage of the new
* <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @return a new, empty {@code HashMap}
*/
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<>();
}
/**
* Creates a <i>mutable</i> {@code HashMap} instance with the same mappings as the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#copyOf(Map)} instead.
*
* <p><b>Note:</b> if {@code K} is an {@link Enum} type, use {@link #newEnumMap} instead.
*
* <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
* deprecated. Instead, use the {@code HashMap} constructor directly, taking advantage of the new
* <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @param map the mappings to be placed in the new map
* @return a new {@code HashMap} initialized with the mappings from {@code map}
*/
public static <K, V> HashMap<K, V> newHashMap(Map<? extends K, ? extends V> map) {
return new HashMap<>(map);
}
/**
* Creates a {@code HashMap} instance, with a high enough "initial capacity" that it <i>should</i>
* hold {@code expectedSize} elements without growth. This behavior cannot be broadly guaranteed,
* but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed that the method
* isn't inadvertently <i>oversizing</i> the returned map.
*
* @param expectedSize the number of entries you expect to add to the returned map
* @return a new, empty {@code HashMap} with enough capacity to hold {@code expectedSize} entries
* without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(int expectedSize) {
return new HashMap<>(capacity(expectedSize));
}
/**
* Returns a capacity that is sufficient to keep the map from being resized as long as it grows no
* larger than expectedSize and the load factor is ≥ its default (0.75).
*/
static int capacity(int expectedSize) {
if (expectedSize < 3) {
checkNonnegative(expectedSize, "expectedSize");
return expectedSize + 1;
}
if (expectedSize < Ints.MAX_POWER_OF_TWO) {
// This is the calculation used in JDK8 to resize when a putAll
// happens; it seems to be the most conservative calculation we
// can make. 0.75 is the default load factor.
return (int) ((float) expectedSize / 0.75F + 1.0F);
}
return Integer.MAX_VALUE; // any large value
}
/**
* Creates a <i>mutable</i>, empty, insertion-ordered {@code LinkedHashMap} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#of()} instead.
*
* <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
* deprecated. Instead, use the {@code LinkedHashMap} constructor directly, taking advantage of
* the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @return a new, empty {@code LinkedHashMap}
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() {
return new LinkedHashMap<>();
}
/**
* Creates a <i>mutable</i>, insertion-ordered {@code LinkedHashMap} instance with the same
* mappings as the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#copyOf(Map)} instead.
*
* <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
* deprecated. Instead, use the {@code LinkedHashMap} constructor directly, taking advantage of
* the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @param map the mappings to be placed in the new map
* @return a new, {@code LinkedHashMap} initialized with the mappings from {@code map}
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(Map<? extends K, ? extends V> map) {
return new LinkedHashMap<>(map);
}
/**
* Creates a {@code LinkedHashMap} instance, with a high enough "initial capacity" that it
* <i>should</i> hold {@code expectedSize} elements without growth. This behavior cannot be
* broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed
* that the method isn't inadvertently <i>oversizing</i> the returned map.
*
* @param expectedSize the number of entries you expect to add to the returned map
* @return a new, empty {@code LinkedHashMap} with enough capacity to hold {@code expectedSize}
* entries without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
* @since 19.0
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) {
return new LinkedHashMap<>(capacity(expectedSize));
}
/**
* Creates a new empty {@link ConcurrentHashMap} instance.
*
* @since 3.0
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentMap() {
return new ConcurrentHashMap<>();
}
/**
* Creates a <i>mutable</i>, empty {@code TreeMap} instance using the natural ordering of its
* elements.
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableSortedMap#of()} instead.
*
* <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
* deprecated. Instead, use the {@code TreeMap} constructor directly, taking advantage of the new
* <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @return a new, empty {@code TreeMap}
*/
public static <K extends Comparable, V> TreeMap<K, V> newTreeMap() {
return new TreeMap<>();
}
/**
* Creates a <i>mutable</i> {@code TreeMap} instance with the same mappings as the specified map
* and using the same ordering as the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSortedMap#copyOfSorted(SortedMap)} instead.
*
* <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
* deprecated. Instead, use the {@code TreeMap} constructor directly, taking advantage of the new
* <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @param map the sorted map whose mappings are to be placed in the new map and whose comparator
* is to be used to sort the new map
* @return a new {@code TreeMap} initialized with the mappings from {@code map} and using the
* comparator of {@code map}
*/
public static <K, V> TreeMap<K, V> newTreeMap(SortedMap<K, ? extends V> map) {
return new TreeMap<>(map);
}
/**
* Creates a <i>mutable</i>, empty {@code TreeMap} instance using the given comparator.
*
* <p><b>Note:</b> if mutability is not required, use {@code
* ImmutableSortedMap.orderedBy(comparator).build()} instead.
*
* <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
* deprecated. Instead, use the {@code TreeMap} constructor directly, taking advantage of the new
* <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @param comparator the comparator to sort the keys with
* @return a new, empty {@code TreeMap}
*/
public static <C, K extends C, V> TreeMap<K, V> newTreeMap(@Nullable Comparator<C> comparator) {
// Ideally, the extra type parameter "C" shouldn't be necessary. It is a
// work-around of a compiler type inference quirk that prevents the
// following code from being compiled:
// Comparator<Class<?>> comparator = null;
// Map<Class<? extends Throwable>, String> map = newTreeMap(comparator);
return new TreeMap<>(comparator);
}
/**
* Creates an {@code EnumMap} instance.
*
* @param type the key type for this map
* @return a new, empty {@code EnumMap}
*/
public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(Class<K> type) {
return new EnumMap<>(checkNotNull(type));
}
/**
* Creates an {@code EnumMap} with the same mappings as the specified map.
*
* <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
* deprecated. Instead, use the {@code EnumMap} constructor directly, taking advantage of the new
* <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @param map the map from which to initialize this {@code EnumMap}
* @return a new {@code EnumMap} initialized with the mappings from {@code map}
* @throws IllegalArgumentException if {@code m} is not an {@code EnumMap} instance and contains
* no mappings
*/
public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(Map<K, ? extends V> map) {
return new EnumMap<>(map);
}
/**
* Creates an {@code IdentityHashMap} instance.
*
* <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
* deprecated. Instead, use the {@code IdentityHashMap} constructor directly, taking advantage of
* the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @return a new, empty {@code IdentityHashMap}
*/
public static <K, V> IdentityHashMap<K, V> newIdentityHashMap() {
return new IdentityHashMap<>();
}
/**
* Computes the difference between two maps. This difference is an immutable snapshot of the state
* of the maps at the time this method is called. It will never change, even if the maps change at
* a later time.
*
* <p>Since this method uses {@code HashMap} instances internally, the keys of the supplied maps
* must be well-behaved with respect to {@link Object#equals} and {@link Object#hashCode}.
*
* <p><b>Note:</b>If you only need to know whether two maps have the same mappings, call {@code
* left.equals(right)} instead of this method.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @return the difference between the two maps
*/
@SuppressWarnings("unchecked")
public static <K, V> MapDifference<K, V> difference(
Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) {
if (left instanceof SortedMap) {
SortedMap<K, ? extends V> sortedLeft = (SortedMap<K, ? extends V>) left;
return difference(sortedLeft, right);
}
return difference(left, right, Equivalence.equals());
}
/**
* Computes the difference between two maps. This difference is an immutable snapshot of the state
* of the maps at the time this method is called. It will never change, even if the maps change at
* a later time.
*
* <p>Since this method uses {@code HashMap} instances internally, the keys of the supplied maps
* must be well-behaved with respect to {@link Object#equals} and {@link Object#hashCode}.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @param valueEquivalence the equivalence relationship to use to compare values
* @return the difference between the two maps
* @since 10.0
*/
public static <K, V> MapDifference<K, V> difference(
Map<? extends K, ? extends V> left,
Map<? extends K, ? extends V> right,
Equivalence<? super V> valueEquivalence) {
Preconditions.checkNotNull(valueEquivalence);
Map<K, V> onlyOnLeft = newLinkedHashMap();
Map<K, V> onlyOnRight = new LinkedHashMap<>(right); // will whittle it down
Map<K, V> onBoth = newLinkedHashMap();
Map<K, MapDifference.ValueDifference<V>> differences = newLinkedHashMap();
doDifference(left, right, valueEquivalence, onlyOnLeft, onlyOnRight, onBoth, differences);
return new MapDifferenceImpl<>(onlyOnLeft, onlyOnRight, onBoth, differences);
}
/**
* Computes the difference between two sorted maps, using the comparator of the left map, or
* {@code Ordering.natural()} if the left map uses the natural ordering of its elements. This
* difference is an immutable snapshot of the state of the maps at the time this method is called.
* It will never change, even if the maps change at a later time.
*
* <p>Since this method uses {@code TreeMap} instances internally, the keys of the right map must
* all compare as distinct according to the comparator of the left map.
*
* <p><b>Note:</b>If you only need to know whether two sorted maps have the same mappings, call
* {@code left.equals(right)} instead of this method.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @return the difference between the two maps
* @since 11.0
*/
public static <K, V> SortedMapDifference<K, V> difference(
SortedMap<K, ? extends V> left, Map<? extends K, ? extends V> right) {
checkNotNull(left);
checkNotNull(right);
Comparator<? super K> comparator = orNaturalOrder(left.comparator());
SortedMap<K, V> onlyOnLeft = Maps.newTreeMap(comparator);
SortedMap<K, V> onlyOnRight = Maps.newTreeMap(comparator);
onlyOnRight.putAll(right); // will whittle it down
SortedMap<K, V> onBoth = Maps.newTreeMap(comparator);
SortedMap<K, MapDifference.ValueDifference<V>> differences = Maps.newTreeMap(comparator);
doDifference(left, right, Equivalence.equals(), onlyOnLeft, onlyOnRight, onBoth, differences);
return new SortedMapDifferenceImpl<>(onlyOnLeft, onlyOnRight, onBoth, differences);
}
private static <K, V> void doDifference(
Map<? extends K, ? extends V> left,
Map<? extends K, ? extends V> right,
Equivalence<? super V> valueEquivalence,
Map<K, V> onlyOnLeft,
Map<K, V> onlyOnRight,
Map<K, V> onBoth,
Map<K, MapDifference.ValueDifference<V>> differences) {
for (Entry<? extends K, ? extends V> entry : left.entrySet()) {
K leftKey = entry.getKey();
V leftValue = entry.getValue();
if (right.containsKey(leftKey)) {
V rightValue = onlyOnRight.remove(leftKey);
if (valueEquivalence.equivalent(leftValue, rightValue)) {
onBoth.put(leftKey, leftValue);
} else {
differences.put(leftKey, ValueDifferenceImpl.create(leftValue, rightValue));
}
} else {
onlyOnLeft.put(leftKey, leftValue);
}
}
}
private static <K, V> Map<K, V> unmodifiableMap(Map<K, ? extends V> map) {
if (map instanceof SortedMap) {
return Collections.unmodifiableSortedMap((SortedMap<K, ? extends V>) map);
} else {
return Collections.unmodifiableMap(map);
}
}
static class MapDifferenceImpl<K, V> implements MapDifference<K, V> {
final Map<K, V> onlyOnLeft;
final Map<K, V> onlyOnRight;
final Map<K, V> onBoth;
final Map<K, ValueDifference<V>> differences;
MapDifferenceImpl(
Map<K, V> onlyOnLeft,
Map<K, V> onlyOnRight,
Map<K, V> onBoth,
Map<K, ValueDifference<V>> differences) {
this.onlyOnLeft = unmodifiableMap(onlyOnLeft);
this.onlyOnRight = unmodifiableMap(onlyOnRight);
this.onBoth = unmodifiableMap(onBoth);
this.differences = unmodifiableMap(differences);
}
@Override
public boolean areEqual() {
return onlyOnLeft.isEmpty() && onlyOnRight.isEmpty() && differences.isEmpty();
}
@Override
public Map<K, V> entriesOnlyOnLeft() {
return onlyOnLeft;
}
@Override
public Map<K, V> entriesOnlyOnRight() {
return onlyOnRight;
}
@Override
public Map<K, V> entriesInCommon() {
return onBoth;
}
@Override
public Map<K, ValueDifference<V>> entriesDiffering() {
return differences;
}
@Override
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof MapDifference) {
MapDifference<?, ?> other = (MapDifference<?, ?>) object;
return entriesOnlyOnLeft().equals(other.entriesOnlyOnLeft())
&& entriesOnlyOnRight().equals(other.entriesOnlyOnRight())
&& entriesInCommon().equals(other.entriesInCommon())
&& entriesDiffering().equals(other.entriesDiffering());
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(
entriesOnlyOnLeft(), entriesOnlyOnRight(), entriesInCommon(), entriesDiffering());
}
@Override
public String toString() {
if (areEqual()) {
return "equal";
}
StringBuilder result = new StringBuilder("not equal");
if (!onlyOnLeft.isEmpty()) {
result.append(": only on left=").append(onlyOnLeft);
}
if (!onlyOnRight.isEmpty()) {
result.append(": only on right=").append(onlyOnRight);
}
if (!differences.isEmpty()) {
result.append(": value differences=").append(differences);
}
return result.toString();
}
}
static class ValueDifferenceImpl<V> implements MapDifference.ValueDifference<V> {
private final @Nullable V left;
private final @Nullable V right;
static <V> ValueDifference<V> create(@Nullable V left, @Nullable V right) {
return new ValueDifferenceImpl<V>(left, right);
}
private ValueDifferenceImpl(@Nullable V left, @Nullable V right) {
this.left = left;
this.right = right;
}
@Override
public V leftValue() {
return left;
}
@Override
public V rightValue() {
return right;
}
@Override
public boolean equals(@Nullable Object object) {
if (object instanceof MapDifference.ValueDifference) {
MapDifference.ValueDifference<?> that = (MapDifference.ValueDifference<?>) object;
return Objects.equal(this.left, that.leftValue())
&& Objects.equal(this.right, that.rightValue());
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(left, right);
}
@Override
public String toString() {
return "(" + left + ", " + right + ")";
}
}
static class SortedMapDifferenceImpl<K, V> extends MapDifferenceImpl<K, V>
implements SortedMapDifference<K, V> {
SortedMapDifferenceImpl(
SortedMap<K, V> onlyOnLeft,
SortedMap<K, V> onlyOnRight,
SortedMap<K, V> onBoth,
SortedMap<K, ValueDifference<V>> differences) {
super(onlyOnLeft, onlyOnRight, onBoth, differences);
}
@Override
public SortedMap<K, ValueDifference<V>> entriesDiffering() {
return (SortedMap<K, ValueDifference<V>>) super.entriesDiffering();
}
@Override
public SortedMap<K, V> entriesInCommon() {
return (SortedMap<K, V>) super.entriesInCommon();
}
@Override
public SortedMap<K, V> entriesOnlyOnLeft() {
return (SortedMap<K, V>) super.entriesOnlyOnLeft();
}
@Override
public SortedMap<K, V> entriesOnlyOnRight() {
return (SortedMap<K, V>) super.entriesOnlyOnRight();
}
}
/**
* Returns the specified comparator if not null; otherwise returns {@code Ordering.natural()}.
* This method is an abomination of generics; the only purpose of this method is to contain the
* ugly type-casting in one place.
*/
@SuppressWarnings("unchecked")
static <E> Comparator<? super E> orNaturalOrder(@Nullable Comparator<? super E> comparator) {
if (comparator != null) { // can't use ? : because of javac bug 5080917
return comparator;
}
return (Comparator<E>) Ordering.natural();
}
/**
* Returns a live {@link Map} view whose keys are the contents of {@code set} and whose values are
* computed on demand using {@code function}. To get an immutable <i>copy</i> instead, use {@link
* #toMap(Iterable, Function)}.
*
* <p>Specifically, for each {@code k} in the backing set, the returned map has an entry mapping
* {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code
* entrySet} views of the returned map iterate in the same order as the backing set.
*
* <p>Modifications to the backing set are read through to the returned map. The returned map
* supports removal operations if the backing set does. Removal operations write through to the
* backing set. The returned map does not support put operations.
*
* <p><b>Warning:</b> If the function rejects {@code null}, caution is required to make sure the
* set does not contain {@code null}, because the view cannot stop {@code null} from being added
* to the set.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of key type {@code K},
* {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for
* which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when
* calling methods on the resulting map view.
*
* @since 14.0
*/
public static <K, V> Map<K, V> asMap(Set<K> set, Function<? super K, V> function) {
return new AsMapView<>(set, function);
}
/**
* Returns a view of the sorted set as a map, mapping keys from the set according to the specified
* function.
*
* <p>Specifically, for each {@code k} in the backing set, the returned map has an entry mapping
* {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code
* entrySet} views of the returned map iterate in the same order as the backing set.
*
* <p>Modifications to the backing set are read through to the returned map. The returned map
* supports removal operations if the backing set does. Removal operations write through to the
* backing set. The returned map does not support put operations.
*
* <p><b>Warning:</b> If the function rejects {@code null}, caution is required to make sure the
* set does not contain {@code null}, because the view cannot stop {@code null} from being added
* to the set.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of key type {@code K},
* {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for
* which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when
* calling methods on the resulting map view.
*
* @since 14.0
*/
public static <K, V> SortedMap<K, V> asMap(SortedSet<K> set, Function<? super K, V> function) {
return new SortedAsMapView<>(set, function);
}
/**
* Returns a view of the navigable set as a map, mapping keys from the set according to the
* specified function.
*
* <p>Specifically, for each {@code k} in the backing set, the returned map has an entry mapping
* {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code
* entrySet} views of the returned map iterate in the same order as the backing set.
*
* <p>Modifications to the backing set are read through to the returned map. The returned map
* supports removal operations if the backing set does. Removal operations write through to the
* backing set. The returned map does not support put operations.
*
* <p><b>Warning:</b> If the function rejects {@code null}, caution is required to make sure the
* set does not contain {@code null}, because the view cannot stop {@code null} from being added
* to the set.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of key type {@code K},
* {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for
* which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when
* calling methods on the resulting map view.
*
* @since 14.0
*/
@GwtIncompatible // NavigableMap
public static <K, V> NavigableMap<K, V> asMap(
NavigableSet<K> set, Function<? super K, V> function) {
return new NavigableAsMapView<>(set, function);
}
private static class AsMapView<K, V> extends ViewCachingAbstractMap<K, V> {
private final Set<K> set;
final Function<? super K, V> function;
Set<K> backingSet() {
return set;
}
AsMapView(Set<K> set, Function<? super K, V> function) {
this.set = checkNotNull(set);
this.function = checkNotNull(function);
}
@Override
public Set<K> createKeySet() {
return removeOnlySet(backingSet());
}
@Override
Collection<V> createValues() {
return Collections2.transform(set, function);
}
@Override
public int size() {
return backingSet().size();
}
@Override
public boolean containsKey(@Nullable Object key) {
return backingSet().contains(key);
}
@Override
public V get(@Nullable Object key) {
return getOrDefault(key, null);
}
@Override
public V getOrDefault(@Nullable Object key, @Nullable V defaultValue) {
if (Collections2.safeContains(backingSet(), key)) {
@SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
K k = (K) key;
return function.apply(k);
} else {
return defaultValue;
}
}
@Override
public V remove(@Nullable Object key) {
if (backingSet().remove(key)) {
@SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
K k = (K) key;
return function.apply(k);
} else {
return null;
}
}
@Override
public void clear() {
backingSet().clear();
}
@Override
protected Set<Entry<K, V>> createEntrySet() {
@WeakOuter
class EntrySetImpl extends EntrySet<K, V> {
@Override
Map<K, V> map() {
return AsMapView.this;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return asMapEntryIterator(backingSet(), function);
}
}
return new EntrySetImpl();
}
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
checkNotNull(action);
// avoids allocation of entries
backingSet().forEach(k -> action.accept(k, function.apply(k)));
}
}
static <K, V> Iterator<Entry<K, V>> asMapEntryIterator(
Set<K> set, final Function<? super K, V> function) {
return new TransformedIterator<K, Entry<K, V>>(set.iterator()) {
@Override
Entry<K, V> transform(final K key) {
return immutableEntry(key, function.apply(key));
}
};
}
private static class SortedAsMapView<K, V> extends AsMapView<K, V> implements SortedMap<K, V> {
SortedAsMapView(SortedSet<K> set, Function<? super K, V> function) {
super(set, function);
}
@Override
SortedSet<K> backingSet() {
return (SortedSet<K>) super.backingSet();
}
@Override
public Comparator<? super K> comparator() {
return backingSet().comparator();
}
@Override
public Set<K> keySet() {
return removeOnlySortedSet(backingSet());
}
@Override
public SortedMap<K, V> subMap(K fromKey, K toKey) {
return asMap(backingSet().subSet(fromKey, toKey), function);
}
@Override
public SortedMap<K, V> headMap(K toKey) {
return asMap(backingSet().headSet(toKey), function);
}
@Override
public SortedMap<K, V> tailMap(K fromKey) {
return asMap(backingSet().tailSet(fromKey), function);
}
@Override
public K firstKey() {
return backingSet().first();
}
@Override
public K lastKey() {
return backingSet().last();
}
}
@GwtIncompatible // NavigableMap
private static final class NavigableAsMapView<K, V> extends AbstractNavigableMap<K, V> {
/*
* Using AbstractNavigableMap is simpler than extending SortedAsMapView and rewriting all the
* NavigableMap methods.
*/
private final NavigableSet<K> set;
private final Function<? super K, V> function;
NavigableAsMapView(NavigableSet<K> ks, Function<? super K, V> vFunction) {
this.set = checkNotNull(ks);
this.function = checkNotNull(vFunction);
}
@Override
public NavigableMap<K, V> subMap(
K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return asMap(set.subSet(fromKey, fromInclusive, toKey, toInclusive), function);
}
@Override
public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
return asMap(set.headSet(toKey, inclusive), function);
}
@Override
public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
return asMap(set.tailSet(fromKey, inclusive), function);
}
@Override
public Comparator<? super K> comparator() {
return set.comparator();
}
@Override
public @Nullable V get(@Nullable Object key) {
return getOrDefault(key, null);
}
@Override
public @Nullable V getOrDefault(@Nullable Object key, @Nullable V defaultValue) {
if (Collections2.safeContains(set, key)) {
@SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
K k = (K) key;
return function.apply(k);
} else {
return defaultValue;
}
}
@Override
public void clear() {
set.clear();
}
@Override
Iterator<Entry<K, V>> entryIterator() {
return asMapEntryIterator(set, function);
}
@Override
Spliterator<Entry<K, V>> entrySpliterator() {
return CollectSpliterators.map(set.spliterator(), e -> immutableEntry(e, function.apply(e)));
}
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
set.forEach(k -> action.accept(k, function.apply(k)));
}
@Override
Iterator<Entry<K, V>> descendingEntryIterator() {
return descendingMap().entrySet().iterator();
}
@Override
public NavigableSet<K> navigableKeySet() {
return removeOnlyNavigableSet(set);
}
@Override
public int size() {
return set.size();
}
@Override
public NavigableMap<K, V> descendingMap() {
return asMap(set.descendingSet(), function);
}
}
private static <E> Set<E> removeOnlySet(final Set<E> set) {
return new ForwardingSet<E>() {
@Override
protected Set<E> delegate() {
return set;
}
@Override
public boolean add(E element) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends E> es) {
throw new UnsupportedOperationException();
}
};
}
private static <E> SortedSet<E> removeOnlySortedSet(final SortedSet<E> set) {
return new ForwardingSortedSet<E>() {
@Override
protected SortedSet<E> delegate() {
return set;
}
@Override
public boolean add(E element) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends E> es) {
throw new UnsupportedOperationException();
}
@Override
public SortedSet<E> headSet(E toElement) {
return removeOnlySortedSet(super.headSet(toElement));
}
@Override
public SortedSet<E> subSet(E fromElement, E toElement) {
return removeOnlySortedSet(super.subSet(fromElement, toElement));
}
@Override
public SortedSet<E> tailSet(E fromElement) {
return removeOnlySortedSet(super.tailSet(fromElement));
}
};
}
@GwtIncompatible // NavigableSet
private static <E> NavigableSet<E> removeOnlyNavigableSet(final NavigableSet<E> set) {
return new ForwardingNavigableSet<E>() {
@Override
protected NavigableSet<E> delegate() {
return set;
}
@Override
public boolean add(E element) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends E> es) {
throw new UnsupportedOperationException();
}
@Override
public SortedSet<E> headSet(E toElement) {
return removeOnlySortedSet(super.headSet(toElement));
}
@Override
public NavigableSet<E> headSet(E toElement, boolean inclusive) {
return removeOnlyNavigableSet(super.headSet(toElement, inclusive));
}
@Override
public SortedSet<E> subSet(E fromElement, E toElement) {
return removeOnlySortedSet(super.subSet(fromElement, toElement));
}
@Override
public NavigableSet<E> subSet(
E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
return removeOnlyNavigableSet(
super.subSet(fromElement, fromInclusive, toElement, toInclusive));
}
@Override
public SortedSet<E> tailSet(E fromElement) {
return removeOnlySortedSet(super.tailSet(fromElement));
}
@Override
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return removeOnlyNavigableSet(super.tailSet(fromElement, inclusive));
}
@Override
public NavigableSet<E> descendingSet() {
return removeOnlyNavigableSet(super.descendingSet());
}
};
}
/**
* Returns an immutable map whose keys are the distinct elements of {@code keys} and whose value
* for each key was computed by {@code valueFunction}. The map's iteration order is the order of
* the first appearance of each key in {@code keys}.
*
* <p>When there are multiple instances of a key in {@code keys}, it is unspecified whether {@code
* valueFunction} will be applied to more than one instance of that key and, if it is, which
* result will be mapped to that key in the returned map.
*
* <p>If {@code keys} is a {@link Set}, a live view can be obtained instead of a copy using {@link
* Maps#asMap(Set, Function)}.
*
* @throws NullPointerException if any element of {@code keys} is {@code null}, or if {@code
* valueFunction} produces {@code null} for any key
* @since 14.0
*/
public static <K, V> ImmutableMap<K, V> toMap(
Iterable<K> keys, Function<? super K, V> valueFunction) {
return toMap(keys.iterator(), valueFunction);
}
/**
* Returns an immutable map whose keys are the distinct elements of {@code keys} and whose value
* for each key was computed by {@code valueFunction}. The map's iteration order is the order of
* the first appearance of each key in {@code keys}.
*
* <p>When there are multiple instances of a key in {@code keys}, it is unspecified whether {@code
* valueFunction} will be applied to more than one instance of that key and, if it is, which
* result will be mapped to that key in the returned map.
*
* @throws NullPointerException if any element of {@code keys} is {@code null}, or if {@code
* valueFunction} produces {@code null} for any key
* @since 14.0
*/
public static <K, V> ImmutableMap<K, V> toMap(
Iterator<K> keys, Function<? super K, V> valueFunction) {
checkNotNull(valueFunction);
// Using LHM instead of a builder so as not to fail on duplicate keys
Map<K, V> builder = newLinkedHashMap();
while (keys.hasNext()) {
K key = keys.next();
builder.put(key, valueFunction.apply(key));
}
return ImmutableMap.copyOf(builder);
}
/**
* Returns a map with the given {@code values}, indexed by keys derived from those values. In
* other words, each input value produces an entry in the map whose key is the result of applying
* {@code keyFunction} to that value. These entries appear in the same order as the input values.
* Example usage:
*
* <pre>{@code
* Color red = new Color("red", 255, 0, 0);
* ...
* ImmutableSet<Color> allColors = ImmutableSet.of(red, green, blue);
*
* Map<String, Color> colorForName =
* uniqueIndex(allColors, toStringFunction());
* assertThat(colorForName).containsEntry("red", red);
* }</pre>
*
* <p>If your index may associate multiple values with each key, use {@link
* Multimaps#index(Iterable, Function) Multimaps.index}.
*
* @param values the values to use when constructing the {@code Map}
* @param keyFunction the function used to produce the key for each value
* @return a map mapping the result of evaluating the function {@code keyFunction} on each value
* in the input collection to that value
* @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
* value in the input collection
* @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code
* keyFunction} produces {@code null} for any value
*/
@CanIgnoreReturnValue
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterable<V> values, Function<? super V, K> keyFunction) {
// TODO(lowasser): consider presizing the builder if values is a Collection
return uniqueIndex(values.iterator(), keyFunction);
}
/**
* Returns a map with the given {@code values}, indexed by keys derived from those values. In
* other words, each input value produces an entry in the map whose key is the result of applying
* {@code keyFunction} to that value. These entries appear in the same order as the input values.
* Example usage:
*
* <pre>{@code
* Color red = new Color("red", 255, 0, 0);
* ...
* Iterator<Color> allColors = ImmutableSet.of(red, green, blue).iterator();
*
* Map<String, Color> colorForName =
* uniqueIndex(allColors, toStringFunction());
* assertThat(colorForName).containsEntry("red", red);
* }</pre>
*
* <p>If your index may associate multiple values with each key, use {@link
* Multimaps#index(Iterator, Function) Multimaps.index}.
*
* @param values the values to use when constructing the {@code Map}
* @param keyFunction the function used to produce the key for each value
* @return a map mapping the result of evaluating the function {@code keyFunction} on each value
* in the input collection to that value
* @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
* value in the input collection
* @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code
* keyFunction} produces {@code null} for any value
* @since 10.0
*/
@CanIgnoreReturnValue
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterator<V> values, Function<? super V, K> keyFunction) {
checkNotNull(keyFunction);
ImmutableMap.Builder<K, V> builder = ImmutableMap.builder();
while (values.hasNext()) {
V value = values.next();
builder.put(keyFunction.apply(value), value);
}
try {
return builder.build();
} catch (IllegalArgumentException duplicateKeys) {
throw new IllegalArgumentException(
duplicateKeys.getMessage()
+ ". To index multiple values under a key, use Multimaps.index.");
}
}
/**
* Creates an {@code ImmutableMap<String, String>} from a {@code Properties} instance. Properties
* normally derive from {@code Map<Object, Object>}, but they typically contain strings, which is
* awkward. This method lets you get a plain-old-{@code Map} out of a {@code Properties}.
*
* @param properties a {@code Properties} object to be converted
* @return an immutable map containing all the entries in {@code properties}
* @throws ClassCastException if any key in {@code Properties} is not a {@code String}
* @throws NullPointerException if any key or value in {@code Properties} is null
*/
@GwtIncompatible // java.util.Properties
public static ImmutableMap<String, String> fromProperties(Properties properties) {
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements(); ) {
String key = (String) e.nextElement();
builder.put(key, properties.getProperty(key));
}
return builder.build();
}
/**
* Returns an immutable map entry with the specified key and value. The {@link Entry#setValue}
* operation throws an {@link UnsupportedOperationException}.
*
* <p>The returned entry is serializable.
*
* <p><b>Java 9 users:</b> consider using {@code java.util.Map.entry(key, value)} if the key and
* value are non-null and the entry does not need to be serializable.
*
* @param key the key to be associated with the returned entry
* @param value the value to be associated with the returned entry
*/
@GwtCompatible(serializable = true)
public static <K, V> Entry<K, V> immutableEntry(@Nullable K key, @Nullable V value) {
return new ImmutableEntry<>(key, value);
}
/**
* Returns an unmodifiable view of the specified set of entries. The {@link Entry#setValue}
* operation throws an {@link UnsupportedOperationException}, as do any operations that would
* modify the returned set.
*
* @param entrySet the entries for which to return an unmodifiable view
* @return an unmodifiable view of the entries
*/
static <K, V> Set<Entry<K, V>> unmodifiableEntrySet(Set<Entry<K, V>> entrySet) {
return new UnmodifiableEntrySet<>(Collections.unmodifiableSet(entrySet));
}
/**
* Returns an unmodifiable view of the specified map entry. The {@link Entry#setValue} operation
* throws an {@link UnsupportedOperationException}. This also has the side-effect of redefining
* {@code equals} to comply with the Entry contract, to avoid a possible nefarious implementation
* of equals.
*
* @param entry the entry for which to return an unmodifiable view
* @return an unmodifiable view of the entry
*/
static <K, V> Entry<K, V> unmodifiableEntry(final Entry<? extends K, ? extends V> entry) {
checkNotNull(entry);
return new AbstractMapEntry<K, V>() {
@Override
public K getKey() {
return entry.getKey();
}
@Override
public V getValue() {
return entry.getValue();
}
};
}
static <K, V> UnmodifiableIterator<Entry<K, V>> unmodifiableEntryIterator(
final Iterator<Entry<K, V>> entryIterator) {
return new UnmodifiableIterator<Entry<K, V>>() {
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public Entry<K, V> next() {
return unmodifiableEntry(entryIterator.next());
}
};
}
/** @see Multimaps#unmodifiableEntries */
@IteratorPattern.ConcreteAggregate(validationErrorLevel = ValidationErrorLevel.ERROR)
@DecoratorPattern.ConcreteDecorator(validationErrorLevel = ValidationErrorLevel.NONE)
static class UnmodifiableEntries<K, V> extends ForwardingCollection<Entry<K, V>> {
private final Collection<Entry<K, V>> entries;
UnmodifiableEntries(Collection<Entry<K, V>> entries) {
this.entries = entries;
}
@Override
protected Collection<Entry<K, V>> delegate() {
return entries;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return unmodifiableEntryIterator(entries.iterator());
}
// See java.util.Collections.UnmodifiableEntrySet for details on attacks.
@Override
public Object[] toArray() {
return standardToArray();
}
@Override
public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
}
/** @see Maps#unmodifiableEntrySet(Set) */
@IteratorPattern.ConcreteAggregate(validationErrorLevel = ValidationErrorLevel.ERROR)
@DecoratorPattern.ConcreteDecorator(validationErrorLevel = ValidationErrorLevel.NONE)
static class UnmodifiableEntrySet<K, V> extends UnmodifiableEntries<K, V>
implements Set<Entry<K, V>> {
UnmodifiableEntrySet(Set<Entry<K, V>> entries) {
super(entries);
}
// See java.util.Collections.UnmodifiableEntrySet for details on attacks.
@Override
public boolean equals(@Nullable Object object) {
return Sets.equalsImpl(this, object);
}
@Override
public int hashCode() {
return Sets.hashCodeImpl(this);
}
}
/**
* Returns a {@link Converter} that converts values using {@link BiMap#get bimap.get()}, and whose
* inverse view converts values using {@link BiMap#inverse bimap.inverse()}{@code .get()}.
*
* <p>To use a plain {@link Map} as a {@link Function}, see {@link
* com.google.common.base.Functions#forMap(Map)} or {@link
* com.google.common.base.Functions#forMap(Map, Object)}.
*
* @since 16.0
*/
public static <A, B> Converter<A, B> asConverter(final BiMap<A, B> bimap) {
return new BiMapConverter<>(bimap);
}
private static final class BiMapConverter<A, B> extends Converter<A, B> implements Serializable {
private final BiMap<A, B> bimap;
BiMapConverter(BiMap<A, B> bimap) {
this.bimap = checkNotNull(bimap);
}
@Override
protected B doForward(A a) {
return convert(bimap, a);
}
@Override
protected A doBackward(B b) {
return convert(bimap.inverse(), b);
}
private static <X, Y> Y convert(BiMap<X, Y> bimap, X input) {
Y output = bimap.get(input);
checkArgument(output != null, "No non-null mapping present for input: %s", input);
return output;
}
@Override
public boolean equals(@Nullable Object object) {
if (object instanceof BiMapConverter) {
BiMapConverter<?, ?> that = (BiMapConverter<?, ?>) object;
return this.bimap.equals(that.bimap);
}
return false;
}
@Override
public int hashCode() {
return bimap.hashCode();
}
// There's really no good way to implement toString() without printing the entire BiMap, right?
@Override
public String toString() {
return "Maps.asConverter(" + bimap + ")";
}
private static final long serialVersionUID = 0L;
}
/**
* Returns a synchronized (thread-safe) bimap backed by the specified bimap. In order to guarantee
* serial access, it is critical that <b>all</b> access to the backing bimap is accomplished
* through the returned bimap.
*
* <p>It is imperative that the user manually synchronize on the returned map when accessing any
* of its collection views:
*
* <pre>{@code
* BiMap<Long, String> map = Maps.synchronizedBiMap(
* HashBiMap.<Long, String>create());
* ...
* Set<Long> set = map.keySet(); // Needn't be in synchronized block
* ...
* synchronized (map) { // Synchronizing on map, not set!
* Iterator<Long> it = set.iterator(); // Must be in synchronized block
* while (it.hasNext()) {
* foo(it.next());
* }
* }
* }</pre>
*
* <p>Failure to follow this advice may result in non-deterministic behavior.
*
* <p>The returned bimap will be serializable if the specified bimap is serializable.
*
* @param bimap the bimap to be wrapped in a synchronized view
* @return a synchronized view of the specified bimap
*/
public static <K, V> BiMap<K, V> synchronizedBiMap(BiMap<K, V> bimap) {
return Synchronized.biMap(bimap, null);
}
/**
* Returns an unmodifiable view of the specified bimap. This method allows modules to provide
* users with "read-only" access to internal bimaps. Query operations on the returned bimap "read
* through" to the specified bimap, and attempts to modify the returned map, whether direct or via
* its collection views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned bimap will be serializable if the specified bimap is serializable.
*
* @param bimap the bimap for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified bimap
*/
public static <K, V> BiMap<K, V> unmodifiableBiMap(BiMap<? extends K, ? extends V> bimap) {
return new UnmodifiableBiMap<>(bimap, null);
}
/** @see Maps#unmodifiableBiMap(BiMap) */
private static class UnmodifiableBiMap<K, V> extends ForwardingMap<K, V>
implements BiMap<K, V>, Serializable {
final Map<K, V> unmodifiableMap;
final BiMap<? extends K, ? extends V> delegate;
@RetainedWith @Nullable BiMap<V, K> inverse;
transient @Nullable Set<V> values;
UnmodifiableBiMap(BiMap<? extends K, ? extends V> delegate, @Nullable BiMap<V, K> inverse) {
unmodifiableMap = Collections.unmodifiableMap(delegate);
this.delegate = delegate;
this.inverse = inverse;
}
@Override
protected Map<K, V> delegate() {
return unmodifiableMap;
}
@Override
public V forcePut(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public BiMap<V, K> inverse() {
BiMap<V, K> result = inverse;
return (result == null)
? inverse = new UnmodifiableBiMap<>(delegate.inverse(), this)
: result;
}
@Override
public Set<V> values() {
Set<V> result = values;
return (result == null) ? values = Collections.unmodifiableSet(delegate.values()) : result;
}
private static final long serialVersionUID = 0;
}
/**
* Returns a view of a map where each value is transformed by a function. All other properties of
* the map, such as iteration order, are left intact. For example, the code:
*
* <pre>{@code
* Map<String, Integer> map = ImmutableMap.of("a", 4, "b", 9);
* Function<Integer, Double> sqrt =
* new Function<Integer, Double>() {
* public Double apply(Integer in) {
* return Math.sqrt((int) in);
* }
* };
* Map<String, Double> transformed = Maps.transformValues(map, sqrt);
* System.out.println(transformed);
* }</pre>
*
* ... prints {@code {a=2.0, b=3.0}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
* removal operations, and these are reflected in the underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys, and even null values provided
* that the function is capable of accepting null input. The transformed map might contain null
* values, if the function sometimes gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the underlying map is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary for the returned map
* to be a view, but it means that the function will be applied many times for bulk operations
* like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code
* function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a
* view, copy the returned map into a new map of your choosing.
*/
public static <K, V1, V2> Map<K, V2> transformValues(
Map<K, V1> fromMap, Function<? super V1, V2> function) {
return transformEntries(fromMap, asEntryTransformer(function));
}
/**
* Returns a view of a sorted map where each value is transformed by a function. All other
* properties of the map, such as iteration order, are left intact. For example, the code:
*
* <pre>{@code
* SortedMap<String, Integer> map = ImmutableSortedMap.of("a", 4, "b", 9);
* Function<Integer, Double> sqrt =
* new Function<Integer, Double>() {
* public Double apply(Integer in) {
* return Math.sqrt((int) in);
* }
* };
* SortedMap<String, Double> transformed =
* Maps.transformValues(map, sqrt);
* System.out.println(transformed);
* }</pre>
*
* ... prints {@code {a=2.0, b=3.0}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
* removal operations, and these are reflected in the underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys, and even null values provided
* that the function is capable of accepting null input. The transformed map might contain null
* values, if the function sometimes gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the underlying map is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary for the returned map
* to be a view, but it means that the function will be applied many times for bulk operations
* like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code
* function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a
* view, copy the returned map into a new map of your choosing.
*
* @since 11.0
*/
public static <K, V1, V2> SortedMap<K, V2> transformValues(
SortedMap<K, V1> fromMap, Function<? super V1, V2> function) {
return transformEntries(fromMap, asEntryTransformer(function));
}
/**
* Returns a view of a navigable map where each value is transformed by a function. All other
* properties of the map, such as iteration order, are left intact. For example, the code:
*
* <pre>{@code
* NavigableMap<String, Integer> map = Maps.newTreeMap();
* map.put("a", 4);
* map.put("b", 9);
* Function<Integer, Double> sqrt =
* new Function<Integer, Double>() {
* public Double apply(Integer in) {
* return Math.sqrt((int) in);
* }
* };
* NavigableMap<String, Double> transformed =
* Maps.transformNavigableValues(map, sqrt);
* System.out.println(transformed);
* }</pre>
*
* ... prints {@code {a=2.0, b=3.0}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
* removal operations, and these are reflected in the underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys, and even null values provided
* that the function is capable of accepting null input. The transformed map might contain null
* values, if the function sometimes gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the underlying map is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary for the returned map
* to be a view, but it means that the function will be applied many times for bulk operations
* like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code
* function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a
* view, copy the returned map into a new map of your choosing.
*
* @since 13.0
*/
@GwtIncompatible // NavigableMap
public static <K, V1, V2> NavigableMap<K, V2> transformValues(
NavigableMap<K, V1> fromMap, Function<? super V1, V2> function) {
return transformEntries(fromMap, asEntryTransformer(function));
}
/**
* Returns a view of a map whose values are derived from the original map's entries. In contrast
* to {@link #transformValues}, this method's entry-transformation logic may depend on the key as
* well as the value.
*
* <p>All other properties of the transformed map, such as iteration order, are left intact. For
* example, the code:
*
* <pre>{@code
* Map<String, Boolean> options =
* ImmutableMap.of("verbose", true, "sort", false);
* EntryTransformer<String, Boolean, String> flagPrefixer =
* new EntryTransformer<String, Boolean, String>() {
* public String transformEntry(String key, Boolean value) {
* return value ? key : "no" + key;
* }
* };
* Map<String, String> transformed =
* Maps.transformEntries(options, flagPrefixer);
* System.out.println(transformed);
* }</pre>
*
* ... prints {@code {verbose=verbose, sort=nosort}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
* removal operations, and these are reflected in the underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys and null values provided that
* the transformer is capable of accepting null inputs. The transformed map might contain null
* values if the transformer sometimes gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the underlying map is.
*
* <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned
* map to be a view, but it means that the transformer will be applied many times for bulk
* operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform
* well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map
* doesn't need to be a view, copy the returned map into a new map of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code
* EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of
* type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as
* {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the
* transformed map.
*
* @since 7.0
*/
public static <K, V1, V2> Map<K, V2> transformEntries(
Map<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesMap<>(fromMap, transformer);
}
/**
* Returns a view of a sorted map whose values are derived from the original sorted map's entries.
* In contrast to {@link #transformValues}, this method's entry-transformation logic may depend on
* the key as well as the value.
*
* <p>All other properties of the transformed map, such as iteration order, are left intact. For
* example, the code:
*
* <pre>{@code
* Map<String, Boolean> options =
* ImmutableSortedMap.of("verbose", true, "sort", false);
* EntryTransformer<String, Boolean, String> flagPrefixer =
* new EntryTransformer<String, Boolean, String>() {
* public String transformEntry(String key, Boolean value) {
* return value ? key : "yes" + key;
* }
* };
* SortedMap<String, String> transformed =
* Maps.transformEntries(options, flagPrefixer);
* System.out.println(transformed);
* }</pre>
*
* ... prints {@code {sort=yessort, verbose=verbose}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
* removal operations, and these are reflected in the underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys and null values provided that
* the transformer is capable of accepting null inputs. The transformed map might contain null
* values if the transformer sometimes gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the underlying map is.
*
* <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned
* map to be a view, but it means that the transformer will be applied many times for bulk
* operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform
* well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map
* doesn't need to be a view, copy the returned map into a new map of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code
* EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of
* type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as
* {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the
* transformed map.
*
* @since 11.0
*/
public static <K, V1, V2> SortedMap<K, V2> transformEntries(
SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesSortedMap<>(fromMap, transformer);
}
/**
* Returns a view of a navigable map whose values are derived from the original navigable map's
* entries. In contrast to {@link #transformValues}, this method's entry-transformation logic may
* depend on the key as well as the value.
*
* <p>All other properties of the transformed map, such as iteration order, are left intact. For
* example, the code:
*
* <pre>{@code
* NavigableMap<String, Boolean> options = Maps.newTreeMap();
* options.put("verbose", false);
* options.put("sort", true);
* EntryTransformer<String, Boolean, String> flagPrefixer =
* new EntryTransformer<String, Boolean, String>() {
* public String transformEntry(String key, Boolean value) {
* return value ? key : ("yes" + key);
* }
* };
* NavigableMap<String, String> transformed =
* LabsMaps.transformNavigableEntries(options, flagPrefixer);
* System.out.println(transformed);
* }</pre>
*
* ... prints {@code {sort=yessort, verbose=verbose}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
* removal operations, and these are reflected in the underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys and null values provided that
* the transformer is capable of accepting null inputs. The transformed map might contain null
* values if the transformer sometimes gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the underlying map is.
*
* <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned
* map to be a view, but it means that the transformer will be applied many times for bulk
* operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform
* well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map
* doesn't need to be a view, copy the returned map into a new map of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code
* EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of
* type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as
* {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the
* transformed map.
*
* @since 13.0
*/
@GwtIncompatible // NavigableMap
public static <K, V1, V2> NavigableMap<K, V2> transformEntries(
final NavigableMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesNavigableMap<>(fromMap, transformer);
}
/**
* A transformation of the value of a key-value pair, using both key and value as inputs. To apply
* the transformation to a map, use {@link Maps#transformEntries(Map, EntryTransformer)}.
*
* @param <K> the key type of the input and output entries
* @param <V1> the value type of the input entry
* @param <V2> the value type of the output entry
* @since 7.0
*/
@FunctionalInterface
public interface EntryTransformer<K, V1, V2> {
/**
* Determines an output value based on a key-value pair. This method is <i>generally
* expected</i>, but not absolutely required, to have the following properties:
*
* <ul>
* <li>Its execution does not cause any observable side effects.
* <li>The computation is <i>consistent with equals</i>; that is, {@link Objects#equal
* Objects.equal}{@code (k1, k2) &&} {@link Objects#equal}{@code (v1, v2)} implies that
* {@code Objects.equal(transformer.transform(k1, v1), transformer.transform(k2, v2))}.
* </ul>
*
* @throws NullPointerException if the key or value is null and this transformer does not accept
* null arguments
*/
V2 transformEntry(@Nullable K key, @Nullable V1 value);
}
/** Views a function as an entry transformer that ignores the entry key. */
static <K, V1, V2> EntryTransformer<K, V1, V2> asEntryTransformer(
final Function<? super V1, V2> function) {
checkNotNull(function);
return new EntryTransformer<K, V1, V2>() {
@Override
public V2 transformEntry(K key, V1 value) {
return function.apply(value);
}
};
}
static <K, V1, V2> Function<V1, V2> asValueToValueFunction(
final EntryTransformer<? super K, V1, V2> transformer, final K key) {
checkNotNull(transformer);
return new Function<V1, V2>() {
@Override
public V2 apply(@Nullable V1 v1) {
return transformer.transformEntry(key, v1);
}
};
}
/** Views an entry transformer as a function from {@code Entry} to values. */
static <K, V1, V2> Function<Entry<K, V1>, V2> asEntryToValueFunction(
final EntryTransformer<? super K, ? super V1, V2> transformer) {
checkNotNull(transformer);
return new Function<Entry<K, V1>, V2>() {
@Override
public V2 apply(Entry<K, V1> entry) {
return transformer.transformEntry(entry.getKey(), entry.getValue());
}
};
}
/** Returns a view of an entry transformed by the specified transformer. */
static <V2, K, V1> Entry<K, V2> transformEntry(
final EntryTransformer<? super K, ? super V1, V2> transformer, final Entry<K, V1> entry) {
checkNotNull(transformer);
checkNotNull(entry);
return new AbstractMapEntry<K, V2>() {
@Override
public K getKey() {
return entry.getKey();
}
@Override
public V2 getValue() {
return transformer.transformEntry(entry.getKey(), entry.getValue());
}
};
}
/** Views an entry transformer as a function from entries to entries. */
static <K, V1, V2> Function<Entry<K, V1>, Entry<K, V2>> asEntryToEntryFunction(
final EntryTransformer<? super K, ? super V1, V2> transformer) {
checkNotNull(transformer);
return new Function<Entry<K, V1>, Entry<K, V2>>() {
@Override
public Entry<K, V2> apply(final Entry<K, V1> entry) {
return transformEntry(transformer, entry);
}
};
}
static class TransformedEntriesMap<K, V1, V2> extends IteratorBasedAbstractMap<K, V2> {
final Map<K, V1> fromMap;
final EntryTransformer<? super K, ? super V1, V2> transformer;
TransformedEntriesMap(
Map<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
this.fromMap = checkNotNull(fromMap);
this.transformer = checkNotNull(transformer);
}
@Override
public int size() {
return fromMap.size();
}
@Override
public boolean containsKey(Object key) {
return fromMap.containsKey(key);
}
@Override
public @Nullable V2 get(@Nullable Object key) {
return getOrDefault(key, null);
}
// safe as long as the user followed the <b>Warning</b> in the javadoc
@SuppressWarnings("unchecked")
@Override
public @Nullable V2 getOrDefault(@Nullable Object key, @Nullable V2 defaultValue) {
V1 value = fromMap.get(key);
return (value != null || fromMap.containsKey(key))
? transformer.transformEntry((K) key, value)
: defaultValue;
}
// safe as long as the user followed the <b>Warning</b> in the javadoc
@SuppressWarnings("unchecked")
@Override
public V2 remove(Object key) {
return fromMap.containsKey(key)
? transformer.transformEntry((K) key, fromMap.remove(key))
: null;
}
@Override
public void clear() {
fromMap.clear();
}
@Override
public Set<K> keySet() {
return fromMap.keySet();
}
@Override
Iterator<Entry<K, V2>> entryIterator() {
return Iterators.transform(
fromMap.entrySet().iterator(), Maps.<K, V1, V2>asEntryToEntryFunction(transformer));
}
@Override
Spliterator<Entry<K, V2>> entrySpliterator() {
return CollectSpliterators.map(
fromMap.entrySet().spliterator(), Maps.<K, V1, V2>asEntryToEntryFunction(transformer));
}
@Override
public void forEach(BiConsumer<? super K, ? super V2> action) {
checkNotNull(action);
// avoids creating new Entry<K, V2> objects
fromMap.forEach((k, v1) -> action.accept(k, transformer.transformEntry(k, v1)));
}
@Override
public Collection<V2> values() {
return new Values<>(this);
}
}
static class TransformedEntriesSortedMap<K, V1, V2> extends TransformedEntriesMap<K, V1, V2>
implements SortedMap<K, V2> {
protected SortedMap<K, V1> fromMap() {
return (SortedMap<K, V1>) fromMap;
}
TransformedEntriesSortedMap(
SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
super(fromMap, transformer);
}
@Override
public Comparator<? super K> comparator() {
return fromMap().comparator();
}
@Override
public K firstKey() {
return fromMap().firstKey();
}
@Override
public SortedMap<K, V2> headMap(K toKey) {
return transformEntries(fromMap().headMap(toKey), transformer);
}
@Override
public K lastKey() {
return fromMap().lastKey();
}
@Override
public SortedMap<K, V2> subMap(K fromKey, K toKey) {
return transformEntries(fromMap().subMap(fromKey, toKey), transformer);
}
@Override
public SortedMap<K, V2> tailMap(K fromKey) {
return transformEntries(fromMap().tailMap(fromKey), transformer);
}
}
@GwtIncompatible // NavigableMap
private static class TransformedEntriesNavigableMap<K, V1, V2>
extends TransformedEntriesSortedMap<K, V1, V2> implements NavigableMap<K, V2> {
TransformedEntriesNavigableMap(
NavigableMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
super(fromMap, transformer);
}
@Override
public Entry<K, V2> ceilingEntry(K key) {
return transformEntry(fromMap().ceilingEntry(key));
}
@Override
public K ceilingKey(K key) {
return fromMap().ceilingKey(key);
}
@Override
public NavigableSet<K> descendingKeySet() {
return fromMap().descendingKeySet();
}
@Override
public NavigableMap<K, V2> descendingMap() {
return transformEntries(fromMap().descendingMap(), transformer);
}
@Override
public Entry<K, V2> firstEntry() {
return transformEntry(fromMap().firstEntry());
}
@Override
public Entry<K, V2> floorEntry(K key) {
return transformEntry(fromMap().floorEntry(key));
}
@Override
public K floorKey(K key) {
return fromMap().floorKey(key);
}
@Override
public NavigableMap<K, V2> headMap(K toKey) {
return headMap(toKey, false);
}
@Override
public NavigableMap<K, V2> headMap(K toKey, boolean inclusive) {
return transformEntries(fromMap().headMap(toKey, inclusive), transformer);
}
@Override
public Entry<K, V2> higherEntry(K key) {
return transformEntry(fromMap().higherEntry(key));
}
@Override
public K higherKey(K key) {
return fromMap().higherKey(key);
}
@Override
public Entry<K, V2> lastEntry() {
return transformEntry(fromMap().lastEntry());
}
@Override
public Entry<K, V2> lowerEntry(K key) {
return transformEntry(fromMap().lowerEntry(key));
}
@Override
public K lowerKey(K key) {
return fromMap().lowerKey(key);
}
@Override
public NavigableSet<K> navigableKeySet() {
return fromMap().navigableKeySet();
}
@Override
public Entry<K, V2> pollFirstEntry() {
return transformEntry(fromMap().pollFirstEntry());
}
@Override
public Entry<K, V2> pollLastEntry() {
return transformEntry(fromMap().pollLastEntry());
}
@Override
public NavigableMap<K, V2> subMap(
K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return transformEntries(
fromMap().subMap(fromKey, fromInclusive, toKey, toInclusive), transformer);
}
@Override
public NavigableMap<K, V2> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
@Override
public NavigableMap<K, V2> tailMap(K fromKey) {
return tailMap(fromKey, true);
}
@Override
public NavigableMap<K, V2> tailMap(K fromKey, boolean inclusive) {
return transformEntries(fromMap().tailMap(fromKey, inclusive), transformer);
}
private @Nullable Entry<K, V2> transformEntry(@Nullable Entry<K, V1> entry) {
return (entry == null) ? null : Maps.transformEntry(transformer, entry);
}
@Override
protected NavigableMap<K, V1> fromMap() {
return (NavigableMap<K, V1>) super.fromMap();
}
}
static <K> Predicate<Entry<K, ?>> keyPredicateOnEntries(Predicate<? super K> keyPredicate) {
return compose(keyPredicate, Maps.<K>keyFunction());
}
static <V> Predicate<Entry<?, V>> valuePredicateOnEntries(Predicate<? super V> valuePredicate) {
return compose(valuePredicate, Maps.<V>valueFunction());
}
/**
* Returns a map containing the mappings in {@code unfiltered} whose keys satisfy a predicate. The
* returned map is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and
* {@code putAll()} methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings whose keys satisfy the filter will be removed from the underlying
* map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
* {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
*/
public static <K, V> Map<K, V> filterKeys(
Map<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
checkNotNull(keyPredicate);
Predicate<Entry<K, ?>> entryPredicate = keyPredicateOnEntries(keyPredicate);
return (unfiltered instanceof AbstractFilteredMap)
? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate)
: new FilteredKeyMap<K, V>(checkNotNull(unfiltered), keyPredicate, entryPredicate);
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} whose keys satisfy a
* predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the
* other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and
* {@code putAll()} methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings whose keys satisfy the filter will be removed from the underlying
* map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
* {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
*
* @since 11.0
*/
public static <K, V> SortedMap<K, V> filterKeys(
SortedMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
// TODO(lowasser): Return a subclass of Maps.FilteredKeyMap for slightly better
// performance.
return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate));
}
/**
* Returns a navigable map containing the mappings in {@code unfiltered} whose keys satisfy a
* predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the
* other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and
* {@code putAll()} methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings whose keys satisfy the filter will be removed from the underlying
* map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
* {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
*
* @since 14.0
*/
@GwtIncompatible // NavigableMap
public static <K, V> NavigableMap<K, V> filterKeys(
NavigableMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
// TODO(lowasser): Return a subclass of Maps.FilteredKeyMap for slightly better
// performance.
return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate));
}
/**
* Returns a bimap containing the mappings in {@code unfiltered} whose keys satisfy a predicate.
* The returned bimap is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the bimap
* and its views. When given a key that doesn't satisfy the predicate, the bimap's {@code put()},
* {@code forcePut()} and {@code putAll()} methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
* bimap or its views, only mappings that satisfy the filter will be removed from the underlying
* bimap.
*
* <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every key in
* the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i>
* needed, it may be faster to copy the filtered bimap and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented
* at {@link Predicate#apply}.
*
* @since 14.0
*/
public static <K, V> BiMap<K, V> filterKeys(
BiMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
checkNotNull(keyPredicate);
return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate));
}
/**
* Returns a map containing the mappings in {@code unfiltered} whose values satisfy a predicate.
* The returned map is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()},
* {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings whose values satisfy the filter will be removed from the underlying
* map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented
* at {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
*/
public static <K, V> Map<K, V> filterValues(
Map<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} whose values satisfy a
* predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the
* other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()},
* {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings whose values satisfy the filter will be removed from the underlying
* map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented
* at {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
*
* @since 11.0
*/
public static <K, V> SortedMap<K, V> filterValues(
SortedMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* Returns a navigable map containing the mappings in {@code unfiltered} whose values satisfy a
* predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the
* other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()},
* {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings whose values satisfy the filter will be removed from the underlying
* map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented
* at {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
*
* @since 14.0
*/
@GwtIncompatible // NavigableMap
public static <K, V> NavigableMap<K, V> filterValues(
NavigableMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* Returns a bimap containing the mappings in {@code unfiltered} whose values satisfy a predicate.
* The returned bimap is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the bimap
* and its views. When given a value that doesn't satisfy the predicate, the bimap's {@code
* put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link
* IllegalArgumentException}. Similarly, the map's entries have a {@link Entry#setValue} method
* that throws an {@link IllegalArgumentException} when the provided value doesn't satisfy the
* predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
* bimap or its views, only mappings that satisfy the filter will be removed from the underlying
* bimap.
*
* <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every value in
* the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i>
* needed, it may be faster to copy the filtered bimap and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented
* at {@link Predicate#apply}.
*
* @since 14.0
*/
public static <K, V> BiMap<K, V> filterValues(
BiMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* Returns a map containing the mappings in {@code unfiltered} that satisfy a predicate. The
* returned map is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code
* put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the
* map's entries have a {@link Entry#setValue} method that throws an {@link
* IllegalArgumentException} when the existing key and the provided value don't satisfy the
* predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings that satisfy the filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented
* at {@link Predicate#apply}.
*/
public static <K, V> Map<K, V> filterEntries(
Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(entryPredicate);
return (unfiltered instanceof AbstractFilteredMap)
? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntryMap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} that satisfy a predicate.
* The returned map is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code
* put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the
* map's entries have a {@link Entry#setValue} method that throws an {@link
* IllegalArgumentException} when the existing key and the provided value don't satisfy the
* predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings that satisfy the filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented
* at {@link Predicate#apply}.
*
* @since 11.0
*/
public static <K, V> SortedMap<K, V> filterEntries(
SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(entryPredicate);
return (unfiltered instanceof FilteredEntrySortedMap)
? filterFiltered((FilteredEntrySortedMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntrySortedMap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} that satisfy a predicate.
* The returned map is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the map
* and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code
* put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the
* map's entries have a {@link Entry#setValue} method that throws an {@link
* IllegalArgumentException} when the existing key and the provided value don't satisfy the
* predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
* or its views, only mappings that satisfy the filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying map and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented
* at {@link Predicate#apply}.
*
* @since 14.0
*/
@GwtIncompatible // NavigableMap
public static <K, V> NavigableMap<K, V> filterEntries(
NavigableMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(entryPredicate);
return (unfiltered instanceof FilteredEntryNavigableMap)
? filterFiltered((FilteredEntryNavigableMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntryNavigableMap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Returns a bimap containing the mappings in {@code unfiltered} that satisfy a predicate. The
* returned bimap is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the bimap
* and its views. When given a key/value pair that doesn't satisfy the predicate, the bimap's
* {@code put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link
* IllegalArgumentException}. Similarly, the map's entries have an {@link Entry#setValue} method
* that throws an {@link IllegalArgumentException} when the existing key and the provided value
* don't satisfy the predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
* bimap or its views, only mappings that satisfy the filter will be removed from the underlying
* bimap.
*
* <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every key/value
* mapping in the underlying bimap and determine which satisfy the filter. When a live view is
* <i>not</i> needed, it may be faster to copy the filtered bimap and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented
* at {@link Predicate#apply}.
*
* @since 14.0
*/
public static <K, V> BiMap<K, V> filterEntries(
BiMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(unfiltered);
checkNotNull(entryPredicate);
return (unfiltered instanceof FilteredEntryBiMap)
? filterFiltered((FilteredEntryBiMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntryBiMap<K, V>(unfiltered, entryPredicate);
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered
* map.
*/
private static <K, V> Map<K, V> filterFiltered(
AbstractFilteredMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
return new FilteredEntryMap<>(
map.unfiltered, Predicates.<Entry<K, V>>and(map.predicate, entryPredicate));
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered
* sorted map.
*/
private static <K, V> SortedMap<K, V> filterFiltered(
FilteredEntrySortedMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate = Predicates.<Entry<K, V>>and(map.predicate, entryPredicate);
return new FilteredEntrySortedMap<>(map.sortedMap(), predicate);
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered
* navigable map.
*/
@GwtIncompatible // NavigableMap
private static <K, V> NavigableMap<K, V> filterFiltered(
FilteredEntryNavigableMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate =
Predicates.<Entry<K, V>>and(map.entryPredicate, entryPredicate);
return new FilteredEntryNavigableMap<>(map.unfiltered, predicate);
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered
* map.
*/
private static <K, V> BiMap<K, V> filterFiltered(
FilteredEntryBiMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate = Predicates.<Entry<K, V>>and(map.predicate, entryPredicate);
return new FilteredEntryBiMap<>(map.unfiltered(), predicate);
}
private abstract static class AbstractFilteredMap<K, V> extends ViewCachingAbstractMap<K, V> {
final Map<K, V> unfiltered;
final Predicate<? super Entry<K, V>> predicate;
AbstractFilteredMap(Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) {
this.unfiltered = unfiltered;
this.predicate = predicate;
}
boolean apply(@Nullable Object key, @Nullable V value) {
// This method is called only when the key is in the map, implying that
// key is a K.
@SuppressWarnings("unchecked")
K k = (K) key;
return predicate.apply(Maps.immutableEntry(k, value));
}
@Override
public V put(K key, V value) {
checkArgument(apply(key, value));
return unfiltered.put(key, value);
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
checkArgument(apply(entry.getKey(), entry.getValue()));
}
unfiltered.putAll(map);
}
@Override
public boolean containsKey(Object key) {
return unfiltered.containsKey(key) && apply(key, unfiltered.get(key));
}
@Override
public V get(Object key) {
V value = unfiltered.get(key);
return ((value != null) && apply(key, value)) ? value : null;
}
@Override
public boolean isEmpty() {
return entrySet().isEmpty();
}
@Override
public V remove(Object key) {
return containsKey(key) ? unfiltered.remove(key) : null;
}
@Override
Collection<V> createValues() {
return new FilteredMapValues<>(this, unfiltered, predicate);
}
}
@IteratorPattern.ConcreteAggregate(validationErrorLevel = ValidationErrorLevel.ERROR)
private static final class FilteredMapValues<K, V> extends Maps.Values<K, V> {
final Map<K, V> unfiltered;
final Predicate<? super Entry<K, V>> predicate;
FilteredMapValues(
Map<K, V> filteredMap, Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) {
super(filteredMap);
this.unfiltered = unfiltered;
this.predicate = predicate;
}
@Override
public boolean remove(Object o) {
Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator();
while (entryItr.hasNext()) {
Entry<K, V> entry = entryItr.next();
if (predicate.apply(entry) && Objects.equal(entry.getValue(), o)) {
entryItr.remove();
return true;
}
}
return false;
}
@Override
public boolean removeAll(Collection<?> collection) {
Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator();
boolean result = false;
while (entryItr.hasNext()) {
Entry<K, V> entry = entryItr.next();
if (predicate.apply(entry) && collection.contains(entry.getValue())) {
entryItr.remove();
result = true;
}
}
return result;
}
@Override
public boolean retainAll(Collection<?> collection) {
Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator();
boolean result = false;
while (entryItr.hasNext()) {
Entry<K, V> entry = entryItr.next();
if (predicate.apply(entry) && !collection.contains(entry.getValue())) {
entryItr.remove();
result = true;
}
}
return result;
}
@Override
public Object[] toArray() {
// creating an ArrayList so filtering happens once
return Lists.newArrayList(iterator()).toArray();
}
@Override
public <T> T[] toArray(T[] array) {
return Lists.newArrayList(iterator()).toArray(array);
}
}
private static class FilteredKeyMap<K, V> extends AbstractFilteredMap<K, V> {
final Predicate<? super K> keyPredicate;
FilteredKeyMap(
Map<K, V> unfiltered,
Predicate<? super K> keyPredicate,
Predicate<? super Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
this.keyPredicate = keyPredicate;
}
@Override
protected Set<Entry<K, V>> createEntrySet() {
return Sets.filter(unfiltered.entrySet(), predicate);
}
@Override
Set<K> createKeySet() {
return Sets.filter(unfiltered.keySet(), keyPredicate);
}
// The cast is called only when the key is in the unfiltered map, implying
// that key is a K.
@Override
@SuppressWarnings("unchecked")
public boolean containsKey(Object key) {
return unfiltered.containsKey(key) && keyPredicate.apply((K) key);
}
}
static class FilteredEntryMap<K, V> extends AbstractFilteredMap<K, V> {
/**
* Entries in this set satisfy the predicate, but they don't validate the input to {@code
* Entry.setValue()}.
*/
final Set<Entry<K, V>> filteredEntrySet;
FilteredEntryMap(Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
filteredEntrySet = Sets.filter(unfiltered.entrySet(), predicate);
}
@Override
protected Set<Entry<K, V>> createEntrySet() {
return new EntrySet();
}
@WeakOuter
private class EntrySet extends ForwardingSet<Entry<K, V>> {
@Override
protected Set<Entry<K, V>> delegate() {
return filteredEntrySet;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return new TransformedIterator<Entry<K, V>, Entry<K, V>>(filteredEntrySet.iterator()) {
@Override
Entry<K, V> transform(final Entry<K, V> entry) {
return new ForwardingMapEntry<K, V>() {
@Override
protected Entry<K, V> delegate() {
return entry;
}
@Override
public V setValue(V newValue) {
checkArgument(apply(getKey(), newValue));
return super.setValue(newValue);
}
};
}
};
}
}
@Override
Set<K> createKeySet() {
return new KeySet();
}
static <K, V> boolean removeAllKeys(
Map<K, V> map, Predicate<? super Entry<K, V>> entryPredicate, Collection<?> keyCollection) {
Iterator<Entry<K, V>> entryItr = map.entrySet().iterator();
boolean result = false;
while (entryItr.hasNext()) {
Entry<K, V> entry = entryItr.next();
if (entryPredicate.apply(entry) && keyCollection.contains(entry.getKey())) {
entryItr.remove();
result = true;
}
}
return result;
}
static <K, V> boolean retainAllKeys(
Map<K, V> map, Predicate<? super Entry<K, V>> entryPredicate, Collection<?> keyCollection) {
Iterator<Entry<K, V>> entryItr = map.entrySet().iterator();
boolean result = false;
while (entryItr.hasNext()) {
Entry<K, V> entry = entryItr.next();
if (entryPredicate.apply(entry) && !keyCollection.contains(entry.getKey())) {
entryItr.remove();
result = true;
}
}
return result;
}
@WeakOuter
class KeySet extends Maps.KeySet<K, V> {
KeySet() {
super(FilteredEntryMap.this);
}
@Override
public boolean remove(Object o) {
if (containsKey(o)) {
unfiltered.remove(o);
return true;
}
return false;
}
@Override
public boolean removeAll(Collection<?> collection) {
return removeAllKeys(unfiltered, predicate, collection);
}
@Override
public boolean retainAll(Collection<?> collection) {
return retainAllKeys(unfiltered, predicate, collection);
}
@Override
public Object[] toArray() {
// creating an ArrayList so filtering happens once
return Lists.newArrayList(iterator()).toArray();
}
@Override
public <T> T[] toArray(T[] array) {
return Lists.newArrayList(iterator()).toArray(array);
}
}
}
private static class FilteredEntrySortedMap<K, V> extends FilteredEntryMap<K, V>
implements SortedMap<K, V> {
FilteredEntrySortedMap(
SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
}
SortedMap<K, V> sortedMap() {
return (SortedMap<K, V>) unfiltered;
}
@Override
public SortedSet<K> keySet() {
return (SortedSet<K>) super.keySet();
}
@Override
SortedSet<K> createKeySet() {
return new SortedKeySet();
}
@WeakOuter
class SortedKeySet extends KeySet implements SortedSet<K> {
@Override
public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override
public SortedSet<K> subSet(K fromElement, K toElement) {
return (SortedSet<K>) subMap(fromElement, toElement).keySet();
}
@Override
public SortedSet<K> headSet(K toElement) {
return (SortedSet<K>) headMap(toElement).keySet();
}
@Override
public SortedSet<K> tailSet(K fromElement) {
return (SortedSet<K>) tailMap(fromElement).keySet();
}
@Override
public K first() {
return firstKey();
}
@Override
public K last() {
return lastKey();
}
}
@Override
public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override
public K firstKey() {
// correctly throws NoSuchElementException when filtered map is empty.
return keySet().iterator().next();
}
@Override
public K lastKey() {
SortedMap<K, V> headMap = sortedMap();
while (true) {
// correctly throws NoSuchElementException when filtered map is empty.
K key = headMap.lastKey();
if (apply(key, unfiltered.get(key))) {
return key;
}
headMap = sortedMap().headMap(key);
}
}
@Override
public SortedMap<K, V> headMap(K toKey) {
return new FilteredEntrySortedMap<>(sortedMap().headMap(toKey), predicate);
}
@Override
public SortedMap<K, V> subMap(K fromKey, K toKey) {
return new FilteredEntrySortedMap<>(sortedMap().subMap(fromKey, toKey), predicate);
}
@Override
public SortedMap<K, V> tailMap(K fromKey) {
return new FilteredEntrySortedMap<>(sortedMap().tailMap(fromKey), predicate);
}
}
@GwtIncompatible // NavigableMap
private static class FilteredEntryNavigableMap<K, V> extends AbstractNavigableMap<K, V> {
/*
* It's less code to extend AbstractNavigableMap and forward the filtering logic to
* FilteredEntryMap than to extend FilteredEntrySortedMap and reimplement all the NavigableMap
* methods.
*/
private final NavigableMap<K, V> unfiltered;
private final Predicate<? super Entry<K, V>> entryPredicate;
private final Map<K, V> filteredDelegate;
FilteredEntryNavigableMap(
NavigableMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
this.unfiltered = checkNotNull(unfiltered);
this.entryPredicate = entryPredicate;
this.filteredDelegate = new FilteredEntryMap<>(unfiltered, entryPredicate);
}
@Override
public Comparator<? super K> comparator() {
return unfiltered.comparator();
}
@Override
public NavigableSet<K> navigableKeySet() {
return new Maps.NavigableKeySet<K, V>(this) {
@Override
public boolean removeAll(Collection<?> collection) {
return FilteredEntryMap.removeAllKeys(unfiltered, entryPredicate, collection);
}
@Override
public boolean retainAll(Collection<?> collection) {
return FilteredEntryMap.retainAllKeys(unfiltered, entryPredicate, collection);
}
};
}
@Override
public Collection<V> values() {
return new FilteredMapValues<>(this, unfiltered, entryPredicate);
}
@Override
Iterator<Entry<K, V>> entryIterator() {
return Iterators.filter(unfiltered.entrySet().iterator(), entryPredicate);
}
@Override
Iterator<Entry<K, V>> descendingEntryIterator() {
return Iterators.filter(unfiltered.descendingMap().entrySet().iterator(), entryPredicate);
}
@Override
public int size() {
return filteredDelegate.size();
}
@Override
public boolean isEmpty() {
return !Iterables.any(unfiltered.entrySet(), entryPredicate);
}
@Override
public @Nullable V get(@Nullable Object key) {
return filteredDelegate.get(key);
}
@Override
public boolean containsKey(@Nullable Object key) {
return filteredDelegate.containsKey(key);
}
@Override
public V put(K key, V value) {
return filteredDelegate.put(key, value);
}
@Override
public V remove(@Nullable Object key) {
return filteredDelegate.remove(key);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
filteredDelegate.putAll(m);
}
@Override
public void clear() {
filteredDelegate.clear();
}
@Override
public Set<Entry<K, V>> entrySet() {
return filteredDelegate.entrySet();
}
@Override
public Entry<K, V> pollFirstEntry() {
return Iterables.removeFirstMatching(unfiltered.entrySet(), entryPredicate);
}
@Override
public Entry<K, V> pollLastEntry() {
return Iterables.removeFirstMatching(unfiltered.descendingMap().entrySet(), entryPredicate);
}
@Override
public NavigableMap<K, V> descendingMap() {
return filterEntries(unfiltered.descendingMap(), entryPredicate);
}
@Override
public NavigableMap<K, V> subMap(
K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return filterEntries(
unfiltered.subMap(fromKey, fromInclusive, toKey, toInclusive), entryPredicate);
}
@Override
public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
return filterEntries(unfiltered.headMap(toKey, inclusive), entryPredicate);
}
@Override
public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
return filterEntries(unfiltered.tailMap(fromKey, inclusive), entryPredicate);
}
}
static final class FilteredEntryBiMap<K, V> extends FilteredEntryMap<K, V>
implements BiMap<K, V> {
@RetainedWith private final BiMap<V, K> inverse;
private static <K, V> Predicate<Entry<V, K>> inversePredicate(
final Predicate<? super Entry<K, V>> forwardPredicate) {
return new Predicate<Entry<V, K>>() {
@Override
public boolean apply(Entry<V, K> input) {
return forwardPredicate.apply(Maps.immutableEntry(input.getValue(), input.getKey()));
}
};
}
FilteredEntryBiMap(BiMap<K, V> delegate, Predicate<? super Entry<K, V>> predicate) {
super(delegate, predicate);
this.inverse =
new FilteredEntryBiMap<>(delegate.inverse(), inversePredicate(predicate), this);
}
private FilteredEntryBiMap(
BiMap<K, V> delegate, Predicate<? super Entry<K, V>> predicate, BiMap<V, K> inverse) {
super(delegate, predicate);
this.inverse = inverse;
}
BiMap<K, V> unfiltered() {
return (BiMap<K, V>) unfiltered;
}
@Override
public V forcePut(@Nullable K key, @Nullable V value) {
checkArgument(apply(key, value));
return unfiltered().forcePut(key, value);
}
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
unfiltered()
.replaceAll(
(key, value) ->
predicate.apply(Maps.immutableEntry(key, value))
? function.apply(key, value)
: value);
}
@Override
public BiMap<V, K> inverse() {
return inverse;
}
@Override
public Set<V> values() {
return inverse.keySet();
}
}
/**
* Returns an unmodifiable view of the specified navigable map. Query operations on the returned
* map read through to the specified map, and attempts to modify the returned map, whether direct
* or via its views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned navigable map will be serializable if the specified navigable map is
* serializable.
*
* <p>This method's signature will not permit you to convert a {@code NavigableMap<? extends K,
* V>} to a {@code NavigableMap<K, V>}. If it permitted this, the returned map's {@code
* comparator()} method might return a {@code Comparator<? extends K>}, which works only on a
* particular subtype of {@code K}, but promise that it's a {@code Comparator<? super K>}, which
* must work on any type of {@code K}.
*
* @param map the navigable map for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified navigable map
* @since 12.0
*/
@GwtIncompatible // NavigableMap
public static <K, V> NavigableMap<K, V> unmodifiableNavigableMap(
NavigableMap<K, ? extends V> map) {
checkNotNull(map);
if (map instanceof UnmodifiableNavigableMap) {
@SuppressWarnings("unchecked") // covariant
NavigableMap<K, V> result = (NavigableMap<K, V>) map;
return result;
} else {
return new UnmodifiableNavigableMap<>(map);
}
}
private static <K, V> @Nullable Entry<K, V> unmodifiableOrNull(
@Nullable Entry<K, ? extends V> entry) {
return (entry == null) ? null : Maps.unmodifiableEntry(entry);
}
@GwtIncompatible // NavigableMap
static class UnmodifiableNavigableMap<K, V> extends ForwardingSortedMap<K, V>
implements NavigableMap<K, V>, Serializable {
private final NavigableMap<K, ? extends V> delegate;
UnmodifiableNavigableMap(NavigableMap<K, ? extends V> delegate) {
this.delegate = delegate;
}
UnmodifiableNavigableMap(
NavigableMap<K, ? extends V> delegate, UnmodifiableNavigableMap<K, V> descendingMap) {
this.delegate = delegate;
this.descendingMap = descendingMap;
}
@Override
protected SortedMap<K, V> delegate() {
return Collections.unmodifiableSortedMap(delegate);
}
@Override
public Entry<K, V> lowerEntry(K key) {
return unmodifiableOrNull(delegate.lowerEntry(key));
}
@Override
public K lowerKey(K key) {
return delegate.lowerKey(key);
}
@Override
public Entry<K, V> floorEntry(K key) {
return unmodifiableOrNull(delegate.floorEntry(key));
}
@Override
public K floorKey(K key) {
return delegate.floorKey(key);
}
@Override
public Entry<K, V> ceilingEntry(K key) {
return unmodifiableOrNull(delegate.ceilingEntry(key));
}
@Override
public K ceilingKey(K key) {
return delegate.ceilingKey(key);
}
@Override
public Entry<K, V> higherEntry(K key) {
return unmodifiableOrNull(delegate.higherEntry(key));
}
@Override
public K higherKey(K key) {
return delegate.higherKey(key);
}
@Override
public Entry<K, V> firstEntry() {
return unmodifiableOrNull(delegate.firstEntry());
}
@Override
public Entry<K, V> lastEntry() {
return unmodifiableOrNull(delegate.lastEntry());
}
@Override
public final Entry<K, V> pollFirstEntry() {
throw new UnsupportedOperationException();
}
@Override
public final Entry<K, V> pollLastEntry() {
throw new UnsupportedOperationException();
}
private transient @Nullable UnmodifiableNavigableMap<K, V> descendingMap;
@Override
public NavigableMap<K, V> descendingMap() {
UnmodifiableNavigableMap<K, V> result = descendingMap;
return (result == null)
? descendingMap = new UnmodifiableNavigableMap<>(delegate.descendingMap(), this)
: result;
}
@Override
public Set<K> keySet() {
return navigableKeySet();
}
@Override
public NavigableSet<K> navigableKeySet() {
return Sets.unmodifiableNavigableSet(delegate.navigableKeySet());
}
@Override
public NavigableSet<K> descendingKeySet() {
return Sets.unmodifiableNavigableSet(delegate.descendingKeySet());
}
@Override
public SortedMap<K, V> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
@Override
public NavigableMap<K, V> subMap(
K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return Maps.unmodifiableNavigableMap(
delegate.subMap(fromKey, fromInclusive, toKey, toInclusive));
}
@Override
public SortedMap<K, V> headMap(K toKey) {
return headMap(toKey, false);
}
@Override
public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
return Maps.unmodifiableNavigableMap(delegate.headMap(toKey, inclusive));
}
@Override
public SortedMap<K, V> tailMap(K fromKey) {
return tailMap(fromKey, true);
}
@Override
public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
return Maps.unmodifiableNavigableMap(delegate.tailMap(fromKey, inclusive));
}
}
/**
* Returns a synchronized (thread-safe) navigable map backed by the specified navigable map. In
* order to guarantee serial access, it is critical that <b>all</b> access to the backing
* navigable map is accomplished through the returned navigable map (or its views).
*
* <p>It is imperative that the user manually synchronize on the returned navigable map when
* iterating over any of its collection views, or the collections views of any of its {@code
* descendingMap}, {@code subMap}, {@code headMap} or {@code tailMap} views.
*
* <pre>{@code
* NavigableMap<K, V> map = synchronizedNavigableMap(new TreeMap<K, V>());
*
* // Needn't be in synchronized block
* NavigableSet<K> set = map.navigableKeySet();
*
* synchronized (map) { // Synchronizing on map, not set!
* Iterator<K> it = set.iterator(); // Must be in synchronized block
* while (it.hasNext()) {
* foo(it.next());
* }
* }
* }</pre>
*
* <p>or:
*
* <pre>{@code
* NavigableMap<K, V> map = synchronizedNavigableMap(new TreeMap<K, V>());
* NavigableMap<K, V> map2 = map.subMap(foo, false, bar, true);
*
* // Needn't be in synchronized block
* NavigableSet<K> set2 = map2.descendingKeySet();
*
* synchronized (map) { // Synchronizing on map, not map2 or set2!
* Iterator<K> it = set2.iterator(); // Must be in synchronized block
* while (it.hasNext()) {
* foo(it.next());
* }
* }
* }</pre>
*
* <p>Failure to follow this advice may result in non-deterministic behavior.
*
* <p>The returned navigable map will be serializable if the specified navigable map is
* serializable.
*
* @param navigableMap the navigable map to be "wrapped" in a synchronized navigable map.
* @return a synchronized view of the specified navigable map.
* @since 13.0
*/
@GwtIncompatible // NavigableMap
public static <K, V> NavigableMap<K, V> synchronizedNavigableMap(
NavigableMap<K, V> navigableMap) {
return Synchronized.navigableMap(navigableMap);
}
/**
* {@code AbstractMap} extension that makes it easy to cache customized keySet, values, and
* entrySet views.
*/
@IteratorPattern.Aggregate(validationErrorLevel = ValidationErrorLevel.NONE)
@GwtCompatible
abstract static class ViewCachingAbstractMap<K, V> extends AbstractMap<K, V> {
/**
* Creates the entry set to be returned by {@link #entrySet()}. This method is invoked at most
* once on a given map, at the time when {@code entrySet} is first called.
*/
abstract Set<Entry<K, V>> createEntrySet();
private transient @Nullable Set<Entry<K, V>> entrySet;
@Override
public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
return (result == null) ? entrySet = createEntrySet() : result;
}
private transient @Nullable Set<K> keySet;
@Override
public Set<K> keySet() {
Set<K> result = keySet;
return (result == null) ? keySet = createKeySet() : result;
}
Set<K> createKeySet() {
return new KeySet<>(this);
}
private transient @Nullable Collection<V> values;
@Override
public Collection<V> values() {
Collection<V> result = values;
return (result == null) ? values = createValues() : result;
}
Collection<V> createValues() {
return new Values<>(this);
}
}
@IteratorPattern.Aggregate(validationErrorLevel = ValidationErrorLevel.ERROR)
abstract static class IteratorBasedAbstractMap<K, V> extends AbstractMap<K, V> {
@Override
public abstract int size();
abstract Iterator<Entry<K, V>> entryIterator();
Spliterator<Entry<K, V>> entrySpliterator() {
return Spliterators.spliterator(
entryIterator(), size(), Spliterator.SIZED | Spliterator.DISTINCT);
}
@Override
public Set<Entry<K, V>> entrySet() {
return new EntrySet<K, V>() {
@Override
Map<K, V> map() {
return IteratorBasedAbstractMap.this;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return entryIterator();
}
@Override
public Spliterator<Entry<K, V>> spliterator() {
return entrySpliterator();
}
@Override
public void forEach(Consumer<? super Entry<K, V>> action) {
forEachEntry(action);
}
};
}
void forEachEntry(Consumer<? super Entry<K, V>> action) {
entryIterator().forEachRemaining(action);
}
@Override
public void clear() {
Iterators.clear(entryIterator());
}
}
/**
* Delegates to {@link Map#get}. Returns {@code null} on {@code ClassCastException} and {@code
* NullPointerException}.
*/
static <V> V safeGet(Map<?, V> map, @Nullable Object key) {
checkNotNull(map);
try {
return map.get(key);
} catch (ClassCastException | NullPointerException e) {
return null;
}
}
/**
* Delegates to {@link Map#containsKey}. Returns {@code false} on {@code ClassCastException} and
* {@code NullPointerException}.
*/
static boolean safeContainsKey(Map<?, ?> map, Object key) {
checkNotNull(map);
try {
return map.containsKey(key);
} catch (ClassCastException | NullPointerException e) {
return false;
}
}
/**
* Delegates to {@link Map#remove}. Returns {@code null} on {@code ClassCastException} and {@code
* NullPointerException}.
*/
static <V> V safeRemove(Map<?, V> map, Object key) {
checkNotNull(map);
try {
return map.remove(key);
} catch (ClassCastException | NullPointerException e) {
return null;
}
}
/** An admittedly inefficient implementation of {@link Map#containsKey}. */
static boolean containsKeyImpl(Map<?, ?> map, @Nullable Object key) {
return Iterators.contains(keyIterator(map.entrySet().iterator()), key);
}
/** An implementation of {@link Map#containsValue}. */
static boolean containsValueImpl(Map<?, ?> map, @Nullable Object value) {
return Iterators.contains(valueIterator(map.entrySet().iterator()), value);
}
/**
* Implements {@code Collection.contains} safely for forwarding collections of map entries. If
* {@code o} is an instance of {@code Entry}, it is wrapped using {@link #unmodifiableEntry} to
* protect against a possible nefarious equals method.
*
* <p>Note that {@code c} is the backing (delegate) collection, rather than the forwarding
* collection.
*
* @param c the delegate (unwrapped) collection of map entries
* @param o the object that might be contained in {@code c}
* @return {@code true} if {@code c} contains {@code o}
*/
static <K, V> boolean containsEntryImpl(Collection<Entry<K, V>> c, Object o) {
if (!(o instanceof Entry)) {
return false;
}
return c.contains(unmodifiableEntry((Entry<?, ?>) o));
}
/**
* Implements {@code Collection.remove} safely for forwarding collections of map entries. If
* {@code o} is an instance of {@code Entry}, it is wrapped using {@link #unmodifiableEntry} to
* protect against a possible nefarious equals method.
*
* <p>Note that {@code c} is backing (delegate) collection, rather than the forwarding collection.
*
* @param c the delegate (unwrapped) collection of map entries
* @param o the object to remove from {@code c}
* @return {@code true} if {@code c} was changed
*/
static <K, V> boolean removeEntryImpl(Collection<Entry<K, V>> c, Object o) {
if (!(o instanceof Entry)) {
return false;
}
return c.remove(unmodifiableEntry((Entry<?, ?>) o));
}
/** An implementation of {@link Map#equals}. */
static boolean equalsImpl(Map<?, ?> map, Object object) {
if (map == object) {
return true;
} else if (object instanceof Map) {
Map<?, ?> o = (Map<?, ?>) object;
return map.entrySet().equals(o.entrySet());
}
return false;
}
/** An implementation of {@link Map#toString}. */
static String toStringImpl(Map<?, ?> map) {
StringBuilder sb = Collections2.newStringBuilderForCollection(map.size()).append('{');
boolean first = true;
for (Entry<?, ?> entry : map.entrySet()) {
if (!first) {
sb.append(", ");
}
first = false;
sb.append(entry.getKey()).append('=').append(entry.getValue());
}
return sb.append('}').toString();
}
/** An implementation of {@link Map#putAll}. */
static <K, V> void putAllImpl(Map<K, V> self, Map<? extends K, ? extends V> map) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
self.put(entry.getKey(), entry.getValue());
}
}
@IteratorPattern.ConcreteAggregate(validationErrorLevel = ValidationErrorLevel.ERROR)
@DecoratorPattern.ConcreteDecorator(validationErrorLevel = ValidationErrorLevel.NONE)
static class KeySet<K, V> extends Sets.ImprovedAbstractSet<K> {
@Weak final Map<K, V> map;
KeySet(Map<K, V> map) {
this.map = checkNotNull(map);
}
Map<K, V> map() {
return map;
}
@Override
public Iterator<K> iterator() {
return keyIterator(map().entrySet().iterator());
}
@Override
public void forEach(Consumer<? super K> action) {
checkNotNull(action);
// avoids entry allocation for those maps that allocate entries on iteration
map.forEach((k, v) -> action.accept(k));
}
@Override
public int size() {
return map().size();
}
@Override
public boolean isEmpty() {
return map().isEmpty();
}
@Override
public boolean contains(Object o) {
return map().containsKey(o);
}
@Override
public boolean remove(Object o) {
if (contains(o)) {
map().remove(o);
return true;
}
return false;
}
@Override
public void clear() {
map().clear();
}
}
static <K> @Nullable K keyOrNull(@Nullable Entry<K, ?> entry) {
return (entry == null) ? null : entry.getKey();
}
static <V> @Nullable V valueOrNull(@Nullable Entry<?, V> entry) {
return (entry == null) ? null : entry.getValue();
}
@IteratorPattern.ConcreteAggregate(validationErrorLevel = ValidationErrorLevel.ERROR)
@DecoratorPattern.ConcreteDecorator(validationErrorLevel = ValidationErrorLevel.NONE)
static class SortedKeySet<K, V> extends KeySet<K, V> implements SortedSet<K> {
SortedKeySet(SortedMap<K, V> map) {
super(map);
}
@Override
SortedMap<K, V> map() {
return (SortedMap<K, V>) super.map();
}
@Override
public Comparator<? super K> comparator() {
return map().comparator();
}
@Override
public SortedSet<K> subSet(K fromElement, K toElement) {
return new SortedKeySet<>(map().subMap(fromElement, toElement));
}
@Override
public SortedSet<K> headSet(K toElement) {
return new SortedKeySet<>(map().headMap(toElement));
}
@Override
public SortedSet<K> tailSet(K fromElement) {
return new SortedKeySet<>(map().tailMap(fromElement));
}
@Override
public K first() {
return map().firstKey();
}
@Override
public K last() {
return map().lastKey();
}
}
@IteratorPattern.ConcreteAggregate(validationErrorLevel = ValidationErrorLevel.ERROR)
@DecoratorPattern.ConcreteDecorator(validationErrorLevel = ValidationErrorLevel.NONE)
@GwtIncompatible // NavigableMap
static class NavigableKeySet<K, V> extends SortedKeySet<K, V> implements NavigableSet<K> {
NavigableKeySet(NavigableMap<K, V> map) {
super(map);
}
@Override
NavigableMap<K, V> map() {
return (NavigableMap<K, V>) map;
}
@Override
public K lower(K e) {
return map().lowerKey(e);
}
@Override
public K floor(K e) {
return map().floorKey(e);
}
@Override
public K ceiling(K e) {
return map().ceilingKey(e);
}
@Override
public K higher(K e) {
return map().higherKey(e);
}
@Override
public K pollFirst() {
return keyOrNull(map().pollFirstEntry());
}
@Override
public K pollLast() {
return keyOrNull(map().pollLastEntry());
}
@Override
public NavigableSet<K> descendingSet() {
return map().descendingKeySet();
}
@Override
public Iterator<K> descendingIterator() {
return descendingSet().iterator();
}
@Override
public NavigableSet<K> subSet(
K fromElement, boolean fromInclusive, K toElement, boolean toInclusive) {
return map().subMap(fromElement, fromInclusive, toElement, toInclusive).navigableKeySet();
}
@Override
public SortedSet<K> subSet(K fromElement, K toElement) {
return subSet(fromElement, true, toElement, false);
}
@Override
public NavigableSet<K> headSet(K toElement, boolean inclusive) {
return map().headMap(toElement, inclusive).navigableKeySet();
}
@Override
public SortedSet<K> headSet(K toElement) {
return headSet(toElement, false);
}
@Override
public NavigableSet<K> tailSet(K fromElement, boolean inclusive) {
return map().tailMap(fromElement, inclusive).navigableKeySet();
}
@Override
public SortedSet<K> tailSet(K fromElement) {
return tailSet(fromElement, true);
}
}
@IteratorPattern.ConcreteAggregate(validationErrorLevel = ValidationErrorLevel.ERROR)
@DecoratorPattern.ConcreteDecorator(validationErrorLevel = ValidationErrorLevel.NONE)
static class Values<K, V> extends AbstractCollection<V> {
@Weak final Map<K, V> map;
Values(Map<K, V> map) {
this.map = checkNotNull(map);
}
final Map<K, V> map() {
return map;
}
@Override
public Iterator<V> iterator() {
return valueIterator(map().entrySet().iterator());
}
@Override
public void forEach(Consumer<? super V> action) {
checkNotNull(action);
// avoids allocation of entries for those maps that generate fresh entries on iteration
map.forEach((k, v) -> action.accept(v));
}
@Override
public boolean remove(Object o) {
try {
return super.remove(o);
} catch (UnsupportedOperationException e) {
for (Entry<K, V> entry : map().entrySet()) {
if (Objects.equal(o, entry.getValue())) {
map().remove(entry.getKey());
return true;
}
}
return false;
}
}
@Override
public boolean removeAll(Collection<?> c) {
try {
return super.removeAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
Set<K> toRemove = Sets.newHashSet();
for (Entry<K, V> entry : map().entrySet()) {
if (c.contains(entry.getValue())) {
toRemove.add(entry.getKey());
}
}
return map().keySet().removeAll(toRemove);
}
}
@Override
public boolean retainAll(Collection<?> c) {
try {
return super.retainAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
Set<K> toRetain = Sets.newHashSet();
for (Entry<K, V> entry : map().entrySet()) {
if (c.contains(entry.getValue())) {
toRetain.add(entry.getKey());
}
}
return map().keySet().retainAll(toRetain);
}
}
@Override
public int size() {
return map().size();
}
@Override
public boolean isEmpty() {
return map().isEmpty();
}
@Override
public boolean contains(@Nullable Object o) {
return map().containsValue(o);
}
@Override
public void clear() {
map().clear();
}
}
@IteratorPattern.Aggregate(validationErrorLevel = ValidationErrorLevel.ERROR)
abstract static class EntrySet<K, V> extends Sets.ImprovedAbstractSet<Entry<K, V>> {
abstract Map<K, V> map();
@Override
public int size() {
return map().size();
}
@Override
public void clear() {
map().clear();
}
@Override
public boolean contains(Object o) {
if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
Object key = entry.getKey();
V value = Maps.safeGet(map(), key);
return Objects.equal(value, entry.getValue()) && (value != null || map().containsKey(key));
}
return false;
}
@Override
public boolean isEmpty() {
return map().isEmpty();
}
@Override
public boolean remove(Object o) {
if (contains(o)) {
Entry<?, ?> entry = (Entry<?, ?>) o;
return map().keySet().remove(entry.getKey());
}
return false;
}
@Override
public boolean removeAll(Collection<?> c) {
try {
return super.removeAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
// if the iterators don't support remove
return Sets.removeAllImpl(this, c.iterator());
}
}
@Override
public boolean retainAll(Collection<?> c) {
try {
return super.retainAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
// if the iterators don't support remove
Set<Object> keys = Sets.newHashSetWithExpectedSize(c.size());
for (Object o : c) {
if (contains(o)) {
Entry<?, ?> entry = (Entry<?, ?>) o;
keys.add(entry.getKey());
}
}
return map().keySet().retainAll(keys);
}
}
}
@IteratorPattern.Aggregate(validationErrorLevel = ValidationErrorLevel.ERROR)
@DecoratorPattern.Decorator(validationErrorLevel = ValidationErrorLevel.NONE)
@GwtIncompatible // NavigableMap
abstract static class DescendingMap<K, V> extends ForwardingMap<K, V>
implements NavigableMap<K, V> {
abstract NavigableMap<K, V> forward();
@Override
protected final Map<K, V> delegate() {
return forward();
}
private transient @Nullable Comparator<? super K> comparator;
@SuppressWarnings("unchecked")
@Override
public Comparator<? super K> comparator() {
Comparator<? super K> result = comparator;
if (result == null) {
Comparator<? super K> forwardCmp = forward().comparator();
if (forwardCmp == null) {
forwardCmp = (Comparator) Ordering.natural();
}
result = comparator = reverse(forwardCmp);
}
return result;
}
// If we inline this, we get a javac error.
private static <T> Ordering<T> reverse(Comparator<T> forward) {
return Ordering.from(forward).reverse();
}
@Override
public K firstKey() {
return forward().lastKey();
}
@Override
public K lastKey() {
return forward().firstKey();
}
@Override
public Entry<K, V> lowerEntry(K key) {
return forward().higherEntry(key);
}
@Override
public K lowerKey(K key) {
return forward().higherKey(key);
}
@Override
public Entry<K, V> floorEntry(K key) {
return forward().ceilingEntry(key);
}
@Override
public K floorKey(K key) {
return forward().ceilingKey(key);
}
@Override
public Entry<K, V> ceilingEntry(K key) {
return forward().floorEntry(key);
}
@Override
public K ceilingKey(K key) {
return forward().floorKey(key);
}
@Override
public Entry<K, V> higherEntry(K key) {
return forward().lowerEntry(key);
}
@Override
public K higherKey(K key) {
return forward().lowerKey(key);
}
@Override
public Entry<K, V> firstEntry() {
return forward().lastEntry();
}
@Override
public Entry<K, V> lastEntry() {
return forward().firstEntry();
}
@Override
public Entry<K, V> pollFirstEntry() {
return forward().pollLastEntry();
}
@Override
public Entry<K, V> pollLastEntry() {
return forward().pollFirstEntry();
}
@Override
public NavigableMap<K, V> descendingMap() {
return forward();
}
private transient @Nullable Set<Entry<K, V>> entrySet;
@Override
public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
return (result == null) ? entrySet = createEntrySet() : result;
}
abstract Iterator<Entry<K, V>> entryIterator();
Set<Entry<K, V>> createEntrySet() {
@WeakOuter
class EntrySetImpl extends EntrySet<K, V> {
@Override
Map<K, V> map() {
return DescendingMap.this;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return entryIterator();
}
}
return new EntrySetImpl();
}
@Override
public Set<K> keySet() {
return navigableKeySet();
}
private transient @Nullable NavigableSet<K> navigableKeySet;
@Override
public NavigableSet<K> navigableKeySet() {
NavigableSet<K> result = navigableKeySet;
return (result == null) ? navigableKeySet = new NavigableKeySet<>(this) : result;
}
@Override
public NavigableSet<K> descendingKeySet() {
return forward().navigableKeySet();
}
@Override
public NavigableMap<K, V> subMap(
K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return forward().subMap(toKey, toInclusive, fromKey, fromInclusive).descendingMap();
}
@Override
public SortedMap<K, V> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
@Override
public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
return forward().tailMap(toKey, inclusive).descendingMap();
}
@Override
public SortedMap<K, V> headMap(K toKey) {
return headMap(toKey, false);
}
@Override
public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
return forward().headMap(fromKey, inclusive).descendingMap();
}
@Override
public SortedMap<K, V> tailMap(K fromKey) {
return tailMap(fromKey, true);
}
@Override
public Collection<V> values() {
return new Values<>(this);
}
@Override
public String toString() {
return standardToString();
}
}
/** Returns a map from the ith element of list to i. */
static <E> ImmutableMap<E, Integer> indexMap(Collection<E> list) {
ImmutableMap.Builder<E, Integer> builder = new ImmutableMap.Builder<>(list.size());
int i = 0;
for (E e : list) {
builder.put(e, i++);
}
return builder.build();
}
/**
* Returns a view of the portion of {@code map} whose keys are contained by {@code range}.
*
* <p>This method delegates to the appropriate methods of {@link NavigableMap} (namely {@link
* NavigableMap#subMap(Object, boolean, Object, boolean) subMap()}, {@link
* NavigableMap#tailMap(Object, boolean) tailMap()}, and {@link NavigableMap#headMap(Object,
* boolean) headMap()}) to actually construct the view. Consult these methods for a full
* description of the returned view's behavior.
*
* <p><b>Warning:</b> {@code Range}s always represent a range of values using the values' natural
* ordering. {@code NavigableMap} on the other hand can specify a custom ordering via a {@link
* Comparator}, which can violate the natural ordering. Using this method (or in general using
* {@code Range}) with unnaturally-ordered maps can lead to unexpected and undefined behavior.
*
* @since 20.0
*/
@Beta
@GwtIncompatible // NavigableMap
public static <K extends Comparable<? super K>, V> NavigableMap<K, V> subMap(
NavigableMap<K, V> map, Range<K> range) {
if (map.comparator() != null
&& map.comparator() != Ordering.natural()
&& range.hasLowerBound()
&& range.hasUpperBound()) {
checkArgument(
map.comparator().compare(range.lowerEndpoint(), range.upperEndpoint()) <= 0,
"map is using a custom comparator which is inconsistent with the natural ordering.");
}
if (range.hasLowerBound() && range.hasUpperBound()) {
return map.subMap(
range.lowerEndpoint(),
range.lowerBoundType() == BoundType.CLOSED,
range.upperEndpoint(),
range.upperBoundType() == BoundType.CLOSED);
} else if (range.hasLowerBound()) {
return map.tailMap(range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED);
} else if (range.hasUpperBound()) {
return map.headMap(range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED);
}
return checkNotNull(map);
}
}
|
package com.baerdev.ad.SW04_2.MultipleArrayHashSetTableTests;
import com.baerdev.ad.SW04_2.MultipleArrayHashSet.ArrayHashSetTable;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Iterator;
import static org.junit.Assert.*;
public class DumbHashSetTestsWithIterator {
@Test
@Category(ArrayHashSetTable.class)
public void addElmentThatNotExistsAndVerifyContains(){
ArrayHashSetTable<Integer> dumbHashSet = new ArrayHashSetTable<>();
dumbHashSet.add(23);
assertTrue(dumbHashSet.contains(23));
}
@Category(ArrayHashSetTable.class)
public void addElmentThatExists(){
ArrayHashSetTable<Integer> dumbHashSet = new ArrayHashSetTable<>();
dumbHashSet.add(23);
assertTrue(dumbHashSet.contains(23));
dumbHashSet.add(23);
assertTrue(dumbHashSet.contains(23));
dumbHashSet.remove(23);
assertTrue(dumbHashSet.contains(23));
dumbHashSet.remove(23);
assertFalse(dumbHashSet.contains(23));
}
@Test
@Category(ArrayHashSetTable.class)
public void addElmentThatNotExistsAndRemove(){
ArrayHashSetTable<Integer> dumbHashSet = new ArrayHashSetTable<>();
dumbHashSet.add(23);
assertTrue(dumbHashSet.contains(23));
dumbHashSet.remove(23);
assertFalse(dumbHashSet.contains(23));
}
@Test
@Category(ArrayHashSetTable.class)
public void fillArrayHashSetAndCheckIfItsFull(){
ArrayHashSetTable<Integer> dumbHashSet = new ArrayHashSetTable<>();
for (int count = 0; count < 10; count++){
dumbHashSet.add(count);
}
assertTrue(dumbHashSet.isFull());
}
@Test(expected = UnsupportedOperationException.class)
@Category(ArrayHashSetTable.class)
public void overfillArrayHashSetAndCheckIfItsFull(){
ArrayHashSetTable<Integer> dumbHashSet = new ArrayHashSetTable<>();
for (int count = 0; count < 12; count++){
dumbHashSet.add(count);
}
assertTrue(dumbHashSet.isFull());
}
@Test
@Category(ArrayHashSetTable.class)
public void checkArrayHashSetWhichIsNotFullAndCheckIfItsFull(){
ArrayHashSetTable<Integer> dumbHashSet = new ArrayHashSetTable<>();
for (int count = 0; count < 5; count++){
dumbHashSet.add(count);
}
assertFalse(dumbHashSet.isFull());
assertEquals(5, dumbHashSet.size());
}
@Test
@Category(ArrayHashSetTable.class)
public void getAllElementsFromTable(){
ArrayHashSetTable<Integer> dumbHashSet = new ArrayHashSetTable<>();
for (int count = 0; count < 5; count++){
dumbHashSet.add(count);
}
dumbHashSet.add(4);
dumbHashSet.add(8);
Iterator<Integer> dumbIterator = dumbHashSet.getIterator();
while (dumbIterator.hasNext()) {
Integer t = dumbIterator.next();
System.out.println(t);
}
}
}
|
package com.structurizr.model;
import com.structurizr.AbstractWorkspaceTestBase;
import org.junit.Test;
import java.util.Collections;
import java.util.Set;
import static org.junit.Assert.*;
public class ModelTests extends AbstractWorkspaceTestBase {
@Test(expected = IllegalArgumentException.class)
public void test_addSoftwareSystem_ThrowsAnException_WhenANullNameIsSpecified() {
model.addSoftwareSystem(null, "");
}
@Test(expected = IllegalArgumentException.class)
public void test_addSoftwareSystem_ThrowsAnException_WhenAnEmptyNameIsSpecified() {
model.addSoftwareSystem(" ", "");
}
@Test(expected = IllegalArgumentException.class)
public void test_addPerson_ThrowsAnException_WhenANullNameIsSpecified() {
model.addPerson(null, "");
}
@Test(expected = IllegalArgumentException.class)
public void test_addPerson_ThrowsAnException_WhenAnEmptyNameIsSpecified() {
model.addPerson(" ", "");
}
@Test
public void test_addSoftwareSystem_AddsTheSoftwareSystem_WhenASoftwareSystemDoesNotExistWithTheSameName() {
assertTrue(model.getSoftwareSystems().isEmpty());
SoftwareSystem softwareSystem = model.addSoftwareSystem(Location.External, "System A", "Some description");
assertEquals(1, model.getSoftwareSystems().size());
assertEquals(Location.External, softwareSystem.getLocation());
assertEquals("System A", softwareSystem.getName());
assertEquals("Some description", softwareSystem.getDescription());
assertEquals("1", softwareSystem.getId());
assertSame(softwareSystem, model.getSoftwareSystems().iterator().next());
}
@Test
public void test_addSoftwareSystem_ThrowsAnException_WhenASoftwareSystemExistsWithTheSameName() {
SoftwareSystem softwareSystem = model.addSoftwareSystem(Location.External, "System A", "Some description");
assertEquals(1, model.getSoftwareSystems().size());
try {
model.addSoftwareSystem(Location.External, "System A", "Description");
fail();
} catch (Exception e) {
assertEquals("A top-level element named 'System A' already exists.", e.getMessage());
}
}
@Test
public void test_addSoftwareSystemWithoutSpecifyingLocation_AddsTheSoftwareSystem_WhenASoftwareSystemDoesNotExistWithTheSameName() {
assertTrue(model.getSoftwareSystems().isEmpty());
SoftwareSystem softwareSystem = model.addSoftwareSystem("System A", "Some description");
assertEquals(1, model.getSoftwareSystems().size());
assertEquals(Location.Unspecified, softwareSystem.getLocation());
assertEquals("System A", softwareSystem.getName());
assertEquals("Some description", softwareSystem.getDescription());
assertEquals("1", softwareSystem.getId());
assertSame(softwareSystem, model.getSoftwareSystems().iterator().next());
}
@Test
public void test_addPerson_AddsThePerson_WhenAPersonDoesNotExistWithTheSameName() {
assertTrue(model.getPeople().isEmpty());
Person person = model.addPerson(Location.Internal, "Some internal user", "Some description");
assertEquals(1, model.getPeople().size());
assertEquals(Location.Internal, person.getLocation());
assertEquals("Some internal user", person.getName());
assertEquals("Some description", person.getDescription());
assertEquals("1", person.getId());
assertSame(person, model.getPeople().iterator().next());
}
@Test
public void test_addPerson_ThrowsAnException_WhenAPersonExistsWithTheSameName() {
Person person = model.addPerson(Location.Internal, "Admin User", "Description");
assertEquals(1, model.getPeople().size());
try {
model.addPerson(Location.External, "Admin User", "Description");
fail();
} catch (Exception e) {
assertEquals("A top-level element named 'Admin User' already exists.", e.getMessage());
}
}
@Test
public void test_addPerson_AddsThePersonWithoutSpecifyingTheLocation_WhenAPersonDoesNotExistWithTheSameName() {
assertTrue(model.getPeople().isEmpty());
Person person = model.addPerson("Some internal user", "Some description");
assertEquals(1, model.getPeople().size());
assertEquals(Location.Unspecified, person.getLocation());
assertEquals("Some internal user", person.getName());
assertEquals("Some description", person.getDescription());
assertEquals("1", person.getId());
assertSame(person, model.getPeople().iterator().next());
}
@Test
public void test_getElement_ReturnsNull_WhenAnElementWithTheSpecifiedIdDoesNotExist() {
assertNull(model.getElement("100"));
}
@Test
public void test_getElement_ReturnsAnElement_WhenAnElementWithTheSpecifiedIdDoesExist() {
Person person = model.addPerson(Location.Internal, "Name", "Description");
assertSame(person, model.getElement(person.getId()));
}
@Test
public void test_contains_ReturnsFalse_WhenTheSpecifiedElementIsNotInTheModel() {
Model newModel = new Model();
SoftwareSystem softwareSystem = newModel.addSoftwareSystem(Location.Unspecified, "Name", "Description");
assertFalse(model.contains(softwareSystem));
}
@Test
public void test_contains_ReturnsTrue_WhenTheSpecifiedElementIsInTheModel() {
SoftwareSystem softwareSystem = model.addSoftwareSystem(Location.Unspecified, "Name", "Description");
assertTrue(model.contains(softwareSystem));
}
@Test
public void test_getSoftwareSystemWithName_ReturnsNull_WhenASoftwareSystemWithTheSpecifiedNameDoesNotExist() {
assertNull(model.getSoftwareSystemWithName("System X"));
}
@Test
public void test_getSoftwareSystemWithName_ReturnsASoftwareSystem_WhenASoftwareSystemWithTheSpecifiedNameExists() {
SoftwareSystem softwareSystem = model.addSoftwareSystem(Location.External, "System A", "Description");
assertSame(softwareSystem, model.getSoftwareSystemWithName("System A"));
}
@Test
public void test_getSoftwareSystemWithId_ThrowsAnException_WhenPassedANullId() {
try {
model.getSoftwareSystemWithId(null);
fail();
} catch (IllegalArgumentException iae) {
assertEquals("A software system ID must be specified.", iae.getMessage());
}
}
@Test
public void test_getSoftwareSystemWithId_ThrowsAnException_WhenPassedAnEmptyId() {
try {
model.getSoftwareSystemWithId(" ");
fail();
} catch (IllegalArgumentException iae) {
assertEquals("A software system ID must be specified.", iae.getMessage());
}
}
@Test
public void test_getSoftwareSystemWithId_ReturnsNull_WhenASoftwareSystemWithTheSpecifiedIdDoesNotExist() {
assertNull(model.getSoftwareSystemWithId("100"));
}
@Test
public void test_getSoftwareSystemWithId_ReturnsASoftwareSystem_WhenASoftwareSystemWithTheSpecifiedIdDoesExist() {
SoftwareSystem softwareSystem = model.addSoftwareSystem(Location.External, "System A", "Description");
assertSame(softwareSystem, model.getSoftwareSystemWithId(softwareSystem.getId()));
}
@Test
public void test_getPersonWithName_ReturnsNull_WhenAPersonWithTheSpecifiedNameDoesNotExist() {
assertNull(model.getPersonWithName("Admin User"));
}
@Test
public void test_getPersonWithName_ReturnsAPerson_WhenAPersonWithTheSpecifiedNameExists() {
Person person = model.addPerson(Location.External, "Admin User", "Description");
assertSame(person, model.getPersonWithName("Admin User"));
}
@Test
public void test_getRelationship_ThrowsAnException_WhenPassedANullId() {
try {
model.getRelationship(null);
fail();
} catch (IllegalArgumentException iae) {
assertEquals("A relationship ID must be specified.", iae.getMessage());
}
}
@Test
public void test_getRelationship_ThrowsAnException_WhenPassedAnEmptyId() {
try {
model.getRelationship(" ");
fail();
} catch (IllegalArgumentException iae) {
assertEquals("A relationship ID must be specified.", iae.getMessage());
}
}
@Test
public void test_addRelationship_AddsARelationshipWithTheSpecifiedDescriptionAndTechnologyAndInteractionStyle() {
SoftwareSystem a = model.addSoftwareSystem("A", "");
SoftwareSystem b = model.addSoftwareSystem("B", "");
Relationship relationship = model.addRelationship(a, b, "Uses", "HTTPS", InteractionStyle.Asynchronous);
assertSame(a, relationship.getSource());
assertSame(b, relationship.getDestination());
assertEquals("Uses", relationship.getDescription());
assertEquals("HTTPS", relationship.getTechnology());
assertEquals(InteractionStyle.Asynchronous, relationship.getInteractionStyle());
assertTrue(model.getRelationships().contains(relationship));
}
@Test
public void test_addRelationship_DisallowsTheSameRelationshipToBeAddedMoreThanOnce() {
SoftwareSystem element1 = model.addSoftwareSystem("Element 1", "Description");
SoftwareSystem element2 = model.addSoftwareSystem("Element 2", "Description");
Relationship relationship1 = element1.uses(element2, "Uses", "");
Relationship relationship2 = element1.uses(element2, "Uses", "");
assertTrue(element1.has(relationship1));
assertNull(relationship2);
assertEquals(1, element1.getRelationships().size());
}
@Test
public void test_addRelationship_AllowsMultipleRelationshipsBetweenElements() {
SoftwareSystem element1 = model.addSoftwareSystem("Element 1", "Description");
SoftwareSystem element2 = model.addSoftwareSystem("Element 2", "Description");
Relationship relationship1 = element1.uses(element2, "Uses in some way", "");
Relationship relationship2 = element1.uses(element2, "Uses in another way", "");
assertTrue(element1.has(relationship1));
assertTrue(element1.has(relationship2));
assertEquals(2, element1.getRelationships().size());
}
@Test
public void test_addRelationship_ThrowsAnException_WhenTheDestinationIsAChildOfTheSource() {
SoftwareSystem softwareSystem = model.addSoftwareSystem("Software System", "");
Container container = softwareSystem.addContainer("Container", "", "");
Component component = container.addComponent("Component", "", "");
try {
softwareSystem.uses(container, "Uses");
fail();
} catch (IllegalArgumentException iae) {
assertEquals("Relationships cannot be added between parents and children.", iae.getMessage());
assertEquals(0, softwareSystem.getRelationships().size());
}
try {
container.uses(component, "Uses");
fail();
} catch (IllegalArgumentException iae) {
assertEquals("Relationships cannot be added between parents and children.", iae.getMessage());
assertEquals(0, softwareSystem.getRelationships().size());
}
try {
softwareSystem.uses(component, "Uses");
fail();
} catch (IllegalArgumentException iae) {
assertEquals("Relationships cannot be added between parents and children.", iae.getMessage());
assertEquals(0, softwareSystem.getRelationships().size());
}
}
@Test
public void test_addRelationship_ThrowsAnException_WhenTheSourceIsAChildOfTheDestination() {
SoftwareSystem softwareSystem = model.addSoftwareSystem("Software System", "");
Container container = softwareSystem.addContainer("Container", "", "");
Component component = container.addComponent("Component", "", "");
try {
container.uses(softwareSystem, "Uses");
fail();
} catch (IllegalArgumentException iae) {
assertEquals("Relationships cannot be added between parents and children.", iae.getMessage());
assertEquals(0, softwareSystem.getRelationships().size());
}
try {
component.uses(container, "Uses");
fail();
} catch (IllegalArgumentException iae) {
assertEquals("Relationships cannot be added between parents and children.", iae.getMessage());
assertEquals(0, softwareSystem.getRelationships().size());
}
try {
component.uses(softwareSystem, "Uses");
fail();
} catch (IllegalArgumentException iae) {
assertEquals("Relationships cannot be added between parents and children.", iae.getMessage());
assertEquals(0, softwareSystem.getRelationships().size());
}
}
@Test
public void test_modifyRelationship_ThrowsAnException_WhenARelationshipIsNotSpecified() {
try {
model.modifyRelationship(null, "Uses", "Technology");
fail();
} catch (IllegalArgumentException iae) {
assertEquals("A relationship must be specified.", iae.getMessage());
}
}
@Test
public void test_modifyRelationship_ModifiesAnExistingRelationship_WhenThatRelationshipDoesNotAlreadyExist() {
SoftwareSystem element1 = model.addSoftwareSystem("Element 1", "Description");
SoftwareSystem element2 = model.addSoftwareSystem("Element 2", "Description");
Relationship relationship = element1.uses(element2, "", "");
model.modifyRelationship(relationship, "Uses", "Technology");
assertEquals("Uses", relationship.getDescription());
assertEquals("Technology", relationship.getTechnology());
}
@Test
public void test_modifyRelationship_ThrowsAnException_WhenThatRelationshipDoesAlreadyExist() {
SoftwareSystem element1 = model.addSoftwareSystem("Element 1", "Description");
SoftwareSystem element2 = model.addSoftwareSystem("Element 2", "Description");
Relationship relationship = element1.uses(element2, "Uses", "Technology");
try {
model.modifyRelationship(relationship, "Uses", "Technology");
fail();
} catch (IllegalArgumentException iae) {
assertEquals("A relationship named \"Uses\" between \"Element 1\" and \"Element 2\" already exists.", iae.getMessage());
}
}
@Test
public void test_addImplicitRelationships_WhenSourceAndDestinationAreComponentsInDifferentSoftwareSystems() {
SoftwareSystem a = model.addSoftwareSystem("A", "");
Container aa = a.addContainer("AA", "", "");
Component aaa = aa.addComponent("AAA", "", "");
SoftwareSystem b = model.addSoftwareSystem("B", "");
Container bb = b.addContainer("BB", "", "");
Component bbb = bb.addComponent("BBB", "", "");
aaa.uses(bbb, "Uses");
assertEquals(1, model.getRelationships().size());
assertTrue(aaa.hasEfferentRelationshipWith(bbb));
// AAA->BBB implies AAA->BB AAA->B AA->BBB AA->BB AA->B A->BBB A->BB A->B
Set<Relationship> implicitRelationships = model.addImplicitRelationships();
assertEquals(9, model.getRelationships().size());
assertEquals(8, implicitRelationships.size());
assertTrue(aaa.hasEfferentRelationshipWith(bb));
assertTrue(aaa.hasEfferentRelationshipWith(b));
assertTrue(aa.hasEfferentRelationshipWith(bbb));
assertTrue(aa.hasEfferentRelationshipWith(bb));
assertTrue(aa.hasEfferentRelationshipWith(b));
assertTrue(a.hasEfferentRelationshipWith(bbb));
assertTrue(a.hasEfferentRelationshipWith(bb));
assertTrue(a.hasEfferentRelationshipWith(b));
}
@Test
public void test_addImplicitRelationships_WhenSourceIsAComponentAndDestinationIsAContainerInADifferentSoftwareSystem() {
SoftwareSystem a = model.addSoftwareSystem("A", "");
Container aa = a.addContainer("AA", "", "");
Component aaa = aa.addComponent("AAA", "", "");
SoftwareSystem b = model.addSoftwareSystem("B", "");
Container bb = b.addContainer("BB", "", "");
aaa.uses(bb, "Uses");
assertEquals(1, model.getRelationships().size());
assertTrue(aaa.hasEfferentRelationshipWith(bb));
// AAA->BB implies AAA->B AA->BB AA->B A->BB A->B
Set<Relationship> implicitRelationships = model.addImplicitRelationships();
assertEquals(6, model.getRelationships().size());
assertEquals(5, implicitRelationships.size());
assertTrue(aaa.hasEfferentRelationshipWith(b));
assertTrue(aa.hasEfferentRelationshipWith(bb));
assertTrue(aa.hasEfferentRelationshipWith(b));
assertTrue(a.hasEfferentRelationshipWith(bb));
assertTrue(a.hasEfferentRelationshipWith(b));
}
@Test
public void test_addImplicitRelationships_WhenSourceIsAComponentAndDestinationIsADifferentSoftwareSystem() {
SoftwareSystem a = model.addSoftwareSystem("A", "");
Container aa = a.addContainer("AA", "", "");
Component aaa = aa.addComponent("AAA", "", "");
SoftwareSystem b = model.addSoftwareSystem("B", "");
aaa.uses(b, "Uses");
assertEquals(1, model.getRelationships().size());
assertTrue(aaa.hasEfferentRelationshipWith(b));
// AAA->B implies AA->B A->B
Set<Relationship> implicitRelationships = model.addImplicitRelationships();
assertEquals(3, model.getRelationships().size());
assertEquals(2, implicitRelationships.size());
assertTrue(aa.hasEfferentRelationshipWith(b));
assertTrue(a.hasEfferentRelationshipWith(b));
}
@Test
public void test_addImplicitRelationships_WhenSourceIsAContainerAndDestinationIsAComponentInADifferentSoftwareSystem() {
SoftwareSystem a = model.addSoftwareSystem("A", "");
Container aa = a.addContainer("AA", "", "");
SoftwareSystem b = model.addSoftwareSystem("B", "");
Container bb = b.addContainer("BB", "", "");
Component bbb = bb.addComponent("BBB", "", "");
aa.uses(bbb, "Uses");
assertEquals(1, model.getRelationships().size());
assertTrue(aa.hasEfferentRelationshipWith(bbb));
// AA->BBB implies AA->BB AA->B A->BBB A->BB A->B
Set<Relationship> implicitRelationships = model.addImplicitRelationships();
assertEquals(6, model.getRelationships().size());
assertEquals(5, implicitRelationships.size());
assertTrue(aa.hasEfferentRelationshipWith(bb));
assertTrue(aa.hasEfferentRelationshipWith(b));
assertTrue(a.hasEfferentRelationshipWith(bbb));
assertTrue(a.hasEfferentRelationshipWith(bb));
assertTrue(a.hasEfferentRelationshipWith(b));
}
@Test
public void test_addImplicitRelationships_WhenSourceAndDestinationAreContainersInDifferentSoftwareSystems() {
SoftwareSystem a = model.addSoftwareSystem("A", "");
Container aa = a.addContainer("AA", "", "");
SoftwareSystem b = model.addSoftwareSystem("B", "");
Container bb = b.addContainer("BB", "", "");
aa.uses(bb, "Uses");
assertEquals(1, model.getRelationships().size());
assertTrue(aa.hasEfferentRelationshipWith(bb));
// AA->BB implies AA->B A->BB A->B
Set<Relationship> implicitRelationships = model.addImplicitRelationships();
assertEquals(4, model.getRelationships().size());
assertEquals(3, implicitRelationships.size());
assertTrue(aa.hasEfferentRelationshipWith(b));
assertTrue(a.hasEfferentRelationshipWith(bb));
assertTrue(a.hasEfferentRelationshipWith(b));
}
@Test
public void test_addImplicitRelationships_WhenSourceIsAContainerAndDestinationIsADifferentSoftwareSystem() {
SoftwareSystem a = model.addSoftwareSystem("A", "");
Container aa = a.addContainer("AA", "", "");
SoftwareSystem b = model.addSoftwareSystem("B", "");
aa.uses(b, "Uses");
assertEquals(1, model.getRelationships().size());
assertTrue(aa.hasEfferentRelationshipWith(b));
// AA->B implies A->B
Set<Relationship> implicitRelationships = model.addImplicitRelationships();
assertEquals(2, model.getRelationships().size());
assertEquals(1, implicitRelationships.size());
assertTrue(a.hasEfferentRelationshipWith(b));
}
@Test
public void test_addImplicitRelationships_WhenSourceIsASoftwareSystemAndDestinationIsAComponentInADifferentSoftwareSystem() {
SoftwareSystem a = model.addSoftwareSystem("A", "");
SoftwareSystem b = model.addSoftwareSystem("B", "");
Container bb = b.addContainer("BB", "", "");
Component bbb = bb.addComponent("BBB", "", "");
a.uses(bbb, "Uses");
assertEquals(1, model.getRelationships().size());
assertTrue(a.hasEfferentRelationshipWith(bbb));
// A->BBB implies A->BB A->B
Set<Relationship> implicitRelationships = model.addImplicitRelationships();
assertEquals(3, model.getRelationships().size());
assertEquals(2, implicitRelationships.size());
assertTrue(a.hasEfferentRelationshipWith(bb));
assertTrue(a.hasEfferentRelationshipWith(b));
}
@Test
public void test_addImplicitRelationships_WhenSourceIsASoftwareSystemAndDestinationIsAContainerInADifferentSoftwareSystem() {
SoftwareSystem a = model.addSoftwareSystem("A", "");
SoftwareSystem b = model.addSoftwareSystem("B", "");
Container bb = b.addContainer("BB", "", "");
a.uses(bb, "Uses");
assertEquals(1, model.getRelationships().size());
assertTrue(a.hasEfferentRelationshipWith(bb));
// A->BB implies A->B
Set<Relationship> implicitRelationships = model.addImplicitRelationships();
assertEquals(2, model.getRelationships().size());
assertEquals(1, implicitRelationships.size());
assertTrue(a.hasEfferentRelationshipWith(b));
}
@Test
public void test_addImplicitRelationships_WhenSourceAndDestinationAreDifferentSoftwareSystems() {
SoftwareSystem a = model.addSoftwareSystem("A", "");
SoftwareSystem b = model.addSoftwareSystem("B", "");
a.uses(b, "Uses");
assertEquals(1, model.getRelationships().size());
assertTrue(a.hasEfferentRelationshipWith(b));
Set<Relationship> implicitRelationships = model.addImplicitRelationships();
assertEquals(1, model.getRelationships().size());
assertEquals(0, implicitRelationships.size());
}
@Test
public void test_addImplicitRelationships_WhenSourceAndDestinationAreComponentsInTheSameContainer() {
SoftwareSystem a = model.addSoftwareSystem("A", "");
Container aa = a.addContainer("AA", "", "");
Component aaa1 = aa.addComponent("AAA1", "", "");
Component aaa2 = aa.addComponent("AAA2", "", "");
aaa1.uses(aaa2, "Uses");
assertEquals(1, model.getRelationships().size());
assertTrue(aaa1.hasEfferentRelationshipWith(aaa2));
Set<Relationship> implicitRelationships = model.addImplicitRelationships();
assertEquals(1, model.getRelationships().size());
assertEquals(0, implicitRelationships.size());
}
@Test
public void test_addImplicitRelationships_WhenSourceAndDestinationAreContainersInTheSameContainer() {
SoftwareSystem a = model.addSoftwareSystem("A", "");
Container aa1 = a.addContainer("AA1", "", "");
Container aa2 = a.addContainer("AA2", "", "");
aa1.uses(aa2, "Uses");
assertEquals(1, model.getRelationships().size());
assertTrue(aa1.hasEfferentRelationshipWith(aa2));
Set<Relationship> implicitRelationships = model.addImplicitRelationships();
assertEquals(1, model.getRelationships().size());
assertEquals(0, implicitRelationships.size());
}
@Test
public void test_addImplicitRelationships_WhenSourceAndDestinationAreComponentsInTheDifferentContainersInTheSameSoftwareSystem() {
SoftwareSystem a = model.addSoftwareSystem("A", "");
Container aa1 = a.addContainer("AA1", "", "");
Container aa2 = a.addContainer("AA2", "", "");
Component aaa1 = aa1.addComponent("AAA1", "", "");
Component aaa2 = aa2.addComponent("AAA2", "", "");
aaa1.uses(aaa2, "Uses");
assertEquals(1, model.getRelationships().size());
assertTrue(aaa1.hasEfferentRelationshipWith(aaa2));
// AAA1->AAA2 implies AAA1->AA2 AA1->AAA2 AA1->AA2
Set<Relationship> implicitRelationships = model.addImplicitRelationships();
assertEquals(4, model.getRelationships().size());
assertEquals(3, implicitRelationships.size());
assertTrue(aaa1.hasEfferentRelationshipWith(aa2));
assertTrue(aa1.hasEfferentRelationshipWith(aaa2));
assertTrue(aa1.hasEfferentRelationshipWith(aa2));
}
@Test
public void test_addSoftwareSystemInstance_ThrowsAnException_WhenANullSoftwareSystemIsSpecified() {
try {
DeploymentNode deploymentNode = model.addDeploymentNode("Deployment Node", "Description", "Technology");
deploymentNode.add((SoftwareSystem) null);
fail();
} catch (Exception e) {
assertEquals("A software system must be specified.", e.getMessage());
}
}
@Test
public void test_addContainerInstance_ThrowsAnException_WhenANullContainerIsSpecified() {
try {
DeploymentNode deploymentNode = model.addDeploymentNode("Deployment Node", "Description", "Technology");
deploymentNode.add((Container)null);
fail();
} catch (Exception e) {
assertEquals("A container must be specified.", e.getMessage());
}
}
@Test
public void test_addDeploymentNode_AddsADeploymentNode_WhenADeploymentEnvironmentIsNotSpecified() {
DeploymentNode deploymentNode = model.addDeploymentNode("Deployment Node", "Description", "Technology");
assertEquals("Deployment Node", deploymentNode.getName());
assertEquals("Description", deploymentNode.getDescription());
assertEquals("Technology", deploymentNode.getTechnology());
assertEquals("Default", deploymentNode.getEnvironment());
}
@Test
public void test_addDeploymentNode_AddsADeploymentNode_WhenADeploymentEnvironmentIsSpecified() {
DeploymentNode deploymentNode = model.addDeploymentNode("Development", "Deployment Node", "Description", "Technology");
assertEquals("Deployment Node", deploymentNode.getName());
assertEquals("Description", deploymentNode.getDescription());
assertEquals("Technology", deploymentNode.getTechnology());
assertEquals("Development", deploymentNode.getEnvironment());
}
@Test
public void test_addElementInstance_AddsElementInstancesAndReplicatesRelationshipsWithinTheDeploymentEnvironment() {
SoftwareSystem softwareSystem1 = model.addSoftwareSystem("Software System 1", "Description");
Container container1 = softwareSystem1.addContainer("Container 1", "Description", "Technology");
SoftwareSystem softwareSystem2 = model.addSoftwareSystem("Software System 2", "Description");
Container container2 = softwareSystem2.addContainer("Container 2", "Description", "Technology");
SoftwareSystem softwareSystem3 = model.addSoftwareSystem("Software System 3", "Description");
Container container3 = softwareSystem3.addContainer("Container 3", "Description", "Technology");
SoftwareSystem softwareSystem4 = model.addSoftwareSystem("Software System 4", "Description");
container1.uses(container2, "Uses 1", "Technology 1", InteractionStyle.Synchronous);
container2.uses(container3, "Uses 2", "Technology 2", InteractionStyle.Asynchronous);
container3.uses(softwareSystem4, "Uses");
DeploymentNode developmentDeploymentNode = model.addDeploymentNode("Development", "Deployment Node", "Description", "Technology");
ContainerInstance containerInstance1 = developmentDeploymentNode.add(container1);
ContainerInstance containerInstance2 = developmentDeploymentNode.add(container2);
ContainerInstance containerInstance3 = developmentDeploymentNode.add(container3);
SoftwareSystemInstance softwareSystemInstance = developmentDeploymentNode.add(softwareSystem4);
// the following live element instances should not affect the relationships of the development element instances
DeploymentNode liveDeploymentNode = model.addDeploymentNode("Live", "Deployment Node", "Description", "Technology");
liveDeploymentNode.add(container1);
liveDeploymentNode.add(container2);
liveDeploymentNode.add(container3);
liveDeploymentNode.add(softwareSystem4);
assertEquals(1, containerInstance1.getRelationships().size());
Relationship relationship = containerInstance1.getRelationships().iterator().next();
assertSame(containerInstance1, relationship.getSource());
assertSame(containerInstance2, relationship.getDestination());
assertEquals("Uses 1", relationship.getDescription());
assertEquals("Technology 1", relationship.getTechnology());
assertEquals(InteractionStyle.Synchronous, relationship.getInteractionStyle());
assertEquals("", relationship.getTags());
assertEquals(1, containerInstance2.getRelationships().size());
relationship = containerInstance2.getRelationships().iterator().next();
assertSame(containerInstance2, relationship.getSource());
assertSame(containerInstance3, relationship.getDestination());
assertEquals("Uses 2", relationship.getDescription());
assertEquals("Technology 2", relationship.getTechnology());
assertEquals(InteractionStyle.Asynchronous, relationship.getInteractionStyle());
assertEquals("", relationship.getTags());
assertEquals(1, containerInstance3.getRelationships().size());
relationship = containerInstance3.getRelationships().iterator().next();
assertSame(containerInstance3, relationship.getSource());
assertSame(softwareSystemInstance, relationship.getDestination());
assertEquals("Uses", relationship.getDescription());
assertNull(relationship.getTechnology());
assertNull(relationship.getInteractionStyle());
assertEquals("", relationship.getTags());
}
@Test
public void test_addElementInstance_AddsElementInstancesAndReplicatesRelationshipsWithinTheDeploymentEnvironmentAndDefaultGroup() {
SoftwareSystem softwareSystem1 = model.addSoftwareSystem("Software System");
Container api = softwareSystem1.addContainer("API");
Container database = softwareSystem1.addContainer("Database");
api.uses(database, "Uses");
DeploymentNode liveDeploymentNode = model.addDeploymentNode("Live", "Deployment Node", "Description", "Technology");
ContainerInstance apiInstance1 = liveDeploymentNode.add(api);
ContainerInstance databaseInstance1 = liveDeploymentNode.add(database);
ContainerInstance apiInstance2 = liveDeploymentNode.add(api);
ContainerInstance databaseInstance2 = liveDeploymentNode.add(database);
assertEquals(2, apiInstance1.getRelationships().size());
assertEquals(2, apiInstance2.getRelationships().size());
// apiInstance1 -> databaseInstance1
Relationship relationship = apiInstance1.getEfferentRelationshipWith(databaseInstance1);
assertEquals("Uses", relationship.getDescription());
// apiInstance1 -> databaseInstance2
relationship = apiInstance1.getEfferentRelationshipWith(databaseInstance2);
assertEquals("Uses", relationship.getDescription());
// apiInstance2 -> databaseInstance1
relationship = apiInstance2.getEfferentRelationshipWith(databaseInstance1);
assertEquals("Uses", relationship.getDescription());
// apiInstance2 -> databaseInstance2
relationship = apiInstance2.getEfferentRelationshipWith(databaseInstance2);
assertEquals("Uses", relationship.getDescription());
}
@Test
public void test_addElementInstance_AddsElementInstancesAndReplicatesRelationshipsWithinTheDeploymentEnvironmentAndSpecifiedGroup() {
// in this test, container instances are added to two deployment groups: "Service 1" and "Service 2"
// relationships are not replicated between element instances in other groups
SoftwareSystem softwareSystem1 = model.addSoftwareSystem("Software System");
Container api = softwareSystem1.addContainer("API");
Container database = softwareSystem1.addContainer("Database");
api.uses(database, "Uses");
DeploymentNode liveDeploymentNode = model.addDeploymentNode("Live", "Deployment Node", "Description", "Technology");
ContainerInstance apiInstance1 = liveDeploymentNode.add(api, "Service 1");
ContainerInstance databaseInstance1 = liveDeploymentNode.add(database, "Service 1");
ContainerInstance apiInstance2 = liveDeploymentNode.add(api, "Service 2");
ContainerInstance databaseInstance2 = liveDeploymentNode.add(database, "Service 2");
assertEquals(1, apiInstance1.getRelationships().size());
assertEquals(1, apiInstance2.getRelationships().size());
// apiInstance1 -> databaseInstance1
Relationship relationship = apiInstance1.getEfferentRelationshipWith(databaseInstance1);
assertEquals("Uses", relationship.getDescription());
// apiInstance2 -> databaseInstance2
relationship = apiInstance2.getEfferentRelationshipWith(databaseInstance2);
assertEquals("Uses", relationship.getDescription());
}
@Test
public void test_getElement_ThrowsAnException_WhenANullIdIsSpecified() {
try {
model.getElement(null);
} catch (IllegalArgumentException iae) {
assertEquals("An element ID must be specified.", iae.getMessage());
}
}
@Test
public void test_getElement_ThrowsAnException_WhenAnEmptyIdIsSpecified() {
try {
model.getElement(" ");
} catch (IllegalArgumentException iae) {
assertEquals("An element ID must be specified.", iae.getMessage());
}
}
@Test
public void test_getElementWithCanonicalName_ThrowsAnException_WhenANullCanonicalNameIsSpecified() {
try {
model.getElementWithCanonicalName(null);
} catch (IllegalArgumentException iae) {
assertEquals("A canonical name must be specified.", iae.getMessage());
}
}
@Test
public void test_getElementWithCanonicalName_ThrowsAnException_WhenAnEmptyCanonicalNameIsSpecified() {
try {
model.getElementWithCanonicalName(" ");
} catch (IllegalArgumentException iae) {
assertEquals("A canonical name must be specified.", iae.getMessage());
}
}
@Test
public void test_getElementWithCanonicalName_ReturnsNull_WhenAnElementWithTheSpecifiedCanonicalNameDoesNotExist() {
assertNull(model.getElementWithCanonicalName("Software System"));
}
@Test
public void test_getElementWithCanonicalName_ReturnsTheElement_WhenAnElementWithTheSpecifiedCanonicalNameExists() {
SoftwareSystem softwareSystem = model.addSoftwareSystem("Software System", "Description");
Container container = softwareSystem.addContainer("Web Application", "Description", "Technology");
assertSame(softwareSystem, model.getElementWithCanonicalName("SoftwareSystem://Software System"));
assertSame(container, model.getElementWithCanonicalName("Container://Software System.Web Application"));
}
@Test
public void test_addImplicitRelationships_SetsTheDescriptionOfThePropagatedRelationship_WhenThereIsOnlyOnePossibleDescription() {
Person user = model.addPerson("Person", "Description");
SoftwareSystem softwareSystem = model.addSoftwareSystem("Software System", "Description");
Container webApplication = softwareSystem.addContainer("Web Application", "Description", "Technology");
user.uses(webApplication, "Uses", "");
model.addImplicitRelationships();
assertEquals(2, user.getRelationships().size());
Relationship relationship = user.getRelationships().stream().filter(r -> r.getDestination() == softwareSystem).findFirst().get();
assertEquals("Uses", relationship.getDescription());
}
@Test
public void test_addImplicitRelationships_DoeNotSetTheDescriptionOfThePropagatedRelationship_WhenThereIsMoreThanOnePossibleDescription() {
Person user = model.addPerson("Person", "Description");
SoftwareSystem softwareSystem = model.addSoftwareSystem("Software System", "Description");
Container webApplication = softwareSystem.addContainer("Web Application", "Description", "Technology");
user.uses(webApplication, "Does something", "");
user.uses(webApplication, "Does something else", "");
model.addImplicitRelationships();
assertEquals(3, user.getRelationships().size());
Relationship relationship = user.getRelationships().stream().filter(r -> r.getDestination() == softwareSystem).findFirst().get();
assertEquals("", relationship.getDescription());
}
@Test
public void test_addImplicitRelationships_SetsTheTechnologyOfThePropagatedRelationship_WhenThereIsOnlyOnePossibleTechnology() {
Person user = model.addPerson("Person", "Description");
SoftwareSystem softwareSystem = model.addSoftwareSystem("Software System", "Description");
Container webApplication = softwareSystem.addContainer("Web Application", "Description", "Technology");
user.uses(webApplication, "Uses", "HTTPS");
model.addImplicitRelationships();
assertEquals(2, user.getRelationships().size());
Relationship relationship = user.getRelationships().stream().filter(r -> r.getDestination() == softwareSystem).findFirst().get();
assertEquals("HTTPS", relationship.getTechnology());
}
@Test
public void test_addImplicitRelationships_DoeNotSetTheTechnologyOfThePropagatedRelationship_WhenThereIsMoreThanOnePossibleTechnology() {
Person user = model.addPerson("Person", "Description");
SoftwareSystem softwareSystem = model.addSoftwareSystem("Software System", "Description");
Container webApplication = softwareSystem.addContainer("Web Application", "Description", "Technology");
user.uses(webApplication, "Does something", "Some technology");
user.uses(webApplication, "Does something else", "Some other technology");
model.addImplicitRelationships();
assertEquals(3, user.getRelationships().size());
Relationship relationship = user.getRelationships().stream().filter(r -> r.getDestination() == softwareSystem).findFirst().get();
assertEquals("", relationship.getTechnology());
}
@Test
public void test_addImplicitRelationships_PropagatesAsyncRelationship_IfThereAreAMixOfInteractionStyles() {
SoftwareSystem softwareSystem = model.addSoftwareSystem("Software System", "");
SoftwareSystem softwareSystemExternal = model.addSoftwareSystem("External system", "");
Container service1 = softwareSystem.addContainer("Service1", "", "Technology1");
Container service2 = softwareSystem.addContainer("Service2", "", "Technology2");
softwareSystemExternal.uses(service1, "Sends an event to", "AMQP", InteractionStyle.Asynchronous);
softwareSystemExternal.uses(service2, "Sends a command to", "HTTPS", InteractionStyle.Synchronous);
model.addImplicitRelationships();
assertEquals(3, softwareSystemExternal.getRelationships().size());
Relationship relationship = softwareSystemExternal.getRelationships().stream().filter(r -> r.getDestination() ==
softwareSystem).findFirst().get();
assertEquals(InteractionStyle.Asynchronous, relationship.getInteractionStyle());
}
@Test
public void test_addImplicitRelationships_PropagatesAsyncRelationship_IfThereAreOnlyAsyncInteractionStyles() {
SoftwareSystem softwareSystem = model.addSoftwareSystem("Software System", "");
SoftwareSystem softwareSystemExternal = model.addSoftwareSystem("External system", "");
Container service1 = softwareSystem.addContainer("Service1", "", "Technology1");
Container service2 = softwareSystem.addContainer("Service2", "", "Technology2");
softwareSystemExternal.uses(service1, "Sends an event to", "AMQP", InteractionStyle.Asynchronous);
softwareSystemExternal.uses(service2, "Sends an event to", "Kafka", InteractionStyle.Asynchronous);
model.addImplicitRelationships();
assertEquals(3, softwareSystemExternal.getRelationships().size());
Relationship relationship = softwareSystemExternal.getRelationships().stream().filter(r -> r.getDestination() ==
softwareSystem).findFirst().get();
assertEquals(InteractionStyle.Asynchronous, relationship.getInteractionStyle());
}
@Test
public void test_addDeploymentNode_ThrowsAnException_WhenADeploymentNodeWithTheSameNameAlreadyExists() {
model.addDeploymentNode("Amazon AWS", "Description", "Technology");
try {
model.addDeploymentNode("Amazon AWS", "Description", "Technology");
fail();
} catch (IllegalArgumentException iae) {
assertEquals("A deployment/infrastructure node named 'Amazon AWS' already exists.", iae.getMessage());
}
}
@Test
public void test_addDeploymentNode_ThrowsAnException_WhenAChildDeploymentNodeWithTheSameNameAlreadyExists() {
DeploymentNode deploymentNode = model.addDeploymentNode("Amazon Web Services");
deploymentNode.addDeploymentNode("AWS Region");
try {
deploymentNode.addDeploymentNode("AWS Region");
fail();
} catch (IllegalArgumentException iae) {
assertEquals("A deployment/infrastructure node named 'AWS Region' already exists.", iae.getMessage());
}
}
@Test
public void test_addDeploymentNode_ThrowsAnException_WhenAChildInfrastructureNodeWithTheSameNameAlreadyExists() {
DeploymentNode deploymentNode = model.addDeploymentNode("Amazon Web Services");
deploymentNode.addInfrastructureNode("Node");
try {
deploymentNode.addDeploymentNode("Node");
fail();
} catch (IllegalArgumentException iae) {
assertEquals("A deployment/infrastructure node named 'Node' already exists.", iae.getMessage());
}
}
@Test
public void test_addInfrastructureNode_ThrowsAnException_WhenAChildDeploymentNodeWithTheSameNameAlreadyExists() {
DeploymentNode deploymentNode = model.addDeploymentNode("Amazon Web Services");
deploymentNode.addDeploymentNode("Node");
try {
deploymentNode.addInfrastructureNode("Node");
fail();
} catch (IllegalArgumentException iae) {
assertEquals("A deployment/infrastructure node named 'Node' already exists.", iae.getMessage());
}
}
@Test
public void test_addInfrastructureNode_ThrowsAnException_WhenAChildInfrastructureNodeWithTheSameNameAlreadyExists() {
DeploymentNode deploymentNode = model.addDeploymentNode("Amazon Web Services");
deploymentNode.addInfrastructureNode("Node");
try {
deploymentNode.addInfrastructureNode("Node");
fail();
} catch (IllegalArgumentException iae) {
assertEquals("A deployment/infrastructure node named 'Node' already exists.", iae.getMessage());
}
}
@Test
public void test_setIdGenerator_ThrowsAnException_WhenANullIdGeneratorIsSpecified() {
try {
model.setIdGenerator(null);
fail();
} catch (IllegalArgumentException iae) {
assertEquals("An ID generator must be provided.", iae.getMessage());
}
}
@Test
public void test_hydrate() {
Person person = new Person();
person.setId("1");
person.setName("Person");
model.setPeople(Collections.singleton(person));
SoftwareSystem softwareSystem = new SoftwareSystem();
softwareSystem.setId("2");
softwareSystem.setName("Software System");
model.setSoftwareSystems(Collections.singleton(softwareSystem));
Container container = new Container();
container.setId("3");
container.setName("Container");
softwareSystem.setContainers(Collections.singleton(container));
Component component = new Component();
component.setId("4");
component.setName("Component");
container.setComponents(Collections.singleton(component));
DeploymentNode deploymentNodeParent = new DeploymentNode();
deploymentNodeParent.setId("5");
deploymentNodeParent.setName("Deployment Node - Parent");
model.setDeploymentNodes(Collections.singleton(deploymentNodeParent));
DeploymentNode deploymentNodeChild = new DeploymentNode();
deploymentNodeChild.setId("6");
deploymentNodeChild.setName("Deployment Node - Child");
deploymentNodeParent.setChildren(Collections.singleton(deploymentNodeChild));
ContainerInstance containerInstance = new ContainerInstance();
containerInstance.setId("7");
containerInstance.setContainerId("3");
deploymentNodeChild.setContainerInstances(Collections.singleton(containerInstance));
Relationship relationship = new Relationship();
relationship.setId("8");
relationship.setSourceId("1");
relationship.setDestinationId("2");
person.setRelationships(Collections.singleton(relationship));
model.hydrate();
assertSame(person, model.getElement("1"));
assertSame(model, person.getModel());
assertSame(softwareSystem, model.getElement("2"));
assertSame(model, softwareSystem.getModel());
assertSame(container, model.getElement("3"));
assertSame(model, container.getModel());
assertSame(softwareSystem, container.getParent());
assertSame(component, model.getElement("4"));
assertSame(model, component.getModel());
assertSame(container, component.getParent());
assertSame(deploymentNodeParent, model.getElement("5"));
assertSame(model, deploymentNodeParent.getModel());
assertNull(deploymentNodeParent.getParent());
assertSame(deploymentNodeChild, model.getElement("6"));
assertSame(model, deploymentNodeChild.getModel());
assertSame(deploymentNodeParent, deploymentNodeChild.getParent());
assertSame(containerInstance, model.getElement("7"));
assertSame(model, containerInstance.getModel());
assertSame(container, containerInstance.getContainer());
assertSame(relationship, model.getRelationship("8"));
assertSame(person, relationship.getSource());
assertSame(softwareSystem, relationship.getDestination());
// test that new elements take the next ID
Element element = model.addPerson("New element", "Description");
assertEquals("9", element.getId());
}
@Test
public void test_impliedRelationshipStrategy() {
// default strategy initially
assertTrue(model.getImpliedRelationshipsStrategy() instanceof DefaultImpliedRelationshipsStrategy);
model.setImpliedRelationshipsStrategy(new CreateImpliedRelationshipsUnlessAnyRelationshipExistsStrategy());
assertTrue(model.getImpliedRelationshipsStrategy() instanceof CreateImpliedRelationshipsUnlessAnyRelationshipExistsStrategy);
}
@Test
public void test_setImpliedRelationshipStrategy_ResetsToTheDefaultStrategy_WhenPassedNull() {
model.setImpliedRelationshipsStrategy(new CreateImpliedRelationshipsUnlessAnyRelationshipExistsStrategy());
model.setImpliedRelationshipsStrategy(null);
assertTrue(model.getImpliedRelationshipsStrategy() instanceof DefaultImpliedRelationshipsStrategy);
}
@Test
public void test_addSoftwareSystemInstance_AllocatesInstanceIdsPerDeploymentNode() {
SoftwareSystem softwareSystem = model.addSoftwareSystem("Software System", "");
DeploymentNode deploymentNodeA = model.addDeploymentNode("Deployment Node A", "", "");
DeploymentNode deploymentNodeB = model.addDeploymentNode("Deployment Node B", "", "");
SoftwareSystemInstance softwareSystemInstanceA1 = deploymentNodeA.add(softwareSystem);
SoftwareSystemInstance softwareSystemInstanceA2 = deploymentNodeA.add(softwareSystem);
SoftwareSystemInstance softwareSystemInstanceB1 = deploymentNodeB.add(softwareSystem);
SoftwareSystemInstance softwareSystemInstanceB2 = deploymentNodeB.add(softwareSystem);
assertEquals("SoftwareSystemInstance://Default/Deployment Node A/Software System[1]", softwareSystemInstanceA1.getCanonicalName());
assertEquals("SoftwareSystemInstance://Default/Deployment Node A/Software System[2]", softwareSystemInstanceA2.getCanonicalName());
assertEquals("SoftwareSystemInstance://Default/Deployment Node B/Software System[1]", softwareSystemInstanceB1.getCanonicalName());
assertEquals("SoftwareSystemInstance://Default/Deployment Node B/Software System[2]", softwareSystemInstanceB2.getCanonicalName());
}
@Test
public void test_addContainerInstance_AllocatesInstanceIdsPerDeploymentNode() {
SoftwareSystem softwareSystem = model.addSoftwareSystem("Software System", "");
Container container = softwareSystem.addContainer("Container", "", "");
DeploymentNode deploymentNodeA = model.addDeploymentNode("Deployment Node A", "", "");
DeploymentNode deploymentNodeB = model.addDeploymentNode("Deployment Node B", "", "");
ContainerInstance containerInstanceA1 = deploymentNodeA.add(container);
ContainerInstance containerInstanceA2 = deploymentNodeA.add(container);
ContainerInstance containerInstanceB1 = deploymentNodeB.add(container);
ContainerInstance containerInstanceB2 = deploymentNodeB.add(container);
assertEquals("ContainerInstance://Default/Deployment Node A/Software System.Container[1]", containerInstanceA1.getCanonicalName());
assertEquals("ContainerInstance://Default/Deployment Node A/Software System.Container[2]", containerInstanceA2.getCanonicalName());
assertEquals("ContainerInstance://Default/Deployment Node B/Software System.Container[1]", containerInstanceB1.getCanonicalName());
assertEquals("ContainerInstance://Default/Deployment Node B/Software System.Container[2]", containerInstanceB2.getCanonicalName());
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.jobmaster;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.executiongraph.utils.SimpleAckingTaskManagerGateway;
import org.apache.flink.runtime.instance.SlotSharingGroupId;
import org.apache.flink.runtime.jobmanager.slots.DummySlotOwner;
import org.apache.flink.runtime.jobmanager.slots.TaskManagerGateway;
import org.apache.flink.runtime.taskmanager.LocalTaskManagerLocation;
import org.apache.flink.runtime.taskmanager.TaskManagerLocation;
/**
* Builder for the {@link TestingLogicalSlot}.
*/
public class TestingLogicalSlotBuilder {
private TaskManagerGateway taskManagerGateway = new SimpleAckingTaskManagerGateway();
private TaskManagerLocation taskManagerLocation = new LocalTaskManagerLocation();
private int slotNumber = 0;
private AllocationID allocationId = new AllocationID();
private SlotRequestId slotRequestId = new SlotRequestId();
private SlotSharingGroupId slotSharingGroupId = new SlotSharingGroupId();
private SlotOwner slotOwner = new DummySlotOwner();
private boolean automaticallyCompleteReleaseFuture = true;
public TestingLogicalSlotBuilder setTaskManagerGateway(TaskManagerGateway taskManagerGateway) {
this.taskManagerGateway = taskManagerGateway;
return this;
}
public TestingLogicalSlotBuilder setTaskManagerLocation(TaskManagerLocation taskManagerLocation) {
this.taskManagerLocation = taskManagerLocation;
return this;
}
public TestingLogicalSlotBuilder setSlotNumber(int slotNumber) {
this.slotNumber = slotNumber;
return this;
}
public TestingLogicalSlotBuilder setAllocationId(AllocationID allocationId) {
this.allocationId = allocationId;
return this;
}
public TestingLogicalSlotBuilder setSlotRequestId(SlotRequestId slotRequestId) {
this.slotRequestId = slotRequestId;
return this;
}
public TestingLogicalSlotBuilder setSlotSharingGroupId(SlotSharingGroupId slotSharingGroupId) {
this.slotSharingGroupId = slotSharingGroupId;
return this;
}
public TestingLogicalSlotBuilder setAutomaticallyCompleteReleaseFuture(boolean automaticallyCompleteReleaseFuture) {
this.automaticallyCompleteReleaseFuture = automaticallyCompleteReleaseFuture;
return this;
}
public TestingLogicalSlotBuilder setSlotOwner(SlotOwner slotOwner) {
this.slotOwner = slotOwner;
return this;
}
public TestingLogicalSlot createTestingLogicalSlot() {
return new TestingLogicalSlot(
taskManagerLocation,
taskManagerGateway,
slotNumber,
allocationId,
slotRequestId,
slotSharingGroupId,
automaticallyCompleteReleaseFuture,
slotOwner);
}
}
|
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.logstash.log;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.spi.LoggerContext;
import org.apache.logging.log4j.spi.LoggerContextFactory;
import java.net.URI;
/**
* Log4j context factory to enable injection of a pre-established context. This may be used in conjunction with
* {@link LogManager#setFactory(LoggerContextFactory)} to ensure that the injected pre-established context is used by the {@link LogManager}
*/
public class LogstashLoggerContextFactory implements LoggerContextFactory {
private final LoggerContext context;
/**
* Constructor
*
* @param context The {@link LoggerContext} that this factory will ALWAYS return.
*/
public LogstashLoggerContextFactory(LoggerContext context) {
this.context = context;
}
@Override
public LoggerContext getContext(String fqcn, ClassLoader loader, Object externalContext, boolean currentContext) {
return context;
}
@Override
public LoggerContext getContext(String fqcn, ClassLoader loader, Object externalContext, boolean currentContext,
URI configLocation, String name) {
return context;
}
@Override
public void removeContext(LoggerContext context) {
//do nothing
}
}
|
package org.crazyit.content;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity
{
MyDatabaseHelper dbHelper;
Button insert = null;
Button search = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 创建MyDatabaseHelper对象,指定数据库版本为1,此处使用相对路径即可
// 数据库文件自动会保存在程序的数据文件夹的databases目录下
dbHelper = new MyDatabaseHelper(this, "myDict.db3", 1);
insert = (Button) findViewById(R.id.insert);
search = (Button) findViewById(R.id.search);
insert.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View source)
{
// 获取用户输入
String word = ((EditText) findViewById(R.id.word))
.getText().toString();
String detail = ((EditText) findViewById(R.id.detail))
.getText().toString();
// 插入生词记录
insertData(dbHelper.getReadableDatabase(), word, detail);
// 显示提示信息
Toast.makeText(MainActivity.this, "添加生词成功!"
, Toast.LENGTH_LONG).show();
}
});
search.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View source)
{
// 获取用户输入
String key = ((EditText) findViewById(R.id.key)).getText()
.toString();
// 执行查询
Cursor cursor = dbHelper.getReadableDatabase().rawQuery(
"select * from dict where word like ? or detail like ?",
new String[] { "%" + key + "%", "%" + key + "%" });
// 创建一个Bundle对象
Bundle data = new Bundle();
data.putSerializable("data", converCursorToList(cursor));
// 创建一个Intent
Intent intent = new Intent(MainActivity.this
, ResultActivity.class);
intent.putExtras(data);
// 启动Activity
startActivity(intent);
}
});
}
protected ArrayList<Map<String, String>>
converCursorToList(Cursor cursor)
{
ArrayList<Map<String, String>> result =
new ArrayList<Map<String, String>>();
// 遍历Cursor结果集
while (cursor.moveToNext())
{
// 将结果集中的数据存入ArrayList中
Map<String, String> map = new HashMap<>();
// 取出查询记录中第2列、第3列的值
map.put("word", cursor.getString(1));
map.put("detail", cursor.getString(2));
result.add(map);
}
return result;
}
private void insertData(SQLiteDatabase db, String word
, String detail)
{
// 执行插入语句
db.execSQL("insert into dict values(null , ? , ?)"
, new String[] {word, detail });
}
@Override
public void onDestroy()
{
super.onDestroy();
// 退出程序时关闭MyDatabaseHelper里的SQLiteDatabase
if (dbHelper != null)
{
dbHelper.close();
}
}
}
|
/*
* 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.chime.model;
import javax.annotation.Generated;
/**
*
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum PhoneNumberStatus {
AcquireInProgress("AcquireInProgress"),
AcquireFailed("AcquireFailed"),
Unassigned("Unassigned"),
Assigned("Assigned"),
ReleaseInProgress("ReleaseInProgress"),
DeleteInProgress("DeleteInProgress"),
ReleaseFailed("ReleaseFailed"),
DeleteFailed("DeleteFailed");
private String value;
private PhoneNumberStatus(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return PhoneNumberStatus corresponding to the value
*
* @throws IllegalArgumentException
* If the specified value does not map to one of the known values in this enum.
*/
public static PhoneNumberStatus fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
}
for (PhoneNumberStatus enumEntry : PhoneNumberStatus.values()) {
if (enumEntry.toString().equals(value)) {
return enumEntry;
}
}
throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.apimanagement;
import com.azure.core.util.Context;
/** Samples for NamedValue Get. */
public final class NamedValueGetSamples {
/*
* operationId: NamedValue_Get
* api-version: 2020-12-01
* x-ms-examples: ApiManagementGetNamedValueWithKeyVault
*/
/**
* Sample code: ApiManagementGetNamedValueWithKeyVault.
*
* @param manager Entry point to ApiManagementManager.
*/
public static void apiManagementGetNamedValueWithKeyVault(
com.azure.resourcemanager.apimanagement.ApiManagementManager manager) {
manager.namedValues().getWithResponse("rg1", "apimService1", "testprop6", Context.NONE);
}
/*
* operationId: NamedValue_Get
* api-version: 2020-12-01
* x-ms-examples: ApiManagementGetNamedValue
*/
/**
* Sample code: ApiManagementGetNamedValue.
*
* @param manager Entry point to ApiManagementManager.
*/
public static void apiManagementGetNamedValue(
com.azure.resourcemanager.apimanagement.ApiManagementManager manager) {
manager.namedValues().getWithResponse("rg1", "apimService1", "testarmTemplateproperties2", Context.NONE);
}
}
|
/*
* Copyright 2003, 2004, 2005, 2006 Research Triangle Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.cidrz.webapp.dynasite.dao.partograph;
import org.apache.commons.dbutils.QueryLoader;
import org.cidrz.project.zeprs.valueobject.partograph.Liquor;
import org.cidrz.project.zeprs.valueobject.BaseRecord;
import org.cidrz.webapp.dynasite.Constants;
import org.cidrz.webapp.dynasite.dao.PersistenceDAO;
import org.cidrz.webapp.dynasite.utils.DatabaseUtils;
import org.cidrz.webapp.dynasite.exception.ObjectNotFoundException;
import javax.servlet.ServletException;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Map;
/**
* @author <a href="mailto:ckelley@rti.org">Chris Kelley</a>
* Date: Jul 6, 2005
* Time: 9:22:16 AM
*/
public class LiquorDAO implements PersistenceDAO {
/**
* Returns one record for patient
*
* @param conn
* @param patientId
* @param pregnancyId
* @return
* @throws java.sql.SQLException
* @throws javax.servlet.ServletException
* @throws java.io.IOException
*/
public BaseRecord getOne(Connection conn, Long patientId, Long pregnancyId) throws SQLException, ServletException, IOException, ObjectNotFoundException {
Map queries = QueryLoader.instance().load("/" + Constants.SQL_PARTO_PROPERTIES);
String sql = (String) queries.get("SQL_RETRIEVE_LIQUOR");
Liquor item = null;
ArrayList values;
values = new ArrayList();
values.add(patientId);
values.add(pregnancyId);
item = (Liquor) DatabaseUtils.getBean(conn, Liquor.class, sql, values);
return item;
}
}
|
package fr.anw.stompUserExample.server.config;
import fr.anw.stompUserExample.server.controllers.RegisterController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.messaging.SessionConnectEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
import org.springframework.web.socket.messaging.SessionSubscribeEvent;
import java.lang.invoke.MethodHandles;
/**
* Spring websocket configuration with STOMP.
*/
@Configuration
@EnableWebSocketMessageBroker
public class WsConfig extends AbstractWebSocketMessageBrokerConfigurer {
private static Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
public static final String ENDPOINT_CONNECT = "/connect";
public static final String SUBSCRIBE_USER_PREFIX = "/private";
public static final String SUBSCRIBE_USER_REPLY = "/reply";
public static final String SUBSCRIBE_QUEUE = "/queue";
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint(ENDPOINT_CONNECT, RegisterController.ENDPOINT_REGISTER)
// assign a random username as principal for each websocket client
// this is needed to be able to communicate with a specific client
.setHandshakeHandler(new AssignPrincipalHandshakeHandler());
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker(SUBSCRIBE_QUEUE, SUBSCRIBE_USER_REPLY);
registry.setUserDestinationPrefix(SUBSCRIBE_USER_PREFIX);
}
// various listeners for debugging purpose
@EventListener
public void handleSubscribeEvent(SessionSubscribeEvent event) {
log.info("<==> handleSubscribeEvent: username="+event.getUser().getName()+", event="+event);
}
@EventListener
public void handleConnectEvent(SessionConnectEvent event) {
log.info("===> handleConnectEvent: username="+event.getUser().getName()+", event="+event);
}
@EventListener
public void handleDisconnectEvent(SessionDisconnectEvent event) {
log.info("<=== handleDisconnectEvent: username="+event.getUser().getName()+", event="+event);
}
}
|
/*
*
* Copyright 2012-2014 Eurocommercial Properties NV
*
*
* 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.estatio.module.lease.integtests.lease;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.SortedSet;
import javax.inject.Inject;
import org.joda.time.LocalDate;
import org.junit.Before;
import org.junit.Test;
import org.apache.isis.applib.fixturescripts.FixtureScript;
import org.apache.isis.applib.services.clock.ClockService;
import org.estatio.module.charge.fixtures.charges.enums.Charge_enum;
import org.estatio.module.invoice.dom.Invoice;
import org.estatio.module.invoice.dom.InvoiceItem;
import org.estatio.module.invoice.dom.InvoiceRunType;
import org.estatio.module.invoice.dom.PaymentMethod;
import org.estatio.module.lease.app.InvoiceServiceMenu;
import org.estatio.module.lease.dom.Fraction;
import org.estatio.module.lease.dom.InvoicingFrequency;
import org.estatio.module.lease.dom.Lease;
import org.estatio.module.lease.dom.LeaseAgreementRoleTypeEnum;
import org.estatio.module.lease.dom.LeaseItem;
import org.estatio.module.lease.dom.LeaseItemType;
import org.estatio.module.lease.dom.LeaseRepository;
import org.estatio.module.lease.dom.LeaseTermForDeposit;
import org.estatio.module.lease.dom.LeaseTermForIndexable;
import org.estatio.module.lease.dom.invoicing.InvoiceCalculationSelection;
import org.estatio.module.lease.dom.invoicing.InvoiceForLease;
import org.estatio.module.lease.dom.invoicing.InvoiceForLeaseRepository;
import org.estatio.module.lease.dom.invoicing.InvoiceItemForLease;
import org.estatio.module.lease.fixtures.lease.enums.Lease_enum;
import org.estatio.module.lease.fixtures.leaseitems.enums.LeaseItemForDeposit_enum;
import org.estatio.module.lease.fixtures.leaseitems.enums.LeaseItemForRent_enum;
import org.estatio.module.lease.integtests.LeaseModuleIntegTestAbstract;
import static org.assertj.core.api.Assertions.assertThat;
import static org.incode.module.base.integtests.VT.ld;
public class LeaseTermsForDeposit_IntegTest extends LeaseModuleIntegTestAbstract {
@Inject
LeaseRepository leaseRepository;
@Inject
InvoiceServiceMenu invoiceService;
@Inject
InvoiceForLeaseRepository invoiceForLeaseRepository;
//EST-1741: behaviour of deposits is covered now also by org.estatio.module.lease.integtests.invoicing.run.InvoiceCalculationForDeposit_IntegTest
public static class LeaseTermForDepositForOxfScenario extends LeaseTermsForDeposit_IntegTest {
LeaseTermForDeposit depositTerm;
Lease topmodelLease;
LocalDate startDate;
@Before
public void setUp() throws Exception {
runFixtureScript(new FixtureScript() {
@Override
protected void execute(ExecutionContext executionContext) {
executionContext.executeChild(this, Lease_enum.OxfTopModel001Gb.builder());
executionContext.executeChild(this, LeaseItemForRent_enum.OxfTopModel001Gb.builder());
executionContext.executeChild(this, LeaseItemForDeposit_enum.OxfTopModel001Gb.builder());
}
});
}
@Test
public void invoiceScenarioTest() throws Exception {
// given
startDate = ld(2010, 10, 1);
topmodelLease = Lease_enum.OxfTopModel001Gb.findUsing(serviceRegistry);
// when
invoiceService.calculateLegacy(
topmodelLease,
InvoiceRunType.NORMAL_RUN,
InvoiceCalculationSelection.ONLY_DEPOSIT,
startDate, startDate, startDate.plusDays(1));
// then
assertThat(invoiceForLeaseRepository.findByLease(topmodelLease).size()).isEqualTo(1);
assertThat(invoiceForLeaseRepository.findByLease(topmodelLease).get(0).getTotalNetAmount()).isEqualTo(new BigDecimal("10000.00"));
// and when (after couple of indexations of rent items)
invoiceService.calculateLegacy(
topmodelLease,
InvoiceRunType.NORMAL_RUN,
InvoiceCalculationSelection.ONLY_DEPOSIT,
startDate.plusYears(5), startDate.plusYears(5), startDate.plusYears(5).plusDays(1));
// then
assertThat(invoiceForLeaseRepository.findByLease(topmodelLease).size()).isEqualTo(2);
assertThat(invoiceForLeaseRepository.findByLease(topmodelLease).get(0).getTotalNetAmount()).isEqualTo(new BigDecimal("652.51"));
assertThat(invoiceForLeaseRepository.findByLease(topmodelLease).get(1).getTotalNetAmount()).isEqualTo(new BigDecimal("10000.00"));
// and after approval of first invoice only the delta is invoiced
final Invoice invoice = invoiceForLeaseRepository.findByLease(topmodelLease).get(0);
mixin(InvoiceForLease._approve.class, invoice).$$();
invoiceService.calculateLegacy(
topmodelLease,
InvoiceRunType.NORMAL_RUN,
InvoiceCalculationSelection.ONLY_DEPOSIT,
startDate.plusYears(5), startDate.plusYears(5), startDate.plusYears(5).plusDays(1));
// then
assertThat(invoiceForLeaseRepository.findByLease(topmodelLease).size()).isEqualTo(2);
assertThat(invoiceForLeaseRepository.findByLease(topmodelLease).get(0).getTotalNetAmount()).isEqualTo(new BigDecimal("652.51"));
// and after terminating the invoiced deposit is credited
depositTerm = (LeaseTermForDeposit) topmodelLease.findFirstItemOfType(LeaseItemType.DEPOSIT).getTerms().first();
depositTerm.terminate(startDate.plusYears(5).minusDays(1));
final Invoice invoice1 = invoiceForLeaseRepository.findByLease(topmodelLease).get(1);
mixin(InvoiceForLease._approve.class, invoice1).$$();
invoiceService.calculateLegacy(
topmodelLease,
InvoiceRunType.RETRO_RUN,
InvoiceCalculationSelection.ONLY_DEPOSIT,
startDate.plusYears(5), startDate.plusYears(5), startDate.plusYears(5).plusDays(1));
//then
assertThat(invoiceForLeaseRepository.findByLease(topmodelLease).size()).isEqualTo(3);
assertThat(invoiceForLeaseRepository.findByLease(topmodelLease).get(1).getTotalNetAmount()).isEqualTo(new BigDecimal("-10652.51"));
}
}
public static class DepositInvoicedInArrearsTest extends LeaseTermsForDeposit_IntegTest {
Lease leaseForMedia;
LeaseItem rentItem;
LocalDate startDateDeposit = new LocalDate(2010,01,01);
@Before
public void setUp() throws Exception {
runFixtureScript(new FixtureScript() {
@Override
protected void execute(ExecutionContext executionContext) {
executionContext.executeChild(this, Lease_enum.OxfMediaX002Gb.builder());
executionContext.executeChild(this, LeaseItemForRent_enum.OxfMediaX002Gb.builder());
}
});
leaseForMedia = Lease_enum.OxfMediaX002Gb.findUsing(serviceRegistry);
rentItem = leaseForMedia.findFirstItemOfType(LeaseItemType.RENT);
LeaseTermForIndexable firstRentTerm = (LeaseTermForIndexable) rentItem.getTerms().first();
assertThat(firstRentTerm.getBaseValue()).isEqualTo(new BigDecimal("20000.00"));
}
@Test
public void depositInvoicedInArrearsTest() {
// given 2 identical deposit items: 1 invoice in arrears, 1 invoiced in advance
LeaseItem depositItemInArrears = wrap(leaseForMedia).newItem(
LeaseItemType.DEPOSIT, LeaseAgreementRoleTypeEnum.LANDLORD,
Charge_enum.GbDeposit.findUsing(serviceRegistry),
InvoicingFrequency.QUARTERLY_IN_ARREARS, PaymentMethod.DIRECT_DEBIT, startDateDeposit);
wrap(depositItemInArrears).newSourceItem(rentItem);
LeaseItem depositItemInAdvance = leaseForMedia.newItem(
LeaseItemType.DEPOSIT, LeaseAgreementRoleTypeEnum.LANDLORD,
Charge_enum.GbDeposit.findUsing(serviceRegistry),
InvoicingFrequency.QUARTERLY_IN_ADVANCE, PaymentMethod.DIRECT_DEBIT, startDateDeposit);
wrap(depositItemInAdvance).newSourceItem(rentItem);
LeaseTermForDeposit termInArrears = (LeaseTermForDeposit) wrap(depositItemInArrears).newTerm(startDateDeposit, null);
termInArrears.setFraction(Fraction.M6);
LeaseTermForDeposit termInAdvance = (LeaseTermForDeposit) wrap(depositItemInAdvance).newTerm(startDateDeposit, null);
termInAdvance.setFraction(Fraction.M6);
transactionService.nextTransaction();
LocalDate dueDate = new LocalDate(2011, 01,01);
// when
setFixtureClockDate(2011, 4, 1);
LocalDate fixtureDate = clockService.now();
wrap(leaseForMedia).verifyUntil(fixtureDate.plusDays(1));
// then
assertThat(rentItem.valueForDate(startDateDeposit)).isEqualTo(new BigDecimal("20563.90"));
assertThat(rentItem.valueForDate(dueDate.minusDays(1))).isEqualTo(new BigDecimal("20563.90"));
assertThat(rentItem.valueForDate(dueDate)).isEqualTo(new BigDecimal("21016.31"));
// and when (NORMAL RUN, inspection value for date deposit on 1-1-2011)
invoiceService.calculate(leaseForMedia, InvoiceRunType.NORMAL_RUN, Arrays.asList(LeaseItemType.DEPOSIT), dueDate, dueDate.minusDays(1), dueDate.plusDays(1));
transactionService.nextTransaction();
// then
assertThat(invoiceForLeaseRepository.findByLease(leaseForMedia).size()).isEqualTo(1);
InvoiceForLease invoice = invoiceForLeaseRepository.findByLease(leaseForMedia).get(0);
assertThat(invoice.getItems().size()).isEqualTo(2);
InvoiceItemForLease invoiceItemInArrears = (InvoiceItemForLease) invoice.getItems().last();
assertThat(invoiceItemInArrears.getSource()).isEqualTo(termInArrears);
// assertThat(invoiceItemInArrears.getNetAmount()).isEqualTo(new BigDecimal("10508.16")); //DONE: is this the expected value (taken from rent on 1-1-2011)? Or is should the expected value be taken from rent on 31-12-2010 instead (10281.95)?
assertThat(invoiceItemInArrears.getNetAmount()).isEqualTo(new BigDecimal("10281.95")); // EST-1741: the behaviour is changed
InvoiceItemForLease invoiceItemInAdvance = (InvoiceItemForLease) invoice.getItems().first();
assertThat(invoiceItemInAdvance.getSource()).isEqualTo(termInAdvance);
assertThat(invoiceItemInAdvance.getNetAmount()).isEqualTo(new BigDecimal("10508.16"));
// and when (NORMAL RUN, inspection value for date deposit on 31-12-2010, duedate for In_ADVANCE item 1-1-2011 not included)
invoiceService.calculate(leaseForMedia, InvoiceRunType.NORMAL_RUN, Arrays.asList(LeaseItemType.DEPOSIT), dueDate, dueDate.minusDays(1), dueDate);
transactionService.nextTransaction();
// then
assertThat(invoiceForLeaseRepository.findByLease(leaseForMedia).size()).isEqualTo(1);
invoice = invoiceForLeaseRepository.findByLease(leaseForMedia).get(0);
assertThat(invoice.getItems().size()).isEqualTo(1);
invoiceItemInArrears = (InvoiceItemForLease) invoice.getItems().first();
assertThat(invoiceItemInArrears.getSource()).isEqualTo(termInArrears);
assertThat(invoiceItemInArrears.getNetAmount()).isEqualTo(new BigDecimal("10281.95"));
// and when (RETRO RUN, inspection value for date deposit on 31-12-2010 - now due date 1-1-2010 for In_ADVANCE item picked up)
invoiceService.calculate(leaseForMedia, InvoiceRunType.RETRO_RUN, Arrays.asList(LeaseItemType.DEPOSIT), dueDate, dueDate.minusDays(1), dueDate);
transactionService.nextTransaction();
// then
assertThat(invoiceForLeaseRepository.findByLease(leaseForMedia).size()).isEqualTo(1);
invoice = invoiceForLeaseRepository.findByLease(leaseForMedia).get(0);
assertThat(invoice.getItems().size()).isEqualTo(2);
SortedSet<InvoiceItem> items = invoice.getItems();
InvoiceItemForLease firstItem = (InvoiceItemForLease) items.first();
InvoiceItemForLease secondItem = (InvoiceItemForLease) invoice.getItems().last();
assertThat(firstItem.getNetAmount()).isEqualTo(new BigDecimal("10281.95"));
assertThat(secondItem.getNetAmount()).isEqualTo(new BigDecimal("10281.95"));
// flaky test, I think because now reliant on value of UUID which is randomly assigned
if(firstItem.getSource().equals(termInArrears)) {
assertThat(firstItem.getSource()).isEqualTo(termInArrears);
assertThat(secondItem.getSource()).isEqualTo(termInAdvance);
} else {
// other way around
assertThat(firstItem.getSource()).isEqualTo(termInAdvance);
assertThat(secondItem.getSource()).isEqualTo(termInArrears);
}
}
@Inject ClockService clockService;
}
}
|
package Blockchain;
import java.net.InetAddress;
public class Connection {
private Integer remotePort;
private InetAddress remoteAddress;
public Connection (Integer remotePort, InetAddress remoteAddress) {
this.remotePort = remotePort;
this.remoteAddress = remoteAddress;
}
public Integer getRemotePort() {
return remotePort;
}
public InetAddress getRemoteAddress() {
return remoteAddress;
}
}
|
package com.bizbox.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Password {
private String email;
private String salt;
}
|
/**
* Copyright 2018 Dingfan Zhao
*
* 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.
*/
/*
* Apache Fineract API Documentation
* Apache Fineract is a secure, multi-tenanted microfinance platform. <br /> The goal of the Apache Fineract API is to empower developers to build apps on top of the Apache Fineract Platform. The reference app [ https://demo.openmf.org ] (username: mifos, password: password) works on the same demo tenant as the interactive links in this documentation. <br/>The API is organized around REST [ https://en.wikipedia.org/wiki/Representational_state_transfer ] <br/> Find out more about Apache Fineract on [ https://demo.openmf.org/api-docs/apiLive.htm#top ] <br/> You can Try The API From Your Browser itself at [ https://demo.openmf.org/api-docs/apiLive.htm#interact ] <br/> The Generic Options are available at [ https://demo.openmf.org/api-docs/apiLive.htm#genopts ] <br/> Find out more about Updating Dates and Numbers at [ https://demo.openmf.org/api-docs/apiLive.htm#dates_and_numbers ] <br/> For the Authentication and the Basic of HTTP and HTTPS refer [ https://demo.openmf.org/api-docs/apiLive.htm#authentication_overview ] <br/> Check about ERROR codes at [ https://demo.openmf.org/api-docs/apiLive.htm#errors ] <br/> <br/> Please refer to the old documentation for any documentation queries [ https://demo.openmf.org/api-docs/apiLive.htm ] <br/> ______________________________________________________________________________________________________________________________
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package org.mifos.chatbot.client.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* GetLoanProductsLiabilityType
*/
public class GetLoanProductsLiabilityType {
@SerializedName("id")
private Integer id = null;
@SerializedName("code")
private String code = null;
@SerializedName("value")
private String value = null;
public GetLoanProductsLiabilityType id(Integer id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@ApiModelProperty(example = "2", value = "")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public GetLoanProductsLiabilityType code(String code) {
this.code = code;
return this;
}
/**
* Get code
* @return code
**/
@ApiModelProperty(example = "accountType.liability", value = "")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public GetLoanProductsLiabilityType value(String value) {
this.value = value;
return this;
}
/**
* Get value
* @return value
**/
@ApiModelProperty(example = "LIABILITY", value = "")
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GetLoanProductsLiabilityType getLoanProductsLiabilityType = (GetLoanProductsLiabilityType) o;
return Objects.equals(this.id, getLoanProductsLiabilityType.id) &&
Objects.equals(this.code, getLoanProductsLiabilityType.code) &&
Objects.equals(this.value, getLoanProductsLiabilityType.value);
}
@Override
public int hashCode() {
return Objects.hash(id, code, value);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class GetLoanProductsLiabilityType {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" code: ").append(toIndentedString(code)).append("\n");
sb.append(" value: ").append(toIndentedString(value)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.modules.debug;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactModuleWithSpec;
import com.facebook.react.common.build.ReactBuildConfig;
import com.facebook.react.turbomodule.core.interfaces.TurboModule;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
public abstract class NativeSourceCodeSpec extends ReactContextBaseJavaModule
implements ReactModuleWithSpec, TurboModule {
public NativeSourceCodeSpec(ReactApplicationContext reactContext) {
super(reactContext);
}
protected abstract Map<String, Object> getTypedExportedConstants();
@Override
public final @Nullable Map<String, Object> getConstants() {
Map<String, Object> constants = getTypedExportedConstants();
if (ReactBuildConfig.DEBUG || ReactBuildConfig.IS_INTERNAL_BUILD) {
Set<String> obligatoryFlowConstants = new HashSet<>(Arrays.asList("scriptURL"));
Set<String> optionalFlowConstants = new HashSet<>();
Set<String> undeclaredConstants = new HashSet<>(constants.keySet());
undeclaredConstants.removeAll(obligatoryFlowConstants);
undeclaredConstants.removeAll(optionalFlowConstants);
if (!undeclaredConstants.isEmpty()) {
throw new IllegalStateException(
String.format("Native Module Flow doesn't declare constants: %s", undeclaredConstants));
}
undeclaredConstants = obligatoryFlowConstants;
undeclaredConstants.removeAll(constants.keySet());
if (!undeclaredConstants.isEmpty()) {
throw new IllegalStateException(
String.format("Native Module doesn't fill in constants: %s", undeclaredConstants));
}
}
return constants;
}
}
|
/*-
* ========================LICENSE_START=================================
* TeamApps Application API
* ---
* Copyright (C) 2020 - 2021 TeamApps.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.
* =========================LICENSE_END==================================
*/
package org.teamapps.application.api.config;
public class ConfigValue {
}
|
package de.fraunhofer.fit.train.model_v2.doi.datacitie.helper;
/**
* 1.1) identifierType Controled List M DataCite/Identifier
* http://bit.ly/2ZoRw8P "Occurrence: 1 Definition: The type of Identifier.
* Allowed values, examples, other constraints: Controlled List Value: DOI"
*
* @author Joao Bosco Jares MSc. (Software Engineer)
* @see www.jbjares.com
* @see jbjares@gmail.com, joao.bosco.jares.alves.chaves@fit.fraunhofer.de
*
*
*/
//@XStreamAlias("IdentifierType")
//@Repository
//@Document(collection = "identifierType")
public enum IdentifierTypeDataciteEnum {
DOI("DOI"),ORCID("ORCID");
private String text;
IdentifierTypeDataciteEnum(String text) {
this.text = text;
}
/**
* 1.1) identifierType Controled List M DataCite/Identifier
* http://bit.ly/2ZoRw8P "Occurrence: 1 Definition: The type of Identifier.
* Allowed values, examples, other constraints: Controlled List Value: DOI"
*
* @author Joao Bosco Jares MSc. (Software Engineer)
* @see www.jbjares.com
* @see jbjares@gmail.com, joao.bosco.jares.alves.chaves@fit.fraunhofer.de
*
*
*/
public String getText() {
return this.text;
}
public static IdentifierTypeDataciteEnum fromString(String text) {
for (IdentifierTypeDataciteEnum b : IdentifierTypeDataciteEnum.values()) {
if (b.text.equalsIgnoreCase(text)) {
return b;
}
}
return null;
}
}
|
package ucmo.workoutapp.repositories;
import org.springframework.data.repository.CrudRepository;
import ucmo.workoutapp.entities.Meal;
public interface MealRepository extends CrudRepository<Meal, Long> {
Meal getById(Long Id);
Iterable<Meal> getAllByMealPlan(Long planId);
}
|
/*
* Swagger Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.*;
/**
* MapTest
*/
public class MapTest {
@JsonProperty("map_map_of_string")
private Map<String, Map<String, String>> mapMapOfString = new HashMap<String, Map<String, String>>();
/**
* Gets or Sets inner
*/
public enum InnerEnum {
UPPER("UPPER"),
LOWER("lower");
private String value;
InnerEnum(String value) {
this.value = value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static InnerEnum fromValue(String text) {
for (InnerEnum b : InnerEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
}
@JsonProperty("map_of_enum_string")
private Map<String, InnerEnum> mapOfEnumString = new HashMap<String, InnerEnum>();
public MapTest mapMapOfString(Map<String, Map<String, String>> mapMapOfString) {
this.mapMapOfString = mapMapOfString;
return this;
}
public MapTest putMapMapOfStringItem(String key, Map<String, String> mapMapOfStringItem) {
this.mapMapOfString.put(key, mapMapOfStringItem);
return this;
}
/**
* Get mapMapOfString
* @return mapMapOfString
**/
@ApiModelProperty(value = "")
public Map<String, Map<String, String>> getMapMapOfString() {
return mapMapOfString;
}
public void setMapMapOfString(Map<String, Map<String, String>> mapMapOfString) {
this.mapMapOfString = mapMapOfString;
}
public MapTest mapOfEnumString(Map<String, InnerEnum> mapOfEnumString) {
this.mapOfEnumString = mapOfEnumString;
return this;
}
public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) {
this.mapOfEnumString.put(key, mapOfEnumStringItem);
return this;
}
/**
* Get mapOfEnumString
* @return mapOfEnumString
**/
@ApiModelProperty(value = "")
public Map<String, InnerEnum> getMapOfEnumString() {
return mapOfEnumString;
}
public void setMapOfEnumString(Map<String, InnerEnum> mapOfEnumString) {
this.mapOfEnumString = mapOfEnumString;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MapTest mapTest = (MapTest) o;
return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) &&
Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString);
}
@Override
public int hashCode() {
return Objects.hash(mapMapOfString, mapOfEnumString);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class MapTest {\n");
sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n");
sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
/*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.tasks.testing.logging;
/**
* Determines how exceptions are formatted in test logging.
*/
public enum TestExceptionFormat {
/**
* Short display of exceptions.
*/
SHORT,
/**
* Full display of exceptions.
*/
FULL
}
|
package examples.cifar10;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import examples.cifar10.GraphBuilderWrapper.Wrap;
import ode.solve.api.FirstOrderSolverConf;
import ode.solve.conf.DormandPrince54Solver;
import ode.solve.conf.SolverConfig;
import ode.vertex.conf.helper.InputStep;
import ode.vertex.conf.helper.OdeHelper;
import org.deeplearning4j.nn.conf.ComputationGraphConfiguration.GraphBuilder;
import org.deeplearning4j.nn.conf.layers.DenseLayer;
import org.deeplearning4j.nn.graph.ComputationGraph;
import org.deeplearning4j.nn.weights.WeightInit;
import org.nd4j.linalg.activations.impl.ActivationIdentity;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import org.nd4j.linalg.dataset.api.iterator.MultiDataSetIterator;
import org.nd4j.linalg.factory.Nd4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.listen.step.Mask;
import util.listen.step.StepCounter;
import static examples.cifar10.LayerUtil.conv1x1;
/**
* OdeNet reference model for. Reimplementation of https://github.com/rtqichen/torchdiffeq/blob/master/examples/odenet_mnist.py
*
* @author Christian Skarby
*/
@Parameters(commandDescription = "Configuration for image classification using an ODE block")
public class OdeNetModel implements ModelFactory {
private static final Logger log = LoggerFactory.getLogger(OdeNetModel.class);
@Parameter(names = "-nrofPreReductions", description = "Number of type A reduction blocks to apply before the first ODE block.")
private int nrofPreReductions = 0;
@Parameter(names = "-useABlock", description = "Use an ODE A block if true.")
private boolean useABlock = false;
@Parameter(names = "-useBBlock", description = "Use an ODE B block if true.")
private boolean useBBlock = false;
@Parameter(names = "-useCBlock", description = "Use an ODE C block if true.")
private boolean useCBlock = false;
@Parameter(names = "-trainTime", description = "Set if time steps for solver shall be trained")
private boolean trainTime = false;
@Override
public ComputationGraph create() {
return create(
//new NanWatchSolver(
new DormandPrince54Solver(new SolverConfig(1e-3, 1e-3, 1e-20, 100)));
}
ComputationGraph create(FirstOrderSolverConf solver) {
log.info("Create model");
solver.addListeners(
Mask.backward(new StepCounter(20, "Average nrof forward steps: ")),
Mask.forward(new StepCounter(20, "Average nrof backward steps: "))
);
String next = "input";
final String time = "time";
final GraphBuilder builder = LayerUtil.initGraphBuilder(Nd4j.getRandom().nextLong(), next, time);
OdeHelper odeConf = new InputStep(solver, 1, false, false);
if (trainTime) {
odeConf = new InputStep(solver, 1, false, true);
}
for(int i = 0; i < nrofPreReductions; i++) {
next = new InceptionReductionABlock("preReductionA" + i).add(new Wrap(builder), next);
}
builder.addLayer("resize", conv1x1(256), next);
next = "resize";
if(useABlock) {
final String timeName = addTimeIfTimeTrain("A", builder, time);
next = new OdeBlockTime(builder.getGlobalConfiguration(), odeConf, new InceptionResNetABlock("", 32), "odeVertexA")
.add(new Wrap(builder), next, timeName);
}
if(useBBlock || useCBlock) {
next = new InceptionReductionABlock("reductionA").add(new Wrap(builder), next);
}
if(useBBlock) {
final String timeName = addTimeIfTimeTrain("B", builder, time);
next = new OdeBlockTime(builder.getGlobalConfiguration(), odeConf, new InceptionResNetBBlock("", 128), "odeVertexB")
.add(new Wrap(builder), next, timeName);
}
if(useCBlock) {
final String timeName = addTimeIfTimeTrain("C", builder, time);
next = new InceptionReductionBBlock("reductionB").add(new Wrap(builder), next);
next = new OdeBlockTime(builder.getGlobalConfiguration(), odeConf, new InceptionResNetCBlock("", 128), "odeVertexC")
.add(new Wrap(builder), next, timeName);
}
next = new Output().add(new Wrap(builder), next);
builder.setOutputs(next);
final ComputationGraph graph = new ComputationGraph(builder.build());
graph.init();
return graph;
}
private String addTimeIfTimeTrain(String blockSuffix, GraphBuilder builder, String timeName) {
if (trainTime) {
builder.addLayer(timeName + blockSuffix, new DenseLayer.Builder()
.nOut(2)
.weightInit(WeightInit.IDENTITY)
.biasInit(0)
.activation(new ActivationIdentity())
.build(), timeName);
return timeName + blockSuffix;
}
return timeName;
}
@Override
public String name() {
return "odenet"
+ (nrofPreReductions > 0 ? "_nrofPreReductions" + nrofPreReductions : "")
+ (useABlock ? "_A" : "")
+ (useBBlock ? "_B" : "")
+ (useCBlock ? "_C" : "")
+ (trainTime ? "_trainTime" : "");
}
@Override
public MultiDataSetIterator wrapIter(DataSetIterator iter) {
return
new AddTimeMultiDataSetIter(
iter
, Nd4j.arange(2)); // Start with time steps 0 to 1
}
}
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2011.12.14 at 03:30:44 PM CET
//
package ch.epfl.bbp.uima.xml.archivearticle3;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlIDREF;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="glyph-data" type="{http://www.w3.org/2001/XMLSchema}IDREF" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "glyph-ref")
public class GlyphRef {
@XmlAttribute(name = "glyph-data")
@XmlIDREF
@XmlSchemaType(name = "IDREF")
protected Object glyphData;
/**
* Gets the value of the glyphData property.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getGlyphData() {
return glyphData;
}
/**
* Sets the value of the glyphData property.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setGlyphData(Object value) {
this.glyphData = value;
}
}
|
package ru.job4j.collections.map.user;
import java.util.HashMap;
import java.util.Map;
/**
* @author Sergey gavrilov (sarmexin@gmail.com)
* @version $Id$
* @since 0.1
*/
public class Database {
private static User user1 = new User("Maxim", 1, new Calendar(1, 12, 1976));
private static User user2 = new User("Maxim", 1, new Calendar(1, 12, 1976));
public static void main(String args[]) {
System.out.println(user1.equals(user2));
System.out.println(user1.hashCode());
System.out.println(user2.hashCode());
Map<User, Object> map = new HashMap<>();
map.put(user1, "One");
map.put(user2, "Two");
System.out.println(map);
}
}
|
package com.adaptionsoft.games.trivia;
import com.adaptionsoft.games.trivia.runner.GameRunner;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class SomeTest {
@Test
public void outputStaysSame() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
GameRunner.main(null);
String result = out.toString();
assertThat(result, is(original));
}
String original = "Chet was added\n" +
"They are player number 1\n" +
"Pat was added\n" +
"They are player number 2\n" +
"Sue was added\n" +
"They are player number 3\n" +
"Chet is the current player\n" +
"They have rolled a 5\n" +
"Chet's new location is 5\n" +
"The category is Science\n" +
"Science Question 0\n" +
"Answer was corrent!!!!\n" +
"Chet now has 1 Gold Coins.\n" +
"Pat is the current player\n" +
"They have rolled a 3\n" +
"Pat's new location is 3\n" +
"The category is Rock\n" +
"Rock Question 0\n" +
"Answer was corrent!!!!\n" +
"Pat now has 1 Gold Coins.\n" +
"Sue is the current player\n" +
"They have rolled a 5\n" +
"Sue's new location is 5\n" +
"The category is Science\n" +
"Science Question 1\n" +
"Answer was corrent!!!!\n" +
"Sue now has 1 Gold Coins.\n" +
"Chet is the current player\n" +
"They have rolled a 4\n" +
"Chet's new location is 9\n" +
"The category is Science\n" +
"Science Question 2\n" +
"Answer was corrent!!!!\n" +
"Chet now has 2 Gold Coins.\n" +
"Pat is the current player\n" +
"They have rolled a 2\n" +
"Pat's new location is 5\n" +
"The category is Science\n" +
"Science Question 3\n" +
"Answer was corrent!!!!\n" +
"Pat now has 2 Gold Coins.\n" +
"Sue is the current player\n" +
"They have rolled a 4\n" +
"Sue's new location is 9\n" +
"The category is Science\n" +
"Science Question 4\n" +
"Question was incorrectly answered\n" +
"Sue was sent to the penalty box\n" +
"Chet is the current player\n" +
"They have rolled a 4\n" +
"Chet's new location is 1\n" +
"The category is Science\n" +
"Science Question 5\n" +
"Question was incorrectly answered\n" +
"Chet was sent to the penalty box\n" +
"Pat is the current player\n" +
"They have rolled a 2\n" +
"Pat's new location is 7\n" +
"The category is Rock\n" +
"Rock Question 1\n" +
"Answer was corrent!!!!\n" +
"Pat now has 3 Gold Coins.\n" +
"Sue is the current player\n" +
"They have rolled a 2\n" +
"Sue is not getting out of the penalty box\n" +
"Chet is the current player\n" +
"They have rolled a 5\n" +
"Chet is getting out of the penalty box\n" +
"Chet's new location is 6\n" +
"The category is Sports\n" +
"Sports Question 0\n" +
"Answer was correct!!!!\n" +
"Chet now has 3 Gold Coins.\n" +
"Pat is the current player\n" +
"They have rolled a 1\n" +
"Pat's new location is 8\n" +
"The category is Pop\n" +
"Pop Question 0\n" +
"Answer was corrent!!!!\n" +
"Pat now has 4 Gold Coins.\n" +
"Sue is the current player\n" +
"They have rolled a 1\n" +
"Sue is getting out of the penalty box\n" +
"Sue's new location is 10\n" +
"The category is Sports\n" +
"Sports Question 1\n" +
"Answer was correct!!!!\n" +
"Sue now has 2 Gold Coins.\n" +
"Chet is the current player\n" +
"They have rolled a 1\n" +
"Chet is getting out of the penalty box\n" +
"Chet's new location is 7\n" +
"The category is Rock\n" +
"Rock Question 2\n" +
"Answer was correct!!!!\n" +
"Chet now has 4 Gold Coins.\n" +
"Pat is the current player\n" +
"They have rolled a 5\n" +
"Pat's new location is 1\n" +
"The category is Science\n" +
"Science Question 6\n" +
"Answer was corrent!!!!\n" +
"Pat now has 5 Gold Coins.\n" +
"Sue is the current player\n" +
"They have rolled a 1\n" +
"Sue is getting out of the penalty box\n" +
"Sue's new location is 11\n" +
"The category is Rock\n" +
"Rock Question 3\n" +
"Answer was correct!!!!\n" +
"Sue now has 3 Gold Coins.\n" +
"Chet is the current player\n" +
"They have rolled a 2\n" +
"Chet is not getting out of the penalty box\n" +
"Pat is the current player\n" +
"They have rolled a 4\n" +
"Pat's new location is 5\n" +
"The category is Science\n" +
"Science Question 7\n" +
"Answer was corrent!!!!\n" +
"Pat now has 6 Gold Coins.\n";
}
|
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.generated;
import com.microsoft.graph.concurrency.*;
import com.microsoft.graph.core.*;
import com.microsoft.graph.extensions.*;
import com.microsoft.graph.http.*;
import com.microsoft.graph.generated.*;
import com.microsoft.graph.options.*;
import com.microsoft.graph.serializer.*;
import java.util.Arrays;
import java.util.EnumSet;
import com.google.gson.JsonObject;
import com.google.gson.annotations.*;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The interface for the Base Workbook Range Columns After Request.
*/
public interface IBaseWorkbookRangeColumnsAfterRequest {
/**
* Patches the WorkbookRangeColumnsAfter
*
* @param srcWorkbookRange The WorkbookRange with which to PATCH
* @param callback The callback to be called after success or failure
*/
void patch(WorkbookRange srcWorkbookRange, final ICallback<WorkbookRange> callback);
/**
* Patches the WorkbookRangeColumnsAfter
*
* @param srcWorkbookRange The WorkbookRange with which to PATCH
* @return The WorkbookRange
* @throws ClientException An exception occurs if there was an error while the request was sent
*/
WorkbookRange patch(WorkbookRange srcWorkbookRange) throws ClientException;
/**
* Puts the WorkbookRangeColumnsAfter
*
* @param srcWorkbookRange The WorkbookRange to PUT
* @param callback The callback to be called after success or failure
*/
void put(WorkbookRange srcWorkbookRange, final ICallback<WorkbookRange> callback);
/**
* Puts the WorkbookRangeColumnsAfter
*
* @param srcWorkbookRange The WorkbookRange to PUT
* @return The WorkbookRange
* @throws ClientException An exception occurs if there was an error while the request was sent
*/
WorkbookRange put(WorkbookRange srcWorkbookRange) throws ClientException;
/**
* Gets the WorkbookRange
* @param callback The callback to be called after success or failure.
*/
void get(final ICallback<WorkbookRange> callback);
/**
* Gets the WorkbookRange
*
* @return The WorkbookRange
* @throws ClientException An exception occurs if there was an error while the request was sent.
*/
WorkbookRange get() throws ClientException;
/**
* Sets the select clause for the request
*
* @param value The select clause
* @return The updated request
*/
IWorkbookRangeColumnsAfterRequest select(final String value);
/**
* Sets the expand clause for the request
*
* @param value The expand clause
* @return The updated request
*/
IWorkbookRangeColumnsAfterRequest expand(final String value);
}
|
package org.social.it.converter;
public interface DomainDtoConverter<I,O> extends Converter<I, O> {
}
|
package tn.medtech.lab5.weather;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MyWeather {
@SerializedName("coord")
@Expose
private Coord coord;
@SerializedName("weather")
@Expose
private List<Weather> weather = null;
@SerializedName("base")
@Expose
private String base;
@SerializedName("main")
@Expose
private Main main;
@SerializedName("visibility")
@Expose
private Integer visibility;
@SerializedName("wind")
@Expose
private Wind wind;
@SerializedName("clouds")
@Expose
private Clouds clouds;
@SerializedName("dt")
@Expose
private Integer dt;
@SerializedName("sys")
@Expose
private Sys sys;
@SerializedName("timezone")
@Expose
private Integer timezone;
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("cod")
@Expose
private Integer cod;
public Coord getCoord() {
return coord;
}
public void setCoord(Coord coord) {
this.coord = coord;
}
public List<Weather> getWeather() {
return weather;
}
public void setWeather(List<Weather> weather) {
this.weather = weather;
}
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
public Integer getVisibility() {
return visibility;
}
public void setVisibility(Integer visibility) {
this.visibility = visibility;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Clouds getClouds() {
return clouds;
}
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
public Integer getDt() {
return dt;
}
public void setDt(Integer dt) {
this.dt = dt;
}
public Sys getSys() {
return sys;
}
public void setSys(Sys sys) {
this.sys = sys;
}
public Integer getTimezone() {
return timezone;
}
public void setTimezone(Integer timezone) {
this.timezone = timezone;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCod() {
return cod;
}
public void setCod(Integer cod) {
this.cod = cod;
}
}
|
package org.springframework.jdbc.support.rowset;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.springframework.jdbc.InvalidResultSetAccessException;
/**
* The default implementation of Spring's {@link SqlRowSet} interface, wrapping a
* {@link java.sql.ResultSet}, catching any {@link SQLException SQLExceptions} and
* translating them to a corresponding Spring {@link InvalidResultSetAccessException}.
*
* The passed-in ResultSet should already be disconnected if the SqlRowSet is supposed
* to be usable in a disconnected fashion. This means that you will usually pass in a
* {@code javax.sql.rowset.CachedRowSet}, which implements the ResultSet interface.
*
* Note: Since JDBC 4.0, it has been clarified that any methods using a String to identify
* the column should be using the column label. The column label is assigned using the ALIAS
* keyword in the SQL query string. When the query doesn't use an ALIAS, the default label is
* the column name. Most JDBC ResultSet implementations follow this new pattern but there are
* exceptions such as the {@code com.sun.rowset.CachedRowSetImpl} class which only uses
* the column name, ignoring any column labels. As of Spring 3.0.5, ResultSetWrappingSqlRowSet
* will translate column labels to the correct column index to provide better support for the
* {@code com.sun.rowset.CachedRowSetImpl} which is the default implementation used by
* {@link org.springframework.jdbc.core.JdbcTemplate} when working with RowSets.
*
* Note: This class implements the {@code java.io.Serializable} marker interface
* through the SqlRowSet interface, but is only actually serializable if the disconnected
* ResultSet/RowSet contained in it is serializable. Most CachedRowSet implementations
* are actually serializable, so this should usually work out.
*
* @author Thomas Risberg
* @since 1.2
* @see java.sql.ResultSet
* @see javax.sql.rowset.CachedRowSet
* @see org.springframework.jdbc.core.JdbcTemplate#queryForRowSet
*/
public class ResultSetWrappingSqlRowSet implements SqlRowSet {
/** use serialVersionUID from Spring 1.2 for interoperability. */
private static final long serialVersionUID = -4688694393146734764L;
private final ResultSet resultSet;
private final SqlRowSetMetaData rowSetMetaData;
private final Map<String, Integer> columnLabelMap;
/**
* Create a new ResultSetWrappingSqlRowSet for the given ResultSet.
* @param resultSet a disconnected ResultSet to wrap
* (usually a {@code javax.sql.rowset.CachedRowSet})
* @throws InvalidResultSetAccessException if extracting
* the ResultSetMetaData failed
* @see javax.sql.rowset.CachedRowSet
* @see java.sql.ResultSet#getMetaData
* @see ResultSetWrappingSqlRowSetMetaData
*/
public ResultSetWrappingSqlRowSet(ResultSet resultSet) throws InvalidResultSetAccessException {
this.resultSet = resultSet;
try {
this.rowSetMetaData = new ResultSetWrappingSqlRowSetMetaData(resultSet.getMetaData());
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
try {
ResultSetMetaData rsmd = resultSet.getMetaData();
if (rsmd != null) {
int columnCount = rsmd.getColumnCount();
this.columnLabelMap = new HashMap<>(columnCount);
for (int i = 1; i <= columnCount; i++) {
String key = rsmd.getColumnLabel(i);
// Make sure to preserve first matching column for any given name,
// as defined in ResultSet's type-level javadoc (lines 81 to 83).
if (!this.columnLabelMap.containsKey(key)) {
this.columnLabelMap.put(key, i);
}
}
}
else {
this.columnLabelMap = Collections.emptyMap();
}
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* Return the underlying ResultSet
* (usually a {@code javax.sql.rowset.CachedRowSet}).
* @see javax.sql.rowset.CachedRowSet
*/
public final ResultSet getResultSet() {
return this.resultSet;
}
/**
* @see java.sql.ResultSetMetaData#getCatalogName(int)
*/
@Override
public final SqlRowSetMetaData getMetaData() {
return this.rowSetMetaData;
}
/**
* @see java.sql.ResultSet#findColumn(String)
*/
@Override
public int findColumn(String columnLabel) throws InvalidResultSetAccessException {
Integer columnIndex = this.columnLabelMap.get(columnLabel);
if (columnIndex != null) {
return columnIndex;
}
else {
try {
return this.resultSet.findColumn(columnLabel);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
}
// RowSet methods for extracting data values
/**
* @see java.sql.ResultSet#getBigDecimal(int)
*/
@Override
public BigDecimal getBigDecimal(int columnIndex) throws InvalidResultSetAccessException {
try {
return this.resultSet.getBigDecimal(columnIndex);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getBigDecimal(String)
*/
@Override
public BigDecimal getBigDecimal(String columnLabel) throws InvalidResultSetAccessException {
return getBigDecimal(findColumn(columnLabel));
}
/**
* @see java.sql.ResultSet#getBoolean(int)
*/
@Override
public boolean getBoolean(int columnIndex) throws InvalidResultSetAccessException {
try {
return this.resultSet.getBoolean(columnIndex);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getBoolean(String)
*/
@Override
public boolean getBoolean(String columnLabel) throws InvalidResultSetAccessException {
return getBoolean(findColumn(columnLabel));
}
/**
* @see java.sql.ResultSet#getByte(int)
*/
@Override
public byte getByte(int columnIndex) throws InvalidResultSetAccessException {
try {
return this.resultSet.getByte(columnIndex);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getByte(String)
*/
@Override
public byte getByte(String columnLabel) throws InvalidResultSetAccessException {
return getByte(findColumn(columnLabel));
}
/**
* @see java.sql.ResultSet#getDate(int)
*/
@Override
public Date getDate(int columnIndex) throws InvalidResultSetAccessException {
try {
return this.resultSet.getDate(columnIndex);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getDate(String)
*/
@Override
public Date getDate(String columnLabel) throws InvalidResultSetAccessException {
return getDate(findColumn(columnLabel));
}
/**
* @see java.sql.ResultSet#getDate(int, Calendar)
*/
@Override
public Date getDate(int columnIndex, Calendar cal) throws InvalidResultSetAccessException {
try {
return this.resultSet.getDate(columnIndex, cal);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getDate(String, Calendar)
*/
@Override
public Date getDate(String columnLabel, Calendar cal) throws InvalidResultSetAccessException {
return getDate(findColumn(columnLabel), cal);
}
/**
* @see java.sql.ResultSet#getDouble(int)
*/
@Override
public double getDouble(int columnIndex) throws InvalidResultSetAccessException {
try {
return this.resultSet.getDouble(columnIndex);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getDouble(String)
*/
@Override
public double getDouble(String columnLabel) throws InvalidResultSetAccessException {
return getDouble(findColumn(columnLabel));
}
/**
* @see java.sql.ResultSet#getFloat(int)
*/
@Override
public float getFloat(int columnIndex) throws InvalidResultSetAccessException {
try {
return this.resultSet.getFloat(columnIndex);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getFloat(String)
*/
@Override
public float getFloat(String columnLabel) throws InvalidResultSetAccessException {
return getFloat(findColumn(columnLabel));
}
/**
* @see java.sql.ResultSet#getInt(int)
*/
@Override
public int getInt(int columnIndex) throws InvalidResultSetAccessException {
try {
return this.resultSet.getInt(columnIndex);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getInt(String)
*/
@Override
public int getInt(String columnLabel) throws InvalidResultSetAccessException {
return getInt(findColumn(columnLabel));
}
/**
* @see java.sql.ResultSet#getLong(int)
*/
@Override
public long getLong(int columnIndex) throws InvalidResultSetAccessException {
try {
return this.resultSet.getLong(columnIndex);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getLong(String)
*/
@Override
public long getLong(String columnLabel) throws InvalidResultSetAccessException {
return getLong(findColumn(columnLabel));
}
/**
* @see java.sql.ResultSet#getNString(int)
*/
@Override
public String getNString(int columnIndex) throws InvalidResultSetAccessException {
try {
return this.resultSet.getNString(columnIndex);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getNString(String)
*/
@Override
public String getNString(String columnLabel) throws InvalidResultSetAccessException {
return getNString(findColumn(columnLabel));
}
/**
* @see java.sql.ResultSet#getObject(int)
*/
@Override
public Object getObject(int columnIndex) throws InvalidResultSetAccessException {
try {
return this.resultSet.getObject(columnIndex);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getObject(String)
*/
@Override
public Object getObject(String columnLabel) throws InvalidResultSetAccessException {
return getObject(findColumn(columnLabel));
}
/**
* @see java.sql.ResultSet#getObject(int, Map)
*/
@Override
public Object getObject(int columnIndex, Map<String, Class<?>> map) throws InvalidResultSetAccessException {
try {
return this.resultSet.getObject(columnIndex, map);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getObject(String, Map)
*/
@Override
public Object getObject(String columnLabel, Map<String, Class<?>> map) throws InvalidResultSetAccessException {
return getObject(findColumn(columnLabel), map);
}
/**
* @see java.sql.ResultSet#getObject(int, Class)
*/
@Override
public <T> T getObject(int columnIndex, Class<T> type) throws InvalidResultSetAccessException {
try {
return this.resultSet.getObject(columnIndex, type);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getObject(String, Class)
*/
@Override
public <T> T getObject(String columnLabel, Class<T> type) throws InvalidResultSetAccessException {
return getObject(findColumn(columnLabel), type);
}
/**
* @see java.sql.ResultSet#getShort(int)
*/
@Override
public short getShort(int columnIndex) throws InvalidResultSetAccessException {
try {
return this.resultSet.getShort(columnIndex);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getShort(String)
*/
@Override
public short getShort(String columnLabel) throws InvalidResultSetAccessException {
return getShort(findColumn(columnLabel));
}
/**
* @see java.sql.ResultSet#getString(int)
*/
@Override
public String getString(int columnIndex) throws InvalidResultSetAccessException {
try {
return this.resultSet.getString(columnIndex);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getString(String)
*/
@Override
public String getString(String columnLabel) throws InvalidResultSetAccessException {
return getString(findColumn(columnLabel));
}
/**
* @see java.sql.ResultSet#getTime(int)
*/
@Override
public Time getTime(int columnIndex) throws InvalidResultSetAccessException {
try {
return this.resultSet.getTime(columnIndex);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getTime(String)
*/
@Override
public Time getTime(String columnLabel) throws InvalidResultSetAccessException {
return getTime(findColumn(columnLabel));
}
/**
* @see java.sql.ResultSet#getTime(int, Calendar)
*/
@Override
public Time getTime(int columnIndex, Calendar cal) throws InvalidResultSetAccessException {
try {
return this.resultSet.getTime(columnIndex, cal);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getTime(String, Calendar)
*/
@Override
public Time getTime(String columnLabel, Calendar cal) throws InvalidResultSetAccessException {
return getTime(findColumn(columnLabel), cal);
}
/**
* @see java.sql.ResultSet#getTimestamp(int)
*/
@Override
public Timestamp getTimestamp(int columnIndex) throws InvalidResultSetAccessException {
try {
return this.resultSet.getTimestamp(columnIndex);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getTimestamp(String)
*/
@Override
public Timestamp getTimestamp(String columnLabel) throws InvalidResultSetAccessException {
return getTimestamp(findColumn(columnLabel));
}
/**
* @see java.sql.ResultSet#getTimestamp(int, Calendar)
*/
@Override
public Timestamp getTimestamp(int columnIndex, Calendar cal) throws InvalidResultSetAccessException {
try {
return this.resultSet.getTimestamp(columnIndex, cal);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getTimestamp(String, Calendar)
*/
@Override
public Timestamp getTimestamp(String columnLabel, Calendar cal) throws InvalidResultSetAccessException {
return getTimestamp(findColumn(columnLabel), cal);
}
// RowSet navigation methods
/**
* @see java.sql.ResultSet#absolute(int)
*/
@Override
public boolean absolute(int row) throws InvalidResultSetAccessException {
try {
return this.resultSet.absolute(row);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#afterLast()
*/
@Override
public void afterLast() throws InvalidResultSetAccessException {
try {
this.resultSet.afterLast();
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#beforeFirst()
*/
@Override
public void beforeFirst() throws InvalidResultSetAccessException {
try {
this.resultSet.beforeFirst();
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#first()
*/
@Override
public boolean first() throws InvalidResultSetAccessException {
try {
return this.resultSet.first();
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#getRow()
*/
@Override
public int getRow() throws InvalidResultSetAccessException {
try {
return this.resultSet.getRow();
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#isAfterLast()
*/
@Override
public boolean isAfterLast() throws InvalidResultSetAccessException {
try {
return this.resultSet.isAfterLast();
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#isBeforeFirst()
*/
@Override
public boolean isBeforeFirst() throws InvalidResultSetAccessException {
try {
return this.resultSet.isBeforeFirst();
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#isFirst()
*/
@Override
public boolean isFirst() throws InvalidResultSetAccessException {
try {
return this.resultSet.isFirst();
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#isLast()
*/
@Override
public boolean isLast() throws InvalidResultSetAccessException {
try {
return this.resultSet.isLast();
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#last()
*/
@Override
public boolean last() throws InvalidResultSetAccessException {
try {
return this.resultSet.last();
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#next()
*/
@Override
public boolean next() throws InvalidResultSetAccessException {
try {
return this.resultSet.next();
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#previous()
*/
@Override
public boolean previous() throws InvalidResultSetAccessException {
try {
return this.resultSet.previous();
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#relative(int)
*/
@Override
public boolean relative(int rows) throws InvalidResultSetAccessException {
try {
return this.resultSet.relative(rows);
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
/**
* @see java.sql.ResultSet#wasNull()
*/
@Override
public boolean wasNull() throws InvalidResultSetAccessException {
try {
return this.resultSet.wasNull();
}
catch (SQLException se) {
throw new InvalidResultSetAccessException(se);
}
}
}
|
package it.clients.symphony.api;
import clients.symphony.api.PresenceClient;
import clients.symphony.api.constants.PodConstants;
import it.commons.BotTest;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import model.UserPresence;
import org.junit.Before;
import org.junit.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class PresenceClientTest extends BotTest {
private PresenceClient presenceClient;
@Before
public void initClient() {
presenceClient = new PresenceClient(symBotClient);
}
@Test
public void getUserPresenceSuccess() {
stubFor(get(urlEqualTo(PodConstants.GETUSERPRESENCE.replace("{uid}", Long.toString(1L)).concat("?local=true")))
.withHeader(HttpHeaders.ACCEPT, equalTo(MediaType.APPLICATION_JSON))
.withQueryParam("local", equalTo("true"))
.willReturn(aResponse()
.withStatus(200)
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody("{ \"category\": \"AVAILABLE\", \"userId\": 1, \"timestamp\": 1533928483800 }")));
UserPresence userPresence = presenceClient.getUserPresence(1L, true);
assertNotNull(userPresence);
assertEquals(1L, userPresence.getUserId().longValue());
assertEquals("AVAILABLE", userPresence.getCategory());
}
@Test
public void setUserPresenceSuccess() {
stubFor(post(urlEqualTo(PodConstants.SETPRESENCE))
.withHeader(HttpHeaders.ACCEPT, equalTo(MediaType.APPLICATION_JSON))
.willReturn(aResponse()
.withStatus(200)
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody("{ \"category\": \"AWAY\", \"userId\": 1, \"timestamp\": 1503286569882 }")));
UserPresence userPresence = presenceClient.setPresence("AWAY");
assertNotNull(userPresence);
assertEquals(1L, userPresence.getUserId().longValue());
assertEquals("AWAY", userPresence.getCategory());
}
@Test
public void registerInterestExtUserSuccess() {
stubFor(post(urlEqualTo(PodConstants.REGISTERPRESENCEINTEREST))
.withHeader(HttpHeaders.ACCEPT, equalTo(MediaType.APPLICATION_JSON))
.willReturn(aResponse()
.withStatus(200)
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody("{ \"format\": \"TEXT\", \"message\": \"OK\" }")));
List<Long> userIds = Stream.of(1L, 2L, 3L).collect(Collectors.toList());
presenceClient.registerInterestExtUser(userIds);
}
}
|
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.springframework.web.context.request;
import org.junit.Before;
import org.junit.Test;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.tests.sample.beans.DerivedTestBean;
import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.tests.sample.beans.factory.DummyFactory;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
*/
public class RequestScopedProxyTests {
private final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
@Before
public void setup() {
this.beanFactory.registerScope("request", new RequestScope());
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory);
reader.loadBeanDefinitions(new ClassPathResource("requestScopedProxyTests.xml", getClass()));
this.beanFactory.preInstantiateSingletons();
}
@Test
public void testGetFromScope() throws Exception {
String name = "requestScopedObject";
TestBean bean = (TestBean) this.beanFactory.getBean(name);
assertTrue(AopUtils.isCglibProxy(bean));
MockHttpServletRequest request = new MockHttpServletRequest();
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getAttribute("scopedTarget." + name));
assertEquals("scoped", bean.getName());
assertNotNull(request.getAttribute("scopedTarget." + name));
TestBean target = (TestBean) request.getAttribute("scopedTarget." + name);
assertEquals(TestBean.class, target.getClass());
assertEquals("scoped", target.getName());
assertSame(bean, this.beanFactory.getBean(name));
assertEquals(bean.toString(), target.toString());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testGetFromScopeThroughDynamicProxy() throws Exception {
String name = "requestScopedProxy";
ITestBean bean = (ITestBean) this.beanFactory.getBean(name);
assertTrue(AopUtils.isJdkDynamicProxy(bean));
MockHttpServletRequest request = new MockHttpServletRequest();
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getAttribute("scopedTarget." + name));
assertEquals("scoped", bean.getName());
assertNotNull(request.getAttribute("scopedTarget." + name));
TestBean target = (TestBean) request.getAttribute("scopedTarget." + name);
assertEquals(TestBean.class, target.getClass());
assertEquals("scoped", target.getName());
assertSame(bean, this.beanFactory.getBean(name));
assertEquals(bean.toString(), target.toString());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testDestructionAtRequestCompletion() throws Exception {
String name = "requestScopedDisposableObject";
DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name);
assertTrue(AopUtils.isCglibProxy(bean));
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getAttribute("scopedTarget." + name));
assertEquals("scoped", bean.getName());
assertNotNull(request.getAttribute("scopedTarget." + name));
assertEquals(DerivedTestBean.class, request.getAttribute("scopedTarget." + name).getClass());
assertEquals("scoped", ((TestBean) request.getAttribute("scopedTarget." + name)).getName());
assertSame(bean, this.beanFactory.getBean(name));
requestAttributes.requestCompleted();
assertTrue(((TestBean) request.getAttribute("scopedTarget." + name)).wasDestroyed());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testGetFromFactoryBeanInScope() throws Exception {
String name = "requestScopedFactoryBean";
TestBean bean = (TestBean) this.beanFactory.getBean(name);
assertTrue(AopUtils.isCglibProxy(bean));
MockHttpServletRequest request = new MockHttpServletRequest();
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getAttribute("scopedTarget." + name));
assertEquals(DummyFactory.SINGLETON_NAME, bean.getName());
assertNotNull(request.getAttribute("scopedTarget." + name));
assertEquals(DummyFactory.class, request.getAttribute("scopedTarget." + name).getClass());
assertSame(bean, this.beanFactory.getBean(name));
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testGetInnerBeanFromScope() throws Exception {
TestBean bean = (TestBean) this.beanFactory.getBean("outerBean");
assertFalse(AopUtils.isAopProxy(bean));
assertTrue(AopUtils.isCglibProxy(bean.getSpouse()));
String name = "scopedInnerBean";
MockHttpServletRequest request = new MockHttpServletRequest();
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getAttribute("scopedTarget." + name));
assertEquals("scoped", bean.getSpouse().getName());
assertNotNull(request.getAttribute("scopedTarget." + name));
assertEquals(TestBean.class, request.getAttribute("scopedTarget." + name).getClass());
assertEquals("scoped", ((TestBean) request.getAttribute("scopedTarget." + name)).getName());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testGetAnonymousInnerBeanFromScope() throws Exception {
TestBean bean = (TestBean) this.beanFactory.getBean("outerBean");
assertFalse(AopUtils.isAopProxy(bean));
assertTrue(AopUtils.isCglibProxy(bean.getSpouse()));
BeanDefinition beanDef = this.beanFactory.getBeanDefinition("outerBean");
BeanDefinitionHolder innerBeanDef =
(BeanDefinitionHolder) beanDef.getPropertyValues().getPropertyValue("spouse").getValue();
String name = innerBeanDef.getBeanName();
MockHttpServletRequest request = new MockHttpServletRequest();
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getAttribute("scopedTarget." + name));
assertEquals("scoped", bean.getSpouse().getName());
assertNotNull(request.getAttribute("scopedTarget." + name));
assertEquals(TestBean.class, request.getAttribute("scopedTarget." + name).getClass());
assertEquals("scoped", ((TestBean) request.getAttribute("scopedTarget." + name)).getName());
}
finally {
RequestContextHolder.setRequestAttributes(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.netbeans.modules.php.editor.completion;
import java.io.File;
import java.util.Collections;
import java.util.Map;
import org.netbeans.api.java.classpath.ClassPath;
import org.netbeans.modules.php.project.api.PhpSourcePath;
import org.netbeans.spi.java.classpath.support.ClassPathSupport;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
/**
*
* @author Petr Pisl
*/
public class PHPCCDocumentationTest extends PHPCodeCompletionTestBase {
public PHPCCDocumentationTest(String testName) {
super(testName);
}
public void test197696() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/issue197696.php", "$this->te^", false, "");
}
public void testArrayReturnType() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/arrayReturnType.php", "functionNam^e();", false, "");
}
public void testFieldWithDesc() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/fieldVar.php", "$c->fieldWithDes^c;", false, "");
}
public void testFieldWithoutDesc() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/fieldVar.php", "$c1->fieldWithoutDes^c;", false, "");
}
public void testFieldWithDescAndArray() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/fieldVar.php", "$c->arrayFieldWithDes^c;", false, "");
}
public void testFieldWithoutDescAndArray() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/fieldVar.php", "$c1->arrayFieldWithoutDes^c;", false, "");
}
public void testPropertyWithArray() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/propertyWithArray.php", "$this->te^", false, "");
}
public void testFunctionWithArrayParamWithoutDesc() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/functionWithArrayParamWithoutDesc.php", "aFunctionNam^e(null);", false, "");
}
public void testFunctionWithArrayReturnWithoutDesc() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/functionWithArrayReturnWithoutDesc.php", "bFunctionNam^e(null);", false, "");
}
public void testIssue207952_01() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/issue207952.php", "$my->aMagic^Method($paramName);", false, "");
}
public void testIssue207952_02() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/issue207952.php", "$my->nonMagic^Method($paramName);", false, "");
}
public void testIssue207952_03() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/issue207952_nonNs.php", "$my->aMagic^Method($paramName);", false, "");
}
public void testIssue207952_04() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/issue207952_nonNs.php", "$my->nonMagic^Method($paramName);", false, "");
}
public void testIssue215408() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/issue215408.php", "ClassName::F^OO;", false, "");
}
public void testIssue245158_01() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/issue245158.php", "$this->a_wi^th;", false, "");
}
public void testIssue245158_02() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/issue245158.php", "$this->b_with^out;", false, "");
}
// {@inheritdoc} tag
public void testInheritdocClassOnlyTag() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/inheritdoc.php", "class GrandchildClass extends ChildC^lass implements ChildInterface {", false, "");
}
public void testInheritdocClassWithInlineTag() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/inheritdoc.php", "class GrandchildInlineTagClass extends ChildInlineTagC^lass {", false, "");
}
public void testInheritdocInterfaceOnlyTag() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/inheritdoc.php", "class GrandchildClass extends ChildClass implements ChildInterf^ace {", false, "");
}
public void testInheritdocInterfaceWithInlineTag() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/inheritdoc.php", "interface GrandchildInlineTagInterface extends ChildInlineTagI^nterface {", false, "");
}
public void testInheritdocChildMethodOnlyTag() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/inheritdoc.php", "$childClass->testOnlyT^ag($param1, $param2);", false, "");
}
public void testInheritdocGrandchildMethodOnlyTag_01() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/inheritdoc.php", "$grandchildClass->testOnlyT^ag($param1, $param2);", false, "");
}
public void testInheritdocGrandchildMethodOnlyTag_02() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/inheritdoc.php", "$grandchildClass->childInterfaceM^ethod();", false, "");
}
public void testInheritdocNoDocMethod() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/inheritdoc.php", "$childClass->testNoD^oc();", false, "");
}
public void testInheritdocNoTagMethod() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/inheritdoc.php", "$childClass->testNoI^nheritdoc();", false, "");
}
public void testInheritdocMethodWithInlineTag() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/inheritdoc.php", "$grandchildClass->testInlin^e($param1, $param2);", false, "");
}
public void testInheritdocMethodWithMissingParam() throws Exception {
checkCompletionDocumentation("testfiles/completion/documentation/inheritdoc.php", "$childClass->testMissing^Param($param1);", false, "");
}
public void testInheritdocMethodWithInvalidTag() throws Exception {
// not {@inheritdoc} but @inheritdoc
// the same result as the normal tag
checkCompletionDocumentation("testfiles/completion/documentation/inheritdoc.php", "$childClass->testInvalidT^ag();", false, "");
}
@Override
protected String alterDocumentationForTest(String documentation) {
int start = documentation.indexOf("file:");
if (start > 0) {
int end = documentation.indexOf(".php", start);
if (end > 0) {
StringBuilder sb = new StringBuilder();
sb.append(documentation.substring(0, start));
sb.append(documentation.substring(end + 4));
return sb.toString();
}
}
return documentation;
}
@Override
protected Map<String, ClassPath> createClassPathsForTest() {
return Collections.singletonMap(
PhpSourcePath.SOURCE_CP,
ClassPathSupport.createClassPath(new FileObject[] {
FileUtil.toFileObject(new File(getDataDir(), "/testfiles/completion/documentation"))
})
);
}
}
|
package hso.autonomy.tools.developer.bundles.developer.perspective;
import hso.autonomy.tools.util.swing.model.IDisplayableItem;
public interface IViewDescriptor extends IDisplayableItem {
String getViewID();
IView createNewView();
boolean acceptsObject(Object o);
boolean requiresObject();
boolean isManuallyOpenable();
}
|
/*
* SoapUI, Copyright (C) 2004-2016 SmartBear Software
*
* Licensed under the EUPL, Version 1.1 or - as soon as they will be approved by the European Commission - subsequent
* versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* http://ec.europa.eu/idabc/eupl
*
* Unless required by applicable law or agreed to in writing, software distributed under the Licence is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the Licence for the specific language governing permissions and limitations
* under the Licence.
*/
package com.eviware.soapui.impl.wsdl.submit.transports.http;
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.impl.rest.support.MediaTypeHandler;
import com.eviware.soapui.impl.rest.support.MediaTypeHandlerRegistry;
import com.eviware.soapui.impl.support.AbstractHttpRequestInterface;
import com.eviware.soapui.impl.support.http.HttpRequest;
import com.eviware.soapui.impl.wsdl.submit.transports.http.support.metrics.SoapUIMetrics;
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCase;
import com.eviware.soapui.impl.wsdl.teststeps.TestRequest;
import com.eviware.soapui.model.iface.Attachment;
import com.eviware.soapui.model.propertyexpansion.PropertyExpansionContext;
import com.eviware.soapui.model.settings.Settings;
import com.eviware.soapui.model.testsuite.TestCase;
import com.eviware.soapui.settings.HttpSettings;
import com.eviware.soapui.settings.UISettings;
import com.eviware.soapui.support.types.StringToStringMap;
import com.eviware.soapui.support.types.StringToStringsMap;
import org.apache.http.Header;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.util.List;
public abstract class BaseHttpResponse implements HttpResponse {
private StringToStringsMap requestHeaders;
private StringToStringsMap responseHeaders;
private long timeTaken;
private long timestamp;
private String contentType;
private SSLInfo sslInfo;
private URL url;
private WeakReference<AbstractHttpRequestInterface<?>> httpRequest;
private String method;
private String version;
private StringToStringMap properties;
private byte[] rawRequestData;
private byte[] rawResponseData;
private byte[] rawResponseBody;
private int requestContentPos = -1;
private String xmlContent;
private Attachment[] attachments = new Attachment[0];
protected HTMLPageSourceDownloader downloader;
private int statusCode;
public BaseHttpResponse(ExtendedHttpMethod httpMethod, AbstractHttpRequestInterface<?> httpRequest,
PropertyExpansionContext context) {
this.httpRequest = new WeakReference<AbstractHttpRequestInterface<?>>(httpRequest);
this.timeTaken = httpMethod.getTimeTaken();
SoapUIMetrics metrics = httpMethod.getMetrics();
method = httpMethod.getMethod();
version = httpMethod.getProtocolVersion().toString();
try {
this.url = httpMethod.getURL();
} catch (Exception e1) {
SoapUI.logError(e1);
}
if (!httpMethod.isFailed()) {
Settings settings = httpRequest.getSettings();
try {
rawResponseBody = httpMethod.getResponseBody();
} catch (IOException e) {
e.printStackTrace();
}
if (settings.getBoolean(HttpSettings.INCLUDE_RESPONSE_IN_TIME_TAKEN)) {
timeTaken += httpMethod.getResponseReadTime();
}
// metrics.getReadTimer().add( httpMethod.getResponseReadTimeNanos() );
// metrics.getTotalTimer().add( httpMethod.getResponseReadTimeNanos() );
metrics.getReadTimer().add(httpMethod.getResponseReadTime());
metrics.getTotalTimer().add(httpMethod.getResponseReadTime());
try {
this.timestamp = System.currentTimeMillis();
this.contentType = httpMethod.getResponseContentType();
this.statusCode = extractStatusCode(httpMethod);
this.sslInfo = httpMethod.getSSLInfo();
this.url = httpMethod.getURL();
metrics.setTimestamp(getTimestamp());
metrics.setHttpStatus(getStatusCode());
} catch (Exception e) {
e.printStackTrace();
}
}
if (httpRequest instanceof TestRequest) {
TestCase tc = ((TestRequest) httpRequest).getTestStep().getTestCase();
if (tc instanceof WsdlTestCase && ((WsdlTestCase) tc).isForLoadTest()) {
initHeadersForLoadTest(httpMethod);
return;
}
}
initHeaders(httpMethod);
AbstractHttpRequestInterface<?> requestInterface = this.httpRequest.get();
if (requestInterface instanceof HttpRequest) {
boolean downloadIncludedResources = ((HttpRequest) requestInterface).getDownloadIncludedResources();
if (downloadIncludedResources) {
long beforeNanos = System.nanoTime();
addIncludedContentsAsAttachments();
long afterNanos = System.nanoTime();
timeTaken += ((afterNanos - beforeNanos) / 1000000);
metrics.getTotalTimer().add(afterNanos - beforeNanos);
context.setProperty(HTMLPageSourceDownloader.MISSING_RESOURCES_LIST, downloader.getMissingResourcesList());
}
}
}
private int extractStatusCode(ExtendedHttpMethod httpMethod) {
if (httpMethod instanceof HttpStatusHolder) {
return ((HttpStatusHolder) httpMethod).getResponseStatusCode();
} else {
return httpMethod.hasHttpResponse() ? httpMethod.getHttpResponse().getStatusLine()
.getStatusCode() : 0;
}
}
private void addIncludedContentsAsAttachments() {
downloader = new HTMLPageSourceDownloader();
try {
List<Attachment> attachmentList = downloader.downloadCssAndImages(url.toString(),
(HttpRequest) httpRequest.get());
attachments = attachmentList.toArray(new Attachment[attachmentList.size()]);
} catch (ClassCastException cce) {
attachments = new Attachment[1];
try {
attachments[0] = downloader.createAttachment(rawResponseData, url, httpRequest.get());
} catch (IOException e) {
SoapUI.log.error(e);
}
} catch (Exception e) {
SoapUI.log.error(e);
}
}
protected void initHeaders(ExtendedHttpMethod httpMethod) {
try {
ByteArrayOutputStream rawResponse = new ByteArrayOutputStream();
ByteArrayOutputStream rawRequest = new ByteArrayOutputStream();
if (!httpMethod.isFailed() && httpMethod.hasHttpResponse()) {
try {
rawResponse.write(extractStatusLine(httpMethod).getBytes());
rawResponse.write("\r\n".getBytes());
} catch (Exception ignore) {
}
}
rawRequest.write((method + " " + String.valueOf(url) + " " + version + "\r\n").getBytes());
requestHeaders = new StringToStringsMap();
Header[] headers = httpMethod.getAllHeaders();
for (Header header : headers) {
requestHeaders.put(header.getName(), header.getValue());
rawRequest.write(toExternalForm(header).getBytes());
}
responseHeaders = new StringToStringsMap();
if (!httpMethod.isFailed() && httpMethod.hasHttpResponse()) {
headers = httpMethod.getAllResponseHeaders();
for (Header header : headers) {
responseHeaders.put(header.getName(), header.getValue());
rawResponse.write(toExternalForm(header).getBytes());
}
responseHeaders.put("#status#", extractStatusLine(httpMethod));
}
if (httpMethod.getRequestEntity() != null) {
rawRequest.write("\r\n".getBytes());
if (httpMethod.getRequestEntity().isRepeatable()) {
requestContentPos = rawRequest.size();
MaxSizeByteArrayOutputStream tempOut = new MaxSizeByteArrayOutputStream(SoapUI.getSettings().getLong(
UISettings.RAW_REQUEST_MESSAGE_SIZE, 0));
httpMethod.getRequestEntity().writeTo(tempOut);
tempOut.writeTo(rawRequest);
} else {
rawRequest.write("<request data not available>".getBytes());
}
}
if (!httpMethod.isFailed() && httpMethod.hasHttpResponse() && httpMethod.getResponseBody() != null) {
rawResponse.write("\r\n".getBytes());
rawResponse.write(httpMethod.getResponseBody());
}
rawResponseData = rawResponse.toByteArray();
rawRequestData = rawRequest.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
}
private String extractStatusLine(ExtendedHttpMethod httpMethod) {
if (httpMethod instanceof HttpStatusHolder) {
return ((HttpStatusHolder) httpMethod).getResponseStatusLine();
} else {
return String.valueOf(httpMethod.getHttpResponse().getStatusLine());
}
}
public static class MaxSizeByteArrayOutputStream extends ByteArrayOutputStream {
private final long maxSize;
public MaxSizeByteArrayOutputStream(long maxSize) {
this.maxSize = maxSize;
}
@Override
public synchronized void write(int b) {
if (maxSize > 0 && size() < maxSize) {
super.write(b);
}
}
@Override
public synchronized void write(byte[] b, int off, int len) {
if (maxSize > 0 && size() < maxSize) {
if (size() + len < maxSize) {
super.write(b, off, len);
} else {
super.write(b, off, (int) (maxSize - size()));
}
}
}
@Override
public void write(byte[] b) throws IOException {
if (maxSize > 0 && size() < maxSize) {
if (size() + b.length < maxSize) {
super.write(b);
} else {
super.write(b, 0, (int) (maxSize - size()));
}
}
}
}
protected void initHeadersForLoadTest(ExtendedHttpMethod httpMethod) {
try {
requestHeaders = new StringToStringsMap();
Header[] headers = httpMethod.getAllHeaders();
for (Header header : headers) {
requestHeaders.put(header.getName(), header.getValue());
}
if (!httpMethod.isFailed() && httpMethod.hasHttpResponse()) {
responseHeaders = new StringToStringsMap();
headers = httpMethod.getHttpResponse().getAllHeaders();
for (Header header : headers) {
responseHeaders.put(header.getName(), header.getValue());
}
responseHeaders.put("#status#", extractStatusLine(httpMethod));
}
} catch (Throwable e) {
e.printStackTrace();
}
}
public StringToStringsMap getRequestHeaders() {
return requestHeaders;
}
public StringToStringsMap getResponseHeaders() {
return responseHeaders;
}
public long getTimeTaken() {
return timeTaken;
}
public SSLInfo getSSLInfo() {
return sslInfo;
}
public long getTimestamp() {
return timestamp;
}
public String getContentType() {
return contentType;
}
public URL getURL() {
return url;
}
public AbstractHttpRequestInterface<?> getRequest() {
return httpRequest.get();
}
public int getStatusCode() {
return statusCode;
}
public Attachment[] getAttachments() {
return attachments;
}
public Attachment[] getAttachmentsForPart(String partName) {
return new Attachment[0];
}
public byte[] getRawRequestData() {
return rawRequestData;
}
public byte[] getRawResponseData() {
return rawResponseData;
}
public byte[] getRawResponseBody() {
return rawResponseBody;
}
public String getMethod() {
return method;
}
public String getHttpVersion() {
return version;
}
public void setProperty(String name, String value) {
if (properties == null) {
properties = new StringToStringMap();
}
properties.put(name, value);
}
public String getProperty(String name) {
return properties == null ? null : properties.get(name);
}
public String[] getPropertyNames() {
return properties == null ? new String[0] : properties.getKeys();
}
public String getRequestContent() {
return requestContentPos == -1 || rawRequestData == null ? null : new String(rawRequestData, requestContentPos,
rawRequestData.length - requestContentPos);
}
public String getContentAsXml() {
if (xmlContent == null) {
MediaTypeHandler typeHandler = MediaTypeHandlerRegistry.getTypeHandler(getContentType());
xmlContent = (typeHandler == null) ? "<xml/>" : typeHandler.createXmlRepresentation(this);
}
return xmlContent;
}
/**
* Returns a {@link String} representation of the header.
*
* @return stringHEAD
*/
public String toExternalForm(Header header) {
return ((null == header.getName() ? "" : header.getName()) + ": "
+ (null == header.getValue() ? "" : header.getValue()) + "\r\n");
}
}
|
/*-
* Copyright (C) 2006 Erik Larsson
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.takari.jdkget.osx.hfs.types.hfsplus;
import java.io.PrintStream;
import io.takari.jdkget.osx.csjc.PrintableStruct;
import io.takari.jdkget.osx.csjc.StructElements;
import io.takari.jdkget.osx.csjc.structelements.Dictionary;
import io.takari.jdkget.osx.hfs.UnicodeNormalizationToolkit;
import io.takari.jdkget.osx.util.Util;
/** This class was generated by CStructToJavaClass. */
public class HFSUniStr255 implements StructElements, PrintableStruct {
/*
* struct HFSUniStr255
* size: max 512 bytes
* description:
*
* BP Size Type Identifier Description
* ------------------------------------------------
* 0 2 UInt16 length
* 2 2*255 UniChar[255] unicode
*/
private final byte[] length = new byte[2];
private final byte[] unicode;
public HFSUniStr255(byte[] data, int offset) {
System.arraycopy(data, offset + 0, length, 0, 2);
unicode = new byte[2 * Util.unsign(getLength())];
System.arraycopy(data, offset + 2, unicode, 0, unicode.length);
}
public HFSUniStr255(String unicodeString) {
char[] unicodeChars = unicodeString.toCharArray();
if (unicodeChars.length > 255)
throw new RuntimeException("String too large.");
System.arraycopy(Util.toByteArrayBE((short) unicodeChars.length), 0, length, 0, 2);
unicode = Util.readByteArrayBE(unicodeChars);
}
public int length() {
return 2 + unicode.length;
}
public short getLength() {
return Util.readShortBE(length);
}
/**
* Returns the raw bytes constituting this UTF-16BE string.
* @return the raw bytes constituting this UTF-16BE string.
*/
public byte[] getRawUnicode() {
return Util.createCopy(unicode);
}
/** This is a char for char representation of what data is in the actual file system. The string will
(if the filesystem is valid) be in decomposed form, as the HFS+ volume format requires. */
public char[] getUnicode() {
return Util.readCharArrayBE(unicode);
}
/** A simple conversion of the decomposed string from getUnicode() into a String object. */
public String getUnicodeAsDecomposedString() {
return new String(getUnicode());
}
/** Returns a composed string that will differ from the decomposed string whenever the decomposed
string contains decomposed characters. In these cases it will be shorter than the decomposed string */
public String getUnicodeAsComposedString() {
return UnicodeNormalizationToolkit.getDefaultInstance().compose(getUnicodeAsDecomposedString());
}
public byte[] getBytes() {
byte[] result = new byte[length()];
System.arraycopy(length, 0, result, 0, 2);
System.arraycopy(unicode, 0, result, 2, unicode.length);
return result;
}
@Override
public void printFields(PrintStream ps, String prefix) {
ps.println(prefix + " length: " + Util.unsign(getLength()));
ps.println(prefix + " unicode (decomposed): \"" + getUnicodeAsDecomposedString() + "\"");
ps.println(prefix + " (composed): \"" + getUnicodeAsComposedString() + "\"");
}
@Override
public void print(PrintStream ps, String prefix) {
ps.println(prefix + "HFSUniStr255:");
printFields(ps, prefix);
}
@Override
public String toString() {
return getUnicodeAsComposedString();
}
/* @Override */
@Override
public Dictionary getStructElements() {
DictionaryBuilder db = new DictionaryBuilder(HFSUniStr255.class.getSimpleName());
db.addUIntBE("length", length, "Length");
db.addEncodedString("unicode", unicode, "UTF-16BE", "Unicode data");
return db.getResult();
}
}
|
package Zarathustra;
import java.util.Scanner;
public class Variables {
public static void main(String[] args) {
/*
* 자바 기본 자료형 int: 정수(byte, short, long) double: 실수(float) char: 문자 String: 문자열
*/
// 변수: 자료형 변수 이름;
int a; // 정수형 변수
double b; // 실수형 변수
char c; // 문자 변수(1자)
String d; // 문자열 변수
// 상수: final 자료형 변수 이름;
// 변경 불가 자료를 저장하기 위해 사용
// 변수 이름은 대문잘 작성!
final int E;
final double F;
final char G;
final String H;
// 자바 예약어는 변수 이름으로 사용 불가.
// int if;
// foible import;
// char System // 비추!
// Strinh String //비추// !
// 회원정보 (이이디, 비밀번호, 이름, 나이)
String userid; // id, uid, 아이
String passwd; // password, pwd
String name; // 이름
// String name, passwd, name;
// String name="x", passwd="y", name="z"
// 동일한 자료형 변수들은 ,로 구분해서 한번에 선언 가능(가독성에 좋지 않아 비추).
int age;
// 리터널: 컴파일러가 이해할 수 있는 형식으로 작성괸 데이터나 값
long jumin = 1234567L;
// 변수 초기화: 변수에 값을 대입
// 변수명 - 값;
userid = "zzyzzy";
passwd = "987654";
name = "suji";
age = 23;
b = 123.256;
float pi = 3.145678F;
c = '수';
G = 'a';
// 변수 VS 상수
c = '우';
// G = 'x'; // 상수는 값이 한번 할당되면 변경 불가
// 선언과 초기화
int i = 132;
double j = 987.124;
boolean k = true; // 논리형 변수
k = false;
// k = 123;
// k = '가';
// 변수/상수 이름
// 변수는 일반적으로 소문자
// 만일 이름을 두 낱말로 구성하는 경우
// camel 표기법을 사용.
int juminCode;
String sayHello;
// 상수는 모두 대문자로 작성
// 두 낱말 이상일 경우
// 각 낱말은 _으로 이어 사용.
final double PI = 3.14;
final int THIS_YEAR = 2017;
final String USER_ID = "zzyzzy";
// JDK7부터도입된 자릿수 표시:
jumin = 1234567l;
jumin = 12_345_67l;
char ch = '가';
// 문자와 숫자 간 변환
System.out.println(ch);
System.out.println((int) ch);
// 특수문자 표현 - escape sequence
System.out.println("가 나");
System.out.println("가\t나");// 탭문자
System.out.println("가\n나"); // 줄바꿈문자
System.out.println("가\"나"); // 큰따옴표 문자
System.out.println("가\'나"); // 작은따옴표 문자
// 변수 출력하는 방법
System.out.println(jumin);
System.out.println(passwd);
System.out.println(name);
System.out.println(age);
System.out.println("아이디: " + userid + "주민번호: " + jumin);
System.out.println(jumin);
System.out.println(passwd);
System.out.println(name);
System.out.println(age);
// 서식화된 출력 - printf
System.out.printf("아이디 : %s, 비밀번호: %s, 나이: %s, 이름: %s \n", userid, passwd, age, name);
String fmt = "아이디 : %s, 비밀번호: %s \n";
System.out.printf(fmt, userid, passwd);
// double vs float : 오차범위 주의
float avg1 = 296 / 3.0f;
double avg2 = 296 / 3.0;
System.out.println(avg1);
System.out.println(avg2);
// 되도록 float 말고 double을 쓰자.
// 키보드로 데이터 입력받기
Scanner sc = new Scanner(System.in);
System.out.print("아이디를 입력하세요");
userid = sc.nextLine();
System.out.print("패스워드를 입력하세요");
passwd = sc.nextLine();
name = sc.nextLine();
age = Integer.parseInt(sc.nextLine());
System.out.printf(fmt, userid, passwd);
}
}
|
/*
* Copyright information and license terms for this software can be
* found in the file LICENSE that is included with the distribution
*/
package org.epics.pvdata;
import junit.framework.TestCase;
import org.epics.pvdata.factory.PVDataFactory;
import org.epics.pvdata.pv.PVByteArray;
import org.epics.pvdata.pv.PVDataCreate;
import org.epics.pvdata.pv.PVDoubleArray;
import org.epics.pvdata.pv.PVFloatArray;
import org.epics.pvdata.pv.PVIntArray;
import org.epics.pvdata.pv.PVLongArray;
import org.epics.pvdata.pv.PVNumberArray;
import org.epics.pvdata.pv.PVShortArray;
import org.epics.pvdata.pv.PVUByteArray;
import org.epics.pvdata.pv.PVUIntArray;
import org.epics.pvdata.pv.PVULongArray;
import org.epics.pvdata.pv.PVUShortArray;
import org.epics.pvdata.pv.ScalarType;
import org.epics.util.array.ArrayByte;
import org.epics.util.array.ArrayDouble;
import org.epics.util.array.ArrayFloat;
import org.epics.util.array.ArrayInteger;
import org.epics.util.array.ArrayLong;
import org.epics.util.array.ArrayShort;
import org.epics.util.array.ArrayUByte;
import org.epics.util.array.ArrayUInteger;
import org.epics.util.array.ArrayULong;
import org.epics.util.array.ArrayUShort;
import org.epics.util.array.CollectionNumbers;
import org.epics.util.array.ListNumber;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
public class NumericArrayTest extends TestCase {
public void testPutDoubleArray1() {
PVDataCreate factory = PVDataFactory.getPVDataCreate();
PVDoubleArray pvArray = (PVDoubleArray) factory.createPVScalarArray(ScalarType.pvDouble);
assertThat(pvArray.get(), instanceOf(ArrayDouble.class));
pvArray.put(0, CollectionNumbers.toListDouble(0,1,2,3,4,5,6,7,8,9));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListDouble(0,1,2,3,4,5,6,7,8,9)));
pvArray.put(2, CollectionNumbers.toListFloat(3,2));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListDouble(0,1,3,2,4,5,6,7,8,9)));
}
public void testPutFloatArray1() {
PVDataCreate factory = PVDataFactory.getPVDataCreate();
PVFloatArray pvArray = (PVFloatArray) factory.createPVScalarArray(ScalarType.pvFloat);
assertThat(pvArray.get(), instanceOf(ArrayFloat.class));
pvArray.put(0, CollectionNumbers.toListFloat(0,1,2,3,4,5,6,7,8,9));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListFloat(0,1,2,3,4,5,6,7,8,9)));
pvArray.put(2, CollectionNumbers.toListDouble(3,2));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListFloat(0,1,3,2,4,5,6,7,8,9)));
}
public void testPutLongArray1() {
PVDataCreate factory = PVDataFactory.getPVDataCreate();
PVLongArray pvArray = (PVLongArray) factory.createPVScalarArray(ScalarType.pvLong);
assertThat(pvArray.get(), instanceOf(ArrayLong.class));
pvArray.put(0, CollectionNumbers.toListLong(0,1,2,3,4,5,6,7,8,9));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListLong(0,1,2,3,4,5,6,7,8,9)));
pvArray.put(2, CollectionNumbers.toListInt(3,2));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListLong(0,1,3,2,4,5,6,7,8,9)));
}
public void testPutULongArray1() {
PVDataCreate factory = PVDataFactory.getPVDataCreate();
PVULongArray pvArray = (PVULongArray) factory.createPVScalarArray(ScalarType.pvULong);
assertThat(pvArray.get(), instanceOf(ArrayULong.class));
pvArray.put(0, CollectionNumbers.toListULong(0,1,2,3,4,5,6,7,8,9));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListULong(0,1,2,3,4,5,6,7,8,9)));
pvArray.put(2, CollectionNumbers.toListInt(3,2));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListULong(0,1,3,2,4,5,6,7,8,9)));
}
public void testPutIntArray1() {
PVDataCreate factory = PVDataFactory.getPVDataCreate();
PVIntArray pvArray = (PVIntArray) factory.createPVScalarArray(ScalarType.pvInt);
assertThat(pvArray.get(), instanceOf(ArrayInteger.class));
pvArray.put(0, CollectionNumbers.toListInt(0,1,2,3,4,5,6,7,8,9));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListInt(0,1,2,3,4,5,6,7,8,9)));
pvArray.put(2, CollectionNumbers.toListLong(3,2));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListInt(0,1,3,2,4,5,6,7,8,9)));
}
public void testPutUIntArray1() {
PVDataCreate factory = PVDataFactory.getPVDataCreate();
PVUIntArray pvArray = (PVUIntArray) factory.createPVScalarArray(ScalarType.pvUInt);
assertThat(pvArray.get(), instanceOf(ArrayUInteger.class));
pvArray.put(0, CollectionNumbers.toListUInt(0,1,2,3,4,5,6,7,8,9));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListUInt(0,1,2,3,4,5,6,7,8,9)));
pvArray.put(2, CollectionNumbers.toListLong(3,2));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListUInt(0,1,3,2,4,5,6,7,8,9)));
}
public void testPutShortArray1() {
PVDataCreate factory = PVDataFactory.getPVDataCreate();
PVShortArray pvArray = (PVShortArray) factory.createPVScalarArray(ScalarType.pvShort);
assertThat(pvArray.get(), instanceOf(ArrayShort.class));
pvArray.put(0, CollectionNumbers.toListShort(new short[] {0,1,2,3,4,5,6,7,8,9}));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListShort(new short[] {0,1,2,3,4,5,6,7,8,9})));
pvArray.put(2, CollectionNumbers.toListInt(3,2));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListShort(new short[] {0,1,3,2,4,5,6,7,8,9})));
}
public void testPutUShortArray1() {
PVDataCreate factory = PVDataFactory.getPVDataCreate();
PVUShortArray pvArray = (PVUShortArray) factory.createPVScalarArray(ScalarType.pvUShort);
assertThat(pvArray.get(), instanceOf(ArrayUShort.class));
pvArray.put(0, CollectionNumbers.toListUShort(new short[] {0,1,2,3,4,5,6,7,8,9}));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListUShort(new short[] {0,1,2,3,4,5,6,7,8,9})));
pvArray.put(2, CollectionNumbers.toListInt(3,2));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListUShort(new short[] {0,1,3,2,4,5,6,7,8,9})));
}
public void testPutByteArray1() {
PVDataCreate factory = PVDataFactory.getPVDataCreate();
PVByteArray pvArray = (PVByteArray) factory.createPVScalarArray(ScalarType.pvByte);
assertThat(pvArray.get(), instanceOf(ArrayByte.class));
pvArray.put(0, CollectionNumbers.toListByte(new byte[] {0,1,2,3,4,5,6,7,8,9}));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListByte(new byte[] {0,1,2,3,4,5,6,7,8,9})));
pvArray.put(2, CollectionNumbers.toListInt(3,2));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListByte(new byte[] {0,1,3,2,4,5,6,7,8,9})));
}
public void testPutUByteArray1() {
PVDataCreate factory = PVDataFactory.getPVDataCreate();
PVUByteArray pvArray = (PVUByteArray) factory.createPVScalarArray(ScalarType.pvUByte);
assertThat(pvArray.get(), instanceOf(ArrayUByte.class));
pvArray.put(0, CollectionNumbers.toListUByte(new byte[] {0,1,2,3,4,5,6,7,8,9}));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListUByte(new byte[] {0,1,2,3,4,5,6,7,8,9})));
pvArray.put(2, CollectionNumbers.toListInt(3,2));
assertThat(pvArray.get(), equalTo(CollectionNumbers.toListUByte(new byte[] {0,1,3,2,4,5,6,7,8,9})));
}
public void testPutNumericArray1() {
PVDataCreate factory = PVDataFactory.getPVDataCreate();
PVNumberArray pvArray = (PVNumberArray) factory.createPVScalarArray(ScalarType.pvInt);
assertThat(pvArray.get(), instanceOf(ArrayInteger.class));
pvArray.put(0, CollectionNumbers.toListInt(0,1,2,3,4,5,6,7,8,9));
assertThat(pvArray.get(), equalTo((ListNumber) CollectionNumbers.toListInt(0,1,2,3,4,5,6,7,8,9)));
pvArray.put(2, CollectionNumbers.toListInt(3,2));
assertThat(pvArray.get(), equalTo((ListNumber) CollectionNumbers.toListInt(0,1,3,2,4,5,6,7,8,9)));
}
}
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.jarRepository.settings;
import com.intellij.ide.IdeBundle;
import com.intellij.jarRepository.JarRepositoryManager;
import com.intellij.jarRepository.RemoteRepositoriesConfiguration;
import com.intellij.jarRepository.RemoteRepositoryDescription;
import com.intellij.jarRepository.services.MavenRepositoryServicesManager;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.CollectionListModel;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.ListUtil;
import com.intellij.ui.SimpleListCellRenderer;
import com.intellij.ui.components.JBList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
public class RemoteRepositoriesConfigurable implements SearchableConfigurable, Configurable.NoScroll {
private JPanel myMainPanel;
private JBList<String> myServiceList;
private JButton myAddServiceButton;
private JButton myEditServiceButton;
private JButton myRemoveServiceButton;
private JButton myTestServiceButton;
private JBList<RemoteRepositoryDescription> myJarRepositoryList;
private JButton myAddRepoButton;
private JButton myEditRepoButton;
private JButton myRemoveRepoButton;
private JButton myResetToDefaultReposButton;
private JButton myResetToDefaultServicesButton;
private JPanel myMavenPanel;
private JPanel myServiceListPanel;
private final Project myProject;
private final CollectionListModel<String> myServicesModel = new CollectionListModel<>();
private final CollectionListModel<RemoteRepositoryDescription> myReposModel = new CollectionListModel<>();
public RemoteRepositoriesConfigurable(Project project) {
myProject = project;
configControls();
}
@Override
public boolean isModified() {
return isServiceListModified() || isRepoListModified();
}
private boolean isServiceListModified() {
return !myServicesModel.getItems().equals(MavenRepositoryServicesManager.getInstance(myProject).getUrls());
}
private boolean isRepoListModified() {
final List<RemoteRepositoryDescription> repos = RemoteRepositoriesConfiguration.getInstance(myProject).getRepositories();
return !myReposModel.getItems().equals(repos);
}
private void configControls() {
myMavenPanel.setBorder(IdeBorderFactory.createTitledBorder(IdeBundle.message("settings.remote.repo.maven.jar.repositories"), false, JBUI.insetsTop(8)).setShowLine(false));
myServiceListPanel.setBorder(IdeBorderFactory.createTitledBorder(IdeBundle.message(
"settings.remote.repo.artifactory.nexus.or.bintray.service.urls"), false, JBUI.insetsTop(8)).setShowLine(false));
setupListControls(
myServiceList, myServicesModel, myAddServiceButton, myEditServiceButton, myRemoveServiceButton,
IdeBundle.message("settings.remote.repo.artifactory.nexus.or.bintray"), IdeBundle.message("settings.remote.repo.service.url"),
IdeBundle.message("settings.remote.repo.no.services"), DataAdapter.STRING_ADAPTER
);
setupListControls(
myJarRepositoryList, myReposModel, myAddRepoButton, myEditRepoButton, myRemoveRepoButton,
IdeBundle.message("settings.remote.repo.maven.repository.url"),
IdeBundle.message("settings.remote.repo.Maven.Repository.URL"),
IdeBundle.message("settings.remote.repo.no.remote.repositories"), DataAdapter.REPOSITORY_DESCRIPTION_ADAPTER
);
ListUtil.disableWhenNoSelection(myTestServiceButton, myServiceList);
myTestServiceButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final String value = myServiceList.getSelectedValue();
if (!StringUtil.isEmpty(value)) {
myTestServiceButton.setEnabled(false);
JarRepositoryManager.searchRepositories(myProject, Collections.singletonList(value), infos -> {
myTestServiceButton.setEnabled(true);
if (infos.isEmpty()) {
Messages.showMessageDialog(IdeBundle.message("settings.remote.repo.no.repositories.found"),
IdeBundle.message("settings.remote.repo.service.connection.failed"), Messages.getWarningIcon());
}
else {
final StringBuilder sb = new StringBuilder();
sb.append(infos.size()).append(" ").append(StringUtil.pluralize("repository", infos.size())).append(" found");
//for (MavenRepositoryInfo info : infos) {
// sb.append("\n ");
// sb.append(info.getId()).append(" (").append(info.getName()).append(")").append(": ").append(info.getUrl());
//}
Messages.showMessageDialog(sb.toString(), IdeBundle.message("settings.remote.repo.service.connection.successful"),
Messages.getInformationIcon());
}
return true;
});
}
}
});
myResetToDefaultReposButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
resetReposModel(RemoteRepositoryDescription.DEFAULT_REPOSITORIES);
}
});
myResetToDefaultServicesButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
resetServicesModel(MavenRepositoryServicesManager.DEFAULT_SERVICES);
}
});
}
private interface DataAdapter<Data, Presentation> {
DataAdapter<String, String> STRING_ADAPTER = new DataAdapter<String, String>() {
@Override
public String toPresentation(String s) {
return s;
}
@Override
public String create(String s) {
return s;
}
@Override
public String change(String current, String changes) {
return changes;
}
};
DataAdapter<RemoteRepositoryDescription, String> REPOSITORY_DESCRIPTION_ADAPTER = new DataAdapter<RemoteRepositoryDescription, String>() {
@Override
public String toPresentation(RemoteRepositoryDescription description) {
return description.getUrl();
}
@Override
public RemoteRepositoryDescription create(String url) {
final UUID uuid = UUID.randomUUID();
return new RemoteRepositoryDescription(uuid.toString(), uuid.toString(), url);
}
@Override
public RemoteRepositoryDescription change(RemoteRepositoryDescription current, String url) {
return new RemoteRepositoryDescription(current.getId(), current.getName(), url);
}
};
Presentation toPresentation(Data data);
Data create(Presentation presentation);
Data change(Data current, Presentation changes);
}
private static <T> void setupListControls(final JBList<T> list,
final CollectionListModel<T> model,
final JButton addButton,
final JButton editButton,
final JButton removeButton,
final String modificationDialogTitle,
final String modificationDialogHint,
final String emptyListHint, DataAdapter<T, String> adapter) {
list.setModel(model);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setCellRenderer(SimpleListCellRenderer.create("", adapter::toPresentation));
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final T value = list.getSelectedValue();
@NonNls String defaultValue = "https://";
String initialValue = value == null ? defaultValue : adapter.toPresentation(value);
final String text = Messages.showInputDialog(
modificationDialogTitle, IdeBundle.message("add.0", modificationDialogHint), Messages.getQuestionIcon(),
initialValue, new URLInputVaslidator()
);
if (StringUtil.isNotEmpty(text)) {
model.add(adapter.create(text));
list.setSelectedValue(text, true);
}
}
});
editButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final int index = list.getSelectedIndex();
final T element = model.getElementAt(index);
final String text = Messages.showInputDialog(
modificationDialogTitle, IdeBundle.message("edit.0", modificationDialogHint), Messages.getQuestionIcon(), adapter.toPresentation(element), new URLInputVaslidator()
);
if (StringUtil.isNotEmpty(text)) {
model.setElementAt(adapter.change(element, text), index);
}
}
});
ListUtil.addRemoveListener(removeButton, list);
ListUtil.disableWhenNoSelection(editButton, list);
list.getEmptyText().setText(emptyListHint);
}
@Override
public String getDisplayName() {
return IdeBundle.message("configurable.RemoteRepositoriesConfigurable.display.name");
}
@Override
public String getHelpTopic() {
return "reference.jar.repositories";
}
@Override
@NotNull
public String getId() {
return getClass().getName();
}
@Override
public JComponent createComponent() {
return myMainPanel;
}
@Override
public void apply() throws ConfigurationException {
List<String> newUrls = ContainerUtil.map(myReposModel.getItems(), RemoteRepositoryDescription::getUrl);
List<String> oldUrls = ContainerUtil.map(RemoteRepositoriesConfiguration.getInstance(myProject).getRepositories(), RemoteRepositoryDescription::getUrl);
MavenRepositoryServicesManager.getInstance(myProject).setUrls(myServicesModel.getItems());
RemoteRepositoriesConfiguration.getInstance(myProject).setRepositories(myReposModel.getItems());
if (!newUrls.containsAll(oldUrls)) {
RepositoryLibrariesReloaderKt.reloadAllRepositoryLibraries(myProject);
}
}
@Override
public void reset() {
resetServicesModel(MavenRepositoryServicesManager.getInstance(myProject).getUrls());
resetReposModel(RemoteRepositoriesConfiguration.getInstance(myProject).getRepositories());
}
private void resetServicesModel(final List<String> urls) {
myServicesModel.removeAll();
myServicesModel.add(urls);
}
private void resetReposModel(final List<RemoteRepositoryDescription> repositories) {
myReposModel.replaceAll(repositories);
}
private static final class URLInputVaslidator implements InputValidator {
@Override
public boolean checkInput(String inputString) {
try {
return StringUtil.isNotEmpty(new URL(inputString).getHost());
}
catch (MalformedURLException e) {
return false;
}
}
@Override
public boolean canClose(String inputString) {
return checkInput(inputString);
}
}
}
|
/*
* Copyright (c) 2014 Spotify AB.
*
* 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.spotify.helios.system;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Range;
import com.spotify.docker.client.DefaultDockerClient;
import com.spotify.helios.Polling;
import com.spotify.helios.agent.AgentMain;
import com.spotify.helios.client.HeliosClient;
import com.spotify.helios.common.descriptors.HostStatus;
import com.spotify.helios.common.descriptors.JobId;
import com.spotify.helios.common.descriptors.PortMapping;
import com.spotify.helios.common.descriptors.TaskStatus;
import org.junit.Test;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Callable;
import static com.spotify.helios.common.descriptors.HostStatus.Status.UP;
import static com.spotify.helios.common.descriptors.Job.EMPTY_ENV;
import static com.spotify.helios.common.descriptors.TaskStatus.State.RUNNING;
import static java.util.concurrent.TimeUnit.MINUTES;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class MultiplePortJobTest extends SystemTestBase {
private final int externalPort1 = temporaryPorts.localPort("external-1");
private final int externalPort2 = temporaryPorts.localPort("external-2");
@Test
public void test() throws Exception {
startDefaultMaster();
final Range<Integer> portRange = temporaryPorts.localPortRange("agent1", 2);
final AgentMain agent1 = startDefaultAgent(testHost(), "--port-range=" +
portRange.lowerEndpoint() + ":" +
portRange.upperEndpoint());
try (final DefaultDockerClient dockerClient = new DefaultDockerClient(DOCKER_HOST.uri())) {
final HeliosClient client = defaultClient();
awaitHostStatus(client, testHost(), UP, LONG_WAIT_MINUTES, MINUTES);
final Map<String, PortMapping> ports1 =
ImmutableMap.of("foo", PortMapping.of(4711),
"bar", PortMapping.of(4712, externalPort1));
final ImmutableMap<String, PortMapping> expectedMapping1 =
ImmutableMap.of("foo", PortMapping.of(4711, portRange.lowerEndpoint()),
"bar", PortMapping.of(4712, externalPort1));
final Map<String, PortMapping> ports2 =
ImmutableMap.of("foo", PortMapping.of(4711),
"bar", PortMapping.of(4712, externalPort2));
final ImmutableMap<String, PortMapping> expectedMapping2 =
ImmutableMap.of("foo", PortMapping.of(4711, portRange.lowerEndpoint() + 1),
"bar", PortMapping.of(4712, externalPort2));
final JobId jobId1 = createJob(testJobName + 1, testJobVersion, BUSYBOX, IDLE_COMMAND,
EMPTY_ENV, ports1);
assertNotNull(jobId1);
deployJob(jobId1, testHost());
final TaskStatus firstTaskStatus1 = awaitJobState(client, testHost(), jobId1, RUNNING,
LONG_WAIT_MINUTES, MINUTES);
final JobId jobId2 = createJob(testJobName + 2, testJobVersion, BUSYBOX, IDLE_COMMAND,
EMPTY_ENV, ports2);
assertNotNull(jobId2);
deployJob(jobId2, testHost());
final TaskStatus firstTaskStatus2 = awaitJobState(client, testHost(), jobId2, RUNNING,
LONG_WAIT_MINUTES, MINUTES);
assertEquals(expectedMapping1, firstTaskStatus1.getPorts());
assertEquals(expectedMapping2, firstTaskStatus2.getPorts());
// TODO (dano): the supervisor should report the allocated ports at all times
// Verify that port allocation is kept across container restarts
dockerClient.killContainer(firstTaskStatus1.getContainerId());
final TaskStatus restartedTaskStatus1 = Polling.await(
LONG_WAIT_MINUTES, MINUTES, new Callable<TaskStatus>() {
@Override
public TaskStatus call() throws Exception {
final HostStatus hostStatus = client.hostStatus(testHost()).get();
final TaskStatus taskStatus = hostStatus.getStatuses().get(jobId1);
return (taskStatus != null && taskStatus.getState() == RUNNING &&
!Objects.equals(taskStatus.getContainerId(), firstTaskStatus1.getContainerId()))
? taskStatus : null;
}
});
assertEquals(expectedMapping1, restartedTaskStatus1.getPorts());
// Verify that port allocation is kept across agent restarts
agent1.stopAsync().awaitTerminated();
dockerClient.killContainer(firstTaskStatus2.getContainerId());
startDefaultAgent(testHost());
final TaskStatus restartedTaskStatus2 = Polling.await(
LONG_WAIT_MINUTES, MINUTES, new Callable<TaskStatus>() {
@Override
public TaskStatus call() throws Exception {
final HostStatus hostStatus = client.hostStatus(testHost()).get();
final TaskStatus taskStatus = hostStatus.getStatuses().get(jobId2);
return (taskStatus != null && taskStatus.getState() == RUNNING &&
!Objects.equals(taskStatus.getContainerId(), firstTaskStatus2.getContainerId()))
? taskStatus : null;
}
});
assertEquals(expectedMapping2, restartedTaskStatus2.getPorts());
}
}
}
|
/*
* 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.solr.client.solrj.io.eval;
import java.io.IOException;
import java.util.Collection;
import java.util.Locale;
import org.apache.solr.client.solrj.io.stream.expr.StreamExpression;
import org.apache.solr.client.solrj.io.stream.expr.StreamFactory;
public class LengthEvaluator extends RecursiveObjectEvaluator implements OneValueWorker {
protected static final long serialVersionUID = 1L;
public LengthEvaluator(StreamExpression expression, StreamFactory factory) throws IOException{
super(expression, factory);
if(1 != containedEvaluators.size()){
throw new IOException(String.format(Locale.ROOT,"Invalid expression %s - expecting exactly 1 value but found %d",expression,containedEvaluators.size()));
}
}
@Override
public Object doWork(Object value) throws IOException{
if(null == value){
throw new IOException(String.format(Locale.ROOT, "Unable to find %s(...) because the value is null", constructingFactory.getFunctionName(getClass())));
}
else if(value instanceof Collection<?>){
return ((Collection<?>)value).size();
}
else{
throw new IOException(String.format(Locale.ROOT, "Unable to find %s(...) because the value is not a collection, instead a %s was found", constructingFactory.getFunctionName(getClass()), value.getClass().getSimpleName()));
}
}
}
|
package com.shaft.api;
import com.shaft.tools.io.ReportManagerHelper;
import io.restassured.config.RestAssuredConfig;
import io.restassured.config.SSLConfig;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import static io.restassured.RestAssured.config;
public class RequestBuilder {
private RestActions session;
private Map<String, String> sessionHeaders;
private Map<String, Object> sessionCookies;
private List<RestAssuredConfig> sessionConfigs;
private RestActions.RequestType requestType;
private String serviceName;
private String serviceURI;
private int targetStatusCode;
private String urlArguments = null;
private List<List<Object>> parameters = null;
private RestActions.ParametersType parametersType = null;
private Object requestBody = null;
private String contentType = null;
private AuthenticationType authenticationType;
private String authenticationUsername;
private String authenticationPassword;
private boolean appendDefaultContentCharsetToContentTypeIfUndefined;
private boolean urlEncodingEnabled;
/**
* Start building a new API request.
*
* @param serviceURI the base URI of the webservice that you want to hit
* @param serviceName the path/name of the webservice that you want to hit {/servicePATH/serviceNAME}
* @param requestType the type of your API request {POST, GET, PATCH, DELETE, PUT}
*/
RequestBuilder(String serviceURI, String serviceName, RestActions.RequestType requestType) {
initializeVariables(new RestActions(serviceURI), serviceName, requestType);
}
/**
* Start building a new API request from an existing RestActions session.
*
* @param session the RestActions session that contains your serviceURI/cookies/headers
* @param serviceName the path/name of the webservice that you want to hit {/servicePATH/serviceNAME}
* @param requestType the type of your API request {POST, GET, PATCH, DELETE, PUT}
*/
RequestBuilder(RestActions session, String serviceName, RestActions.RequestType requestType) {
initializeVariables(session, serviceName, requestType);
}
private void initializeVariables(RestActions session, String serviceName, RestActions.RequestType requestType) {
this.session = session;
this.serviceURI = session.getServiceURI();
this.sessionCookies = session.getSessionCookies();
this.sessionHeaders = session.getSessionHeaders();
this.sessionConfigs = session.getSessionConfigs();
this.requestType = requestType;
this.serviceName = serviceName;
this.targetStatusCode = 200;
this.contentType = ContentType.ANY.toString();
this.authenticationType = AuthenticationType.NONE;
this.appendDefaultContentCharsetToContentTypeIfUndefined = true;
this.urlEncodingEnabled = true;
}
/**
* set useRelaxedHTTPSValidation configuration to trust all hosts regardless if the SSL certificate is invalid in the request builder
* 'SSL' is the protocol name by default
*
* @return a self-reference to be used to continue building your API request
*/
public RequestBuilder useRelaxedHTTPSValidation() {
useRelaxedHTTPSValidation("SSL");
return this;
}
/**
* set useRelaxedHTTPSValidation configuration to trust all hosts regardless if the SSL certificate is invalid in the request builder
* *
*
* @param protocol The standard name of the requested protocol.
* @return a self-reference to be used to continue building your API request
*/
@SuppressWarnings("UnusedReturnValue")
public RequestBuilder useRelaxedHTTPSValidation(String protocol) {
addConfig(config().sslConfig(SSLConfig.sslConfig().relaxedHTTPSValidation(protocol)));
return this;
}
/**
* Sets the expected target status code for the API request that you're currently building. By default, this value is set to 200, but you can change it by calling this method.
*
* @param targetStatusCode the expected target status code.
* @return a self-reference to be used to continue building your API request
*/
public RequestBuilder setTargetStatusCode(int targetStatusCode) {
this.targetStatusCode = targetStatusCode;
return this;
}
/**
* Sets the url arguments (if any) for the API request that you're currently building. A request usually has only one of the following: urlArguments, parameters+type, or body
*
* @param urlArguments '&' separated arguments without a preceding '?', is nullable, Example: "username=test&password=test"
* @return a self-reference to be used to continue building your API request
*/
public RequestBuilder setUrlArguments(String urlArguments) {
this.urlArguments = urlArguments;
return this;
}
/**
* Sets the parameters (if any) for the API request that you're currently building. A request usually has only one of the following: urlArguments, parameters+type, or body
*
* @param parameters a list of key/value pairs that will be sent as parameters with this API call, is nullable, Example: Arrays.asList(Arrays.asList("itemId", "123"), Arrays.asList("contents", XMLcontents));
* @param parametersType FORM, QUERY
* @return a self-reference to be used to continue building your API request
*/
public RequestBuilder setParameters(List<List<Object>> parameters, RestActions.ParametersType parametersType) {
this.parameters = parameters;
this.parametersType = parametersType;
return this;
}
/**
* Sets the body (if any) for the API request that you're currently building. A request usually has only one of the following: urlArguments, parameters+type, or body
*
* @param requestBody Specify an Object request content that will automatically be serialized to JSON or XML and sent with the request. If the object is a primitive or Number the object will be converted to a String and put in the request body. This works for the POST, PUT and PATCH methods only. Trying to do this for the other http methods will cause an exception to be thrown.
* @return a self-reference to be used to continue building your API request
*/
public RequestBuilder setRequestBody(Object requestBody) {
this.requestBody = requestBody;
return this;
}
/**
* Sets the content type for the API request that you're currently building. By default, this value is set to ContentType.ANY but you can change it by calling this method.
*
* @param contentType Enumeration of common IANA content-types. This may be used to specify a request or response content-type more easily than specifying the full string each time. Example: ContentType.ANY
* @return a self-reference to be used to continue building your API request
*/
public RequestBuilder setContentType(ContentType contentType) {
this.contentType = contentType.toString();
return this;
}
/**
* Sets the content type for the API request that you're currently building. By default, this value is set to ContentType.ANY but you can change it by calling this method.
*
* @param contentType String value representing IANA content-type.
* @return a self-reference to be used to continue building your API request
*/
public RequestBuilder setContentType(String contentType) {
this.contentType = contentType;
return this;
}
/**
* Tells whether REST Assured should automatically append the content charset to the content-type header if not defined explicitly.
* Note that this does not affect multipart form data.
* Default is true.
*
* @param appendDefaultContentCharsetToContentTypeIfUndefined Whether REST Assured should automatically append the content charset to the content-type header if not defined explicitly.
* @return a self-reference to be used to continue building your API request
*/
public RequestBuilder appendDefaultContentCharsetToContentTypeIfUndefined(boolean appendDefaultContentCharsetToContentTypeIfUndefined) {
this.appendDefaultContentCharsetToContentTypeIfUndefined = appendDefaultContentCharsetToContentTypeIfUndefined;
return this;
}
/**
* Tells whether REST Assured should automatically encode the URI if not defined explicitly.
* Note that this does not affect multipart form data.
* Default is true.
*
* @param urlEncodingEnabled Whether REST Assured should automatically encode the URI if not defined explicitly.
* @return a self-reference to be used to continue building your API request
*/
public RequestBuilder enableUrlEncoding(boolean urlEncodingEnabled) {
this.urlEncodingEnabled = urlEncodingEnabled;
return this;
}
/**
* Append a header to the current session to be used in the current and all the following requests. This feature is commonly used for authentication tokens.
*
* @param key the name of the header that you want to add
* @param value the value that will be put inside the key
* @return a self-reference to be used to continue building your API request
*/
public RequestBuilder addHeader(String key, String value) {
this.sessionHeaders.put(key, value);
return this;
}
/**
* Append a config to the current session to be used in the current and all the following requests.
*
* @param config the rest assured config you want to add.
* @return a self-reference to be used to continue building your API request
*/
@SuppressWarnings("UnusedReturnValue")
public RequestBuilder addConfig(RestAssuredConfig config) {
this.sessionConfigs.add(config);
return this;
}
/**
* Append a cookie to the current session to be used in the current and all the following requests. This feature is commonly used for authentication cookies.
*
* @param key the name of the cookie that you want to add
* @param value the value that will be put inside the key
* @return a self-reference to be used to continue building your API request
*/
public RequestBuilder addCookie(String key, Object value) {
this.sessionCookies.put(key, value);
return this;
}
/**
* Set the authentication method that will be used by the API request that you're currently building. By default, this value is set to AuthenticationType.NONE but you can change it by calling this method. If you use thie method the authentication token will be saved automatically for all the following requests using the same session.
*
* @param username the value of the username that you will be using to authenticate the current API request.
* @param password the value of the password that you will be using to authenticate the current API request.
* @param authenticationType the type of your authentication method {BASIC, FORM, NONE}
* @return a self-reference to be used to continue building your API request
*/
public RequestBuilder setAuthentication(String username, String password, AuthenticationType authenticationType) {
this.authenticationType = authenticationType;
this.authenticationUsername = username;
this.authenticationPassword = password;
return this;
}
/**
* After you finish building your request, use this method to trigger the request and get back the response object.
*
* @return Response; returns the full response object for further manipulation
*/
public Response performRequest() {
String request = session.prepareRequestURL(serviceURI, urlArguments, serviceName);
RequestSpecification specs = session.prepareRequestSpecs(parameters, parametersType, requestBody, contentType, sessionCookies, sessionHeaders, sessionConfigs, appendDefaultContentCharsetToContentTypeIfUndefined, urlEncodingEnabled);
switch (this.authenticationType) {
case BASIC -> specs.auth().preemptive().basic(this.authenticationUsername, this.authenticationPassword);
case FORM -> specs.auth().form(this.authenticationUsername, this.authenticationPassword);
case NONE -> {
} //do nothing
}
Response response = null;
try {
if (requestType.equals(RestActions.RequestType.POST) || requestType.equals(RestActions.RequestType.PATCH)
|| requestType.equals(RestActions.RequestType.PUT) || requestType.equals(RestActions.RequestType.GET)
|| requestType.equals(RestActions.RequestType.DELETE)) {
response = session.sendRequest(requestType, request, specs);
} else {
RestActions.failAction(request);
}
boolean responseStatus = session.evaluateResponseStatusCode(Objects.requireNonNull(response), targetStatusCode);
String reportMessage = session.prepareReportMessage(response, targetStatusCode, requestType, serviceName,
contentType, urlArguments);
if (!"".equals(reportMessage) && Boolean.TRUE.equals(responseStatus)) {
RestActions.passAction(reportMessage, requestBody, specs, response);
} else {
RestActions.failAction(reportMessage, requestBody, specs, response);
}
} catch (Exception rootCauseException) {
ReportManagerHelper.log(rootCauseException);
if (response != null) {
RestActions.failAction(request + ", Response Time: " + response.timeIn(TimeUnit.MILLISECONDS) + "ms", requestBody, specs,
response, rootCauseException);
} else {
RestActions.failAction(request, rootCauseException);
}
}
return response;
}
/**
* The type of your authentication method {BASIC, FORM, NONE}
*/
public enum AuthenticationType {
BASIC, FORM, NONE
}
}
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.RecursionManager;
import com.intellij.psi.*;
import com.intellij.psi.util.*;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import static com.intellij.codeInsight.AnnotationUtil.*;
/**
* @author anna
*/
public abstract class NullableNotNullManager {
protected static final Logger LOG = Logger.getInstance(NullableNotNullManager.class);
protected final Project myProject;
protected NullableNotNullManager(Project project) {
myProject = project;
}
/**
* @return list of default non-container annotations that apply to the nullable element
*/
abstract @NotNull List<String> getDefaultNullables();
/**
* @return list of default non-container annotations that apply to the not-null element
*/
abstract @NotNull List<String> getDefaultNotNulls();
/**
* @return list of all default non-container annotations that affect nullability (including nullable, not-null and unknown)
*/
abstract @NotNull List<String> getAllDefaultAnnotations();
public static NullableNotNullManager getInstance(Project project) {
return ServiceManager.getService(project, NullableNotNullManager.class);
}
/**
* @return if owner has a @NotNull or @Nullable annotation, or is in scope of @ParametersAreNullableByDefault or ParametersAreNonnullByDefault
*/
public boolean hasNullability(@NotNull PsiModifierListOwner owner) {
return isNullable(owner, false) || isNotNull(owner, false);
}
public abstract void setNotNulls(String @NotNull ... annotations);
public abstract void setNullables(String @NotNull ... annotations);
public abstract @NotNull String getDefaultNullable();
/**
* Returns an annotation which marks given element as Nullable, if any. Usage of this method is discouraged.
* Use {@link #findEffectiveNullabilityInfo(PsiModifierListOwner)} instead.
*/
public @Nullable PsiAnnotation getNullableAnnotation(@NotNull PsiModifierListOwner owner, boolean checkBases) {
return findNullityAnnotationWithDefault(owner, checkBases, true);
}
public abstract void setDefaultNullable(@NotNull String defaultNullable);
public abstract @NotNull String getDefaultNotNull();
/**
* Returns an annotation which marks given element as NotNull, if any. Usage of this method is discouraged.
* Use {@link #findEffectiveNullabilityInfo(PsiModifierListOwner)} instead.
*/
public @Nullable PsiAnnotation getNotNullAnnotation(@NotNull PsiModifierListOwner owner, boolean checkBases) {
return findNullityAnnotationWithDefault(owner, checkBases, false);
}
public @Nullable PsiAnnotation copyNotNullAnnotation(@NotNull PsiModifierListOwner original, @NotNull PsiModifierListOwner generated) {
NullabilityAnnotationInfo info = findOwnNullabilityInfo(original);
if (info == null || info.getNullability() != Nullability.NOT_NULL) return null;
return copyAnnotation(info.getAnnotation(), generated);
}
public @Nullable PsiAnnotation copyNullableAnnotation(@NotNull PsiModifierListOwner original, @NotNull PsiModifierListOwner generated) {
NullabilityAnnotationInfo info = findOwnNullabilityInfo(original);
if (info == null || info.getNullability() != Nullability.NULLABLE) return null;
return copyAnnotation(info.getAnnotation(), generated);
}
public @Nullable PsiAnnotation copyNullableOrNotNullAnnotation(@NotNull PsiModifierListOwner original, @NotNull PsiModifierListOwner generated) {
NullabilityAnnotationInfo src = findOwnNullabilityInfo(original);
if (src == null) return null;
NullabilityAnnotationInfo effective = findEffectiveNullabilityInfo(generated);
if (effective != null && effective.getNullability() == src.getNullability()) return null;
return copyAnnotation(src.getAnnotation(), generated);
}
private static @Nullable PsiAnnotation copyAnnotation(@NotNull PsiAnnotation annotation, @NotNull PsiModifierListOwner target) {
String qualifiedName = annotation.getQualifiedName();
if (qualifiedName != null) {
if (JavaPsiFacade.getInstance(annotation.getProject()).findClass(qualifiedName, target.getResolveScope()) == null) {
return null;
}
// type annotations are part of target's type and should not to be copied explicitly to avoid duplication
if (!AnnotationTargetUtil.isTypeAnnotation(annotation)) {
PsiModifierList modifierList = target.getModifierList();
if (modifierList != null && !modifierList.hasAnnotation(qualifiedName)) {
return modifierList.addAnnotation(qualifiedName);
}
}
}
return null;
}
/** @deprecated use {@link #copyNotNullAnnotation(PsiModifierListOwner, PsiModifierListOwner)} */
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2021.1")
public PsiAnnotation copyNotNullAnnotation(@NotNull PsiModifierListOwner owner) {
NullabilityAnnotationInfo info = findOwnNullabilityInfo(owner);
if (info == null || info.getNullability() != Nullability.NOT_NULL) return null;
String qualifiedName = info.getAnnotation().getQualifiedName();
return qualifiedName != null
? JavaPsiFacade.getElementFactory(owner.getProject()).createAnnotationFromText("@" + qualifiedName, owner)
: null;
}
public abstract void setDefaultNotNull(@NotNull String defaultNotNull);
private @Nullable PsiAnnotation findNullityAnnotationWithDefault(@NotNull PsiModifierListOwner owner, boolean checkBases, boolean nullable) {
PsiAnnotation annotation = findPlainNullityAnnotation(owner, checkBases);
if (annotation != null) {
String qName = annotation.getQualifiedName();
if (qName == null) return null;
List<String> contradictory = nullable ? getNotNullsWithNickNames() : getNullablesWithNickNames();
if (contradictory.contains(qName)) return null;
return annotation;
}
PsiType type = getOwnerType(owner);
if (type == null || TypeConversionUtil.isPrimitiveAndNotNull(type)) return null;
// even if javax.annotation.Nullable is not configured, it should still take precedence over ByDefault annotations
List<String> annotations = nullable ? getDefaultNotNulls() : getDefaultNullables();
int flags = (checkBases ? CHECK_HIERARCHY : 0) | CHECK_EXTERNAL | CHECK_INFERRED | CHECK_TYPE;
if (isAnnotated(owner, annotations, flags)) {
return null;
}
if (!nullable && hasHardcodedContracts(owner)) {
return null;
}
if (owner instanceof PsiParameter && !nullable && checkBases) {
List<PsiParameter> superParameters = getSuperAnnotationOwners((PsiParameter)owner);
if (!superParameters.isEmpty()) {
return takeAnnotationFromSuperParameters((PsiParameter)owner, superParameters);
}
}
NullabilityAnnotationInfo nullityDefault = findNullityDefaultInHierarchy(owner);
Nullability wantedNullability = nullable ? Nullability.NULLABLE : Nullability.NOT_NULL;
return nullityDefault != null && nullityDefault.getNullability() == wantedNullability ? nullityDefault.getAnnotation() : null;
}
/**
* Returns own nullability annotation info for given element. Returned annotation is not inherited and
* not container annotation for class/package. Still it could be inferred or external.
*
* @param owner element to find a nullability info for
* @return own nullability annotation info.
*/
public @Nullable NullabilityAnnotationInfo findOwnNullabilityInfo(@NotNull PsiModifierListOwner owner) {
PsiType type = getOwnerType(owner);
if (type == null || TypeConversionUtil.isPrimitiveAndNotNull(type)) return null;
List<String> nullables = getNullablesWithNickNames();
PsiAnnotation annotation = findPlainNullityAnnotation(owner, false);
if (annotation != null) {
return new NullabilityAnnotationInfo(annotation,
nullables.contains(annotation.getQualifiedName()) ? Nullability.NULLABLE : Nullability.NOT_NULL,
false);
}
return null;
}
/**
* Returns information about explicit nullability annotation (without looking into external/inferred annotations,
* but looking into container annotations). This method is rarely useful in client code, it's designed mostly
* to aid the inference procedure.
*
* @param owner element to get the info about
* @return the annotation info or null if no explicit annotation found
*/
public @Nullable NullabilityAnnotationInfo findExplicitNullability(PsiModifierListOwner owner) {
PsiAnnotation annotation = findPlainAnnotation(owner, getAllNullabilityAnnotationsWithNickNames(), false, true);
if (annotation != null) {
Nullability nullability =
getNullablesWithNickNames().contains(annotation.getQualifiedName()) ? Nullability.NULLABLE : Nullability.NOT_NULL;
return new NullabilityAnnotationInfo(annotation, nullability, false);
}
return findNullityDefaultInHierarchy(owner);
}
/**
* Returns nullability annotation info which has effect for given element.
*
* @param owner element to find an annotation for
* @return effective nullability annotation info, or null if not found.
*/
public @Nullable NullabilityAnnotationInfo findEffectiveNullabilityInfo(@NotNull PsiModifierListOwner owner) {
PsiType type = getOwnerType(owner);
if (type == null || TypeConversionUtil.isPrimitiveAndNotNull(type)) return null;
return CachedValuesManager.getCachedValue(owner, () -> CachedValueProvider.Result
.create(doFindEffectiveNullabilityAnnotation(owner), PsiModificationTracker.MODIFICATION_COUNT));
}
private @Nullable NullabilityAnnotationInfo doFindEffectiveNullabilityAnnotation(@NotNull PsiModifierListOwner owner) {
Set<String> annotationNames = getAllNullabilityAnnotationsWithNickNames();
Set<String> extraAnnotations = new HashSet<>(getAllDefaultAnnotations());
extraAnnotations.addAll(annotationNames);
PsiAnnotation annotation = findPlainAnnotation(owner, extraAnnotations, true, false);
if (annotation != null) {
if (!annotationNames.contains(annotation.getQualifiedName())) {
// Deliberately excluded known standard annotation still has precedence over default class-level or package-level annotation:
// return null in this case
return null;
}
List<String> nullables = getNullablesWithNickNames();
return new NullabilityAnnotationInfo(annotation,
nullables.contains(annotation.getQualifiedName()) ? Nullability.NULLABLE : Nullability.NOT_NULL,
false);
}
if (owner instanceof PsiParameter) {
List<PsiParameter> superParameters = getSuperAnnotationOwners((PsiParameter)owner);
if (!superParameters.isEmpty()) {
for (PsiParameter parameter: superParameters) {
PsiAnnotation plain = findPlainAnnotation(parameter, extraAnnotations, false, false);
// Plain not null annotation is not inherited
if (plain != null) return null;
NullabilityAnnotationInfo defaultInfo = findNullityDefaultInHierarchy(parameter);
if (defaultInfo != null) {
return defaultInfo.getNullability() == Nullability.NOT_NULL ? defaultInfo : null;
}
}
return null;
}
}
NullabilityAnnotationInfo defaultInfo = findNullityDefaultInHierarchy(owner);
if (defaultInfo != null && (defaultInfo.getNullability() == Nullability.NULLABLE || !hasHardcodedContracts(owner))) {
return defaultInfo;
}
return null;
}
private PsiAnnotation takeAnnotationFromSuperParameters(@NotNull PsiParameter owner, @NotNull List<? extends PsiParameter> superOwners) {
return RecursionManager.doPreventingRecursion(owner, true, () -> {
for (PsiParameter superOwner : superOwners) {
PsiAnnotation anno = findNullityAnnotationWithDefault(superOwner, false, false);
if (anno != null) return anno;
}
return null;
});
}
private PsiAnnotation findPlainNullityAnnotation(@NotNull PsiModifierListOwner owner, boolean checkBases) {
Set<String> qNames = getAllNullabilityAnnotationsWithNickNames();
return findPlainAnnotation(owner, qNames, checkBases, false);
}
/**
* @return an annotation (if any) with the given nullability semantics on the given declaration or its type. In case of conflicts,
* type annotations are preferred.
*/
public @Nullable PsiAnnotation findExplicitNullabilityAnnotation(@NotNull PsiModifierListOwner owner, @NotNull Nullability nullability) {
if (nullability == Nullability.UNKNOWN) return null;
List<String> names = nullability == Nullability.NULLABLE ? getNullablesWithNickNames() : getNotNullsWithNickNames();
return findPlainAnnotation(owner, new HashSet<>(names), false, false);
}
private static @Nullable PsiAnnotation findPlainAnnotation(@NotNull PsiModifierListOwner owner,
@NotNull Set<String> qualifiedNames, boolean checkBases, boolean skipExternal) {
PsiAnnotation memberAnno = checkBases && owner instanceof PsiMethod
? findAnnotationInHierarchy(owner, qualifiedNames, skipExternal)
: findAnnotation(owner, qualifiedNames, skipExternal);
PsiType type = getOwnerType(owner);
if (memberAnno != null && type instanceof PsiArrayType && AnnotationTargetUtil.isTypeAnnotation(memberAnno)) {
// Ambiguous TYPE_USE annotation on array type: we consider that it annotates an array component instead.
memberAnno = null;
}
if (memberAnno != null) {
PsiAnnotation annotation = preferTypeAnnotation(memberAnno, type);
if (annotation != memberAnno && !qualifiedNames.contains(annotation.getQualifiedName())) return null;
return annotation;
}
if (type instanceof PsiPrimitiveType) return null;
return findAnnotationInTypeHierarchy(type, qualifiedNames);
}
private static @NotNull PsiAnnotation preferTypeAnnotation(@NotNull PsiAnnotation memberAnno, @Nullable PsiType type) {
if (type != null) {
for (PsiAnnotation typeAnno : type.getApplicableAnnotations()) {
if (areDifferentNullityAnnotations(memberAnno, typeAnno)) {
return typeAnno;
}
}
}
return memberAnno;
}
private static boolean areDifferentNullityAnnotations(@NotNull PsiAnnotation memberAnno, @NotNull PsiAnnotation typeAnno) {
NullableNotNullManager manager = getInstance(memberAnno.getProject());
List<String> notNulls = manager.getNotNullsWithNickNames();
List<String> nullables = manager.getNullablesWithNickNames();
return nullables.contains(typeAnno.getQualifiedName()) && notNulls.contains(memberAnno.getQualifiedName()) ||
nullables.contains(memberAnno.getQualifiedName()) && notNulls.contains(typeAnno.getQualifiedName());
}
protected @NotNull List<String> getNullablesWithNickNames() {
return getNullables();
}
protected @NotNull List<String> getNotNullsWithNickNames() {
return getNotNulls();
}
protected @NotNull Set<String> getAllNullabilityAnnotationsWithNickNames() {
Set<String> qNames = new HashSet<>(getNullablesWithNickNames());
qNames.addAll(getNotNullsWithNickNames());
return Collections.unmodifiableSet(qNames);
}
protected boolean hasHardcodedContracts(@NotNull PsiElement element) {
return false;
}
private static @Nullable PsiType getOwnerType(@NotNull PsiModifierListOwner owner) {
if (owner instanceof PsiVariable) return ((PsiVariable)owner).getType();
if (owner instanceof PsiMethod) return ((PsiMethod)owner).getReturnType();
return null;
}
public boolean isNullable(@NotNull PsiModifierListOwner owner, boolean checkBases) {
return findNullityAnnotationWithDefault(owner, checkBases, true) != null;
}
public boolean isNotNull(@NotNull PsiModifierListOwner owner, boolean checkBases) {
return findNullityAnnotationWithDefault(owner, checkBases, false) != null;
}
@Nullable
NullabilityAnnotationInfo findNullityDefaultInHierarchy(@NotNull PsiModifierListOwner owner) {
PsiAnnotation.TargetType[] placeTargetTypes = AnnotationTargetUtil.getTargetsForLocation(owner.getModifierList());
PsiElement element = owner.getParent();
while (element != null) {
if (element instanceof PsiModifierListOwner) {
NullabilityAnnotationInfo result = getNullityDefault((PsiModifierListOwner)element, placeTargetTypes, owner, false);
if (result != null) {
return result;
}
}
if (element instanceof PsiClassOwner) {
String packageName = ((PsiClassOwner)element).getPackageName();
return findNullityDefaultOnPackage(placeTargetTypes, JavaPsiFacade.getInstance(element.getProject()).findPackage(packageName),
owner);
}
element = element.getContext();
}
return null;
}
private @Nullable NullabilityAnnotationInfo findNullityDefaultOnPackage(PsiAnnotation.TargetType @NotNull [] placeTargetTypes,
@Nullable PsiPackage psiPackage,
PsiModifierListOwner owner) {
boolean superPackage = false;
while (psiPackage != null) {
NullabilityAnnotationInfo onPkg = getNullityDefault(psiPackage, placeTargetTypes, owner, superPackage);
if (onPkg != null) return onPkg;
superPackage = true;
psiPackage = psiPackage.getParentPackage();
}
return null;
}
abstract @Nullable NullabilityAnnotationInfo getNullityDefault(@NotNull PsiModifierListOwner container,
PsiAnnotation.TargetType @NotNull [] placeTargetTypes,
PsiModifierListOwner owner, boolean superPackage);
public abstract @NotNull List<String> getNullables();
public abstract @NotNull List<String> getNotNulls();
/**
* Returns true if given element is known to be nullable
*
* @param owner element to check
* @return true if given element is known to be nullable
*/
public static boolean isNullable(@NotNull PsiModifierListOwner owner) {
return getNullability(owner) == Nullability.NULLABLE;
}
/**
* Returns true if given element is known to be non-nullable
*
* @param owner element to check
* @return true if given element is known to be non-nullable
*/
public static boolean isNotNull(@NotNull PsiModifierListOwner owner) {
return getNullability(owner) == Nullability.NOT_NULL;
}
/**
* Returns nullability of given element defined by annotations.
*
* @param owner element to find nullability for
* @return found nullability; {@link Nullability#UNKNOWN} if not specified or non-applicable
*/
public static @NotNull Nullability getNullability(@NotNull PsiModifierListOwner owner) {
NullabilityAnnotationInfo info = getInstance(owner.getProject()).findEffectiveNullabilityInfo(owner);
return info == null ? Nullability.UNKNOWN : info.getNullability();
}
public abstract @NotNull List<String> getInstrumentedNotNulls();
public abstract void setInstrumentedNotNulls(@NotNull List<String> names);
/**
* Checks if given annotation specifies the nullability (either nullable or not-null)
* @param annotation annotation to check
* @return true if given annotation specifies nullability
*/
public static boolean isNullabilityAnnotation(@NotNull PsiAnnotation annotation) {
return getInstance(annotation.getProject()).getAllNullabilityAnnotationsWithNickNames().contains(annotation.getQualifiedName());
}
}
|
import java.util.*;
class A_testLocalVarUse_in {
public void foo() {
AbstractList list = new ArrayList();
List list2 = list;
}
}
|
/**
*
* Class SynchState$Factory$Class.java
*
* Generated by KMFStudio at 29 July 2003 10:22:58
* Visit http://www.cs.ukc.ac.uk/kmf
*
*/
package uk.ac.ukc.cs.kmf.kmfstudio.uml.Behavioral_Elements.State_Machines;
import uk.ac.ukc.cs.kmf.kmfstudio.uml.UmlFactory$Class;
import uk.ac.ukc.cs.kmf.kmfstudio.uml.UmlVisitor;
import uk.ac.ukc.cs.kmf.kmfstudio.uml.repository.UmlRepository;
public class SynchState$Factory$Class
extends UmlFactory$Class
implements SynchState$Factory
{
/** Default factory constructor */
public SynchState$Factory$Class() {
}
public SynchState$Factory$Class(UmlRepository repository) {
this.repository = repository;
}
/** Default build method */
public Object build() {
SynchState obj = new SynchState$Class();
repository.addElement("uml.Behavioral_Elements.State_Machines.SynchState", obj);
return obj;
}
/** Specialized build method */
public Object build(uk.ac.ukc.cs.kmf.kmfstudio.uml.Foundation.Data_Types.Name name, uk.ac.ukc.cs.kmf.kmfstudio.uml.Foundation.Data_Types.VisibilityKind visibility, Boolean isSpecification) {
SynchState obj = new SynchState$Class(name, visibility, isSpecification);
repository.addElement("uml.Behavioral_Elements.State_Machines.SynchState", obj);
return obj;
}
/** Override toString method */
public String toString() {
return "SynchState_Factory";
}
/** Accept 'uk.ac.ukc.cs.kmf.kmfstudio.uml.Behavioral_Elements.State_Machines.SynchState$Visitor' */
public Object accept(UmlVisitor v, Object data) {
return v.visit(this, data);
}
}
|
/*
*
* Copyright (c) 2006-2019, Speedment, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); You may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.speedment.runtime.core.internal.db;
import com.speedment.runtime.core.db.JavaTypeMap;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.Optional;
final class RuleUtil {
/**
* All default rules that need more than just the jdbc type name to trigger.
* Overrides the inner defaults of JavaTypeMapImpl
*/
static final JavaTypeMap.Rule DEFAULT_RULE = (sqlTypeMapping, md) -> {
final String typeName = md.getTypeName().toUpperCase();
final int columnSize = md.getColumnSize();
switch (typeName) {
case "BIT": {
if (columnSize > 31) { // jdbc will return unsigned 32 bit for BIT(32) which does not fit in Integer
return Optional.of(Long.class);
}
if (columnSize == 0 || columnSize == 1) {
return Optional.of(Boolean.class);
}
break;
}
case "NCHAR":
case "NVARCHAR2": {
return Optional.of(String.class);
}
case "BINARY_FLOAT": {
return Optional.of(Float.class);
}
case "BINARY_DOUBLE": {
return Optional.of(Double.class);
}
case "NUMBER":
case "DECIMAL": {
if (md.getDecimalDigits() == 0) {
if (columnSize <= 2) {
return Optional.of(Byte.class);
} else if (columnSize <= 4) {
return Optional.of(Short.class);
} else if (columnSize <= 9) {
return Optional.of(Integer.class);
} else if (columnSize <= 18) {
return Optional.of(Long.class);
} else {
return Optional.of(BigInteger.class);
}
}
}
}
if (typeName.matches("TIMESTAMP\\([0-9]\\) WITH LOCAL TIME ZONE")) {
return Optional.of(Timestamp.class);
}
if (typeName.matches("TIMESTAMP\\([0-9]\\) WITH TIME ZONE")) {
return Optional.of(Timestamp.class);
}
if (typeName.matches("INTERVAL YEAR\\([0-9]\\) TO MONTH")) {
return Optional.of(String.class);
}
if (typeName.matches("INTERVAL DAY\\([0-9]\\) TO SECOND\\([0-9]\\)")) {
return Optional.of(String.class);
}
return Optional.empty();
};
}
|
/*
* To change this license header, choose License Headers in Project Properties. To change this
* template file, choose Tools | Templates and open the template in the editor.
*/
package br.senac.tads.dsw.exemplosspring.sessao;
import java.io.Serializable;
import java.time.LocalDateTime;
import br.senac.tads.dsw.exemplosspring.sessao.item.Item;
/**
*
* @author ftsuda
*/
public class ItemSelecionado implements Serializable {
private static final long serialVersionUID = 1L;
private Item item;
private LocalDateTime dataHoraInclusao;
private String userAgent;
public ItemSelecionado() {
}
public ItemSelecionado(Item item, String userAgent) {
this.item = item;
this.dataHoraInclusao = LocalDateTime.now();
this.userAgent = userAgent;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public LocalDateTime getDataHoraInclusao() {
return dataHoraInclusao;
}
public void setDataHoraInclusao(LocalDateTime dataHoraInclusao) {
this.dataHoraInclusao = dataHoraInclusao;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
}
|
package com.example.android.sunshine.common;
import com.google.android.gms.wearable.DataMap;
import java.util.Calendar;
public final class Protocol {
private Protocol() {
}
public static String PATH_WEATHER_DATA = "/weatherdata";
private static String KEY_CONDITION = "WEATHER_CONDITION";
private static String KEY_TEMP_MIN = "WEATHER_TEMP_MIN";
private static String KEY_TEMP_MAX = "WEATHER_TEMP_MAX";
private static String KEY_TEMP_UNIT = "WEATHER_TEMP_UNIT";
public static WeatherDataTelegram telegramFromData(DataMap dm) {
int conditionId = dm.getInt(KEY_CONDITION);
double tempMin = dm.getDouble(KEY_TEMP_MIN);
double tempMax = dm.getDouble(KEY_TEMP_MAX);
int unitValue = dm.getInt(KEY_TEMP_UNIT);
return new WeatherDataTelegram(
WeatherUnit.fromValue(unitValue),
conditionId,
tempMax,
tempMin
);
}
public static void addTelegramToData(WeatherDataTelegram telegram, DataMap dm) {
dm.putInt(KEY_CONDITION, telegram.getWeatherConditionId());
dm.putDouble(KEY_TEMP_MIN, telegram.getTemperatureMin());
dm.putDouble(KEY_TEMP_MAX, telegram.getTemperatureMax());
dm.putInt(KEY_TEMP_UNIT, telegram.getWeatherUnit().getValue());
}
}
|
package ksl.academic.algorithm.epi.graph;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public class TaskScheduling {
public static void main(String[] args) {
Vertex[] v = {
new Vertex("0"), // 2 7
new Vertex("1"), // 2 7
new Vertex("2"), // 3 4 7
new Vertex("3"), // 1 4 6
new Vertex("4"), // 0
new Vertex("5") // 4 5
};
Edge[] e = {
new Edge(v[5], v[2]),
new Edge(v[5], v[0]),
new Edge(v[4], v[0]),
new Edge(v[4], v[1]),
new Edge(v[2], v[3]),
new Edge(v[3], v[1]),
new Edge(v[5], v[4])
};
Graph g = new Graph(v, e);
System.out.println(g);
List<Vertex> path = topological(g);
for (Vertex p : path) {
System.out.print(p.id + " ");
}
}
static List<Vertex> topological(Graph g) {
List<Vertex> result = new LinkedList<>();
// nodes with no incoming edge must be first!, (i.e., can't start with node 2)
for (Vertex x : g.getVertices()) {
System.out.println("Starts visiting: " + x);
if (!visit(g, x, result)) {
return null;
}
System.out.println("Finished visiting: " + x);
}
return result;
}
static boolean visit(Graph g, Vertex v, List<Vertex> result) {
if (v.isCompleted) return true;
if (v.isVisited) return false;
v.isVisited = true;
for (Vertex adj : g.getAdj(v)) {
visit(g, adj, result);
}
v.isCompleted = true;
System.out.println("adding result after visiting all ancestors: " + v);
result.add(0, v);
return true;
}
static class Graph {
Map<Vertex, List<Vertex>> adjList;
Map<String, Edge> edgeList;
public Graph(Vertex[] vertices, Edge[] edges) {
this.adjList = new HashMap<>();
this.edgeList = new HashMap<>();
for (Vertex v : vertices) {
adjList.put(v, new ArrayList<>());
}
for (Edge e : edges) add(e);
}
public Set<Vertex> getVertices() {
return adjList.keySet();
}
public List<Vertex> getAdj(Vertex v) {
return adjList.get(v);
}
private void add(Edge e) {
Objects.requireNonNull(e, "Edges can't be null");
String edgeId = e.id;
if (edgeList.containsKey(edgeId)) return;
add(e.source, e.target);
edgeList.put(edgeId, e);
}
/**
* Adding vertex and its neighbor, directional.
* Must add both direction for undirected graph.
*
* @param v
* @param t
*/
private Vertex add(Vertex v, Vertex... t) {
if (!adjList.containsKey(v)) {
adjList.put(v, new ArrayList<>());
}
adjList.get(v).addAll(Arrays.asList(t));
return v;
}
public int getWeight(Vertex s, Vertex t) {
String edgeId = Edge.genId(s, t);
return edgeList.get(edgeId).weight;
}
/**
* The string representation of this graph:
* <p>
* A: C
* B: D
* C: E D
* D:
* E: B
*/
public String toString() {
final String TAB = " ";
StringBuilder sb = new StringBuilder();
Vertex[] vertices = adjList.keySet().toArray(new Vertex[]{});
Arrays.sort(vertices);
sb.append("Adjacency List: \n");
for (Vertex v : vertices) {
sb.append(TAB + v.id + ": ");
for (Vertex adj : adjList.get(v)) {
sb.append(adj.id + " ");
}
sb.append("\n");
}
sb.append("Edge List: \n");
for (Edge e : edgeList.values()) {
sb.append(TAB + e).append(System.lineSeparator());
}
return sb.toString();
}
}
// Data class, don't need getter/setter
static class Vertex implements Comparable<Vertex> {
String id;
int weight;
boolean isCompleted;
boolean isVisited;
public Vertex(String id) {
this.id = id;
this.weight = Integer.MAX_VALUE;
}
public String toString() {
return id + ":" + weight;
}
@Override
public int compareTo(Vertex o) {
if (o == null) return -1;
return weight - o.weight;
}
public boolean equals(Object o) {
if (o == this) return true;
if (this.getClass() != o.getClass()) return false;
return Objects.equals(id, ((Vertex) o).id);
}
public int hashCode() {
return Objects.hash(id);
}
}
static class Edge {
int weight;
Vertex source;
Vertex target;
String id;
public Edge(Vertex source, Vertex target) {
this.source = source;
this.target = target;
this.weight = 0;
this.id = genId(source, target);
}
public Edge(Vertex source, Vertex target, int weight) {
this.source = source;
this.target = target;
this.weight = weight;
this.id = genId(source, target);
}
public static String genId(Vertex s, Vertex t) {
return s.id + t.id;
}
public String toString() {
return "|" + id + "|=" + weight;
}
}
}
|
package fr.guddy.androidstarter.mvp.repo_list;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.hannesdorfmann.mosby.mvp.viewstate.MvpViewStateFragment;
import com.hannesdorfmann.mosby.mvp.viewstate.ViewState;
import com.orhanobut.logger.Logger;
import java.util.List;
import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import fr.guddy.androidstarter.BuildConfig;
import fr.guddy.androidstarter.R;
import fr.guddy.androidstarter.persistence.entities.RepoEntity;
import hugo.weaving.DebugLog;
import icepick.Icepick;
import io.nlopez.smartadapters.SmartAdapter;
import io.nlopez.smartadapters.utils.ViewEventListener;
import pl.aprilapps.switcher.Switcher;
public class FragmentRepoList
extends MvpViewStateFragment<RepoListMvp.View, RepoListMvp.Presenter>
implements RepoListMvp.View, ViewEventListener<RepoEntity>, SwipeRefreshLayout.OnRefreshListener {
private static final String TAG = FragmentRepoList.class.getSimpleName();
private static final boolean DEBUG = true;
//region Mock callback constant
/**
* A dummy implementation of the {@link Callbacks} interface that does
* nothing. Used only when this fragment is not attached to an activity.
*/
private static final Callbacks sDummyCallbacks = (final Long plId) -> {
};
//endregion
//region Injected views
@BindView(R.id.FragmentRepoList_TextView_Empty)
TextView mTextViewEmpty;
@BindView(R.id.FragmentRepoList_ProgressBar_Loading)
ProgressBar mProgressBarLoading;
@BindView(R.id.FragmentRepoList_RecyclerView)
RecyclerView mRecyclerView;
@BindView(R.id.FragmentRepoList_TextView_Error)
TextView mTextViewError;
@BindView(R.id.FragmentRepoList_SwipeRefreshLayout_Empty)
SwipeRefreshLayout mSwipeRefreshLayoutEmpty;
@BindView(R.id.FragmentRepoList_SwipeRefreshLayout_Error)
SwipeRefreshLayout mSwipeRefreshLayoutError;
@BindView(R.id.FragmentRepoList_SwipeRefreshLayout_Content)
SwipeRefreshLayout mSwipeRefreshLayoutContent;
@BindViews({
R.id.FragmentRepoList_SwipeRefreshLayout_Empty,
R.id.FragmentRepoList_SwipeRefreshLayout_Error,
R.id.FragmentRepoList_SwipeRefreshLayout_Content
})
List<SwipeRefreshLayout> mSwipeRefreshLayouts;
//endregion
//region Fields
static final ButterKnife.Setter<SwipeRefreshLayout, SwipeRefreshLayout.OnRefreshListener> SET_LISTENER =
(@NonNull final SwipeRefreshLayout poView, @NonNull final SwipeRefreshLayout.OnRefreshListener poListener, final int piIndex)
->
poView.setOnRefreshListener(poListener);
static final ButterKnife.Action<SwipeRefreshLayout> STOP_REFRESHING =
(@NonNull final SwipeRefreshLayout poView, final int piIndex)
->
poView.setRefreshing(false);
private Switcher mSwitcher;
private Callbacks mCallbacks = sDummyCallbacks;
private Unbinder mUnbinder;
//endregion
//region Constructor
public FragmentRepoList() {
}
//endregion
//region Lifecycle
@Override
public void onAttach(final Context poContext) {
super.onAttach(poContext);
// Activities containing this fragment must implement its callbacks.
if (!(poContext instanceof Callbacks)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) poContext;
}
@Override
public View onCreateView(final LayoutInflater poInflater, final ViewGroup poContainer, final Bundle poSavedInstanceState) {
View view = poInflater.inflate(R.layout.fragment_repo_list, poContainer, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onViewCreated(final View poView, final Bundle poSavedInstanceState) {
super.onViewCreated(poView, poSavedInstanceState);
Icepick.restoreInstanceState(this, poSavedInstanceState);
mUnbinder = ButterKnife.bind(this, poView);
ButterKnife.apply(mSwipeRefreshLayouts, SET_LISTENER, this);
mSwitcher = new Switcher.Builder()
.withEmptyView(mSwipeRefreshLayoutEmpty)
.withProgressView(mProgressBarLoading)
.withErrorView(mSwipeRefreshLayoutError)
.withContentView(mSwipeRefreshLayoutContent)
.build();
}
@Override
public void onActivityCreated(final Bundle poSavedInstanceState) {
super.onActivityCreated(poSavedInstanceState);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
@Override
public void onSaveInstanceState(final Bundle poOutState) {
super.onSaveInstanceState(poOutState);
Icepick.saveInstanceState(this, poOutState);
}
@Override
public void onDestroyView() {
super.onDestroyView();
mUnbinder.unbind();
}
@Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the dummy implementation.
mCallbacks = sDummyCallbacks;
}
//endregion
//region ViewEventListener
@DebugLog
@Override
public void onViewEvent(final int piActionID, final RepoEntity poRepo, final int piPosition, final View poView) {
if (piActionID == CellRepo.ROW_PRESSED) {
mCallbacks.onItemSelected(poRepo.getBaseId());
}
}
//endregion
//region MvpFragment
@DebugLog
@NonNull
@Override
public RepoListMvp.Presenter createPresenter() {
return new PresenterRepoList();
}
//endregion
//region ViewRepoList
@DebugLog
@Override
public void showEmpty() {
ButterKnife.apply(mSwipeRefreshLayouts, STOP_REFRESHING);
mSwitcher.showEmptyView();
}
//endregion
//region MvpLceView
@DebugLog
@Override
public void showLoading(final boolean pbPullToRefresh) {
if (!pbPullToRefresh) {
mSwitcher.showProgressView();
}
}
@DebugLog
@Override
public void showContent() {
ButterKnife.apply(mSwipeRefreshLayouts, STOP_REFRESHING);
mSwitcher.showContentView();
}
@DebugLog
@Override
public void showError(final Throwable poThrowable, final boolean pbPullToRefresh) {
if (BuildConfig.DEBUG && DEBUG) {
Logger.t(TAG).e(poThrowable, "");
}
ButterKnife.apply(mSwipeRefreshLayouts, STOP_REFRESHING);
mSwitcher.showErrorView();
}
@DebugLog
@Override
public void setData(final RepoListMvp.Model poData) {
((RepoListMvp.ViewState) viewState).data = poData;
SmartAdapter.items(poData.repos)
.map(RepoEntity.class, CellRepo.class)
.listener(FragmentRepoList.this)
.into(mRecyclerView);
}
@DebugLog
@Override
public void loadData(final boolean pbPullToRefresh) {
getPresenter().loadRepos(pbPullToRefresh);
}
//endregion
//region MvpViewStateFragment
@DebugLog
@NonNull
@Override
public ViewState createViewState() {
return new RepoListMvp.ViewState();
}
@DebugLog
@Override
public void onNewViewStateInstance() {
loadData(false);
}
//endregion
//region SwipeRefreshLayout.OnRefreshListener
@Override
public void onRefresh() {
loadData(true);
}
//endregion
//region Callback definition
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
public interface Callbacks {
/**
* Callback for when an item has been selected.
*/
void onItemSelected(final Long plId);
}
//endregion
}
|
// Targeted by JavaCPP version 1.5.7-SNAPSHOT: DO NOT EDIT THIS FILE
package org.bytedeco.arrow_dataset;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import org.bytedeco.arrow.*;
import static org.bytedeco.arrow.global.arrow.*;
import org.bytedeco.parquet.*;
import static org.bytedeco.arrow.global.parquet.*;
import static org.bytedeco.arrow.global.arrow_dataset.*;
/** \brief Create a generator that takes in a stream of generators and pulls from each
* one in sequence.
*
* This generator is async-reentrant but will never pull from source reentrantly and
* will never pull from any subscription reentrantly.
*
* This generator may queue 1 instance of T
*
* TODO: Could potentially make a bespoke implementation instead of MergedGenerator that
* forwards async-reentrant requests instead of buffering them (which is what
* MergedGenerator does) */
@Name("arrow::Enumerated<std::shared_ptr<arrow::dataset::Fragment> >") @Properties(inherit = org.bytedeco.arrow.presets.arrow_dataset.class)
public class FragmentEnumerated extends Pointer {
static { Loader.load(); }
/** Default native constructor. */
public FragmentEnumerated() { super((Pointer)null); allocate(); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public FragmentEnumerated(long size) { super((Pointer)null); allocateArray(size); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public FragmentEnumerated(Pointer p) { super(p); }
private native void allocate();
private native void allocateArray(long size);
@Override public FragmentEnumerated position(long position) {
return (FragmentEnumerated)super.position(position);
}
@Override public FragmentEnumerated getPointer(long i) {
return new FragmentEnumerated((Pointer)this).offsetAddress(i);
}
public native @SharedPtr @ByRef Fragment value(); public native FragmentEnumerated value(Fragment setter);
public native int index(); public native FragmentEnumerated index(int setter);
public native @Cast("bool") boolean last(); public native FragmentEnumerated last(boolean setter);
}
|
package game;
import static org.junit.Assert.*;
import game.MasterMind.Color;
import org.junit.Test;
import util.Pair;
public class MasterMindTest {
@Test
public void testGuess() {
MasterMind mm = new MasterMind(new Color[]{Color.R, Color.G, Color.B, Color.Y});
Pair<Integer> p = mm.guess(new Color[]{Color.G, Color.G, Color.R, Color.R});
assertEquals(1, p.getLeft().intValue());
assertEquals(1, p.getRight().intValue());
}
}
|
package me.jeeson.android.socialsdk.platform;
import android.content.Context;
/**
* 社会化平台的创建接口协议
* Created by Jeeson on 2018/6/20.
*/
public interface PlatformCreator {
IPlatform create(Context context, int target);
}
|
package org.ei.drishti.util;
public interface CacheableData<T> {
public T fetch();
}
|
/*
* Copyright (C) 2017. the original author or authors.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sunflower.ewf.websocket;
import java.nio.ByteBuffer;
/**
* A binary WebSocket message.
*
* @author Rossen Stoyanchev
* @since 4.0
*/
public final class BinaryMessage extends AbstractWebSocketMessage<ByteBuffer> {
/**
* Create a new binary WebSocket message with the given ByteBuffer payload.
*
* @param payload the non-null payload
*/
public BinaryMessage(ByteBuffer payload) {
super(payload, true);
}
/**
* Create a new binary WebSocket message with the given payload representing the full or partial
* message content. When the {@code isLast} boolean flag is set to {@code false} the message is
* sent as partial content and more partial messages will be expected until the boolean flag is
* set to {@code true}.
*
* @param payload the non-null payload
* @param isLast if the message is the last of a series of partial messages
*/
public BinaryMessage(ByteBuffer payload, boolean isLast) {
super(payload, isLast);
}
/**
* Create a new binary WebSocket message with the given byte[] payload.
*
* @param payload a non-null payload; note that this value is not copied so care must be taken not
* to modify the array.
*/
public BinaryMessage(byte[] payload) {
this(payload, true);
}
/**
* Create a new binary WebSocket message with the given byte[] payload representing the full or
* partial message content. When the {@code isLast} boolean flag is set to {@code false} the
* message is sent as partial content and more partial messages will be expected until the boolean
* flag is set to {@code true}.
*
* @param payload a non-null payload; note that this value is not copied so care must be taken not
* to modify the array.
* @param isLast if the message is the last of a series of partial messages
*/
public BinaryMessage(byte[] payload, boolean isLast) {
this(payload, 0, ((payload == null) ? 0 : payload.length), isLast);
}
/**
* Create a new binary WebSocket message by wrapping an existing byte array.
*
* @param payload a non-null payload; note that this value is not copied so care must be taken not
* to modify the array.
* @param offset the offset into the array where the payload starts
* @param length the length of the array considered for the payload
* @param isLast if the message is the last of a series of partial messages
*/
public BinaryMessage(byte[] payload, int offset, int length, boolean isLast) {
super(payload != null ? ByteBuffer.wrap(payload, offset, length) : null, isLast);
}
@Override
public int getPayloadLength() {
return getPayload().remaining();
}
@Override
protected String toStringPayload() {
return getPayload().toString();
}
}
|
/*
* 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.
*/
module org.trellisldp.jpms.vocabulary {
exports org.trellisldp.vocabulary;
requires org.apache.commons.rdf.api;
requires org.apache.jena.arq;
requires org.apache.jena.base;
requires org.apache.jena.core;
uses org.apache.commons.rdf.api.RDF;
}
|
package uk.ivanc.archimvvm;
import android.view.View;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import rx.Observable;
import rx.schedulers.Schedulers;
import uk.ivanc.archimvvm.model.GithubService;
import uk.ivanc.archimvvm.model.Repository;
import uk.ivanc.archimvvm.model.User;
import uk.ivanc.archimvvm.util.MockModelFabric;
import uk.ivanc.archimvvm.viewmodel.RepositoryViewModel;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class RepositoryViewModelTest {
GithubService githubService;
ArchiApplication application;
Repository repository;
User owner;
RepositoryViewModel viewModel;
@Before
public void setUp() {
githubService = mock(GithubService.class);
application = (ArchiApplication) RuntimeEnvironment.application;
// Mock the retrofit service so we don't call the API directly
application.setGithubService(githubService);
// Change the default subscribe schedulers so all observables
// will now run on the same thread
application.setDefaultSubscribeScheduler(Schedulers.immediate());
// Default behaviour is to load a mock owner when the view model is instantiated
repository = MockModelFabric.newRepository("Repository");
owner = MockModelFabric.newUser("owner");
when(githubService.userFromUrl(repository.owner.url))
.thenReturn(Observable.just(owner));
viewModel = new RepositoryViewModel(application, repository);
}
@Test
public void shouldGetDescription() {
assertEquals(repository.description, viewModel.getDescription());
}
@Test
public void shouldGetHomepage() {
assertEquals(repository.homepage, viewModel.getHomepage());
}
@Test
public void shouldGetLanguage() {
assertEquals(application.getString(R.string.text_language, repository.language),
viewModel.getLanguage());
}
@Test
public void shouldReturnHomepageVisibilityGone() {
repository.homepage = null;
assertEquals(View.GONE, viewModel.getHomepageVisibility());
}
@Test
public void shouldReturnLanguageVisibilityGone() {
repository.language = null;
assertEquals(View.GONE, viewModel.getLanguageVisibility());
}
@Test
public void shouldReturnForkVisibilityVisible() {
repository.fork = true;
assertEquals(View.VISIBLE, viewModel.getForkVisibility());
}
@Test
public void shouldReturnForkVisibilityGone() {
repository.fork = false;
assertEquals(View.GONE, viewModel.getForkVisibility());
}
@Test
public void shouldLoadFullOwnerOnInstantiation() {
assertEquals(owner.name, viewModel.ownerName.get());
assertEquals(owner.email, viewModel.ownerEmail.get());
assertEquals(owner.location, viewModel.ownerLocation.get());
assertEquals(View.VISIBLE, viewModel.ownerEmailVisibility.get());
assertEquals(View.VISIBLE, viewModel.ownerLocationVisibility.get());
assertEquals(View.VISIBLE, viewModel.ownerLayoutVisibility.get());
}
}
|
/*
* Copyright 2012-2017 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.health.model.transform;
import java.util.Map;
import java.util.List;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.health.model.*;
import com.amazonaws.protocol.json.*;
/**
* EntityFilterMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class EntityFilterJsonMarshaller {
/**
* Marshall the given parameter object, and output to a SdkJsonGenerator
*/
public void marshall(EntityFilter entityFilter, StructuredJsonGenerator jsonGenerator) {
if (entityFilter == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
jsonGenerator.writeStartObject();
java.util.List<String> eventArnsList = entityFilter.getEventArns();
if (eventArnsList != null) {
jsonGenerator.writeFieldName("eventArns");
jsonGenerator.writeStartArray();
for (String eventArnsListValue : eventArnsList) {
if (eventArnsListValue != null) {
jsonGenerator.writeValue(eventArnsListValue);
}
}
jsonGenerator.writeEndArray();
}
java.util.List<String> entityArnsList = entityFilter.getEntityArns();
if (entityArnsList != null) {
jsonGenerator.writeFieldName("entityArns");
jsonGenerator.writeStartArray();
for (String entityArnsListValue : entityArnsList) {
if (entityArnsListValue != null) {
jsonGenerator.writeValue(entityArnsListValue);
}
}
jsonGenerator.writeEndArray();
}
java.util.List<String> entityValuesList = entityFilter.getEntityValues();
if (entityValuesList != null) {
jsonGenerator.writeFieldName("entityValues");
jsonGenerator.writeStartArray();
for (String entityValuesListValue : entityValuesList) {
if (entityValuesListValue != null) {
jsonGenerator.writeValue(entityValuesListValue);
}
}
jsonGenerator.writeEndArray();
}
java.util.List<DateTimeRange> lastUpdatedTimesList = entityFilter.getLastUpdatedTimes();
if (lastUpdatedTimesList != null) {
jsonGenerator.writeFieldName("lastUpdatedTimes");
jsonGenerator.writeStartArray();
for (DateTimeRange lastUpdatedTimesListValue : lastUpdatedTimesList) {
if (lastUpdatedTimesListValue != null) {
DateTimeRangeJsonMarshaller.getInstance().marshall(lastUpdatedTimesListValue, jsonGenerator);
}
}
jsonGenerator.writeEndArray();
}
java.util.List<java.util.Map<String, String>> tagsList = entityFilter.getTags();
if (tagsList != null) {
jsonGenerator.writeFieldName("tags");
jsonGenerator.writeStartArray();
for (java.util.Map<String, String> tagsListValue : tagsList) {
if (tagsListValue != null) {
jsonGenerator.writeStartObject();
for (Map.Entry<String, String> TagsListMapEntry : tagsListValue.entrySet()) {
if (TagsListMapEntry.getValue() != null) {
jsonGenerator.writeFieldName(TagsListMapEntry.getKey());
jsonGenerator.writeValue(TagsListMapEntry.getValue());
}
}
jsonGenerator.writeEndObject();
}
}
jsonGenerator.writeEndArray();
}
java.util.List<String> statusCodesList = entityFilter.getStatusCodes();
if (statusCodesList != null) {
jsonGenerator.writeFieldName("statusCodes");
jsonGenerator.writeStartArray();
for (String statusCodesListValue : statusCodesList) {
if (statusCodesListValue != null) {
jsonGenerator.writeValue(statusCodesListValue);
}
}
jsonGenerator.writeEndArray();
}
jsonGenerator.writeEndObject();
} catch (Throwable t) {
throw new SdkClientException("Unable to marshall request to JSON: " + t.getMessage(), t);
}
}
private static EntityFilterJsonMarshaller instance;
public static EntityFilterJsonMarshaller getInstance() {
if (instance == null)
instance = new EntityFilterJsonMarshaller();
return instance;
}
}
|
package io.fabric.sdk.android.services.persistence;
import java.io.File;
public interface FileStore {
File getCacheDir();
File getExternalCacheDir();
File getExternalFilesDir();
File getFilesDir();
}
|
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.integration.producer;
import java.io.File;
import java.io.FileOutputStream;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ProducerApplication implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
new File("target/input").mkdirs();
if (args.length > 0) {
FileOutputStream stream = new FileOutputStream(
"target/input/data" + System.currentTimeMillis() + ".txt");
for (String arg : args) {
stream.write(arg.getBytes());
}
stream.flush();
stream.close();
}
}
public static void main(String[] args) throws Exception {
SpringApplication.run(ProducerApplication.class, args);
}
}
|
package com.klinker.android.twitter_l.views.widgets.swipe_refresh_layout.material;
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION;
import android.os.Handler;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.*;
import android.view.animation.Animation.AnimationListener;
import android.widget.AbsListView;
import com.klinker.android.twitter_l.utils.SystemBarVisibility;
public class MaterialSwipeRefreshLayout extends ViewGroup {
public static final int LARGE = 0;
public static final int DEFAULT = 1;
private static final String LOG_TAG = MaterialSwipeRefreshLayout.class.getSimpleName();
private static final int MAX_ALPHA = 255;
private static final int STARTING_PROGRESS_ALPHA = 76;
private static final int CIRCLE_DIAMETER = 40;
private static final int CIRCLE_DIAMETER_LARGE = 56;
private static final float DECELERATE_INTERPOLATION_FACTOR = 2.0F;
private static final int INVALID_POINTER = -1;
private static final float DRAG_RATE = 0.5F;
private static final float MAX_PROGRESS_ANGLE = 0.8F;
private static final int SCALE_DOWN_DURATION = 150;
private static final int ALPHA_ANIMATION_DURATION = 300;
private static final int ANIMATE_TO_TRIGGER_DURATION = 200;
private static final int ANIMATE_TO_START_DURATION = 200;
private static final int CIRCLE_BG_LIGHT = -328966;
private static final int DEFAULT_CIRCLE_TARGET = 64;
private View mTarget;
private MaterialSwipeRefreshLayout.OnRefreshListener mListener;
private boolean mRefreshing;
private int mTouchSlop;
private float mTotalDragDistance;
private int mMediumAnimationDuration;
private int mCurrentTargetOffsetTop;
private boolean mOriginalOffsetCalculated;
private float mInitialMotionY;
private boolean mIsBeingDragged;
private int mActivePointerId;
private boolean mScale;
private boolean mReturningToStart;
private final DecelerateInterpolator mDecelerateInterpolator;
private static final int[] LAYOUT_ATTRS = new int[]{16842766};
private CircleImageView mCircleView;
private int mCircleViewIndex;
protected int mFrom;
private float mStartingScale;
protected int mOriginalOffsetTop;
private MaterialProgressDrawable mProgress;
private Animation mScaleAnimation;
private Animation mScaleDownAnimation;
private Animation mAlphaStartAnimation;
private Animation mAlphaMaxAnimation;
private Animation mScaleDownToStartAnimation;
private float mSpinnerFinalOffset;
private boolean mNotify;
private int mCircleWidth;
private int mCircleHeight;
private boolean mUsingCustomStart;
private AnimationListener mRefreshListener;
private final Animation mAnimateToCorrectPosition;
private final Animation mAnimateToStartPosition;
private void setColorViewAlpha(int targetAlpha) {
this.mCircleView.getBackground().setAlpha(targetAlpha);
this.mProgress.setAlpha(targetAlpha);
}
public void setProgressViewOffset(boolean scale, int start, int end) {
this.mScale = scale;
this.mCircleView.setVisibility(8);
this.mOriginalOffsetTop = this.mCurrentTargetOffsetTop = start;
this.mSpinnerFinalOffset = (float)end;
this.mUsingCustomStart = true;
this.mCircleView.invalidate();
}
SystemBarVisibility watcher;
public void setBarVisibilityWatcher(SystemBarVisibility watcher) {
this.watcher = watcher;
}
public void setProgressViewEndTarget(boolean scale, int end) {
this.mSpinnerFinalOffset = (float)end;
this.mScale = scale;
this.mCircleView.invalidate();
}
public void setSize(int size) {
if(size == 0 || size == 1) {
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
if(size == 0) {
this.mCircleHeight = this.mCircleWidth = (int)(56.0F * metrics.density);
} else {
this.mCircleHeight = this.mCircleWidth = (int)(40.0F * metrics.density);
}
this.mCircleView.setImageDrawable((Drawable)null);
this.mProgress.updateSizes(size);
this.mCircleView.setImageDrawable(this.mProgress);
}
}
public MaterialSwipeRefreshLayout(Context context) {
this(context, (AttributeSet)null);
}
public MaterialSwipeRefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
this.mRefreshing = false;
this.mTotalDragDistance = -1.0F;
this.mOriginalOffsetCalculated = false;
this.mActivePointerId = -1;
this.mCircleViewIndex = -1;
this.mRefreshListener = new AnimationListener() {
public void onAnimationStart(Animation animation) {
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
if(MaterialSwipeRefreshLayout.this.mRefreshing) {
MaterialSwipeRefreshLayout.this.mProgress.setAlpha(255);
MaterialSwipeRefreshLayout.this.mProgress.start();
if(MaterialSwipeRefreshLayout.this.mNotify && MaterialSwipeRefreshLayout.this.mListener != null) {
MaterialSwipeRefreshLayout.this.mListener.onRefresh();
}
} else {
MaterialSwipeRefreshLayout.this.mProgress.stop();
MaterialSwipeRefreshLayout.this.mCircleView.setVisibility(8);
MaterialSwipeRefreshLayout.this.setColorViewAlpha(255);
if(MaterialSwipeRefreshLayout.this.mScale) {
MaterialSwipeRefreshLayout.this.setAnimationProgress(0.0F);
} else {
MaterialSwipeRefreshLayout.this.setTargetOffsetTopAndBottom(MaterialSwipeRefreshLayout.this.mOriginalOffsetTop - MaterialSwipeRefreshLayout.this.mCurrentTargetOffsetTop, true);
}
}
MaterialSwipeRefreshLayout.this.mCurrentTargetOffsetTop = MaterialSwipeRefreshLayout.this.mCircleView.getTop();
}
};
this.mAnimateToCorrectPosition = new Animation() {
public void applyTransformation(float interpolatedTime, Transformation t) {
boolean targetTop = false;
boolean endTarget = false;
int endTarget1;
if(!MaterialSwipeRefreshLayout.this.mUsingCustomStart) {
endTarget1 = (int)(MaterialSwipeRefreshLayout.this.mSpinnerFinalOffset - (float)Math.abs(MaterialSwipeRefreshLayout.this.mOriginalOffsetTop));
} else {
endTarget1 = (int) MaterialSwipeRefreshLayout.this.mSpinnerFinalOffset;
}
int targetTop1 = MaterialSwipeRefreshLayout.this.mFrom + (int)((float)(endTarget1 - MaterialSwipeRefreshLayout.this.mFrom) * interpolatedTime);
int offset = targetTop1 - MaterialSwipeRefreshLayout.this.mCircleView.getTop();
MaterialSwipeRefreshLayout.this.setTargetOffsetTopAndBottom(offset, false);
}
};
this.mAnimateToStartPosition = new Animation() {
public void applyTransformation(float interpolatedTime, Transformation t) {
MaterialSwipeRefreshLayout.this.moveToStart(interpolatedTime);
}
};
this.mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
int i = 17694721;
this.mMediumAnimationDuration = this.getResources().getInteger(i);
this.setWillNotDraw(false);
this.mDecelerateInterpolator = new DecelerateInterpolator(2.0F);
TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
this.setEnabled(a.getBoolean(0, true));
a.recycle();
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
this.mCircleWidth = (int)(40.0F * metrics.density);
this.mCircleHeight = (int)(40.0F * metrics.density);
this.createProgressView();
ViewCompat.setChildrenDrawingOrderEnabled(this, true);
this.mSpinnerFinalOffset = 64.0F * metrics.density;
this.mTotalDragDistance = this.mSpinnerFinalOffset;
}
protected int getChildDrawingOrder(int childCount, int i) {
return this.mCircleViewIndex < 0?i:(i == childCount - 1?this.mCircleViewIndex:(i >= this.mCircleViewIndex?i + 1:i));
}
private void createProgressView() {
this.mCircleView = new CircleImageView(this.getContext(), -328966, 20.0F);
this.mProgress = new MaterialProgressDrawable(this.getContext(), this);
this.mProgress.setBackgroundColor(-328966);
this.mCircleView.setImageDrawable(this.mProgress);
this.mCircleView.setVisibility(8);
this.addView(this.mCircleView);
}
public void setOnRefreshListener(MaterialSwipeRefreshLayout.OnRefreshListener listener) {
this.mListener = listener;
}
private boolean isAlphaUsedForScale() {
return VERSION.SDK_INT < 11;
}
public void setRefreshing(boolean refreshing) {
if(refreshing && this.mRefreshing != refreshing) {
this.mRefreshing = refreshing;
boolean endTarget = false;
int endTarget1;
if(!this.mUsingCustomStart) {
endTarget1 = (int)(this.mSpinnerFinalOffset + (float)this.mOriginalOffsetTop);
} else {
endTarget1 = (int)this.mSpinnerFinalOffset;
}
this.setTargetOffsetTopAndBottom(endTarget1 - this.mCurrentTargetOffsetTop, true);
this.mNotify = false;
this.startScaleUpAnimation(this.mRefreshListener);
} else {
this.setRefreshing(refreshing, false);
}
}
private void startScaleUpAnimation(AnimationListener listener) {
this.mCircleView.setVisibility(0);
if(VERSION.SDK_INT >= 11) {
this.mProgress.setAlpha(255);
}
this.mScaleAnimation = new Animation() {
public void applyTransformation(float interpolatedTime, Transformation t) {
MaterialSwipeRefreshLayout.this.setAnimationProgress(interpolatedTime);
}
};
this.mScaleAnimation.setDuration((long)this.mMediumAnimationDuration);
if(listener != null) {
this.mCircleView.setAnimationListener(listener);
}
this.mCircleView.clearAnimation();
this.mCircleView.startAnimation(this.mScaleAnimation);
}
private void setAnimationProgress(float progress) {
if(this.isAlphaUsedForScale()) {
this.setColorViewAlpha((int)(progress * 255.0F));
} else {
ViewCompat.setScaleX(this.mCircleView, progress);
ViewCompat.setScaleY(this.mCircleView, progress);
}
}
private void setRefreshing(boolean refreshing, boolean notify) {
if(this.mRefreshing != refreshing) {
this.mNotify = notify;
this.ensureTarget();
this.mRefreshing = refreshing;
if(this.mRefreshing) {
this.animateOffsetToCorrectPosition(this.mCurrentTargetOffsetTop, this.mRefreshListener);
} else {
this.startScaleDownAnimation(this.mRefreshListener);
}
}
}
private void startScaleDownAnimation(AnimationListener listener) {
this.mScaleDownAnimation = new Animation() {
public void applyTransformation(float interpolatedTime, Transformation t) {
MaterialSwipeRefreshLayout.this.setAnimationProgress(1.0F - interpolatedTime);
}
};
this.mScaleDownAnimation.setDuration(150L);
this.mCircleView.setAnimationListener(listener);
this.mCircleView.clearAnimation();
this.mCircleView.startAnimation(this.mScaleDownAnimation);
// sometimes this thing gets stuck..
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mProgress.stop();
}
}, 160l);
}
private void startProgressAlphaStartAnimation() {
this.mAlphaStartAnimation = this.startAlphaAnimation(this.mProgress.getAlpha(), 76);
}
private void startProgressAlphaMaxAnimation() {
this.mAlphaMaxAnimation = this.startAlphaAnimation(this.mProgress.getAlpha(), 255);
}
private Animation startAlphaAnimation(final int startingAlpha, final int endingAlpha) {
if(this.mScale && this.isAlphaUsedForScale()) {
return null;
} else {
Animation alpha = new Animation() {
public void applyTransformation(float interpolatedTime, Transformation t) {
MaterialSwipeRefreshLayout.this.mProgress.setAlpha((int)((float)startingAlpha + (float)(endingAlpha - startingAlpha) * interpolatedTime));
}
};
alpha.setDuration(300L);
this.mCircleView.setAnimationListener((AnimationListener)null);
this.mCircleView.clearAnimation();
this.mCircleView.startAnimation(alpha);
return alpha;
}
}
public void setProgressBackgroundColor(int colorRes) {
this.mCircleView.setBackgroundColor(colorRes);
this.mProgress.setBackgroundColor(this.getResources().getColor(colorRes));
}
/** @deprecated */
@Deprecated
public void setColorScheme(int... colors) {
this.setColorSchemeResources(colors);
}
public void setColorSchemeResources(int... colorResIds) {
Resources res = this.getResources();
int[] colorRes = new int[colorResIds.length];
for(int i = 0; i < colorResIds.length; ++i) {
colorRes[i] = res.getColor(colorResIds[i]);
}
this.setColorSchemeColors(colorRes);
}
public void setColorSchemeColors(int... colors) {
this.ensureTarget();
this.mProgress.setColorSchemeColors(colors);
}
public boolean isRefreshing() {
return this.mRefreshing;
}
private void ensureTarget() {
if(this.mTarget == null) {
for(int i = 0; i < this.getChildCount(); ++i) {
View child = this.getChildAt(i);
if(!child.equals(this.mCircleView)) {
this.mTarget = child;
break;
}
}
}
}
public void setDistanceToTriggerSync(int distance) {
this.mTotalDragDistance = (float)distance;
}
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int width = this.getMeasuredWidth();
int height = this.getMeasuredHeight();
if(this.getChildCount() != 0) {
if(this.mTarget == null) {
this.ensureTarget();
}
if(this.mTarget != null) {
View child = this.mTarget;
int childLeft = this.getPaddingLeft();
int childTop = this.getPaddingTop();
int childWidth = width - this.getPaddingLeft() - this.getPaddingRight();
int childHeight = height - this.getPaddingTop() - this.getPaddingBottom();
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
int circleWidth = this.mCircleView.getMeasuredWidth();
int circleHeight = this.mCircleView.getMeasuredHeight();
this.mCircleView.layout(width / 2 - circleWidth / 2, this.mCurrentTargetOffsetTop, width / 2 + circleWidth / 2, this.mCurrentTargetOffsetTop + circleHeight);
}
}
}
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if(this.mTarget == null) {
this.ensureTarget();
}
if(this.mTarget != null) {
this.mTarget.measure(MeasureSpec.makeMeasureSpec(this.getMeasuredWidth() - this.getPaddingLeft() - this.getPaddingRight(), 1073741824), MeasureSpec.makeMeasureSpec(this.getMeasuredHeight() - this.getPaddingTop() - this.getPaddingBottom(), 1073741824));
this.mCircleView.measure(MeasureSpec.makeMeasureSpec(this.mCircleWidth, 1073741824), MeasureSpec.makeMeasureSpec(this.mCircleHeight, 1073741824));
if(!this.mUsingCustomStart && !this.mOriginalOffsetCalculated) {
this.mOriginalOffsetCalculated = true;
this.mCurrentTargetOffsetTop = this.mOriginalOffsetTop = -this.mCircleView.getMeasuredHeight();
}
this.mCircleViewIndex = -1;
for(int index = 0; index < this.getChildCount(); ++index) {
if(this.getChildAt(index) == this.mCircleView) {
this.mCircleViewIndex = index;
break;
}
}
}
}
public boolean canChildScrollUp() {
if(VERSION.SDK_INT < 14) {
if(!(this.mTarget instanceof AbsListView)) {
return this.mTarget.getScrollY() > 0;
} else {
AbsListView absListView = (AbsListView)this.mTarget;
return absListView.getChildCount() > 0 && (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0).getTop() < absListView.getPaddingTop());
}
} else {
return ViewCompat.canScrollVertically(this.mTarget, -1);
}
}
public boolean onInterceptTouchEvent(MotionEvent ev) {
this.ensureTarget();
int action = MotionEventCompat.getActionMasked(ev);
if(this.mReturningToStart && action == 0) {
this.mReturningToStart = false;
}
if(this.isEnabled() && !this.mReturningToStart && !this.canChildScrollUp() && !this.mRefreshing) {
switch(action) {
case 0:
this.setTargetOffsetTopAndBottom(this.mOriginalOffsetTop - this.mCircleView.getTop(), true);
this.mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
this.mIsBeingDragged = false;
float initialMotionY = this.getMotionEventY(ev, this.mActivePointerId);
if(initialMotionY == -1.0F) {
return false;
}
this.mInitialMotionY = initialMotionY;
case 2:
if(this.mActivePointerId == -1) {
Log.e(LOG_TAG, "Got ACTION_MOVE event but don\'t have an active pointer id.");
return false;
}
float y = this.getMotionEventY(ev, this.mActivePointerId);
if(y == -1.0F) {
return false;
}
float yDiff = y - this.mInitialMotionY;
if(yDiff > (float)this.mTouchSlop && !this.mIsBeingDragged) {
this.mIsBeingDragged = true;
this.mProgress.setAlpha(76);
}
break;
case 1:
case 3:
this.mIsBeingDragged = false;
this.mActivePointerId = -1;
case 4:
case 5:
default:
break;
case 6:
this.onSecondaryPointerUp(ev);
}
return this.mIsBeingDragged;
} else {
return false;
}
}
private float getMotionEventY(MotionEvent ev, int activePointerId) {
int index = MotionEventCompat.findPointerIndex(ev, activePointerId);
return index < 0?-1.0F:MotionEventCompat.getY(ev, index);
}
public void requestDisallowInterceptTouchEvent(boolean b) {
}
private boolean isAnimationRunning(Animation animation) {
return animation != null && animation.hasStarted() && !animation.hasEnded();
}
public boolean onTouchEvent(MotionEvent ev) {
int action = MotionEventCompat.getActionMasked(ev);
if(this.mReturningToStart && action == 0) {
this.mReturningToStart = false;
}
if(this.isEnabled() && !this.mReturningToStart && !this.canChildScrollUp()) {
int pointerIndex;
float y;
float overscrollTop;
switch(action) {
case 0:
this.mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
this.mIsBeingDragged = false;
break;
case 1:
case 3:
if(this.mActivePointerId == -1) {
if(action == 1) {
Log.e(LOG_TAG, "Got ACTION_UP event but don\'t have an active pointer id.");
}
return false;
}
pointerIndex = MotionEventCompat.findPointerIndex(ev, this.mActivePointerId);
y = MotionEventCompat.getY(ev, pointerIndex);
overscrollTop = (y - this.mInitialMotionY) * 0.5F;
this.mIsBeingDragged = false;
if(overscrollTop > this.mTotalDragDistance) {
this.setRefreshing(true, true);
} else {
this.mRefreshing = false;
this.mProgress.setStartEndTrim(0.0F, 0.0F);
AnimationListener listener1 = null;
if(!this.mScale) {
listener1 = new AnimationListener() {
public void onAnimationStart(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
if(!MaterialSwipeRefreshLayout.this.mScale) {
MaterialSwipeRefreshLayout.this.startScaleDownAnimation((AnimationListener)null);
}
}
public void onAnimationRepeat(Animation animation) {
}
};
}
this.animateOffsetToStartPosition(this.mCurrentTargetOffsetTop, listener1);
this.mProgress.showArrow(false);
}
this.mActivePointerId = -1;
return false;
case 2:
pointerIndex = MotionEventCompat.findPointerIndex(ev, this.mActivePointerId);
if(pointerIndex < 0) {
Log.e(LOG_TAG, "Got ACTION_MOVE event but have an invalid active pointer id.");
return false;
}
y = MotionEventCompat.getY(ev, pointerIndex);
overscrollTop = (y - this.mInitialMotionY) * 0.5F;
if(this.mIsBeingDragged) {
this.mProgress.showArrow(true);
float listener = overscrollTop / this.mTotalDragDistance;
if(listener < 0.0F) {
return false;
}
float dragPercent = Math.min(1.0F, Math.abs(listener));
float adjustedPercent = (float)Math.max((double)dragPercent - 0.4D, 0.0D) * 5.0F / 3.0F;
float extraOS = Math.abs(overscrollTop) - this.mTotalDragDistance;
float slingshotDist = this.mUsingCustomStart?this.mSpinnerFinalOffset - (float)this.mOriginalOffsetTop:this.mSpinnerFinalOffset;
float tensionSlingshotPercent = Math.max(0.0F, Math.min(extraOS, slingshotDist * 2.0F) / slingshotDist);
float tensionPercent = (float)((double)(tensionSlingshotPercent / 4.0F) - Math.pow((double)(tensionSlingshotPercent / 4.0F), 2.0D)) * 2.0F;
float extraMove = slingshotDist * tensionPercent * 2.0F;
int targetY = this.mOriginalOffsetTop + (int)(slingshotDist * dragPercent + extraMove);
if(this.mCircleView.getVisibility() != 0) {
this.mCircleView.setVisibility(0);
}
if(!this.mScale) {
ViewCompat.setScaleX(this.mCircleView, 1.0F);
ViewCompat.setScaleY(this.mCircleView, 1.0F);
}
float rotation;
if(overscrollTop < this.mTotalDragDistance) {
if(this.mScale) {
this.setAnimationProgress(overscrollTop / this.mTotalDragDistance);
}
if(this.mProgress.getAlpha() > 76 && !this.isAnimationRunning(this.mAlphaStartAnimation)) {
this.startProgressAlphaStartAnimation();
}
rotation = adjustedPercent * 0.8F;
this.mProgress.setStartEndTrim(0.0F, Math.min(0.8F, rotation));
this.mProgress.setArrowScale(Math.min(1.0F, adjustedPercent));
} else if(this.mProgress.getAlpha() < 255 && !this.isAnimationRunning(this.mAlphaMaxAnimation)) {
this.startProgressAlphaMaxAnimation();
}
rotation = (-0.25F + 0.4F * adjustedPercent + tensionPercent * 2.0F) * 0.5F;
this.mProgress.setProgressRotation(rotation);
this.setTargetOffsetTopAndBottom(targetY - this.mCurrentTargetOffsetTop, true);
}
case 4:
default:
break;
case 5:
pointerIndex = MotionEventCompat.getActionIndex(ev);
this.mActivePointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
break;
case 6:
this.onSecondaryPointerUp(ev);
}
return true;
} else {
return false;
}
}
private void animateOffsetToCorrectPosition(int from, AnimationListener listener) {
this.mFrom = from;
this.mAnimateToCorrectPosition.reset();
this.mAnimateToCorrectPosition.setDuration(200L);
this.mAnimateToCorrectPosition.setInterpolator(this.mDecelerateInterpolator);
if(listener != null) {
this.mCircleView.setAnimationListener(listener);
}
this.mCircleView.clearAnimation();
this.mCircleView.startAnimation(this.mAnimateToCorrectPosition);
}
private void animateOffsetToStartPosition(int from, AnimationListener listener) {
if(this.mScale) {
this.startScaleDownReturnToStartAnimation(from, listener);
} else {
this.mFrom = from;
this.mAnimateToStartPosition.reset();
this.mAnimateToStartPosition.setDuration(200L);
this.mAnimateToStartPosition.setInterpolator(this.mDecelerateInterpolator);
if(listener != null) {
this.mCircleView.setAnimationListener(listener);
}
this.mCircleView.clearAnimation();
this.mCircleView.startAnimation(this.mAnimateToStartPosition);
}
}
private void moveToStart(float interpolatedTime) {
boolean targetTop = false;
int targetTop1 = this.mFrom + (int)((float)(this.mOriginalOffsetTop - this.mFrom) * interpolatedTime);
int offset = targetTop1 - this.mCircleView.getTop();
this.setTargetOffsetTopAndBottom(offset, false);
}
private void startScaleDownReturnToStartAnimation(int from, AnimationListener listener) {
this.mFrom = from;
if(this.isAlphaUsedForScale()) {
this.mStartingScale = (float)this.mProgress.getAlpha();
} else {
this.mStartingScale = ViewCompat.getScaleX(this.mCircleView);
}
this.mScaleDownToStartAnimation = new Animation() {
public void applyTransformation(float interpolatedTime, Transformation t) {
float targetScale = MaterialSwipeRefreshLayout.this.mStartingScale + -MaterialSwipeRefreshLayout.this.mStartingScale * interpolatedTime;
MaterialSwipeRefreshLayout.this.setAnimationProgress(targetScale);
MaterialSwipeRefreshLayout.this.moveToStart(interpolatedTime);
}
};
this.mScaleDownToStartAnimation.setDuration(150L);
if(listener != null) {
this.mCircleView.setAnimationListener(listener);
}
this.mCircleView.clearAnimation();
this.mCircleView.startAnimation(this.mScaleDownToStartAnimation);
}
private void setTargetOffsetTopAndBottom(int offset, boolean requiresUpdate) {
if (watcher != null) {
watcher.showBars();
}
this.mCircleView.bringToFront();
this.mCircleView.offsetTopAndBottom(offset);
this.mCurrentTargetOffsetTop = this.mCircleView.getTop();
if(requiresUpdate && VERSION.SDK_INT < 11) {
this.invalidate();
}
}
private void onSecondaryPointerUp(MotionEvent ev) {
int pointerIndex = MotionEventCompat.getActionIndex(ev);
int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if(pointerId == this.mActivePointerId) {
int newPointerIndex = pointerIndex == 0?1:0;
this.mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
}
}
public interface OnRefreshListener {
void onRefresh();
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.util;
import com.google.auth.Credentials;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Map;
import org.apache.beam.sdk.options.PipelineOptions;
/**
* Construct an oauth credential to be used by the SDK and the SDK workers.
* Always returns a null Credential object.
*/
public class NoopCredentialFactory implements CredentialFactory {
private static final NoopCredentialFactory INSTANCE = new NoopCredentialFactory();
private static final NoopCredentials NOOP_CREDENTIALS = new NoopCredentials();
public static NoopCredentialFactory fromOptions(PipelineOptions options) {
return INSTANCE;
}
@Override
public Credentials getCredential() throws IOException {
return NOOP_CREDENTIALS;
}
private static class NoopCredentials extends Credentials {
@Override
public String getAuthenticationType() {
return null;
}
@Override
public Map<String, List<String>> getRequestMetadata(URI uri) throws IOException {
return null;
}
@Override
public boolean hasRequestMetadata() {
return false;
}
@Override
public boolean hasRequestMetadataOnly() {
return false;
}
@Override
public void refresh() throws IOException {}
}
}
|
/*
* Copyright 2009-2017. DigitalGlobe, 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 org.mrgeo.data.vector.mbvectortiles;
import org.apache.hadoop.mapreduce.InputFormat;
import org.mrgeo.data.vector.FeatureIdWritable;
import org.mrgeo.data.vector.VectorInputFormatContext;
import org.mrgeo.data.vector.VectorInputFormatProvider;
import org.mrgeo.geometry.Geometry;
public class MbVectorTilesInputFormatProvider extends VectorInputFormatProvider
{
// private PgVectorDataProvider dataProvider;
private MbVectorTilesSettings dbSettings;
public MbVectorTilesInputFormatProvider(VectorInputFormatContext context,
MbVectorTilesDataProvider dataProvider,
MbVectorTilesSettings dbSettings)
{
super(context);
// this.dataProvider = dataProvider;
this.dbSettings = dbSettings;
}
@Override
public InputFormat<FeatureIdWritable, Geometry> getInputFormat(String input)
{
return new MbVectorTilesInputFormat(dbSettings);
}
}
|
package com.fintech.crypto.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonIgnoreType;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "mine_histories")
@JsonIgnoreProperties({"contract"})
@Getter
@Setter
public class MineHistory extends AbstractEntity {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "contract_id", referencedColumnName = "c_ref")
private Contract contract;
@Column(name = "amount_mined", precision = 8)
private double amountMined;
public void setContract(Contract contract) {
this.contract = contract;
}
public double getAmountMined() {
return amountMined;
}
public void setAmountMined(double amountMined) {
this.amountMined = amountMined;
}
}
|
/*
* Copyright 2012 University of Chicago
*
* 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.griphyn.vdl.mapping;
import java.util.Comparator;
public class PathComparator implements Comparator<Path> {
@SuppressWarnings("unchecked")
public int compare(Path p1, Path p2) {
for (int i = 0; i < Math.min(p1.size(), p2.size()); i++) {
int d;
d = indexOrder(p1.isArrayIndex(i), p2.isArrayIndex(i));
if (d != 0) {
return d;
}
Comparable<Object> e1 = (Comparable<Object>) p1.getElement(i);
Comparable<Object> e2 = (Comparable<Object>) p2.getElement(i);
if (p1.isArrayIndex(i)) {
if (e1.getClass() != e2.getClass()) {
d = e1.getClass().getName().compareTo(e2.getClass().getName());
}
}
if (d == 0) {
d = e1.compareTo(e2);
}
if (d != 0) {
return d;
}
}
//the longer one wins
return p1.size() - p2.size();
}
private int indexOrder(boolean i1, boolean i2) {
//it doesn't matter much what the order between indices and non-indices is,
//but it needs to be consistent
if (i1) {
if (!i2) {
return -1;
}
}
else {
if (i2) {
return 1;
}
}
return 0;
}
}
|
//=====================================================================
//
//File: $RCSfile: UnitTestGenerator.pl,v $
//Version: $Revision: 1.14 $
//Modified: $Date: 2013/01/10 23:21:36 $
//
// WARNING: Do not edit this generated file
// Generated by: UnitTestGenerator.pl
// Version: 1.14
// Matrix: CopyPasteSourceDestinationTestMatrixFull.txt
//
//(c) Copyright 2007-2014 by Mentor Graphics 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. See the
// License for the specific language governing permissions and limitations under
// the License.
//=====================================================================
package com.mentor.nucleus.bp.core.test.cpts_full;
import org.eclipse.ui.IEditorPart;
import com.mentor.nucleus.bp.core.*;
import com.mentor.nucleus.bp.core.common.NonRootModelElement;
import com.mentor.nucleus.bp.test.common.*;
import com.mentor.nucleus.bp.ui.canvas.*;
import com.mentor.nucleus.bp.ui.graphics.editor.*;
import com.mentor.nucleus.bp.ui.canvas.test.*;
public class CopyPasteSourceDestinationTests_37 extends CopyPasteSourceDestinationTests {
protected String getResultName() {
return super.getResultName();
}
public CopyPasteSourceDestinationTests_37(String arg0) {
super("CopyPasteSourceDestinationTests_37", arg0);
}
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Perform the test for the given matrix column (A100) and row (B44).
*
*/
public void testA100_B44() {
test_id = getTestId("A100", "B44", "1");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B44");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B45).
*
*/
public void testA100_B45() {
test_id = getTestId("A100", "B45", "2");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B45");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B46).
*
*/
public void testA100_B46() {
test_id = getTestId("A100", "B46", "3");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B46");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B47).
*
*/
public void testA100_B47() {
test_id = getTestId("A100", "B47", "4");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B47");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B48).
*
*/
public void testA100_B48() {
test_id = getTestId("A100", "B48", "5");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B48");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B49).
*
*/
public void testA100_B49() {
test_id = getTestId("A100", "B49", "6");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B49");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B50).
*
*/
public void testA100_B50() {
test_id = getTestId("A100", "B50", "7");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B50");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B51).
*
*/
public void testA100_B51() {
test_id = getTestId("A100", "B51", "8");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B51");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B52).
*
*/
public void testA100_B52() {
test_id = getTestId("A100", "B52", "9");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B52");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B53).
*
*/
public void testA100_B53() {
test_id = getTestId("A100", "B53", "10");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B53");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B54).
*
*/
public void testA100_B54() {
test_id = getTestId("A100", "B54", "11");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B54");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B55).
*
*/
public void testA100_B55() {
test_id = getTestId("A100", "B55", "12");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B55");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B56).
*
*/
public void testA100_B56() {
test_id = getTestId("A100", "B56", "13");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B56");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B57).
*
*/
public void testA100_B57() {
test_id = getTestId("A100", "B57", "14");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B57");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B58).
*
*/
public void testA100_B58() {
test_id = getTestId("A100", "B58", "15");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B58");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B59).
*
*/
public void testA100_B59() {
test_id = getTestId("A100", "B59", "16");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B59");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B60).
*
*/
public void testA100_B60() {
test_id = getTestId("A100", "B60", "17");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B60");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B61).
*
*/
public void testA100_B61() {
test_id = getTestId("A100", "B61", "18");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B61");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B62).
*
*/
public void testA100_B62() {
test_id = getTestId("A100", "B62", "19");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B62");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B63).
*
*/
public void testA100_B63() {
test_id = getTestId("A100", "B63", "20");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B63");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B64).
*
*/
public void testA100_B64() {
test_id = getTestId("A100", "B64", "21");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B64");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B65).
*
*/
public void testA100_B65() {
test_id = getTestId("A100", "B65", "22");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B65");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B66).
*
*/
public void testA100_B66() {
test_id = getTestId("A100", "B66", "23");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B66");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B67).
*
*/
public void testA100_B67() {
test_id = getTestId("A100", "B67", "24");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B67");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B68).
*
*/
public void testA100_B68() {
test_id = getTestId("A100", "B68", "25");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B68");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B69).
*
*/
public void testA100_B69() {
test_id = getTestId("A100", "B69", "26");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B69");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B70).
*
*/
public void testA100_B70() {
test_id = getTestId("A100", "B70", "27");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B70");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B71).
*
*/
public void testA100_B71() {
test_id = getTestId("A100", "B71", "28");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B71");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B72).
*
*/
public void testA100_B72() {
test_id = getTestId("A100", "B72", "29");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B72");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B73).
*
*/
public void testA100_B73() {
test_id = getTestId("A100", "B73", "30");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B73");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B74).
*
*/
public void testA100_B74() {
test_id = getTestId("A100", "B74", "31");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B74");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B75).
*
*/
public void testA100_B75() {
test_id = getTestId("A100", "B75", "32");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B75");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B76).
*
*/
public void testA100_B76() {
test_id = getTestId("A100", "B76", "33");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B76");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B77).
*
*/
public void testA100_B77() {
test_id = getTestId("A100", "B77", "34");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B77");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B78).
*
*/
public void testA100_B78() {
test_id = getTestId("A100", "B78", "35");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B78");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B79).
*
*/
public void testA100_B79() {
test_id = getTestId("A100", "B79", "36");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B79");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B80).
*
*/
public void testA100_B80() {
test_id = getTestId("A100", "B80", "37");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B80");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B81).
*
*/
public void testA100_B81() {
test_id = getTestId("A100", "B81", "38");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B81");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B82).
*
*/
public void testA100_B82() {
test_id = getTestId("A100", "B82", "39");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B82");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B83).
*
*/
public void testA100_B83() {
test_id = getTestId("A100", "B83", "40");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B83");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B84).
*
*/
public void testA100_B84() {
test_id = getTestId("A100", "B84", "41");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B84");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B85).
*
*/
public void testA100_B85() {
test_id = getTestId("A100", "B85", "42");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B85");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B86).
*
*/
public void testA100_B86() {
test_id = getTestId("A100", "B86", "43");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B86");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B87).
*
*/
public void testA100_B87() {
test_id = getTestId("A100", "B87", "44");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B87");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B88).
*
*/
public void testA100_B88() {
test_id = getTestId("A100", "B88", "45");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B88");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B89).
*
*/
public void testA100_B89() {
test_id = getTestId("A100", "B89", "46");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B89");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B90).
*
*/
public void testA100_B90() {
test_id = getTestId("A100", "B90", "47");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B90");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B91).
*
*/
public void testA100_B91() {
test_id = getTestId("A100", "B91", "48");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B91");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B92).
*
*/
public void testA100_B92() {
test_id = getTestId("A100", "B92", "49");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B92");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A100) and row (B93).
*
*/
public void testA100_B93() {
test_id = getTestId("A100", "B93", "50");
NonRootModelElement src = selectA("A100");
NonRootModelElement dest = selectB("B93");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B1).
*
*/
public void testA101_B1() {
test_id = getTestId("A101", "B1", "51");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B1");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B2).
*
*/
public void testA101_B2() {
test_id = getTestId("A101", "B2", "52");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B2");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B3).
*
*/
public void testA101_B3() {
test_id = getTestId("A101", "B3", "53");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B3");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B4).
*
*/
public void testA101_B4() {
test_id = getTestId("A101", "B4", "54");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B4");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B5).
*
*/
public void testA101_B5() {
test_id = getTestId("A101", "B5", "55");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B5");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B6).
*
*/
public void testA101_B6() {
test_id = getTestId("A101", "B6", "56");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B6");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B7).
*
*/
public void testA101_B7() {
test_id = getTestId("A101", "B7", "57");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B7");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B8).
*
*/
public void testA101_B8() {
test_id = getTestId("A101", "B8", "58");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B8");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B9).
*
*/
public void testA101_B9() {
test_id = getTestId("A101", "B9", "59");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B9");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B10).
*
*/
public void testA101_B10() {
test_id = getTestId("A101", "B10", "60");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B10");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B11).
*
*/
public void testA101_B11() {
test_id = getTestId("A101", "B11", "61");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B11");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B12).
*
*/
public void testA101_B12() {
test_id = getTestId("A101", "B12", "62");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B12");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B13).
*
*/
public void testA101_B13() {
test_id = getTestId("A101", "B13", "63");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B13");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B14).
*
*/
public void testA101_B14() {
test_id = getTestId("A101", "B14", "64");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B14");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B15).
*
*/
public void testA101_B15() {
test_id = getTestId("A101", "B15", "65");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B15");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B16).
*
*/
public void testA101_B16() {
test_id = getTestId("A101", "B16", "66");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B16");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B17).
*
*/
public void testA101_B17() {
test_id = getTestId("A101", "B17", "67");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B17");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B18).
*
*/
public void testA101_B18() {
test_id = getTestId("A101", "B18", "68");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B18");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B19).
*
*/
public void testA101_B19() {
test_id = getTestId("A101", "B19", "69");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B19");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B20).
*
*/
public void testA101_B20() {
test_id = getTestId("A101", "B20", "70");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B20");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B21).
*
*/
public void testA101_B21() {
test_id = getTestId("A101", "B21", "71");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B21");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B22).
*
*/
public void testA101_B22() {
test_id = getTestId("A101", "B22", "72");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B22");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B23).
*
*/
public void testA101_B23() {
test_id = getTestId("A101", "B23", "73");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B23");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B24).
*
*/
public void testA101_B24() {
test_id = getTestId("A101", "B24", "74");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B24");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B25).
*
*/
public void testA101_B25() {
test_id = getTestId("A101", "B25", "75");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B25");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B26).
*
*/
public void testA101_B26() {
test_id = getTestId("A101", "B26", "76");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B26");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B27).
*
*/
public void testA101_B27() {
test_id = getTestId("A101", "B27", "77");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B27");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B28).
*
*/
public void testA101_B28() {
test_id = getTestId("A101", "B28", "78");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B28");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B29).
*
*/
public void testA101_B29() {
test_id = getTestId("A101", "B29", "79");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B29");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B30).
*
*/
public void testA101_B30() {
test_id = getTestId("A101", "B30", "80");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B30");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B31).
*
*/
public void testA101_B31() {
test_id = getTestId("A101", "B31", "81");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B31");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B32).
*
*/
public void testA101_B32() {
test_id = getTestId("A101", "B32", "82");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B32");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B33).
*
*/
public void testA101_B33() {
test_id = getTestId("A101", "B33", "83");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B33");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B34).
*
*/
public void testA101_B34() {
test_id = getTestId("A101", "B34", "84");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B34");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B35).
*
*/
public void testA101_B35() {
test_id = getTestId("A101", "B35", "85");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B35");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B36).
*
*/
public void testA101_B36() {
test_id = getTestId("A101", "B36", "86");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B36");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B37).
*
*/
public void testA101_B37() {
test_id = getTestId("A101", "B37", "87");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B37");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B38).
*
*/
public void testA101_B38() {
test_id = getTestId("A101", "B38", "88");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B38");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B39).
*
*/
public void testA101_B39() {
test_id = getTestId("A101", "B39", "89");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B39");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B40).
*
*/
public void testA101_B40() {
test_id = getTestId("A101", "B40", "90");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B40");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B41).
*
*/
public void testA101_B41() {
test_id = getTestId("A101", "B41", "91");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B41");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B42).
*
*/
public void testA101_B42() {
test_id = getTestId("A101", "B42", "92");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B42");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B43).
*
*/
public void testA101_B43() {
test_id = getTestId("A101", "B43", "93");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B43");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B44).
*
*/
public void testA101_B44() {
test_id = getTestId("A101", "B44", "94");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B44");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B45).
*
*/
public void testA101_B45() {
test_id = getTestId("A101", "B45", "95");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B45");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B46).
*
*/
public void testA101_B46() {
test_id = getTestId("A101", "B46", "96");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B46");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B47).
*
*/
public void testA101_B47() {
test_id = getTestId("A101", "B47", "97");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B47");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B48).
*
*/
public void testA101_B48() {
test_id = getTestId("A101", "B48", "98");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B48");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B49).
*
*/
public void testA101_B49() {
test_id = getTestId("A101", "B49", "99");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B49");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B50).
*
*/
public void testA101_B50() {
test_id = getTestId("A101", "B50", "100");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B50");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B51).
*
*/
public void testA101_B51() {
test_id = getTestId("A101", "B51", "101");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B51");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B52).
*
*/
public void testA101_B52() {
test_id = getTestId("A101", "B52", "102");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B52");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B53).
*
*/
public void testA101_B53() {
test_id = getTestId("A101", "B53", "103");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B53");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B54).
*
*/
public void testA101_B54() {
test_id = getTestId("A101", "B54", "104");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B54");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B55).
*
*/
public void testA101_B55() {
test_id = getTestId("A101", "B55", "105");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B55");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B56).
*
*/
public void testA101_B56() {
test_id = getTestId("A101", "B56", "106");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B56");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B57).
*
*/
public void testA101_B57() {
test_id = getTestId("A101", "B57", "107");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B57");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B58).
*
*/
public void testA101_B58() {
test_id = getTestId("A101", "B58", "108");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B58");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B59).
*
*/
public void testA101_B59() {
test_id = getTestId("A101", "B59", "109");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B59");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B60).
*
*/
public void testA101_B60() {
test_id = getTestId("A101", "B60", "110");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B60");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B61).
*
*/
public void testA101_B61() {
test_id = getTestId("A101", "B61", "111");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B61");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B62).
*
*/
public void testA101_B62() {
test_id = getTestId("A101", "B62", "112");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B62");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B63).
*
*/
public void testA101_B63() {
test_id = getTestId("A101", "B63", "113");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B63");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B64).
*
*/
public void testA101_B64() {
test_id = getTestId("A101", "B64", "114");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B64");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B65).
*
*/
public void testA101_B65() {
test_id = getTestId("A101", "B65", "115");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B65");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B66).
*
*/
public void testA101_B66() {
test_id = getTestId("A101", "B66", "116");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B66");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B67).
*
*/
public void testA101_B67() {
test_id = getTestId("A101", "B67", "117");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B67");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B68).
*
*/
public void testA101_B68() {
test_id = getTestId("A101", "B68", "118");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B68");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B69).
*
*/
public void testA101_B69() {
test_id = getTestId("A101", "B69", "119");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B69");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B70).
*
*/
public void testA101_B70() {
test_id = getTestId("A101", "B70", "120");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B70");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B71).
*
*/
public void testA101_B71() {
test_id = getTestId("A101", "B71", "121");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B71");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B72).
*
*/
public void testA101_B72() {
test_id = getTestId("A101", "B72", "122");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B72");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B73).
*
*/
public void testA101_B73() {
test_id = getTestId("A101", "B73", "123");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B73");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B74).
*
*/
public void testA101_B74() {
test_id = getTestId("A101", "B74", "124");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B74");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B75).
*
*/
public void testA101_B75() {
test_id = getTestId("A101", "B75", "125");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B75");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B76).
*
*/
public void testA101_B76() {
test_id = getTestId("A101", "B76", "126");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B76");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B77).
*
*/
public void testA101_B77() {
test_id = getTestId("A101", "B77", "127");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B77");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B78).
*
*/
public void testA101_B78() {
test_id = getTestId("A101", "B78", "128");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B78");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B79).
*
*/
public void testA101_B79() {
test_id = getTestId("A101", "B79", "129");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B79");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B80).
*
*/
public void testA101_B80() {
test_id = getTestId("A101", "B80", "130");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B80");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B81).
*
*/
public void testA101_B81() {
test_id = getTestId("A101", "B81", "131");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B81");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B82).
*
*/
public void testA101_B82() {
test_id = getTestId("A101", "B82", "132");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B82");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B83).
*
*/
public void testA101_B83() {
test_id = getTestId("A101", "B83", "133");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B83");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B84).
*
*/
public void testA101_B84() {
test_id = getTestId("A101", "B84", "134");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B84");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B85).
*
*/
public void testA101_B85() {
test_id = getTestId("A101", "B85", "135");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B85");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B86).
*
*/
public void testA101_B86() {
test_id = getTestId("A101", "B86", "136");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B86");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B87).
*
*/
public void testA101_B87() {
test_id = getTestId("A101", "B87", "137");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B87");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B88).
*
*/
public void testA101_B88() {
test_id = getTestId("A101", "B88", "138");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B88");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B89).
*
*/
public void testA101_B89() {
test_id = getTestId("A101", "B89", "139");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B89");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B90).
*
*/
public void testA101_B90() {
test_id = getTestId("A101", "B90", "140");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B90");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B91).
*
*/
public void testA101_B91() {
test_id = getTestId("A101", "B91", "141");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B91");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B92).
*
*/
public void testA101_B92() {
test_id = getTestId("A101", "B92", "142");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B92");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A101) and row (B93).
*
*/
public void testA101_B93() {
test_id = getTestId("A101", "B93", "143");
NonRootModelElement src = selectA("A101");
NonRootModelElement dest = selectB("B93");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B1).
*
*/
public void testA102_B1() {
test_id = getTestId("A102", "B1", "144");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B1");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B2).
*
*/
public void testA102_B2() {
test_id = getTestId("A102", "B2", "145");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B2");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B3).
*
*/
public void testA102_B3() {
test_id = getTestId("A102", "B3", "146");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B3");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B4).
*
*/
public void testA102_B4() {
test_id = getTestId("A102", "B4", "147");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B4");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B5).
*
*/
public void testA102_B5() {
test_id = getTestId("A102", "B5", "148");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B5");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B6).
*
*/
public void testA102_B6() {
test_id = getTestId("A102", "B6", "149");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B6");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B7).
*
*/
public void testA102_B7() {
test_id = getTestId("A102", "B7", "150");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B7");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B8).
*
*/
public void testA102_B8() {
test_id = getTestId("A102", "B8", "151");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B8");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B9).
*
*/
public void testA102_B9() {
test_id = getTestId("A102", "B9", "152");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B9");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B10).
*
*/
public void testA102_B10() {
test_id = getTestId("A102", "B10", "153");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B10");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B11).
*
*/
public void testA102_B11() {
test_id = getTestId("A102", "B11", "154");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B11");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B12).
*
*/
public void testA102_B12() {
test_id = getTestId("A102", "B12", "155");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B12");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B13).
*
*/
public void testA102_B13() {
test_id = getTestId("A102", "B13", "156");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B13");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B14).
*
*/
public void testA102_B14() {
test_id = getTestId("A102", "B14", "157");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B14");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B15).
*
*/
public void testA102_B15() {
test_id = getTestId("A102", "B15", "158");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B15");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B16).
*
*/
public void testA102_B16() {
test_id = getTestId("A102", "B16", "159");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B16");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B17).
*
*/
public void testA102_B17() {
test_id = getTestId("A102", "B17", "160");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B17");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B18).
*
*/
public void testA102_B18() {
test_id = getTestId("A102", "B18", "161");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B18");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B19).
*
*/
public void testA102_B19() {
test_id = getTestId("A102", "B19", "162");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B19");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B20).
*
*/
public void testA102_B20() {
test_id = getTestId("A102", "B20", "163");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B20");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B21).
*
*/
public void testA102_B21() {
test_id = getTestId("A102", "B21", "164");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B21");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B22).
*
*/
public void testA102_B22() {
test_id = getTestId("A102", "B22", "165");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B22");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B23).
*
*/
public void testA102_B23() {
test_id = getTestId("A102", "B23", "166");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B23");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B24).
*
*/
public void testA102_B24() {
test_id = getTestId("A102", "B24", "167");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B24");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B25).
*
*/
public void testA102_B25() {
test_id = getTestId("A102", "B25", "168");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B25");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B26).
*
*/
public void testA102_B26() {
test_id = getTestId("A102", "B26", "169");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B26");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B27).
*
*/
public void testA102_B27() {
test_id = getTestId("A102", "B27", "170");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B27");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B28).
*
*/
public void testA102_B28() {
test_id = getTestId("A102", "B28", "171");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B28");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B29).
*
*/
public void testA102_B29() {
test_id = getTestId("A102", "B29", "172");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B29");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B30).
*
*/
public void testA102_B30() {
test_id = getTestId("A102", "B30", "173");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B30");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B31).
*
*/
public void testA102_B31() {
test_id = getTestId("A102", "B31", "174");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B31");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B32).
*
*/
public void testA102_B32() {
test_id = getTestId("A102", "B32", "175");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B32");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B33).
*
*/
public void testA102_B33() {
test_id = getTestId("A102", "B33", "176");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B33");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B34).
*
*/
public void testA102_B34() {
test_id = getTestId("A102", "B34", "177");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B34");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B35).
*
*/
public void testA102_B35() {
test_id = getTestId("A102", "B35", "178");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B35");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B36).
*
*/
public void testA102_B36() {
test_id = getTestId("A102", "B36", "179");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B36");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B37).
*
*/
public void testA102_B37() {
test_id = getTestId("A102", "B37", "180");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B37");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B38).
*
*/
public void testA102_B38() {
test_id = getTestId("A102", "B38", "181");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B38");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B39).
*
*/
public void testA102_B39() {
test_id = getTestId("A102", "B39", "182");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B39");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B40).
*
*/
public void testA102_B40() {
test_id = getTestId("A102", "B40", "183");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B40");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B41).
*
*/
public void testA102_B41() {
test_id = getTestId("A102", "B41", "184");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B41");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B42).
*
*/
public void testA102_B42() {
test_id = getTestId("A102", "B42", "185");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B42");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B43).
*
*/
public void testA102_B43() {
test_id = getTestId("A102", "B43", "186");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B43");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B44).
*
*/
public void testA102_B44() {
test_id = getTestId("A102", "B44", "187");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B44");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B45).
*
*/
public void testA102_B45() {
test_id = getTestId("A102", "B45", "188");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B45");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B46).
*
*/
public void testA102_B46() {
test_id = getTestId("A102", "B46", "189");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B46");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B47).
*
*/
public void testA102_B47() {
test_id = getTestId("A102", "B47", "190");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B47");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B48).
*
*/
public void testA102_B48() {
test_id = getTestId("A102", "B48", "191");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B48");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B49).
*
*/
public void testA102_B49() {
test_id = getTestId("A102", "B49", "192");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B49");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B50).
*
*/
public void testA102_B50() {
test_id = getTestId("A102", "B50", "193");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B50");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B51).
*
*/
public void testA102_B51() {
test_id = getTestId("A102", "B51", "194");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B51");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B52).
*
*/
public void testA102_B52() {
test_id = getTestId("A102", "B52", "195");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B52");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B53).
*
*/
public void testA102_B53() {
test_id = getTestId("A102", "B53", "196");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B53");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B54).
*
*/
public void testA102_B54() {
test_id = getTestId("A102", "B54", "197");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B54");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B55).
*
*/
public void testA102_B55() {
test_id = getTestId("A102", "B55", "198");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B55");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B56).
*
*/
public void testA102_B56() {
test_id = getTestId("A102", "B56", "199");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B56");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B57).
*
*/
public void testA102_B57() {
test_id = getTestId("A102", "B57", "200");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B57");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B58).
*
*/
public void testA102_B58() {
test_id = getTestId("A102", "B58", "201");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B58");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B59).
*
*/
public void testA102_B59() {
test_id = getTestId("A102", "B59", "202");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B59");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B60).
*
*/
public void testA102_B60() {
test_id = getTestId("A102", "B60", "203");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B60");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B61).
*
*/
public void testA102_B61() {
test_id = getTestId("A102", "B61", "204");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B61");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B62).
*
*/
public void testA102_B62() {
test_id = getTestId("A102", "B62", "205");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B62");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B63).
*
*/
public void testA102_B63() {
test_id = getTestId("A102", "B63", "206");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B63");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B64).
*
*/
public void testA102_B64() {
test_id = getTestId("A102", "B64", "207");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B64");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B65).
*
*/
public void testA102_B65() {
test_id = getTestId("A102", "B65", "208");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B65");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B66).
*
*/
public void testA102_B66() {
test_id = getTestId("A102", "B66", "209");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B66");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B67).
*
*/
public void testA102_B67() {
test_id = getTestId("A102", "B67", "210");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B67");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B68).
*
*/
public void testA102_B68() {
test_id = getTestId("A102", "B68", "211");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B68");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B69).
*
*/
public void testA102_B69() {
test_id = getTestId("A102", "B69", "212");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B69");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B70).
*
*/
public void testA102_B70() {
test_id = getTestId("A102", "B70", "213");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B70");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B71).
*
*/
public void testA102_B71() {
test_id = getTestId("A102", "B71", "214");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B71");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B72).
*
*/
public void testA102_B72() {
test_id = getTestId("A102", "B72", "215");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B72");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B73).
*
*/
public void testA102_B73() {
test_id = getTestId("A102", "B73", "216");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B73");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B74).
*
*/
public void testA102_B74() {
test_id = getTestId("A102", "B74", "217");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B74");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B75).
*
*/
public void testA102_B75() {
test_id = getTestId("A102", "B75", "218");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B75");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B76).
*
*/
public void testA102_B76() {
test_id = getTestId("A102", "B76", "219");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B76");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B77).
*
*/
public void testA102_B77() {
test_id = getTestId("A102", "B77", "220");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B77");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B78).
*
*/
public void testA102_B78() {
test_id = getTestId("A102", "B78", "221");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B78");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B79).
*
*/
public void testA102_B79() {
test_id = getTestId("A102", "B79", "222");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B79");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B80).
*
*/
public void testA102_B80() {
test_id = getTestId("A102", "B80", "223");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B80");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B81).
*
*/
public void testA102_B81() {
test_id = getTestId("A102", "B81", "224");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B81");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B82).
*
*/
public void testA102_B82() {
test_id = getTestId("A102", "B82", "225");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B82");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B83).
*
*/
public void testA102_B83() {
test_id = getTestId("A102", "B83", "226");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B83");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B84).
*
*/
public void testA102_B84() {
test_id = getTestId("A102", "B84", "227");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B84");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B85).
*
*/
public void testA102_B85() {
test_id = getTestId("A102", "B85", "228");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B85");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B86).
*
*/
public void testA102_B86() {
test_id = getTestId("A102", "B86", "229");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B86");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B87).
*
*/
public void testA102_B87() {
test_id = getTestId("A102", "B87", "230");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B87");
A_B_Action(src, dest);
assertTrue("Paste was allowed but was not successful", checkResult_pasteSuccessful(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B88).
*
*/
public void testA102_B88() {
test_id = getTestId("A102", "B88", "231");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B88");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B89).
*
*/
public void testA102_B89() {
test_id = getTestId("A102", "B89", "232");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B89");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B90).
*
*/
public void testA102_B90() {
test_id = getTestId("A102", "B90", "233");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B90");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B91).
*
*/
public void testA102_B91() {
test_id = getTestId("A102", "B91", "234");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B91");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B92).
*
*/
public void testA102_B92() {
test_id = getTestId("A102", "B92", "235");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B92");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A102) and row (B93).
*
*/
public void testA102_B93() {
test_id = getTestId("A102", "B93", "236");
NonRootModelElement src = selectA("A102");
NonRootModelElement dest = selectB("B93");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A103) and row (B1).
*
*/
public void testA103_B1() {
test_id = getTestId("A103", "B1", "237");
NonRootModelElement src = selectA("A103");
NonRootModelElement dest = selectB("B1");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A103) and row (B2).
*
*/
public void testA103_B2() {
test_id = getTestId("A103", "B2", "238");
NonRootModelElement src = selectA("A103");
NonRootModelElement dest = selectB("B2");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A103) and row (B3).
*
*/
public void testA103_B3() {
test_id = getTestId("A103", "B3", "239");
NonRootModelElement src = selectA("A103");
NonRootModelElement dest = selectB("B3");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A103) and row (B4).
*
*/
public void testA103_B4() {
test_id = getTestId("A103", "B4", "240");
NonRootModelElement src = selectA("A103");
NonRootModelElement dest = selectB("B4");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A103) and row (B5).
*
*/
public void testA103_B5() {
test_id = getTestId("A103", "B5", "241");
NonRootModelElement src = selectA("A103");
NonRootModelElement dest = selectB("B5");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A103) and row (B6).
*
*/
public void testA103_B6() {
test_id = getTestId("A103", "B6", "242");
NonRootModelElement src = selectA("A103");
NonRootModelElement dest = selectB("B6");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A103) and row (B7).
*
*/
public void testA103_B7() {
test_id = getTestId("A103", "B7", "243");
NonRootModelElement src = selectA("A103");
NonRootModelElement dest = selectB("B7");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A103) and row (B8).
*
*/
public void testA103_B8() {
test_id = getTestId("A103", "B8", "244");
NonRootModelElement src = selectA("A103");
NonRootModelElement dest = selectB("B8");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A103) and row (B9).
*
*/
public void testA103_B9() {
test_id = getTestId("A103", "B9", "245");
NonRootModelElement src = selectA("A103");
NonRootModelElement dest = selectB("B9");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A103) and row (B10).
*
*/
public void testA103_B10() {
test_id = getTestId("A103", "B10", "246");
NonRootModelElement src = selectA("A103");
NonRootModelElement dest = selectB("B10");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A103) and row (B11).
*
*/
public void testA103_B11() {
test_id = getTestId("A103", "B11", "247");
NonRootModelElement src = selectA("A103");
NonRootModelElement dest = selectB("B11");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A103) and row (B12).
*
*/
public void testA103_B12() {
test_id = getTestId("A103", "B12", "248");
NonRootModelElement src = selectA("A103");
NonRootModelElement dest = selectB("B12");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A103) and row (B13).
*
*/
public void testA103_B13() {
test_id = getTestId("A103", "B13", "249");
NonRootModelElement src = selectA("A103");
NonRootModelElement dest = selectB("B13");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (A103) and row (B14).
*
*/
public void testA103_B14() {
test_id = getTestId("A103", "B14", "250");
NonRootModelElement src = selectA("A103");
NonRootModelElement dest = selectB("B14");
A_B_Action(src, dest);
assertTrue("Paste menu item was available even though destination was invalid", checkResult_pasteNotAllowed(src,dest));
GraphicalEditor editor = getActiveEditor();
if(editor != null && useDrawResults) {
validateOrGenerateResults(editor, generateResults);
}
}
}
|
/*
* Copyright 2012-2016, the original author or authors.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.flipkart.flux.dao;
import com.flipkart.flux.client.FluxClientInterceptorModule;
import com.flipkart.flux.dao.iface.AuditDAO;
import com.flipkart.flux.domain.AuditRecord;
import com.flipkart.flux.domain.State;
import com.flipkart.flux.domain.StateMachine;
import com.flipkart.flux.domain.Status;
import com.flipkart.flux.guice.module.AkkaModule;
import com.flipkart.flux.guice.module.ContainerModule;
import com.flipkart.flux.guice.module.DeploymentUnitModule;
import com.flipkart.flux.guice.module.HibernateModule;
import com.flipkart.flux.impl.boot.TaskModule;
import com.flipkart.flux.module.DeploymentUnitTestModule;
import com.flipkart.flux.module.RuntimeTestModule;
import com.flipkart.flux.rule.DbClearWithTestSMRule;
import com.flipkart.flux.runner.GuiceJunit4Runner;
import com.flipkart.flux.runner.Modules;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import static org.assertj.core.api.Assertions.assertThat;
/**
* <code>AuditDAOTest</code> class tests the functionality of {@link AuditDAO} using JUnit tests.
* @author shyam.akirala
* @author kartik.bommepally
*/
@RunWith(GuiceJunit4Runner.class)
@Modules({DeploymentUnitTestModule.class,HibernateModule.class,RuntimeTestModule.class,ContainerModule.class,AkkaModule.class,TaskModule.class,FluxClientInterceptorModule.class})
public class AuditDAOTest {
@Inject
AuditDAO auditDAO;
@Inject
@Rule
public DbClearWithTestSMRule dbClearWithTestSMRule;
@Before
public void setup() {}
@Test
public void createAuditRecordTest() {
StateMachine stateMachine = dbClearWithTestSMRule.getStateMachine();
State state = null;
for(Object ob : stateMachine.getStates()) {
state = (State) ob;
break;
}
AuditRecord auditRecord = new AuditRecord(stateMachine.getId(), (state!=null) ? state.getId() : null, 0L, Status.completed, null, null);
Long recordId = auditDAO.create(auditRecord).getId();
AuditRecord auditRecord1 = auditDAO.findById(recordId);
assertThat(auditRecord1).isEqualTo(auditRecord);
}
}
|
/*
* 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.calcite.schema;
import org.apache.calcite.adapter.enumerable.AggImplementor;
/**
* Function that can be translated to java code.
*
* @see org.apache.calcite.adapter.enumerable.AggImplementor
* @see org.apache.calcite.adapter.enumerable.WinAggImplementor
* @see org.apache.calcite.adapter.enumerable.StrictAggImplementor
* @see org.apache.calcite.adapter.enumerable.StrictWinAggImplementor
*/
public interface ImplementableAggFunction extends AggregateFunction {
/**
* Returns implementor that translates the function to linq4j expression.
*
* @param windowContext true when aggregate is used in window context
* @return implementor that translates the function to linq4j expression.
*/
AggImplementor getImplementor(boolean windowContext);
}
|
package cn.miozus.gulimall.ware.service;
import cn.miozus.gulimall.common.utils.PageUtils;
import cn.miozus.gulimall.ware.entity.PurchaseEntity;
import cn.miozus.gulimall.ware.vo.MergeVo;
import cn.miozus.gulimall.ware.vo.PurchaseDoneVo;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
import java.util.Map;
/**
* 采购信息
*
* @author SuDongpo
* @email miozus@outlook.com
* @date 2021-08-09 14:20:54
*/
public interface PurchaseService extends IService<PurchaseEntity> {
PageUtils queryPage(Map<String, Object> params);
PageUtils queryUnreceiveListPage(Map<String, Object> params);
void mergePurchase(MergeVo mergeVo);
void receivePurchase(List<Long> ids);
void done(PurchaseDoneVo doneVo);
}
|
/*
* Copyright 2011-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.stepfunctions.model;
import java.io.Serializable;
/**
*
*/
public class StartExecutionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The Amazon Resource Name (ARN) that identifies the execution.
* </p>
*/
private String executionArn;
/**
* <p>
* The date the execution was started.
* </p>
*/
private java.util.Date startDate;
/**
* <p>
* The Amazon Resource Name (ARN) that identifies the execution.
* </p>
*
* @param executionArn
* The Amazon Resource Name (ARN) that identifies the execution.
*/
public void setExecutionArn(String executionArn) {
this.executionArn = executionArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) that identifies the execution.
* </p>
*
* @return The Amazon Resource Name (ARN) that identifies the execution.
*/
public String getExecutionArn() {
return this.executionArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) that identifies the execution.
* </p>
*
* @param executionArn
* The Amazon Resource Name (ARN) that identifies the execution.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartExecutionResult withExecutionArn(String executionArn) {
setExecutionArn(executionArn);
return this;
}
/**
* <p>
* The date the execution was started.
* </p>
*
* @param startDate
* The date the execution was started.
*/
public void setStartDate(java.util.Date startDate) {
this.startDate = startDate;
}
/**
* <p>
* The date the execution was started.
* </p>
*
* @return The date the execution was started.
*/
public java.util.Date getStartDate() {
return this.startDate;
}
/**
* <p>
* The date the execution was started.
* </p>
*
* @param startDate
* The date the execution was started.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartExecutionResult withStartDate(java.util.Date startDate) {
setStartDate(startDate);
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 (getExecutionArn() != null)
sb.append("ExecutionArn: " + getExecutionArn() + ",");
if (getStartDate() != null)
sb.append("StartDate: " + getStartDate());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof StartExecutionResult == false)
return false;
StartExecutionResult other = (StartExecutionResult) obj;
if (other.getExecutionArn() == null ^ this.getExecutionArn() == null)
return false;
if (other.getExecutionArn() != null && other.getExecutionArn().equals(this.getExecutionArn()) == false)
return false;
if (other.getStartDate() == null ^ this.getStartDate() == null)
return false;
if (other.getStartDate() != null && other.getStartDate().equals(this.getStartDate()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getExecutionArn() == null) ? 0 : getExecutionArn().hashCode());
hashCode = prime * hashCode + ((getStartDate() == null) ? 0 : getStartDate().hashCode());
return hashCode;
}
@Override
public StartExecutionResult clone() {
try {
return (StartExecutionResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
package com.solvd.carina.gui.android.component;
import com.solvd.carina.gui.common.component.base.BaseFooter;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebDriver;
public class AndroidFooter extends BaseFooter {
public AndroidFooter(WebDriver driver, SearchContext searchContext) {
super(driver, searchContext);
}
}
|
/*
* The MIT License
*
* Copyright 2019 Steven Gordon <s.d.gordon@cqu.edu.au>.
*
* 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 multiframeapp;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
/**
*
* @author Steven Gordon <s.d.gordon@cqu.edu.au>
*/
public class WelcomeFrame extends JFrame {
private JButton btnEdit;
private JButton btnDisplay;
private JButton btnExit;
private JPanel pnlButtons;
/* List of people */
private ArrayList<Person> people;
public WelcomeFrame() {
/* Initialise people */
people = new ArrayList<Person>();
/* Set the graphic layout of components on frame */
this.setLayout(new FlowLayout());
/* Construct panel for buttons and set layout */
pnlButtons = new JPanel();
this.setLayout(new FlowLayout());
/* Construct buttons */
btnEdit = new JButton("Edit");
btnDisplay = new JButton("Display");
btnExit = new JButton("Exit");
/* Associate actions with buttons */
btnEdit.addActionListener(new EditButtonAction());
btnDisplay.addActionListener(new DisplayButtonAction());
btnExit.addActionListener(new ExitButtonAction());
/* Add buttons to panel, and panel to frame */
pnlButtons.add(btnEdit);
pnlButtons.add(btnDisplay);
pnlButtons.add(btnExit);
this.add(pnlButtons);
}
/* Action performed when Edit button pressed */
private class EditButtonAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
/* Dispose of current frame */
for (Frame f : Frame.getFrames()) {
if (f.getTitle().equals("Welcome Frame")) {
f.dispose();
}
}
/* Create a new Edit Frame */
EditFrame frame = new EditFrame(people);
frame.setTitle("Edit Frame");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(600, 300);
frame.setVisible(true);
}
}
/* Action performed when Display button pressed */
private class DisplayButtonAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
/* Dispose of current frame */
for (Frame f : Frame.getFrames()) {
if (f.getTitle().equals("Welcome Frame")) {
f.dispose();
}
}
/* Create a new Display Frame */
DisplayFrame frame = new DisplayFrame(people);
frame.setTitle("Display Frame");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(600, 300);
frame.setVisible(true);
}
}
/* Action performed when Exit button pressed */
private class ExitButtonAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
/* Exit */
System.exit(0);
}
}
}
|
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
@test
@bug 6334074 8022536
@summary test supported text flavors reported properly
@run main TextFlavorTest
*/
import javax.print.*;
import javax.print.attribute.standard.*;
import javax.print.attribute.*;
import java.io.*;
public class TextFlavorTest {
public static void main(String[] args) throws Exception {
PrintService service[] =
PrintServiceLookup.lookupPrintServices(null, null);
if (service.length == 0) {
System.out.println("No print service found.");
return;
}
for (int y = 0; y < service.length; y ++) {
DocFlavor flavors[] = service[y].getSupportedDocFlavors();
if (flavors == null) continue;
for (int x = 0; x < flavors.length; x ++) {
if (!service[y].isDocFlavorSupported(flavors[x])) {
String msg = "DocFlavor " + flavors[x] +
" is not supported by service "+ service[y];
throw new RuntimeException(msg);
}
}
}
System.out.println("Test passed.");
}
}
|
/*
* Copyright 2016, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.architecture.blueprints.todoapp.taskdetail;
import com.example.android.architecture.blueprints.todoapp.TestUseCaseScheduler;
import com.example.android.architecture.blueprints.todoapp.UseCaseHandler;
import com.example.android.architecture.blueprints.todoapp.addedittask.domain.usecase.DeleteTask;
import com.example.android.architecture.blueprints.todoapp.addedittask.domain.usecase.GetTask;
import com.example.android.architecture.blueprints.todoapp.data.source.TasksDataSource;
import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository;
import com.example.android.architecture.blueprints.todoapp.tasks.domain.model.Task;
import com.example.android.architecture.blueprints.todoapp.tasks.domain.usecase.ActivateTask;
import com.example.android.architecture.blueprints.todoapp.tasks.domain.usecase.CompleteTask;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Unit tests for the implementation of {@link TaskDetailPresenter}
*/
public class TaskDetailPresenterTest {
public static final String TITLE_TEST = "title";
public static final String DESCRIPTION_TEST = "description";
public static final String INVALID_TASK_ID = "";
public static final Task ACTIVE_TASK = new Task(TITLE_TEST, DESCRIPTION_TEST);
public static final Task COMPLETED_TASK = new Task(TITLE_TEST, DESCRIPTION_TEST, true);
@Mock
private TasksRepository mTasksRepository;
@Mock
private TaskDetailContract.View mTaskDetailView;
/**
* {@link ArgumentCaptor} is a powerful Mockito API to capture argument values and use them to
* perform further actions or assertions on them.
*/
@Captor
private ArgumentCaptor<TasksDataSource.GetTaskCallback> mGetTaskCallbackCaptor;
private TaskDetailPresenter mTaskDetailPresenter;
@Before
public void setup() {
// Mockito has a very convenient way to inject mocks by using the @Mock annotation. To
// inject the mocks in the test the initMocks method needs to be called.
MockitoAnnotations.initMocks(this);
// The presenter won't update the view unless it's active.
when(mTaskDetailView.isActive()).thenReturn(true);
}
@Test
public void getActiveTaskFromRepositoryAndLoadIntoView() {
// When tasks presenter is asked to open a task
mTaskDetailPresenter = givenTaskDetailPresenter(ACTIVE_TASK.getId());
mTaskDetailPresenter.start();
// Then task is loaded from model, callback is captured and progress indicator is shown
verify(mTasksRepository).getTask(eq(ACTIVE_TASK.getId()), mGetTaskCallbackCaptor.capture());
InOrder inOrder = inOrder(mTaskDetailView);
inOrder.verify(mTaskDetailView).setLoadingIndicator(true);
// When task is finally loaded
mGetTaskCallbackCaptor.getValue().onTaskLoaded(ACTIVE_TASK); // Trigger callback
// Then progress indicator is hidden and title, description and completion status are shown
// in UI
inOrder.verify(mTaskDetailView).setLoadingIndicator(false);
verify(mTaskDetailView).showTitle(TITLE_TEST);
verify(mTaskDetailView).showDescription(DESCRIPTION_TEST);
verify(mTaskDetailView).showCompletionStatus(false);
}
@Test
public void getCompletedTaskFromRepositoryAndLoadIntoView() {
mTaskDetailPresenter = givenTaskDetailPresenter(COMPLETED_TASK.getId());
mTaskDetailPresenter.start();
// Then task is loaded from model, callback is captured and progress indicator is shown
verify(mTasksRepository).getTask(
eq(COMPLETED_TASK.getId()), mGetTaskCallbackCaptor.capture());
InOrder inOrder = inOrder(mTaskDetailView);
inOrder.verify(mTaskDetailView).setLoadingIndicator(true);
// When task is finally loaded
mGetTaskCallbackCaptor.getValue().onTaskLoaded(COMPLETED_TASK); // Trigger callback
// Then progress indicator is hidden and title, description and completion status are shown
// in UI
inOrder.verify(mTaskDetailView).setLoadingIndicator(false);
verify(mTaskDetailView).showTitle(TITLE_TEST);
verify(mTaskDetailView).showDescription(DESCRIPTION_TEST);
verify(mTaskDetailView).showCompletionStatus(true);
}
@Test
public void getUnknownTaskFromRepositoryAndLoadIntoView() {
// When loading of a task is requested with an invalid task ID.
mTaskDetailPresenter = givenTaskDetailPresenter(INVALID_TASK_ID);
mTaskDetailPresenter.start();
verify(mTaskDetailView).showMissingTask();
}
@Test
public void deleteTask() {
// Given an initialized TaskDetailPresenter with stubbed task
Task task = new Task(TITLE_TEST, DESCRIPTION_TEST);
// When the deletion of a task is requested
mTaskDetailPresenter = givenTaskDetailPresenter(task.getId());
mTaskDetailPresenter.deleteTask();
// Then the repository and the view are notified
verify(mTasksRepository).deleteTask(task.getId());
verify(mTaskDetailView).showTaskDeleted();
}
@Test
public void completeTask() {
// Given an initialized presenter with an active task
Task task = new Task(TITLE_TEST, DESCRIPTION_TEST);
mTaskDetailPresenter = givenTaskDetailPresenter(task.getId());
mTaskDetailPresenter.start();
// When the presenter is asked to complete the task
mTaskDetailPresenter.completeTask();
// Then a request is sent to the task repository and the UI is updated
verify(mTasksRepository).completeTask(task.getId());
verify(mTaskDetailView).showTaskMarkedComplete();
}
@Test
public void activateTask() {
// Given an initialized presenter with a completed task
Task task = new Task(TITLE_TEST, DESCRIPTION_TEST, true);
mTaskDetailPresenter = givenTaskDetailPresenter(task.getId());
mTaskDetailPresenter.start();
// When the presenter is asked to activate the task
mTaskDetailPresenter.activateTask();
// Then a request is sent to the task repository and the UI is updated
verify(mTasksRepository).activateTask(task.getId());
verify(mTaskDetailView).showTaskMarkedActive();
}
@Test
public void activeTaskIsShownWhenEditing() {
// When the edit of an ACTIVE_TASK is requested
mTaskDetailPresenter = givenTaskDetailPresenter(ACTIVE_TASK.getId());
mTaskDetailPresenter.editTask();
// Then the view is notified
verify(mTaskDetailView).showEditTask(ACTIVE_TASK.getId());
}
@Test
public void invalidTaskIsNotShownWhenEditing() {
// When the edit of an invalid task id is requested
mTaskDetailPresenter = givenTaskDetailPresenter(INVALID_TASK_ID);
mTaskDetailPresenter.editTask();
// Then the edit mode is never started
verify(mTaskDetailView, never()).showEditTask(INVALID_TASK_ID);
// instead, the error is shown.
verify(mTaskDetailView).showMissingTask();
}
private TaskDetailPresenter givenTaskDetailPresenter(String id) {
UseCaseHandler useCaseHandler = new UseCaseHandler(new TestUseCaseScheduler());
GetTask getTask = new GetTask(mTasksRepository);
CompleteTask completeTask = new CompleteTask(mTasksRepository);
ActivateTask activateTask = new ActivateTask(mTasksRepository);
DeleteTask deleteTask = new DeleteTask(mTasksRepository);
return new TaskDetailPresenter(useCaseHandler, id, mTaskDetailView,
getTask, completeTask, activateTask, deleteTask);
}
}
|
/*
* This file was automatically generated by EvoSuite
* Fri Nov 06 22:44:36 GMT 2020
*/
package accessories.plugins.time;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import accessories.plugins.time.JDayChooser;
import accessories.plugins.time.JMonthChooser;
import accessories.plugins.time.JYearChooser;
import java.awt.Color;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.util.Date;
import java.util.Locale;
import javax.swing.DebugGraphics;
import javax.swing.JButton;
import javax.swing.text.DefaultCaret;
import org.apache.batik.gvt.text.GVTAttributedCharacterIterator;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.evosuite.runtime.mock.java.util.MockDate;
import org.evosuite.runtime.mock.java.util.MockGregorianCalendar;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class JDayChooser_ESTest extends JDayChooser_ESTest_scaffolding {
/**
//Test case number: 0
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test00() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.setMonth((-1882));
assertFalse(jDayChooser0.isWeekOfYearVisible());
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertTrue(jDayChooser0.isDayBordersVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 1
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test01() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.drawDays();
assertEquals(14, jDayChooser0.getDay());
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
}
/**
//Test case number: 2
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test02() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser(false);
JDayChooser.DecoratorButton jDayChooser_DecoratorButton0 = jDayChooser0.new DecoratorButton();
jDayChooser_DecoratorButton0.isFocusable();
assertEquals(14, jDayChooser0.getDay());
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
}
/**
//Test case number: 3
/*Coverage entropy=2.5604230937343346
*/
@Test(timeout = 4000)
public void test03() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser(true);
JDayChooser.DecoratorButton jDayChooser_DecoratorButton0 = jDayChooser0.new DecoratorButton();
DefaultCaret defaultCaret0 = new DefaultCaret();
jDayChooser_DecoratorButton0.addMouseListener(defaultCaret0);
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertTrue(jDayChooser0.isDayBordersVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 4
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test04() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.initDecorations();
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertTrue(jDayChooser0.isDayBordersVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 5
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test05() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.init();
assertFalse(jDayChooser0.isWeekOfYearVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 6
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test06() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.drawWeeks();
assertTrue(jDayChooser0.isDayBordersVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 7
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test07() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser(true);
jDayChooser0.isWeekOfYearVisible();
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 8
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test08() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser(false);
jDayChooser0.setDayBordersVisible(false);
jDayChooser0.isDayBordersVisible();
assertFalse(jDayChooser0.isWeekOfYearVisible());
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 9
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test09() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser(true);
SystemColor systemColor0 = SystemColor.windowBorder;
jDayChooser0.setSundayForeground(systemColor0);
jDayChooser0.getSundayForeground();
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 10
/*Coverage entropy=2.7039446318508733
*/
@Test(timeout = 4000)
public void test10() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.setDecorationBackgroundColor((Color) null);
jDayChooser0.getDecorationBackgroundColor();
assertEquals(14, jDayChooser0.getDay());
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertFalse(jDayChooser0.isWeekOfYearVisible());
}
/**
//Test case number: 11
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test11() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser(false);
jDayChooser0.dayPanel = null;
jDayChooser0.getDayPanel();
assertFalse(jDayChooser0.isWeekOfYearVisible());
assertEquals(14, jDayChooser0.getDay());
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertTrue(jDayChooser0.isDayBordersVisible());
}
/**
//Test case number: 12
/*Coverage entropy=2.616230775360895
*/
@Test(timeout = 4000)
public void test12() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser(false);
jDayChooser0.defaultMinSelectableDate = null;
// Undeclared exception!
try {
jDayChooser0.setMinSelectableDate((Date) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
/**
//Test case number: 13
/*Coverage entropy=2.6527697871323417
*/
@Test(timeout = 4000)
public void test13() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
// Undeclared exception!
try {
jDayChooser0.setLocale((Locale) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
/**
//Test case number: 14
/*Coverage entropy=2.593621512459067
*/
@Test(timeout = 4000)
public void test14() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.days = null;
// Undeclared exception!
try {
jDayChooser0.setDay((-1518));
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("accessories.plugins.time.JDayChooser", e);
}
}
/**
//Test case number: 15
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test15() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
JButton[] jButtonArray0 = new JButton[2];
JButton jButton0 = new JButton();
jButtonArray0[1] = jButton0;
jDayChooser0.weeks = jButtonArray0;
// Undeclared exception!
try {
jDayChooser0.drawDays();
fail("Expecting exception: ArrayIndexOutOfBoundsException");
} catch(ArrayIndexOutOfBoundsException e) {
//
// 2
//
verifyException("accessories.plugins.time.JDayChooser", e);
}
}
/**
//Test case number: 16
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test16() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
// Undeclared exception!
try {
jDayChooser0.addListeners(298);
fail("Expecting exception: ArrayIndexOutOfBoundsException");
} catch(ArrayIndexOutOfBoundsException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
/**
//Test case number: 17
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test17() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
JDayChooser.DecoratorButton jDayChooser_DecoratorButton0 = jDayChooser0.new DecoratorButton();
ActionEvent actionEvent0 = new ActionEvent(jDayChooser_DecoratorButton0, 22, "day", 210);
// Undeclared exception!
try {
jDayChooser0.actionPerformed(actionEvent0);
fail("Expecting exception: NumberFormatException");
} catch(NumberFormatException e) {
//
// For input string: \"\"
//
verifyException("java.lang.NumberFormatException", e);
}
}
/**
//Test case number: 18
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test18() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
ActionEvent actionEvent0 = new ActionEvent("day", 251, "day", 251);
// Undeclared exception!
try {
jDayChooser0.actionPerformed(actionEvent0);
fail("Expecting exception: ClassCastException");
} catch(ClassCastException e) {
//
// java.lang.String cannot be cast to javax.swing.JButton
//
verifyException("accessories.plugins.time.JDayChooser", e);
}
}
/**
//Test case number: 19
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test19() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.updateUI();
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 20
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test20() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.setFocus();
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 21
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test21() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
Color color0 = Color.blue;
jDayChooser0.setForeground(color0);
assertEquals(14, jDayChooser0.getDay());
assertFalse(jDayChooser0.isWeekOfYearVisible());
}
/**
//Test case number: 22
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test22() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.weeks = null;
Font font0 = Font.decode("day");
jDayChooser0.setFont(font0);
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 23
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test23() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.setFont((Font) null);
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 24
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test24() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
jDayChooser0.setDecorationBackgroundVisible(true);
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 25
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test25() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.setDecorationBordersVisible(false);
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 26
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test26() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.addListeners(15);
assertTrue(jDayChooser0.isDayBordersVisible());
assertEquals(14, jDayChooser0.getDay());
assertFalse(jDayChooser0.isWeekOfYearVisible());
}
/**
//Test case number: 27
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test27() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.getDaysInMonth();
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
assertEquals(14, jDayChooser0.getDay());
assertTrue(jDayChooser0.isDayBordersVisible());
}
/**
//Test case number: 28
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test28() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
JDayChooser.DecoratorButton jDayChooser_DecoratorButton0 = jDayChooser0.new DecoratorButton();
DebugGraphics debugGraphics0 = new DebugGraphics();
jDayChooser_DecoratorButton0.paint(debugGraphics0);
assertFalse(jDayChooser0.isWeekOfYearVisible());
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertTrue(jDayChooser0.isDayBordersVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 29
/*Coverage entropy=2.662701752014223
*/
@Test(timeout = 4000)
public void test29() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.setMaxDayCharacters(762);
assertTrue(jDayChooser0.isDayBordersVisible());
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertEquals(0, jDayChooser0.getMaxDayCharacters());
assertFalse(jDayChooser0.isWeekOfYearVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 30
/*Coverage entropy=2.6527697871323417
*/
@Test(timeout = 4000)
public void test30() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.setMaxDayCharacters((-820));
assertEquals(14, jDayChooser0.getDay());
assertFalse(jDayChooser0.isWeekOfYearVisible());
assertEquals(0, jDayChooser0.getMaxDayCharacters());
}
/**
//Test case number: 31
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test31() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.setMaxDayCharacters(0);
assertTrue(jDayChooser0.isDayBordersVisible());
assertEquals(14, jDayChooser0.getDay());
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
}
/**
//Test case number: 32
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test32() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.setMinSelectableDate((Date) null);
assertFalse(jDayChooser0.isWeekOfYearVisible());
assertEquals(14, jDayChooser0.getDay());
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
}
/**
//Test case number: 33
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test33() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
MockDate mockDate0 = new MockDate();
jDayChooser0.setMinSelectableDate(mockDate0);
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 34
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test34() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.setMaxSelectableDate((Date) null);
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 35
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test35() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
java.sql.Date date0 = new java.sql.Date(1000L);
jDayChooser0.setMaxSelectableDate(date0);
assertEquals(14, jDayChooser0.getDay());
assertTrue(jDayChooser0.isDayBordersVisible());
}
/**
//Test case number: 36
/*Coverage entropy=2.662701752014223
*/
@Test(timeout = 4000)
public void test36() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
MockDate mockDate0 = new MockDate(8806, 8806, 8806, 8806, 8806);
jDayChooser0.setSelectableDateRange(mockDate0, (Date) null);
assertEquals(14, jDayChooser0.getDay());
assertFalse(jDayChooser0.isDecorationBordersVisible());
}
/**
//Test case number: 37
/*Coverage entropy=2.6266116706270752
*/
@Test(timeout = 4000)
public void test37() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser(true);
jDayChooser0.setSelectableDateRange((Date) null, (Date) null);
assertTrue(jDayChooser0.isDayBordersVisible());
assertEquals(14, jDayChooser0.getDay());
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
}
/**
//Test case number: 38
/*Coverage entropy=2.616230775360895
*/
@Test(timeout = 4000)
public void test38() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser(true);
jDayChooser0.setWeekOfYearVisible(false);
assertEquals(14, jDayChooser0.getDay());
assertFalse(jDayChooser0.isDecorationBordersVisible());
}
/**
//Test case number: 39
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test39() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.setWeekOfYearVisible(false);
assertTrue(jDayChooser0.isDayBordersVisible());
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 40
/*Coverage entropy=2.6527697871323417
*/
@Test(timeout = 4000)
public void test40() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
assertFalse(jDayChooser0.isWeekOfYearVisible());
jDayChooser0.setWeekOfYearVisible(true);
assertTrue(jDayChooser0.isDayBordersVisible());
}
/**
//Test case number: 41
/*Coverage entropy=2.669576756952125
*/
@Test(timeout = 4000)
public void test41() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.setEnabled(false);
assertTrue(jDayChooser0.isDayBordersVisible());
assertEquals(14, jDayChooser0.getDay());
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertFalse(jDayChooser0.isWeekOfYearVisible());
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
}
/**
//Test case number: 42
/*Coverage entropy=2.7100799133333875
*/
@Test(timeout = 4000)
public void test42() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
GVTAttributedCharacterIterator.TextAttribute gVTAttributedCharacterIterator_TextAttribute0 = GVTAttributedCharacterIterator.TextAttribute.ARABIC_FORM;
KeyEvent keyEvent0 = new KeyEvent(jDayChooser0, (int) gVTAttributedCharacterIterator_TextAttribute0.ADJUST_ALL, (long) gVTAttributedCharacterIterator_TextAttribute0.ARABIC_INITIAL, (int) gVTAttributedCharacterIterator_TextAttribute0.WRITING_MODE_RTL, (int) gVTAttributedCharacterIterator_TextAttribute0.WRITING_MODE_TTB, 'R');
jDayChooser0.keyPressed(keyEvent0);
assertTrue(jDayChooser0.isDayBordersVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 43
/*Coverage entropy=2.7100799133333875
*/
@Test(timeout = 4000)
public void test43() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
KeyEvent keyEvent0 = new KeyEvent(jDayChooser0, 40, 40, (-811), 40, ':');
jDayChooser0.keyPressed(keyEvent0);
assertEquals(21, jDayChooser0.getDay());
}
/**
//Test case number: 44
/*Coverage entropy=2.7100799133333875
*/
@Test(timeout = 4000)
public void test44() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
KeyEvent keyEvent0 = new KeyEvent(jDayChooser0, 2071, 2071, (-644), 38, 'r');
jDayChooser0.keyPressed(keyEvent0);
assertEquals(7, jDayChooser0.getDay());
}
/**
//Test case number: 45
/*Coverage entropy=2.7100799133333875
*/
@Test(timeout = 4000)
public void test45() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
KeyEvent keyEvent0 = new KeyEvent(jDayChooser0, (-986), (-986), (-986), 37, 'g');
jDayChooser0.keyPressed(keyEvent0);
assertEquals(13, jDayChooser0.getDay());
}
/**
//Test case number: 46
/*Coverage entropy=2.7100799133333875
*/
@Test(timeout = 4000)
public void test46() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
KeyEvent keyEvent0 = new KeyEvent(jDayChooser0, 36, 36, (-811), 36, '<');
jDayChooser0.keyPressed(keyEvent0);
assertEquals(1, jDayChooser0.getDay());
}
/**
//Test case number: 47
/*Coverage entropy=2.749972735605312
*/
@Test(timeout = 4000)
public void test47() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
KeyEvent keyEvent0 = new KeyEvent(jDayChooser0, 5, 5, '<', 34, '<');
// Undeclared exception!
try {
jDayChooser0.keyPressed(keyEvent0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("accessories.plugins.time.JDayChooser", e);
}
}
/**
//Test case number: 48
/*Coverage entropy=2.7100799133333875
*/
@Test(timeout = 4000)
public void test48() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
KeyEvent keyEvent0 = new KeyEvent(jDayChooser0, 35, 35, 35, 35, 'R');
assertEquals(14, jDayChooser0.getDay());
jDayChooser0.keyPressed(keyEvent0);
assertEquals(28, jDayChooser0.getDay());
}
/**
//Test case number: 49
/*Coverage entropy=2.749972735605312
*/
@Test(timeout = 4000)
public void test49() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
KeyEvent keyEvent0 = new KeyEvent(jDayChooser0, 33, 33, (-867), 33, '<');
// Undeclared exception!
try {
jDayChooser0.keyPressed(keyEvent0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("accessories.plugins.time.JDayChooser", e);
}
}
/**
//Test case number: 50
/*Coverage entropy=2.630470240160676
*/
@Test(timeout = 4000)
public void test50() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.setDay(105);
jDayChooser0.setMonth(105);
assertEquals(31, jDayChooser0.getDay());
}
/**
//Test case number: 51
/*Coverage entropy=2.630470240160676
*/
@Test(timeout = 4000)
public void test51() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.day = 3784;
jDayChooser0.setMonth((-1845));
assertEquals(30, jDayChooser0.getDay());
}
/**
//Test case number: 52
/*Coverage entropy=2.668445301176189
*/
@Test(timeout = 4000)
public void test52() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
Locale locale0 = Locale.ITALIAN;
jDayChooser0.setLocale(locale0);
jDayChooser0.setYear(0);
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertTrue(jDayChooser0.isDayBordersVisible());
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 53
/*Coverage entropy=2.608820614830946
*/
@Test(timeout = 4000)
public void test53() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser(true);
jDayChooser0.setMaxDayCharacters(4);
assertEquals(4, jDayChooser0.getMaxDayCharacters());
}
/**
//Test case number: 54
/*Coverage entropy=2.6789477095792162
*/
@Test(timeout = 4000)
public void test54() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.setMaxDayCharacters(2);
Locale locale0 = Locale.GERMANY;
jDayChooser0.setLocale(locale0);
assertEquals(2, jDayChooser0.getMaxDayCharacters());
}
/**
//Test case number: 55
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test55() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser(true);
jDayChooser0.keyTyped((KeyEvent) null);
assertEquals(14, jDayChooser0.getDay());
assertTrue(jDayChooser0.isDayBordersVisible());
}
/**
//Test case number: 56
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test56() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser(true);
MockGregorianCalendar mockGregorianCalendar0 = new MockGregorianCalendar();
jDayChooser0.setCalendar(mockGregorianCalendar0);
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 57
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test57() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
int int0 = jDayChooser0.getDay();
assertEquals(14, int0);
assertFalse(jDayChooser0.isDecorationBordersVisible());
}
/**
//Test case number: 58
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test58() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser(false);
FocusEvent focusEvent0 = new FocusEvent(jDayChooser0, 171, false, jDayChooser0);
jDayChooser0.focusGained(focusEvent0);
assertEquals(14, jDayChooser0.getDay());
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
assertFalse(jDayChooser0.isDecorationBordersVisible());
}
/**
//Test case number: 59
/*Coverage entropy=2.698009616895563
*/
@Test(timeout = 4000)
public void test59() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
Date date0 = jDayChooser0.getMinSelectableDate();
jDayChooser0.setSelectableDateRange(date0, date0);
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertEquals(14, jDayChooser0.getDay());
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
assertTrue(jDayChooser0.isDayBordersVisible());
}
/**
//Test case number: 60
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test60() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
JMonthChooser jMonthChooser0 = new JMonthChooser(false);
jDayChooser0.setMonthChooser(jMonthChooser0);
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 61
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test61() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.getWeekdayForeground();
assertEquals(14, jDayChooser0.getDay());
assertFalse(jDayChooser0.isDecorationBordersVisible());
}
/**
//Test case number: 62
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test62() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.getDayPanel();
assertTrue(jDayChooser0.isDayBordersVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 63
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test63() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.getSelectedDay();
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 64
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test64() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser(true);
KeyEvent keyEvent0 = new KeyEvent(jDayChooser0, (-2678), 14L, 6, (-2678), 'V');
jDayChooser0.keyReleased(keyEvent0);
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 65
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test65() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
JYearChooser jYearChooser0 = new JYearChooser();
jDayChooser0.setYearChooser(jYearChooser0);
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 66
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test66() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser(false);
FocusEvent focusEvent0 = new FocusEvent(jDayChooser0, 0, true);
jDayChooser0.focusLost(focusEvent0);
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 67
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test67() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
Color color0 = jDayChooser0.getDecorationBackgroundColor();
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
assertEquals(14, jDayChooser0.getDay());
assertEquals(238, color0.getBlue());
}
/**
//Test case number: 68
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test68() throws Throwable {
// Undeclared exception!
try {
JDayChooser.main((String[]) null);
fail("Expecting exception: HeadlessException");
} catch(HeadlessException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("java.awt.GraphicsEnvironment", e);
}
}
/**
//Test case number: 69
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test69() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.getMaxDayCharacters();
assertEquals(14, jDayChooser0.getDay());
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
}
/**
//Test case number: 70
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test70() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.setWeekdayForeground((Color) null);
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 71
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test71() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.getLocale();
assertEquals(14, jDayChooser0.getDay());
assertTrue(jDayChooser0.isDayBordersVisible());
}
/**
//Test case number: 72
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test72() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
boolean boolean0 = jDayChooser0.isDecorationBordersVisible();
assertFalse(boolean0);
assertEquals(14, jDayChooser0.getDay());
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
}
/**
//Test case number: 73
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test73() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
// Undeclared exception!
try {
jDayChooser0.actionPerformed((ActionEvent) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("accessories.plugins.time.JDayChooser", e);
}
}
/**
//Test case number: 74
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test74() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.isDecorationBackgroundVisible();
assertTrue(jDayChooser0.isDayBordersVisible());
assertEquals(14, jDayChooser0.getDay());
assertFalse(jDayChooser0.isWeekOfYearVisible());
}
/**
//Test case number: 75
/*Coverage entropy=2.7376047233857554
*/
@Test(timeout = 4000)
public void test75() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
Color color0 = jDayChooser0.getSundayForeground();
jDayChooser0.setDecorationBackgroundColor(color0);
Color color1 = jDayChooser0.getDecorationBackgroundColor();
assertEquals(14, jDayChooser0.getDay());
assertTrue(jDayChooser0.isDayBordersVisible());
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertEquals(0, color1.getGreen());
}
/**
//Test case number: 76
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test76() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.getMaxSelectableDate();
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertFalse(jDayChooser0.isWeekOfYearVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 77
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test77() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.isDayBordersVisible();
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertEquals(14, jDayChooser0.getDay());
}
/**
//Test case number: 78
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test78() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
// Undeclared exception!
try {
jDayChooser0.getTemporaryCalendar();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("accessories.plugins.time.JDayChooser", e);
}
}
/**
//Test case number: 79
/*Coverage entropy=2.6354848637097823
*/
@Test(timeout = 4000)
public void test79() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser();
jDayChooser0.setAlwaysFireDayProperty(false);
assertEquals(14, jDayChooser0.getDay());
assertFalse(jDayChooser0.isDecorationBordersVisible());
}
/**
//Test case number: 80
/*Coverage entropy=2.5983833927870665
*/
@Test(timeout = 4000)
public void test80() throws Throwable {
JDayChooser jDayChooser0 = new JDayChooser(false);
jDayChooser0.isWeekOfYearVisible();
assertTrue(jDayChooser0.isDecorationBackgroundVisible());
assertFalse(jDayChooser0.isDecorationBordersVisible());
assertEquals(14, jDayChooser0.getDay());
}
}
|
// ============================================================================
//
// Copyright (C) 2006-2015 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.commons.ui.swt.advanced.dataeditor;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.widgets.Composite;
import org.talend.commons.ui.swt.advanced.dataeditor.button.AddAllPushButton;
import org.talend.commons.ui.swt.advanced.dataeditor.button.AddPushButton;
import org.talend.commons.ui.swt.advanced.dataeditor.button.CopyPushButton;
import org.talend.commons.ui.swt.advanced.dataeditor.button.CopyPushButtonForExtendedTable;
import org.talend.commons.ui.swt.advanced.dataeditor.button.ExportPushButton;
import org.talend.commons.ui.swt.advanced.dataeditor.button.ImportPushButton;
import org.talend.commons.ui.swt.advanced.dataeditor.button.MoveDownPushButton;
import org.talend.commons.ui.swt.advanced.dataeditor.button.MoveDownPushButtonForExtendedTable;
import org.talend.commons.ui.swt.advanced.dataeditor.button.MoveUpPushButton;
import org.talend.commons.ui.swt.advanced.dataeditor.button.MoveUpPushButtonForExtendedTable;
import org.talend.commons.ui.swt.advanced.dataeditor.button.PastePushButton;
import org.talend.commons.ui.swt.advanced.dataeditor.button.RemovePushButton;
import org.talend.commons.ui.swt.advanced.dataeditor.button.RemovePushButtonForExtendedTable;
import org.talend.commons.ui.swt.advanced.dataeditor.button.ResetDBTypesPushButton;
import org.talend.commons.ui.swt.advanced.dataeditor.button.SaveAsGenericSchemaPushButton;
import org.talend.commons.ui.swt.advanced.dataeditor.button.SelectContextVariablesPushButton;
import org.talend.commons.ui.swt.advanced.dataeditor.control.ExtendedPushButton;
import org.talend.commons.ui.swt.extended.table.AbstractExtendedTableViewer;
/**
* DOC cantoine class global comment. Detailled comment <br/>
*
* TGU same purpose as TargetSchemaToolbarEditorView2 but uses EMF model directly $Id:
* TargetSchemaToolbarEditorView2.java,v 1.1 2006/08/02 19:43:45 cantoine Exp $
*
*/
public class ExtendedToolbarView extends AbstractExtendedToolbar {
protected AddPushButton addButton;
protected AddAllPushButton addallButton;
protected RemovePushButton removeButton;
protected MoveUpPushButton moveUpButton;
protected MoveDownPushButton moveDownButton;
protected CopyPushButton copyButton;
protected PastePushButton pasteButton;
private ExportPushButton exportButton;
private ImportPushButton importButton;
protected SaveAsGenericSchemaPushButton saveAsGenericSchemaButton;
protected ResetDBTypesPushButton resetDBTypesButton;
protected SelectContextVariablesPushButton selectContextVariablesButton;
/**
* DOC amaumont MatadataToolbarEditor constructor comment.
*
* @param parent
* @param style
* @param targetSchemaEditorView
*/
public ExtendedToolbarView(Composite parent, int style, AbstractExtendedTableViewer extendedTableViewer) {
super(parent, style, extendedTableViewer);
// // Force the height of the toolbars
// GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
// gridData.minimumHeight = 40;
// gridData.heightHint = 40;
// toolbar.setLayoutData(gridData);
}
/**
* Override this method if needed to instanciate only the buttons of your choice.
*
*/
protected void createComponents(Composite parent) {
addButton = createAddPushButton();
removeButton = createRemovePushButton();
moveUpButton = createMoveUpPushButton();
moveDownButton = createMoveDownPushButton();
copyButton = createCopyPushButton();
pasteButton = createPastePushButton();
addallButton = createAddAllPushButton();
exportButton = createExportPushButton();
importButton = createImportPushButton();
saveAsGenericSchemaButton = createSaveAsGenericSchemaButton();
selectContextVariablesButton = createSelectContextVariablesPushButton();
// loadButton = new Button(toolbar, SWT.PUSH);
// loadButton.setToolTipText("Import");
// loadButton.setImage(ImageProvider.getImage(EImage.IMPORT_ICON));
//
// exportButton = new Button(toolbar, SWT.PUSH);
// exportButton.setToolTipText("Export");
// exportButton.setImage(ImageProvider.getImage(EImage.EXPORT_ICON));
}
/**
* DOC YeXiaowei Comment method "createAddAllPushButton".
*
* @return
*/
protected AddAllPushButton createAddAllPushButton() {
return null;
}
protected AddPushButton createAddPushButton() {
return null;
}
protected RemovePushButton createRemovePushButton() {
return new RemovePushButtonForExtendedTable(toolbar, extendedTableViewer);
}
protected MoveUpPushButton createMoveUpPushButton() {
return new MoveUpPushButtonForExtendedTable(toolbar, extendedTableViewer);
}
protected MoveDownPushButton createMoveDownPushButton() {
return new MoveDownPushButtonForExtendedTable(toolbar, extendedTableViewer);
}
protected CopyPushButton createCopyPushButton() {
return new CopyPushButtonForExtendedTable(toolbar, extendedTableViewer);
}
protected PastePushButton createPastePushButton() {
return null;
}
protected ExportPushButton createExportPushButton() {
return null;
}
protected ImportPushButton createImportPushButton() {
return null;
}
protected SaveAsGenericSchemaPushButton createSaveAsGenericSchemaButton() {
return null;
}
protected SelectContextVariablesPushButton createSelectContextVariablesPushButton() {
return null;
}
/**
* Getter for addButton.
*
* @return the addButton
*/
public AddPushButton getAddButton() {
return this.addButton;
}
/**
* Getter for copyButton.
*
* @return the copyButton
*/
public CopyPushButton getCopyButton() {
return this.copyButton;
}
/**
* Getter for moveDownButton.
*
* @return the moveDownButton
*/
public MoveDownPushButton getMoveDownButton() {
return this.moveDownButton;
}
/**
* Getter for moveUpButton.
*
* @return the moveUpButton
*/
public MoveUpPushButton getMoveUpButton() {
return this.moveUpButton;
}
/**
* Getter for pastButton.
*
* @return the pastButton
*/
public PastePushButton getPasteButton() {
return this.pasteButton;
}
/**
* Getter for removeButton.
*
* @return the removeButton
*/
public RemovePushButton getRemoveButton() {
return this.removeButton;
}
/**
* Getter for exportButton.
*
* @return the exportButton
*/
public ExportPushButton getExportButton() {
return this.exportButton;
}
/**
* Getter for importButton.
*
* @return the importButton
*/
public ImportPushButton getImportButton() {
return this.importButton;
}
/**
* Getter for resetDBTypesButton.
*
* @return the resetDBTypesButton
*/
public ResetDBTypesPushButton getResetDBTypesButton() {
return resetDBTypesButton;
}
public SelectContextVariablesPushButton getSelectContextVariablesButton() {
return selectContextVariablesButton;
}
/*
* (non-Javadoc)
*
* @see org.talend.commons.ui.swt.advanced.dataeditor.AbstractExtendedToolbar#updateEnabledStateOfButtons()
*/
@Override
public void updateEnabledStateOfButtons() {
List<ExtendedPushButton> buttons = getButtons();
for (ExtendedPushButton button : buttons) {
button.getButton().setEnabled(button.getEnabledState());
}
}
/*
* (non-Javadoc)
*
* @see org.talend.commons.ui.swt.advanced.dataeditor.AbstractExtendedToolbar#getButtons()
*/
@Override
public List<ExtendedPushButton> getButtons() {
ArrayList<ExtendedPushButton> list = new ArrayList<ExtendedPushButton>();
if (getAddButton() != null) {
list.add(getAddButton());
}
if (getRemoveButton() != null) {
list.add(getRemoveButton());
}
if (getMoveDownButton() != null) {
list.add(getMoveDownButton());
}
if (getMoveUpButton() != null) {
list.add(getMoveUpButton());
}
if (getCopyButton() != null) {
list.add(getCopyButton());
}
if (getPasteButton() != null) {
list.add(getPasteButton());
}
if (getExportButton() != null) {
list.add(getExportButton());
}
if (getImportButton() != null) {
list.add(getImportButton());
}
if (getResetDBTypesButton() != null) {
list.add(getResetDBTypesButton());
}
if (getSaveAsGenericSchemaButton() != null) {
list.add(getSaveAsGenericSchemaButton());
}
if (getSelectContextVariablesButton() != null) {
list.add(getSelectContextVariablesButton());
}
if (getAddallButton() != null) {
list.add(getAddallButton());
}
return list;
}
/**
* Getter for saveAsGenericSchemaButton.
*
* @return the saveAsGenericSchemaButton
*/
public SaveAsGenericSchemaPushButton getSaveAsGenericSchemaButton() {
return saveAsGenericSchemaButton;
}
/**
* Getter for addallButton.
*
* @return the addallButton
*/
public AddAllPushButton getAddallButton() {
return this.addallButton;
}
}
//
|
package net.minecraft.util.datafix.versions;
import com.mojang.datafixers.DSL;
import com.mojang.datafixers.schemas.Schema;
import com.mojang.datafixers.types.templates.TypeTemplate;
import java.util.Map;
import java.util.function.Supplier;
import net.minecraft.util.datafix.NamespacedSchema;
import net.minecraft.util.datafix.TypeReferences;
public class V1125 extends NamespacedSchema
{
public V1125(int versionKey, Schema parent)
{
super(versionKey, parent);
}
public Map<String, Supplier<TypeTemplate>> registerBlockEntities(Schema p_registerBlockEntities_1_)
{
Map<String, Supplier<TypeTemplate>> map = super.registerBlockEntities(p_registerBlockEntities_1_);
p_registerBlockEntities_1_.registerSimple(map, "minecraft:bed");
return map;
}
public void registerTypes(Schema p_registerTypes_1_, Map<String, Supplier<TypeTemplate>> p_registerTypes_2_, Map<String, Supplier<TypeTemplate>> p_registerTypes_3_)
{
super.registerTypes(p_registerTypes_1_, p_registerTypes_2_, p_registerTypes_3_);
p_registerTypes_1_.registerType(false, TypeReferences.ADVANCEMENTS, () ->
{
return DSL.optionalFields("minecraft:adventure/adventuring_time", DSL.optionalFields("criteria", DSL.compoundList(TypeReferences.BIOME.in(p_registerTypes_1_), DSL.constType(DSL.string()))), "minecraft:adventure/kill_a_mob", DSL.optionalFields("criteria", DSL.compoundList(TypeReferences.ENTITY_NAME.in(p_registerTypes_1_), DSL.constType(DSL.string()))), "minecraft:adventure/kill_all_mobs", DSL.optionalFields("criteria", DSL.compoundList(TypeReferences.ENTITY_NAME.in(p_registerTypes_1_), DSL.constType(DSL.string()))), "minecraft:husbandry/bred_all_animals", DSL.optionalFields("criteria", DSL.compoundList(TypeReferences.ENTITY_NAME.in(p_registerTypes_1_), DSL.constType(DSL.string()))));
});
p_registerTypes_1_.registerType(false, TypeReferences.BIOME, () ->
{
return DSL.constType(func_233457_a_());
});
p_registerTypes_1_.registerType(false, TypeReferences.ENTITY_NAME, () ->
{
return DSL.constType(func_233457_a_());
});
}
}
|
/*
* Copyright 2013-2018 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.iot.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.iot.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* DeleteV2LoggingLevelResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteV2LoggingLevelResultJsonUnmarshaller implements Unmarshaller<DeleteV2LoggingLevelResult, JsonUnmarshallerContext> {
public DeleteV2LoggingLevelResult unmarshall(JsonUnmarshallerContext context) throws Exception {
DeleteV2LoggingLevelResult deleteV2LoggingLevelResult = new DeleteV2LoggingLevelResult();
return deleteV2LoggingLevelResult;
}
private static DeleteV2LoggingLevelResultJsonUnmarshaller instance;
public static DeleteV2LoggingLevelResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new DeleteV2LoggingLevelResultJsonUnmarshaller();
return instance;
}
}
|
package com.youcruit.onfido.api.applicants;
import com.google.gson.annotations.SerializedName;
public enum IdNumberType {
@SerializedName("nino")
NINO,
@SerializedName("ssn")
SSN,
@SerializedName("driving_license")
DRIVING_LICENSE;
}
|
/**
* Copyright 2014-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.webase.node.mgr.role;
import com.alibaba.fastjson.JSON;
import com.webank.webase.node.mgr.base.code.ConstantCode;
import com.webank.webase.node.mgr.base.exception.NodeMgrException;
import java.util.List;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* services for role data.
*/
@Log4j2
@Service
public class RoleService {
@Autowired
private RoleMapper roleMapper;
/**
* query role count.
*/
public int countOfRole(RoleListParam param) {
log.debug("start countOfRole. param:{} ", JSON.toJSONString(param));
Integer roleCount = roleMapper.countOfRole(param);
int count = roleCount == null ? 0 : roleCount.intValue();
log.debug("end countOfRole. count:{} ", count);
return count;
}
/**
* query role .
*/
public List<TbRole> listOfRole(RoleListParam param) {
log.debug("start listOfRole. param:{} ", JSON.toJSONString(param));
List<TbRole> list = roleMapper.listOfRole(param);
log.debug("end listOfRole. list:{} ", JSON.toJSONString(list));
return list;
}
/**
* query role by roleId.
*/
public TbRole queryRoleById(Integer roleId) {
log.debug("start queryRoleById. roleId:{} ", roleId);
TbRole roleInfo = roleMapper.queryRoleById(roleId);
log.debug("end queryRoleById. roleInfo:{} ", JSON.toJSONString(roleInfo));
return roleInfo;
}
/**
* check roleId.
*/
public void roleIdExist(Integer roleId) throws NodeMgrException {
log.debug("start roleIdExist. roleId:{} ", roleId);
if (roleId == null) {
log.info("fail roleIdExist. roleId is null ");
throw new NodeMgrException(ConstantCode.ROLE_ID_EMPTY);
}
TbRole roleInfo = roleMapper.queryRoleById(roleId);
if (roleInfo == null) {
log.info("fail roleIdExist. did not found role row by id");
throw new NodeMgrException(ConstantCode.INVALID_ROLE_ID);
}
log.debug("end roleIdExist. ");
}
}
|
/*
* Copyright (c) 2019-2020 GeyserMC. http://geysermc.org
*
* 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.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.platform.spigot.world.manager;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.geysermc.adapters.spigot.SpigotAdapters;
import org.geysermc.adapters.spigot.SpigotWorldAdapter;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.world.block.BlockTranslator;
public class GeyserSpigotNativeWorldManager extends GeyserSpigotWorldManager {
protected final SpigotWorldAdapter adapter;
public GeyserSpigotNativeWorldManager(boolean use3dBiomes) {
super(use3dBiomes);
adapter = SpigotAdapters.getWorldAdapter();
}
@Override
public int getBlockAt(GeyserSession session, int x, int y, int z) {
Player player = Bukkit.getPlayer(session.getPlayerEntity().getUsername());
if (player == null) {
return BlockTranslator.JAVA_AIR_ID;
}
return adapter.getBlockAt(player.getWorld(), x, y, z);
}
}
|
package com.taotao.service.impl;
import java.util.Date;
import java.util.List;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.pojo.EasyUIDataGridResult;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.IDUtils;
import com.taotao.mapper.TbItemDescMapper;
import com.taotao.mapper.TbItemMapper;
import com.taotao.pojo.TbItem;
import com.taotao.pojo.TbItemDesc;
import com.taotao.pojo.TbItemExample;
import com.taotao.service.ItemService;
@Service
public class ItemServiceImpl implements ItemService {
@Autowired
private TbItemMapper itemMapper;
@Autowired
private TbItemDescMapper itemDescMapper;
@Override
public TbItem getItemById(long itemId) {
return itemMapper.selectByPrimaryKey(itemId);
}
@Override
public EasyUIDataGridResult getItemList(int page, int rows) {
// 分页处理
PageHelper.startPage(page, rows);
// 执行查询
TbItemExample example = new TbItemExample();
List<TbItem> list = itemMapper.selectByExample(example);
// 取分页信息
PageInfo<TbItem> pageInfo = new PageInfo<>(list);
EasyUIDataGridResult result = new EasyUIDataGridResult(pageInfo.getTotal(), list);
return result;
}
@Override
public TaotaoResult createItem(TbItem item, String desc) {
// 生成商品Id
long itemId = IDUtils.genItemId();
// 补全Item属性
item.setId(itemId);
// 商品状态,1-正常,2-下架,3-删除
item.setStatus((byte) 1);
// 创建时间
Date date = new Date();
item.setCreated(date);
item.setUpdated(date);
// 插入商品表
itemMapper.insert(item);
// 商品描述
TbItemDesc itemDesc = new TbItemDesc();
itemDesc.setItemId(itemId);
itemDesc.setItemDesc(desc);
itemDesc.setCreated(date);
itemDesc.setUpdated(date);
itemDescMapper.insert(itemDesc);
return TaotaoResult.ok();
}
}
|
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.springframework.web.method.support;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.MethodParameter;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.HandlerMethod;
/**
* Extension of {@link HandlerMethod} that invokes the underlying method with
* argument values resolved from the current HTTP request through a list of
* {@link HandlerMethodArgumentResolver}.
*
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @since 3.1
*/
public class InvocableHandlerMethod extends HandlerMethod {
private static final Object[] EMPTY_ARGS = new Object[0];
@Nullable
private WebDataBinderFactory dataBinderFactory;
private HandlerMethodArgumentResolverComposite resolvers = new HandlerMethodArgumentResolverComposite();
private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
/**
* Create an instance from a {@code HandlerMethod}.
*/
public InvocableHandlerMethod(HandlerMethod handlerMethod) {
super(handlerMethod);
}
/**
* Create an instance from a bean instance and a method.
*/
public InvocableHandlerMethod(Object bean, Method method) {
super(bean, method);
}
/**
* Construct a new handler method with the given bean instance, method name and parameters.
* @param bean the object bean
* @param methodName the method name
* @param parameterTypes the method parameter types
* @throws NoSuchMethodException when the method cannot be found
*/
public InvocableHandlerMethod(Object bean, String methodName, Class<?>... parameterTypes)
throws NoSuchMethodException {
super(bean, methodName, parameterTypes);
}
/**
* Set the {@link WebDataBinderFactory} to be passed to argument resolvers allowing them to create
* a {@link WebDataBinder} for data binding and type conversion purposes.
* @param dataBinderFactory the data binder factory.
*/
public void setDataBinderFactory(WebDataBinderFactory dataBinderFactory) {
this.dataBinderFactory = dataBinderFactory;
}
/**
* Set {@link HandlerMethodArgumentResolver HandlerMethodArgumentResolvers} to use to use for resolving method argument values.
*/
public void setHandlerMethodArgumentResolvers(HandlerMethodArgumentResolverComposite argumentResolvers) {
this.resolvers = argumentResolvers;
}
/**
* Set the ParameterNameDiscoverer for resolving parameter names when needed
* (e.g. default request attribute name).
* <p>Default is a {@link org.springframework.core.DefaultParameterNameDiscoverer}.
*/
public void setParameterNameDiscoverer(ParameterNameDiscoverer parameterNameDiscoverer) {
this.parameterNameDiscoverer = parameterNameDiscoverer;
}
/**
* Invoke the method after resolving its argument values in the context of the given request.
* <p>Argument values are commonly resolved through
* {@link HandlerMethodArgumentResolver HandlerMethodArgumentResolvers}.
* The {@code providedArgs} parameter however may supply argument values to be used directly,
* i.e. without argument resolution. Examples of provided argument values include a
* {@link WebDataBinder}, a {@link SessionStatus}, or a thrown exception instance.
* Provided argument values are checked before argument resolvers.
* <p>Delegates to {@link #getMethodArgumentValues} and calls {@link #doInvoke} with the
* resolved arguments.
* @param request the current request
* @param mavContainer the ModelAndViewContainer for this request
* @param providedArgs "given" arguments matched by type, not resolved
* @return the raw value returned by the invoked method
* @throws Exception raised if no suitable argument resolver can be found,
* or if the method raised an exception
* @see #getMethodArgumentValues
* @see #doInvoke
*/
@Nullable
public Object invokeForRequest(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,
Object... providedArgs) throws Exception {
// 这个方法做了 参数适配。根据Controller 中接口方法定义的参数做参数适配。
Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
if (logger.isTraceEnabled()) {
logger.trace("Arguments: " + Arrays.toString(args));
}
return doInvoke(args);
}
/**
* Get the method argument values for the current request, checking the provided
* argument values and falling back to the configured argument resolvers.
* <p>The resulting array will be passed into {@link #doInvoke}.
* @since 5.1.2
*/
/*
做参数适配。工作
*/
protected Object[] getMethodArgumentValues(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,
Object... providedArgs) throws Exception {
MethodParameter[] parameters = getMethodParameters();
if (ObjectUtils.isEmpty(parameters)) {
return EMPTY_ARGS;
}
Object[] args = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
MethodParameter parameter = parameters[i];
parameter.initParameterNameDiscovery(this.parameterNameDiscoverer);
args[i] = findProvidedArgument(parameter, providedArgs);
if (args[i] != null) {
continue;
}
if (!this.resolvers.supportsParameter(parameter)) {
throw new IllegalStateException(formatArgumentError(parameter, "No suitable resolver"));
}
try {
args[i] = this.resolvers.resolveArgument(parameter, mavContainer, request, this.dataBinderFactory);
}
catch (Exception ex) {
// Leave stack trace for later, exception may actually be resolved and handled...
if (logger.isDebugEnabled()) {
String exMsg = ex.getMessage();
if (exMsg != null && !exMsg.contains(parameter.getExecutable().toGenericString())) {
logger.debug(formatArgumentError(parameter, exMsg));
}
}
throw ex;
}
}
return args;
}
/**
* Invoke the handler method with the given argument values.
*/
@Nullable
protected Object doInvoke(Object... args) throws Exception {
ReflectionUtils.makeAccessible(getBridgedMethod());
try {
return getBridgedMethod().invoke(getBean(), args);
}
catch (IllegalArgumentException ex) {
assertTargetBean(getBridgedMethod(), getBean(), args);
String text = (ex.getMessage() != null ? ex.getMessage() : "Illegal argument");
throw new IllegalStateException(formatInvokeError(text, args), ex);
}
catch (InvocationTargetException ex) {
// Unwrap for HandlerExceptionResolvers ...
Throwable targetException = ex.getTargetException();
if (targetException instanceof RuntimeException) {
throw (RuntimeException) targetException;
}
else if (targetException instanceof Error) {
throw (Error) targetException;
}
else if (targetException instanceof Exception) {
throw (Exception) targetException;
}
else {
throw new IllegalStateException(formatInvokeError("Invocation failure", args), targetException);
}
}
}
}
|
/*
* 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.hbase.codec.prefixtree;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellComparator;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.CellComparator.MetaCellComparator;
import org.apache.hadoop.hbase.KeyValueUtil;
import org.apache.hadoop.hbase.codec.prefixtree.decode.DecoderFactory;
import org.apache.hadoop.hbase.codec.prefixtree.decode.PrefixTreeArraySearcher;
import org.apache.hadoop.hbase.codec.prefixtree.encode.EncoderFactory;
import org.apache.hadoop.hbase.codec.prefixtree.encode.PrefixTreeEncoder;
import org.apache.hadoop.hbase.codec.prefixtree.scanner.CellSearcher;
import org.apache.hadoop.hbase.io.encoding.DataBlockEncoder;
import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
import org.apache.hadoop.hbase.io.encoding.EncodingState;
import org.apache.hadoop.hbase.io.encoding.HFileBlockDecodingContext;
import org.apache.hadoop.hbase.io.encoding.HFileBlockDefaultDecodingContext;
import org.apache.hadoop.hbase.io.encoding.HFileBlockDefaultEncodingContext;
import org.apache.hadoop.hbase.io.encoding.HFileBlockEncodingContext;
import org.apache.hadoop.hbase.io.hfile.BlockType;
import org.apache.hadoop.hbase.io.hfile.HFileContext;
import org.apache.hadoop.hbase.util.ByteBufferUtils;
import org.apache.hadoop.io.WritableUtils;
/**
* <p>
* This class is created via reflection in DataBlockEncoding enum. Update the enum if class name or
* package changes.
* </p>
* PrefixTreeDataBlockEncoder implementation of DataBlockEncoder. This is the primary entry point
* for PrefixTree encoding and decoding. Encoding is delegated to instances of
* {@link PrefixTreeEncoder}, and decoding is delegated to instances of
* {@link org.apache.hadoop.hbase.codec.prefixtree.scanner.CellSearcher}. Encoder and decoder instances are
* created and recycled by static PtEncoderFactory and PtDecoderFactory.
*/
@InterfaceAudience.Private
public class PrefixTreeCodec implements DataBlockEncoder {
/**
* no-arg constructor for reflection
*/
public PrefixTreeCodec() {
}
@Override
public ByteBuffer decodeKeyValues(DataInputStream source, HFileBlockDecodingContext decodingCtx)
throws IOException {
return decodeKeyValues(source, 0, 0, decodingCtx);
}
/**
* I don't think this method is called during normal HBase operation, so efficiency is not
* important.
*/
public ByteBuffer decodeKeyValues(DataInputStream source, int allocateHeaderLength,
int skipLastBytes, HFileBlockDecodingContext decodingCtx) throws IOException {
ByteBuffer sourceAsBuffer = ByteBufferUtils.drainInputStreamToBuffer(source);// waste
sourceAsBuffer.mark();
PrefixTreeBlockMeta blockMeta = new PrefixTreeBlockMeta(sourceAsBuffer);
sourceAsBuffer.rewind();
int numV1BytesWithHeader = allocateHeaderLength + blockMeta.getNumKeyValueBytes();
byte[] keyValueBytesWithHeader = new byte[numV1BytesWithHeader];
ByteBuffer result = ByteBuffer.wrap(keyValueBytesWithHeader);
result.rewind();
CellSearcher searcher = null;
try {
boolean includesMvcc = decodingCtx.getHFileContext().isIncludesMvcc();
searcher = DecoderFactory.checkOut(sourceAsBuffer, includesMvcc);
while (searcher.advance()) {
KeyValue currentCell = KeyValueUtil.copyToNewKeyValue(searcher.current());
// needs to be modified for DirectByteBuffers. no existing methods to
// write VLongs to byte[]
int offset = result.arrayOffset() + result.position();
System.arraycopy(currentCell.getBuffer(), currentCell.getOffset(), result.array(), offset,
currentCell.getLength());
int keyValueLength = KeyValueUtil.length(currentCell);
ByteBufferUtils.skip(result, keyValueLength);
offset += keyValueLength;
if (includesMvcc) {
ByteBufferUtils.writeVLong(result, currentCell.getMvccVersion());
}
}
result.position(result.limit());//make it appear as if we were appending
return result;
} finally {
DecoderFactory.checkIn(searcher);
}
}
@Override
public ByteBuffer getFirstKeyInBlock(ByteBuffer block) {
block.rewind();
PrefixTreeArraySearcher searcher = null;
try {
// should i includeMemstoreTS (second argument)? i think PrefixKeyDeltaEncoder is, so i will
searcher = DecoderFactory.checkOut(block, true);
if (!searcher.positionAtFirstCell()) {
return null;
}
return KeyValueUtil.copyKeyToNewByteBuffer(searcher.current());
} finally {
DecoderFactory.checkIn(searcher);
}
}
@Override
public HFileBlockEncodingContext newDataBlockEncodingContext(
DataBlockEncoding encoding, byte[] header, HFileContext meta) {
if(DataBlockEncoding.PREFIX_TREE != encoding){
//i'm not sure why encoding is in the interface. Each encoder implementation should probably
//know it's encoding type
throw new IllegalArgumentException("only DataBlockEncoding.PREFIX_TREE supported");
}
return new HFileBlockDefaultEncodingContext(encoding, header, meta);
}
@Override
public HFileBlockDecodingContext newDataBlockDecodingContext(HFileContext meta) {
return new HFileBlockDefaultDecodingContext(meta);
}
/**
* Is this the correct handling of an illegal comparator? How to prevent that from getting all
* the way to this point.
*/
@Override
public EncodedSeeker createSeeker(CellComparator comparator,
HFileBlockDecodingContext decodingCtx) {
if (comparator instanceof MetaCellComparator) {
throw new IllegalArgumentException(
"DataBlockEncoding.PREFIX_TREE not compatible with hbase:meta " + "table");
}
return new PrefixTreeSeeker(decodingCtx.getHFileContext().isIncludesMvcc());
}
@Override
public int encode(Cell cell, HFileBlockEncodingContext encodingCtx, DataOutputStream out)
throws IOException {
PrefixTreeEncodingState state = (PrefixTreeEncodingState) encodingCtx.getEncodingState();
PrefixTreeEncoder builder = state.builder;
builder.write(cell);
int size = KeyValueUtil.length(cell);
if (encodingCtx.getHFileContext().isIncludesMvcc()) {
size += WritableUtils.getVIntSize(cell.getSequenceId());
}
return size;
}
private static class PrefixTreeEncodingState extends EncodingState {
PrefixTreeEncoder builder = null;
}
@Override
public void startBlockEncoding(HFileBlockEncodingContext blkEncodingCtx, DataOutputStream out)
throws IOException {
if (blkEncodingCtx.getClass() != HFileBlockDefaultEncodingContext.class) {
throw new IOException(this.getClass().getName() + " only accepts "
+ HFileBlockDefaultEncodingContext.class.getName() + " as the " + "encoding context.");
}
HFileBlockDefaultEncodingContext encodingCtx =
(HFileBlockDefaultEncodingContext) blkEncodingCtx;
encodingCtx.prepareEncoding(out);
PrefixTreeEncoder builder = EncoderFactory.checkOut(out, encodingCtx.getHFileContext()
.isIncludesMvcc());
PrefixTreeEncodingState state = new PrefixTreeEncodingState();
state.builder = builder;
blkEncodingCtx.setEncodingState(state);
}
@Override
public void endBlockEncoding(HFileBlockEncodingContext encodingCtx, DataOutputStream out,
byte[] uncompressedBytesWithHeader) throws IOException {
PrefixTreeEncodingState state = (PrefixTreeEncodingState) encodingCtx.getEncodingState();
PrefixTreeEncoder builder = state.builder;
builder.flush();
EncoderFactory.checkIn(builder);
// do i need to check this, or will it always be DataBlockEncoding.PREFIX_TREE?
if (encodingCtx.getDataBlockEncoding() != DataBlockEncoding.NONE) {
encodingCtx.postEncoding(BlockType.ENCODED_DATA);
} else {
encodingCtx.postEncoding(BlockType.DATA);
}
}
}
|
package org.testobject.kernel.inference.input;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.testobject.commons.math.algebra.Rectangle;
import org.testobject.commons.util.image.Image;
import org.testobject.commons.util.thread.ThreadUtil;
import org.testobject.kernel.api.events.Timestamp;
import org.testobject.kernel.api.events.input.MouseEvent;
import org.testobject.kernel.api.events.output.Events.Event;
import org.testobject.kernel.api.events.output.Events.Type.Key;
import org.testobject.kernel.inference.input.InputStateMachine.Callback;
/**
*
* @author enijkamp
*
*/
public class InputStateMachineTest {
@Test
public void testWrongBeforeImage() throws IOException, InterruptedException {
InputBuilder inputs = new InputBuilder();
{
inputs.frame(0l);
inputs.click(100l);
inputs.frame(150l);
InputTransition state = inputs.waitForStateChange();
assertThat(state.getBefore().timestamp, is(0l));
assertThat(state.getAfter().timestamp, is(150l));
}
{
inputs.click(1000l);
inputs.frame(1100l);
inputs.click(1300l);
inputs.frame(1400l);
{
InputTransition state = inputs.waitForStateChange();
assertThat(state.getBefore().timestamp, is(150l));
assertThat(state.getAfter().timestamp, is(1100l));
}
{
InputTransition state = inputs.waitForStateChange();
assertThat(state.getBefore().timestamp, is(1100l));
assertThat(state.getAfter().timestamp, is(1400l));
}
}
}
@Test
public void testFbuTimeout() throws IOException, InterruptedException {
final int fbuTimeout = 1000;
final int maxTimeout = 2000;
InputBuilder inputs = new InputBuilder(fbuTimeout, maxTimeout);
{
inputs.frame(0l);
inputs.click(100l);
inputs.frame(200l);
inputs.frame(2000l);
inputs.frame(3000l);
InputTransition state = inputs.waitForStateChange();
assertThat(inputs.states.isEmpty(), is(true));
assertThat(state.getBefore().timestamp, is(0l));
assertThat(state.getAfter().timestamp, is(200l));
}
}
@Test
public void testMaxTimeout() throws IOException, InterruptedException {
final int fbuTimeout = 1000;
final int maxTimeout = 2000;
InputBuilder inputs = new InputBuilder(fbuTimeout, maxTimeout);
{
inputs.frame(0l);
inputs.click(1100l);
inputs.frame(1500l);
inputs.frame(2000l);
inputs.frame(2500l);
inputs.frame(3000l);
inputs.frame(3500l);
inputs.frame(4000);
InputTransition state = inputs.waitForStateChange();
assertThat(inputs.states.isEmpty(), is(true));
assertThat(state.getBefore().timestamp, is(0l));
assertThat(state.getAfter().timestamp, is(3500l));
}
}
@Test
public void testTimeoutTriggersOnlyOneTransition() throws IOException, InterruptedException {
final int fbuTimeout = 1000;
final int maxTimeout = 2000;
InputBuilder inputs = new InputBuilder(fbuTimeout, maxTimeout);
{
// can trigger either handleFbuTimeout() or handleMaxTimeout(), but never both
inputs.frame(0l);
inputs.click(2000l);
inputs.frame(2500l);
inputs.frame(3501l);
inputs.frame(4500l);
inputs.frame(5000l);
Thread.sleep(1000);
InputTransition state = inputs.waitForStateChange(maxTimeout + 100);
assertThat(inputs.states.isEmpty(), is(true));
assertThat(state.getBefore().timestamp, is(0l));
assertThat(state.getAfter().timestamp, anyOf(is(2500l), is(4500l)));
}
}
@Test
public void testCharKeysConcat() throws IOException, InterruptedException {
InputBuilder inputs = new InputBuilder();
{
inputs.frame(0l);
inputs.charKey(100l, (int) 'a');
inputs.charKey(150l, (int) 'b');
inputs.charKey(200l, (int) 'c');
inputs.frame(600l);
{
InputTransition abc = inputs.waitForStateChange();
assertThat(abc.getBefore().timestamp, is(0l));
assertThat(abc.getAfter().timestamp, is(600l));
assertThat(toString(abc.getTypeEvent().keys), is("abc"));
}
}
}
@Test
public void testHardwareKeysTransition() throws IOException, InterruptedException {
InputBuilder inputs = new InputBuilder();
{
final int ENTER = 13;
inputs.frame(0l);
inputs.charKey(100l, (int) 'a');
inputs.charKey(150l, (int) 'b');
inputs.charKey(200l, (int) 'c');
inputs.ctrlKey(250l, ENTER);
inputs.charKey(300l, (int) 'd');
inputs.charKey(300l, (int) 'e');
inputs.frame(600l);
{
InputTransition abc = inputs.waitForStateChange();
assertThat(abc.getBefore().timestamp, is(0l));
assertThat(abc.getAfter().timestamp, is(0l));
assertThat(toString(abc.getTypeEvent().keys), is("abc"));
}
{
InputTransition enter = inputs.waitForStateChange();
assertThat(enter.getBefore().timestamp, is(0l));
assertThat(enter.getAfter().timestamp, is(0l));
assertThat(enter.getTypeEvent().keys.get(0).key, is(ENTER));
}
{
InputTransition de = inputs.waitForStateChange();
assertThat(de.getBefore().timestamp, is(0l));
assertThat(de.getAfter().timestamp, is(600l));
assertThat(toString(de.getTypeEvent().keys), is("de"));
}
}
}
private String toString(List<Key> keys) {
String string = "";
for (Key key : keys) {
string += (char) key.key;
}
return string;
}
private static class InputBuilder {
public long currentTime = 0l;
public InputStateMachine stateMachine;
public Image.Int buffer = new Image.Int(100, 100);
public List<Rectangle.Int> updates = Collections.singletonList(new Rectangle.Int(0, 0, 100, 100));
public BlockingQueue<InputTransition> states = new LinkedBlockingQueue<>();
public InputBuilder() {
this(InputStateMachine.WAIT_FOR_DAMAGES_FBU_MS, InputStateMachine.WAIT_FOR_DAMAGES_MAX_MS);
}
public InputBuilder(long waitForDamagesFbuMs, long waitForDamagesMaxMs) {
this.stateMachine = new InputStateMachine(InputStateMachine.IsIgnorableRegion.Factory.stub(), waitForDamagesFbuMs,
waitForDamagesMaxMs, InputStateMachine.TransitionSequence.Stub.create(), createCallback());
}
private Callback createCallback() {
return new Callback() {
@Override
public void beginTransition(long transition) {}
@Override
public void beginRequest(long transition, Framebuffer before, Event event) {}
@Override
public void endRequest(long transition, Framebuffer before, Event event) {}
@Override
public void endTransition(long transition, Framebuffer before, Framebuffer after, Event event) {
states.add(new InputTransition(before, after, event));
}
};
}
public InputBuilder frame(long targetTime) throws IOException, InterruptedException {
Thread.sleep(targetTime - currentTime);
stateMachine.updateFrameBuffer(new Timestamp(targetTime, targetTime, targetTime), buffer, updates);
this.currentTime = targetTime;
return this;
}
public InputBuilder click(long targetTime) throws IOException, InterruptedException {
Thread.sleep(targetTime - currentTime);
stateMachine.mouseEvent(new Timestamp(targetTime, targetTime, targetTime), MouseEvent.Type.DOWN, 50, 50);
ThreadUtil.sleep(10);
stateMachine.mouseEvent(new Timestamp(targetTime, targetTime, targetTime), MouseEvent.Type.UP, 50, 50);
this.currentTime = targetTime;
return this;
}
public InputBuilder charKey(long targetTime, int keycode) throws IOException, InterruptedException {
Thread.sleep(targetTime - currentTime);
stateMachine.keyEvent(new Timestamp(targetTime, targetTime, targetTime), keycode, false, true);
this.currentTime = targetTime;
return this;
}
public InputBuilder ctrlKey(long targetTime, int keycode) throws IOException, InterruptedException {
Thread.sleep(targetTime - currentTime);
stateMachine.keyEvent(new Timestamp(targetTime, targetTime, targetTime), keycode, true, true);
this.currentTime = targetTime;
return this;
}
public InputTransition waitForStateChange() throws InterruptedException {
return states.poll(InputStateMachine.WAIT_FOR_DAMAGES_FBU_MS + 500, TimeUnit.MILLISECONDS);
}
public InputTransition waitForStateChange(long ms) throws InterruptedException {
return states.poll(ms, TimeUnit.MILLISECONDS);
}
}
}
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|rs
operator|.
name|security
operator|.
name|jose
operator|.
name|jwa
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|rs
operator|.
name|security
operator|.
name|jose
operator|.
name|support
operator|.
name|Serialization
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_class
specifier|public
specifier|abstract
class|class
name|JwaSignRfcConformanceTest
extends|extends
name|AbstractSignTest
block|{
annotation|@
name|Test
specifier|public
name|void
name|testRsaRs256JwsCompact
parameter_list|()
throws|throws
name|Exception
block|{
name|test
argument_list|(
literal|"RSA"
argument_list|,
literal|"RS256"
argument_list|,
name|Serialization
operator|.
name|COMPACT
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testRsaRs256JwsJsonFlattened
parameter_list|()
throws|throws
name|Exception
block|{
name|test
argument_list|(
literal|"RSA"
argument_list|,
literal|"RS256"
argument_list|,
name|Serialization
operator|.
name|FLATTENED
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testRsaRs256JwsJson
parameter_list|()
throws|throws
name|Exception
block|{
name|test
argument_list|(
literal|"RSA"
argument_list|,
literal|"RS256"
argument_list|,
name|Serialization
operator|.
name|JSON
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testEcEs256JwsCompact
parameter_list|()
throws|throws
name|Exception
block|{
name|test
argument_list|(
literal|"EC"
argument_list|,
literal|"ES256"
argument_list|,
name|Serialization
operator|.
name|COMPACT
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testEcEs256JwsJsonFlattened
parameter_list|()
throws|throws
name|Exception
block|{
name|test
argument_list|(
literal|"EC"
argument_list|,
literal|"ES256"
argument_list|,
name|Serialization
operator|.
name|FLATTENED
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testEcEs256JwsJson
parameter_list|()
throws|throws
name|Exception
block|{
name|test
argument_list|(
literal|"EC"
argument_list|,
literal|"ES256"
argument_list|,
name|Serialization
operator|.
name|JSON
argument_list|)
expr_stmt|;
block|}
block|}
end_class
end_unit
|
package com.vondear.rxtools.view;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.text.TextPaint;
import java.util.ArrayList;
/**
*
* @author Vondear
* @date 12/24/15
*/
public class RxRotateBarBasic {
private static final int ITEM_OFFSET = 1;
private static final int SHADOW_ALPHA = (int) (255 * 0.2); // 20%
private static final int UN_RATING_ALPHA = (int) (255 * 0.3); // 30%
private static final int RATING_ALPHA = (int) (255 * 1.0); // 100%
private static final int OUTLINE_ALPHA = (int) (255 * 0.4); // 40%
private boolean isSingle = false;
private boolean isShowTitle = true;
private int outlineWidth, ratingBarWidth, shadowWidth, textWidth;
private float mStartAngle;
private float mSweepAngle;
private int maxRate = 10;
private int mCurRate;
private ArrayList<Rate> rates;
private Paint ratedPaint, unRatedPaint, shadowPaint, outlinePaint;
private TextPaint titlePaint;
private int mRadius;
private String mTitle;
private int mCenterX, mCenterY;
private RectF outlineOval, ratingOval, shadowOval;
public RxRotateBarBasic(int curRate, String title) {
this.mCurRate = curRate;
this.mTitle = title;
outlinePaint = new Paint();
ratedPaint = new Paint();
unRatedPaint = new Paint();
shadowPaint = new Paint();
titlePaint = new TextPaint();
// set default color
setRatingBarColor(Color.WHITE);
}
protected void init() {
// in this order to init
initRatingBar();
initOval();
initPaint();
}
private void initOval() {
mRadius = mCenterX > mCenterY ? mCenterY : mCenterX;
// text bar : 1/10 of radius
textWidth = mRadius / 10;
// rating bar : 1/10 of radius
ratingBarWidth = mRadius / 10;
// shadow : 1/3 of rating bar
shadowWidth = ratingBarWidth / 3;
// outline : 1/3 of shadow
outlineWidth = shadowWidth / 3;
int outlineRadius = mRadius - (textWidth / 2); // outline include text and outline, radius is base on textWidth
int paddingRadius = outlineRadius - (textWidth / 2); // padding space draw nothing, radius is base on textWidth
int ratingBarRadius = paddingRadius - (textWidth / 2) - (ratingBarWidth / 2);
int shadowRadius = ratingBarRadius - (ratingBarWidth / 2) - (shadowWidth / 2);
outlineOval = new RectF();
ratingOval = new RectF();
shadowOval = new RectF();
outlineOval.left = mCenterX - outlineRadius;
outlineOval.top = mCenterY - outlineRadius;
outlineOval.right = mCenterX + outlineRadius;
outlineOval.bottom = mCenterY + outlineRadius;
ratingOval.left = mCenterX - ratingBarRadius;
ratingOval.top = mCenterY - ratingBarRadius;
ratingOval.right = mCenterX + ratingBarRadius;
ratingOval.bottom = mCenterY + ratingBarRadius;
shadowOval.left = mCenterX - shadowRadius;
shadowOval.top = mCenterY - shadowRadius;
shadowOval.right = mCenterX + shadowRadius;
shadowOval.bottom = mCenterY + shadowRadius;
}
private void initPaint() {
outlinePaint.setAntiAlias(true);
outlinePaint.setStyle(Paint.Style.STROKE);
outlinePaint.setStrokeWidth(outlineWidth);
outlinePaint.setAlpha(OUTLINE_ALPHA);
ratedPaint.setAntiAlias(true);
ratedPaint.setStyle(Paint.Style.STROKE);
ratedPaint.setStrokeWidth(ratingBarWidth);
ratedPaint.setAlpha(RATING_ALPHA);
unRatedPaint.setAntiAlias(true);
unRatedPaint.setStyle(Paint.Style.STROKE);
unRatedPaint.setStrokeWidth(ratingBarWidth);
unRatedPaint.setAlpha(UN_RATING_ALPHA);
shadowPaint.setAntiAlias(true);
shadowPaint.setStyle(Paint.Style.STROKE);
shadowPaint.setStrokeWidth(shadowWidth);
shadowPaint.setAlpha(SHADOW_ALPHA);
titlePaint.setAntiAlias(true);
titlePaint.setTextSize(textWidth);
titlePaint.setAlpha(RATING_ALPHA);
}
private void initRatingBar() {
rates = new ArrayList<>();
float itemSweepAngle;
if (isSingle) {
itemSweepAngle = (mSweepAngle - (ITEM_OFFSET * (maxRate))) / maxRate;
} else {
itemSweepAngle = (mSweepAngle - (ITEM_OFFSET * (maxRate - 1))) / maxRate;
}
for (int i = 0; i < maxRate; i++) {
float itemStartAngle = mStartAngle + i * (itemSweepAngle + ITEM_OFFSET);
rates.add(new Rate(itemStartAngle, itemSweepAngle));
}
}
protected void drawUnRate(Canvas canvas) {
for (Rate arc : rates) {
arc.drawArc(canvas, ratingOval, unRatedPaint);
}
}
protected void drawRate(Canvas canvas, int index) {
if (index >= maxRate) {
return;
}
Rate arc = rates.get(index);
arc.drawArc(canvas, ratingOval, ratedPaint);
}
protected void drawShadow(Canvas canvas) {
for (Rate arc : rates) {
arc.drawArc(canvas, shadowOval, shadowPaint);
}
}
protected void drawTitle(Canvas canvas, int alpha) {
if (alpha > 0 && isShowTitle) {
Path path = new Path();
float circumference = (float) (Math.PI * (outlineOval.right - outlineOval.left));
float textAngle = (360 / circumference) * titlePaint.measureText(getTitle());
float startAngle = mStartAngle + mSweepAngle / 2 - textAngle / 2;
if (isSingle) {
// when single, draw 360 the path will be a circle
path.addArc(outlineOval, startAngle - mSweepAngle / 2, mSweepAngle / 2);
} else {
path.addArc(outlineOval, startAngle, mSweepAngle);
}
titlePaint.setAlpha(alpha);
canvas.drawTextOnPath(mTitle, path, 0, textWidth / 3, titlePaint);
}
}
protected void drawOutLine(Canvas canvas) {
float circumference = (float) (Math.PI * (outlineOval.right - outlineOval.left));
float textAngle = (360 / circumference) * titlePaint.measureText(getTitle());
float sweepAngle = (mSweepAngle - textAngle - 1 - 1) / 2;
if (isShowTitle) {
// text left
float leftStartAngle = mStartAngle;
canvas.drawArc(outlineOval, leftStartAngle, sweepAngle, false, outlinePaint);
// text right
float rightStartAngle = mStartAngle + mSweepAngle - sweepAngle;
canvas.drawArc(outlineOval, rightStartAngle, sweepAngle, false, outlinePaint);
} else {
canvas.drawArc(outlineOval, mStartAngle, mSweepAngle, false, outlinePaint);
}
}
public void setMaxRate(int maxRate) {
this.maxRate = maxRate;
}
public int getRate() {
return mCurRate;
}
public void setRate(int curRate) {
this.mCurRate = curRate;
}
protected void setStartAngle(float mStartAngle) {
this.mStartAngle = mStartAngle;
}
protected void setSweepAngle(float mSweepAngle) {
this.mSweepAngle = mSweepAngle;
}
protected void setCenterX(int mCenterX) {
this.mCenterX = mCenterX;
}
protected void setCenterY(int mCenterY) {
this.mCenterY = mCenterY;
}
protected void setIsSingle(boolean isSingle) {
this.isSingle = isSingle;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
this.mTitle = title;
}
public void setRatedColor(int color) {
ratedPaint.setColor(color);
}
public void setUnRatedColor(int color) {
unRatedPaint.setColor(color);
}
public void setTitleColor(int color) {
titlePaint.setColor(color);
}
public void setOutlineColor(int color) {
outlinePaint.setColor(color);
}
public void setShadowColor(int color) {
shadowPaint.setColor(color);
}
public void isShowTitle(boolean isShow) {
isShowTitle = isShow;
}
public void setRatingBarColor(int color) {
ratedPaint.setColor(color);
unRatedPaint.setColor(color);
titlePaint.setColor(color);
outlinePaint.setColor(color);
shadowPaint.setColor(color);
}
/**
* Rate class
*/
public class Rate {
private float startAngle, sweepAngle;
public Rate(float startAngle, float sweepAngle) {
this.startAngle = startAngle;
this.sweepAngle = sweepAngle;
}
public void drawArc(Canvas canvas, RectF oval, Paint paint) {
canvas.drawArc(oval, startAngle, sweepAngle, false, paint);
}
}
}
|
/**
* 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.task;
import backtype.storm.generated.TaskHeartbeat;
import com.alibaba.jstorm.utils.TimeUtils;
/**
* TkHbCacheTime is describle taskheartcache (Map<topologyId, Map<taskid, Map<tkHbCacheTime, time>>>)
*/
public class TkHbCacheTime {
private int nimbusTime;
private int taskReportedTime;
private int taskAssignedTime;
public int getNimbusTime() {
return nimbusTime;
}
public void setNimbusTime(int nimbusTime) {
this.nimbusTime = nimbusTime;
}
public int getTaskReportedTime() {
return taskReportedTime;
}
public void setTaskReportedTime(int taskReportedTime) {
this.taskReportedTime = taskReportedTime;
}
public int getTaskAssignedTime() {
return taskAssignedTime;
}
public void setTaskAssignedTime(int taskAssignedTime) {
this.taskAssignedTime = taskAssignedTime;
}
public void update(TaskHeartbeat taskHeartbeat) {
if (taskHeartbeat != null) {
int nowSecs = TimeUtils.current_time_secs();
this.nimbusTime = nowSecs;
this.taskReportedTime = taskHeartbeat.get_time();
this.taskAssignedTime = taskHeartbeat.get_time() - taskHeartbeat.get_uptime();
}
}
}
|
package com.robly.sublists;
import com.fasterxml.jackson.annotation.JsonProperty;
public class SubLists {
@JsonProperty("sub_list")
SubList subList = null;
public void setSubList(SubList subList) {
this.subList = subList;
}
public SubList getSubList() {
return subList;
}
}
|
package week_3_4_Question1;
import java.util.ArrayList;
import java.util.Scanner;
public class BusinessAddress implements Address {
ArrayList<String> BusinessAddress = new ArrayList<String>();
Scanner scanner = new Scanner(System.in);
@Override
public ArrayList<String> addressInformation() {
// TODO Auto-generated method stub
String address;
System.out.println("Add business address: ");
address = scanner.nextLine();
BusinessAddress.add(address);
return BusinessAddress;
}
@Override
public ArrayList<String> removeAddress() {
// TODO Auto-generated method stub
String address;
System.out.println("Remove business address: ");
address = scanner.nextLine();
BusinessAddress.remove(address);
return BusinessAddress;
}
}
|
/*****************************************************************
* 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
*
* 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 org.apache.cayenne.access.translator.select;
import org.apache.cayenne.access.sqlbuilder.sqltree.ColumnNode;
import org.apache.cayenne.map.DataMap;
import org.apache.cayenne.map.DbEntity;
import org.apache.cayenne.map.DbRelationship;
import org.apache.cayenne.map.JoinType;
import org.junit.Test;
import java.sql.Types;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.*;
public class DbEntityColumnExtractorTest extends BaseColumnExtractorTest {
@Test
public void testExtractNoPrefix() {
TranslatableQueryWrapper wrapper = new MockQueryWrapperBuilder()
.withMetaData(new MockQueryMetadataBuilder()
.withDbEntity(createMockDbEntity("mock"))
.build())
.build();
TranslatorContext context = new MockTranslatorContext(wrapper);
DbEntityColumnExtractor extractor = new DbEntityColumnExtractor(context);
extractor.extract(null);
assertEquals(2, context.getResultNodeList().size());
ResultNodeDescriptor descriptor0 = context.getResultNodeList().get(0);
ResultNodeDescriptor descriptor1 = context.getResultNodeList().get(1);
assertNull(descriptor0.getProperty());
assertNotNull(descriptor0.getNode());
assertThat(descriptor0.getNode(), instanceOf(ColumnNode.class));
assertFalse(descriptor0.isAggregate());
assertTrue(descriptor0.isInDataRow());
assertEquals("id", descriptor0.getDataRowKey());
assertNotNull(descriptor0.getDbAttribute());
assertEquals(Types.BIGINT, descriptor0.getJdbcType());
assertNull(descriptor1.getProperty());
assertNotNull(descriptor1.getNode());
assertThat(descriptor1.getNode(), instanceOf(ColumnNode.class));
assertFalse(descriptor1.isAggregate());
assertTrue(descriptor1.isInDataRow());
assertNotNull(descriptor1.getDbAttribute());
assertEquals("name", descriptor1.getDataRowKey());
assertEquals(Types.VARBINARY, descriptor1.getJdbcType());
assertEquals("byte[]", descriptor1.getJavaType());
}
@Test
public void testExtractWithPrefix() {
DbEntity mockDbEntity = createMockDbEntity("mock1");
DbEntity mock2DbEntity = createMockDbEntity("mock2");
DataMap dataMap = new DataMap();
dataMap.addDbEntity(mockDbEntity);
dataMap.addDbEntity(mock2DbEntity);
mockDbEntity.setDataMap(dataMap);
TranslatableQueryWrapper wrapper = new MockQueryWrapperBuilder()
.withMetaData(new MockQueryMetadataBuilder()
.withDbEntity(mockDbEntity)
.build())
.build();
TranslatorContext context = new MockTranslatorContext(wrapper);
DbRelationship relationship = new DbRelationship();
relationship.setSourceEntity(mockDbEntity);
relationship.setTargetEntityName("mock1");
context.getTableTree().addJoinTable("prefix", relationship, JoinType.INNER);
DbEntityColumnExtractor extractor = new DbEntityColumnExtractor(context);
extractor.extract("prefix");
assertEquals(2, context.getResultNodeList().size());
ResultNodeDescriptor descriptor0 = context.getResultNodeList().get(0);
ResultNodeDescriptor descriptor1 = context.getResultNodeList().get(1);
assertNull(descriptor0.getProperty());
assertNotNull(descriptor0.getNode());
assertThat(descriptor0.getNode(), instanceOf(ColumnNode.class));
assertFalse(descriptor0.isAggregate());
assertTrue(descriptor0.isInDataRow());
assertEquals("prefix.id", descriptor0.getDataRowKey());
assertNotNull(descriptor0.getDbAttribute());
assertEquals(Types.BIGINT, descriptor0.getJdbcType());
assertNull(descriptor1.getProperty());
assertNotNull(descriptor1.getNode());
assertThat(descriptor1.getNode(), instanceOf(ColumnNode.class));
assertFalse(descriptor1.isAggregate());
assertTrue(descriptor1.isInDataRow());
assertNotNull(descriptor1.getDbAttribute());
assertEquals("prefix.name", descriptor1.getDataRowKey());
assertEquals(Types.VARBINARY, descriptor1.getJdbcType());
}
}
|
package andbook.example.locationservice;
import android.annotation.SuppressLint;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import noman.googleplaces.NRPlaces;
import noman.googleplaces.PlaceType;
import noman.googleplaces.PlacesException;
import noman.googleplaces.PlacesListener;
import util.GpsCheck;
import util.getApiKey;
public class MyLocationBankActivity extends AppCompatActivity implements
LocationListener, OnMapReadyCallback, PlacesListener{
private FusedLocationProviderClient fusedLocationProviderClient;
private Location location;
private LocationRequest locationRequest;
private GoogleMap googleMap;
private SupportMapFragment mapFragment;
private LatLng currentPosition;
private Marker current_marker = null;
private List<Marker> previous_marker = null;
@Override
protected void onPause(){
super.onPause();
// 현재 위치 따오지 않음
if(fusedLocationProviderClient != null)
fusedLocationProviderClient.removeLocationUpdates(locationCallback)
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
fusedLocationProviderClient = null;
}
});
}
@SuppressLint("MissingPermission")
@Override
protected void onStart() {
super.onStart();
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
if (googleMap!=null)
googleMap.setMyLocationEnabled(true);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mybank);
Button connect_BANK_Btn = (Button) findViewById(R.id.contact_bank);
GpsCheck.checkGPS_ON_OFF(MyLocationBankActivity.this); // GPS 확인 유무
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); // 상태바 제거
// 사용자 현재 위치 요청 업데이트
locationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); // 전력과 정확도의 밸런스 고려
LocationSettingsRequest.Builder builder =
new LocationSettingsRequest.Builder();
builder.addLocationRequest(locationRequest);
// 사용자의 현재 위치 표시하기
fusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(this);
// 구글맵 현재 위치 띄우기
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.bankMap);
if (mapFragment != null)
mapFragment.getMapAsync(MyLocationBankActivity.this);
// 구글맵에 찍을 마커 Array 생성
previous_marker = new ArrayList<Marker>();
connect_BANK_Btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
googleMap.clear(); // 지도 클리어
if (previous_marker != null)
previous_marker.clear(); // 지역정보 마커 클리어
new NRPlaces.Builder()
.listener(MyLocationBankActivity.this)
.latlng(currentPosition.latitude,currentPosition.longitude)//현재 위치
.radius(2000) // 2000 미터 내에서 검색
.type(PlaceType.BANK) // 은행
.key(getApiKey.place_api_key.trim())
.language("ko", "KR")
.build()
.execute();
}
});
}
@SuppressLint("MissingPermission")
@Override
public void onMapReady(GoogleMap map) {
googleMap = map;
// 현재 위치를 나타내기 위해 locationRequest: 사용자 위치 업데이트 완료
// locationcallback: 현재 위치에 대한 콜백 메서드
// Looper: 현재 처리할 쓰레드(비동기 처리)
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.animateCamera(CameraUpdateFactory.zoomTo(13));
googleMap.setMyLocationEnabled(true);
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
Toast.makeText(getApplicationContext(), "runnig...", Toast.LENGTH_SHORT).show();
}
});
}
LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0)
location = locationList.get(locationList.size() - 1);
currentPosition =
new LatLng(location.getLatitude(), location.getLongitude());
String markerTitle = getCurrentAddress(currentPosition);
setCurrentLocation(location, markerTitle);
}
};
private void setCurrentLocation(Location location, String markerTitle) {
if (current_marker != null)
current_marker.remove(); // 현재 마커 제거
LatLng currentLatLng = new LatLng(location.getLatitude(), location.getLongitude()); // 위치 따오기
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(currentLatLng);
markerOptions.title(markerTitle);
markerOptions.draggable(true);
current_marker = googleMap.addMarker(markerOptions);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(currentLatLng);
googleMap.moveCamera(cameraUpdate);
}
// 현재 위치 주소 불러오기
private String getCurrentAddress(LatLng latlng) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(
latlng.latitude,
latlng.longitude,
1);
} catch (IOException ioException) {
//네트워크 문제
Toast.makeText(this, "지오코더 서비스 사용불가", Toast.LENGTH_LONG).show();
return "지오코더 서비스 사용불가";
} catch (IllegalArgumentException illegalArgumentException) {
Toast.makeText(this, "잘못된 GPS 좌표", Toast.LENGTH_LONG).show();
return "잘못된 GPS 좌표";
}
if (addresses == null || addresses.size() == 0) {
Toast.makeText(this, "주소 미발견", Toast.LENGTH_LONG).show();
return "주소 미발견";
} else {
Address address = addresses.get(0);
return address.getAddressLine(0); // 현재 위치 한글로 변환 하여 전달
}
}
// 일정시간 && 일정거리 변화 할시 호출 되는 콜백 메서드
@Override
public void onLocationChanged(Location location) {
Log.i("진입 위치 변화", "변화");
currentPosition = new LatLng(location.getLatitude(), location.getLongitude());
String errorMessage = "";
if (current_marker != null)
current_marker.remove();
//현재 위치에 마커 생성
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("현재위치");
current_marker = googleMap.addMarker(markerOptions);
//지도 상에서 보여주는 영역 이동
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(13));
googleMap.getUiSettings().setCompassEnabled(true);
// 지오코더 주소로 변환
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(
location.getLatitude(),
location.getLongitude(),
1);
} catch (IOException ioException) {
errorMessage = "지오코더 서비스 사용불가";
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
} catch (IllegalArgumentException illegalArgumentException) {
errorMessage = "잘못된 GPS 좌표";
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
if (addresses == null || addresses.size() == 0) {
if (errorMessage.isEmpty())
errorMessage = "주소 미발견";
;
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
} else {
Address address = addresses.get(0);
Toast.makeText(this, address.getAddressLine(0), Toast.LENGTH_LONG).show();
}
}
@Override
public void onPlacesFailure(PlacesException e) {
Log.i("진입 PlacesFailure", "onPlacesFailure()");
}
@Override
public void onPlacesStart() {
Log.i("진입 PlacesStart", "onPlacesStart()");
}
// 장소에대한 검색이 성공적으로 이뤄지면 여러장소 마커 띄우기 위한 콜백 메서드
@Override
public void onPlacesSuccess(final List<noman.googleplaces.Place> places) {
Log.i("진입 PlacesSuccess", "onPlacesSuccess()");
runOnUiThread(new Runnable() {
@Override
public void run() {
for (noman.googleplaces.Place place : places) {
LatLng latLng = new LatLng(place.getLatitude(),
place.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(place.getName());
Marker item = googleMap.addMarker(markerOptions);
previous_marker.add(item);
}
// 중복 마커 제거
HashSet<Marker> hashSet = new HashSet<Marker>();
hashSet.addAll(previous_marker);
previous_marker.clear();
previous_marker.addAll(hashSet);
}
});
}
@Override
public void onPlacesFinished() {
Log.i("진입 PlacesFinished", "onPlacesFinished()");
}
}
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.http;
import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.jdisc.http.ServerConfig;
import com.yahoo.vespa.model.container.xml.ContainerModelBuilder;
import org.junit.Test;
import org.w3c.dom.Element;
import static org.junit.Assert.assertTrue;
/**
* @author bjorncs
*/
public class StrictFilteringTest extends DomBuilderTest {
@Test
public void default_request_and_response_filters_in_services_xml_are_listen_in_server_config() {
Element xml = parse(
"<container version='1.0'>",
" <http>",
" <filtering strict-mode=\"true\">",
" <request-chain id='request-chain-with-binding'>",
" <filter id='my-filter' class='MyFilter'/>",
" <binding>http://*/my-chain-binding</binding>",
" </request-chain>",
" </filtering>",
" <server id='server1' port='8000' />",
" </http>",
"</container>");
buildContainerCluster(xml);
ServerConfig config = root.getConfig(ServerConfig.class, "container/http/jdisc-jetty/server1");
assertTrue(config.strictFiltering());
}
private void buildContainerCluster(Element containerElem) {
new ContainerModelBuilder(true, ContainerModelBuilder.Networking.enable).build(DeployState.createTestState(), null, null, root, containerElem);
root.freezeModelTopology();
}
}
|
/*
* Copyright 2000-2017 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.java.psi.formatter.java;
import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.util.IncorrectOperationException;
/**
* Is intended to hold java formatting indentation-specific tests.
*
* @author Denis Zhdanov
*/
public class JavaFormatterIndentationTest extends AbstractJavaFormatterTest {
public void testClassInitializationBlockIndentation() {
// Checking that initialization block body is correctly indented.
doMethodTest(
"checking(new Expectations() {{\n" +
"one(tabConfiguration).addFilter(with(equal(PROPERTY)), with(aListContaining(\"a-c\")));\n" +
"}});",
"checking(new Expectations() {{\n" +
" one(tabConfiguration).addFilter(with(equal(PROPERTY)), with(aListContaining(\"a-c\")));\n" +
"}});"
);
// Checking that closing curly brace of initialization block that is not the first block on a line is correctly indented.
doTextTest("class Class {\n" + " private Type field; {\n" + " }\n" + "}",
"class Class {\n" + " private Type field;\n\n {\n" + " }\n" + "}");
doTextTest(
"class T {\n" +
" private final DecimalFormat fmt = new DecimalFormat(); {\n" +
" fmt.setGroupingUsed(false);\n" +
" fmt.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));\n" +
" }\n" +
"}",
"class T {\n" +
" private final DecimalFormat fmt = new DecimalFormat();\n\n {\n" +
" fmt.setGroupingUsed(false);\n" +
" fmt.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));\n" +
" }\n" +
"}"
);
}
public void testNestedMethodsIndentation() {
// Inspired by IDEA-43962
getSettings().getRootSettings().getIndentOptions(JavaFileType.INSTANCE).CONTINUATION_INDENT_SIZE = 4;
doMethodTest(
"BigDecimal.ONE\n" +
" .add(BigDecimal.ONE\n" +
" .add(BigDecimal.ONE\n" +
" .add(BigDecimal.ONE\n" +
" .add(BigDecimal.ONE\n" +
".add(BigDecimal.ONE\n" +
" .add(BigDecimal.ONE\n" +
" .add(BigDecimal.ONE\n" +
" .add(BigDecimal.ONE\n" +
" .add(BigDecimal.ONE)))))))));",
"BigDecimal.ONE\n" +
" .add(BigDecimal.ONE\n" +
" .add(BigDecimal.ONE\n" +
" .add(BigDecimal.ONE\n" +
" .add(BigDecimal.ONE\n" +
" .add(BigDecimal.ONE\n" +
" .add(BigDecimal.ONE\n" +
" .add(BigDecimal.ONE\n" +
" .add(BigDecimal.ONE\n" +
" .add(BigDecimal.ONE)))))))));"
);
}
public void testShiftedChainedIfElse() {
getSettings().BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED2;
getSettings().ELSE_ON_NEW_LINE = true;
getSettings().getRootSettings().getIndentOptions(JavaFileType.INSTANCE).INDENT_SIZE = 4;
doMethodTest(
"long a = System.currentTimeMillis();\n" +
" if (a == 0){\n" +
" }else if (a > 1){\n" +
" }else if (a > 2){\n" +
" }else if (a > 3){\n" +
" }else if (a > 4){\n" +
" }else if (a > 5){\n" +
" }else{\n" +
" }",
"long a = System.currentTimeMillis();\n" +
"if (a == 0)\n" +
" {\n" +
" }\n" +
"else if (a > 1)\n" +
" {\n" +
" }\n" +
"else if (a > 2)\n" +
" {\n" +
" }\n" +
"else if (a > 3)\n" +
" {\n" +
" }\n" +
"else if (a > 4)\n" +
" {\n" +
" }\n" +
"else if (a > 5)\n" +
" {\n" +
" }\n" +
"else\n" +
" {\n" +
" }"
);
}
public void testAlignedSubBlockIndentation() {
getSettings().ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true;
getSettings().getRootSettings().getIndentOptions(JavaFileType.INSTANCE).CONTINUATION_INDENT_SIZE = 8;
// Inspired by IDEA-54671
doTextTest(
"class Test {\n" +
" public void foo() {\n" +
" test(11\n" +
" + 12\n" +
" + 13,\n" +
" 21\n" +
" + 22\n" +
" + 23\n" +
" )" +
" }\n" +
"}",
"class Test {\n" +
" public void foo() {\n" +
" test(11\n" +
" + 12\n" +
" + 13,\n" +
" 21\n" +
" + 22\n" +
" + 23\n" +
" )\n" +
" }\n" +
"}"
);
}
public void testEnumIndentation() throws IncorrectOperationException {
// Inspired by IDEADEV-2840
doTextTest("enum Xyz {\n" + "FOO,\n" + "BAR,\n" + "}", "enum Xyz {\n" + " FOO,\n" + " BAR,\n" + "}");
}
public void testFirstColumnComment() throws IncorrectOperationException {
// Inspired by IDEADEV-14116
getSettings().KEEP_FIRST_COLUMN_COMMENT = false;
doTextTest("class Foo{\n" + "private int foo; // this is a foo\n" + "}",
"class Foo {\n" + " private int foo; // this is a foo\n" + "}");
}
public void testCaseFromSwitch() throws IncorrectOperationException {
// Inspired by IDEADEV-22920
getSettings().INDENT_CASE_FROM_SWITCH = false;
doTextTest(
"class Foo{\n" +
"void foo () {\n" +
"switch(someValue) {\n" +
" // This comment is correctly not-indented\n" +
" case 1:\n" +
" doSomething();\n" +
" break;\n" +
"\n" +
" // This comment should not be indented, but it is\n" +
" case 2:\n" +
" doSomethingElse();\n" +
" break;\n" +
"}\n" +
"}\n" +
"}",
"class Foo {\n" +
" void foo() {\n" +
" switch (someValue) {\n" +
" // This comment is correctly not-indented\n" +
" case 1:\n" +
" doSomething();\n" +
" break;\n" +
"\n" +
" // This comment should not be indented, but it is\n" +
" case 2:\n" +
" doSomethingElse();\n" +
" break;\n" +
" }\n" +
" }\n" +
"}");
}
public void testBinaryExpressionsWithRelativeIndents() {
// Inspired by IDEA-21795
getIndentOptions().USE_RELATIVE_INDENTS = true;
getIndentOptions().CONTINUATION_INDENT_SIZE = 4;
doTextTest(
"public class FormattingTest {\n" +
"\n" +
" public boolean test1(int a, int b, int c, int d) {\n" +
" return a == 1 &&\n" +
" b == 2;\n" +
" }\n" +
"\n" +
" public boolean multilineSignOnCurrent(int a, int b, int c, int d) {\n" +
" return a == 0 &&\n" +
" (b == 0 ||\n" +
" c == 0) &&\n" +
" d == 0;\n" +
" }\n" +
"\n" +
" public boolean multilineSignOnNext(int a, int b, int c, int d) {\n" +
" return a == 0\n" +
" && (b == 0\n" +
" || c == 0)\n" +
" && d == 0;\n" +
" }\n" +
"\n" +
" public boolean expectedMultilineSignOnNext(int a, int b, int c, int d) {\n" +
" return a == 0\n" +
" && (b == 0\n" +
" || c == 0)\n" +
" && d == 0;\n" +
" }\n" +
"}",
"public class FormattingTest {\n" +
"\n" +
" public boolean test1(int a, int b, int c, int d) {\n" +
" return a == 1 &&\n" +
" b == 2;\n" +
" }\n" +
"\n" +
" public boolean multilineSignOnCurrent(int a, int b, int c, int d) {\n" +
" return a == 0 &&\n" +
" (b == 0 ||\n" +
" c == 0) &&\n" +
" d == 0;\n" +
" }\n" +
"\n" +
" public boolean multilineSignOnNext(int a, int b, int c, int d) {\n" +
" return a == 0\n" +
" && (b == 0\n" +
" || c == 0)\n" +
" && d == 0;\n" +
" }\n" +
"\n" +
" public boolean expectedMultilineSignOnNext(int a, int b, int c, int d) {\n" +
" return a == 0\n" +
" && (b == 0\n" +
" || c == 0)\n" +
" && d == 0;\n" +
" }\n" +
"}"
);
}
public void testBracesShiftedOnNextLineOnMethodWithJavadoc() {
// Inspired by IDEA-62997
getSettings().METHOD_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE_SHIFTED;
String precededByJavadoc =
"/**\n" +
" * test\n" +
" */\n" +
"public int getFoo()\n" +
" {\n" +
" return foo;\n" +
" }";
String precededBySingleLineComment =
"// test\n" +
"public int getFoo()\n" +
" {\n" +
" return foo;\n" +
" }";
String precededByMultiLineComment =
"/*\n" +
"test\n" +
"*/\n" +
"public int getFoo()\n" +
" {\n" +
" return foo;\n" +
" }";
doClassTest(precededByJavadoc, precededByJavadoc);
doClassTest(precededBySingleLineComment, precededBySingleLineComment);
doClassTest(precededByMultiLineComment, precededByMultiLineComment);
}
public void testAnonymousClassInstancesAsMethodCallArguments() {
// Inspired by IDEA-65987
doMethodTest(
"foo(\"long string as the first argument\", new Runnable() {\n" +
"public void run() { \n" +
"} \n" +
"}, \n" +
"new Runnable() { \n" +
"public void run() { \n" +
"} \n" +
"} \n" +
"); ",
"foo(\"long string as the first argument\", new Runnable() {\n" +
" public void run() {\n" +
" }\n" +
" },\n" +
" new Runnable() {\n" +
" public void run() {\n" +
" }\n" +
" }\n" +
");"
);
doMethodTest(
"foo(1,\n" +
"2, new Runnable() {\n" +
"@Override\n" +
"public void run() {\n" +
"}\n" +
"});",
"foo(1,\n" +
" 2, new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" }\n" +
" });"
);
doMethodTest(
"foo(new Runnable() {\n" +
"@Override\n" +
"public void run() {\n" +
"}\n" +
"},\n" +
"new Runnable() {\n" +
"@Override\n" +
"public void run() {\n" +
"}\n" +
"});",
"foo(new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" }\n" +
" },\n" +
" new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" }\n" +
" });"
);
}
public void testAnonymousClassInstancesAsAlignedMethodCallArguments() {
getSettings().ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true;
doMethodTest(
"foo(new Runnable() {\n" +
"@Override\n" +
"public void run() {\n" +
"}\n" +
"},\n" +
"new Runnable() {\n" +
"@Override\n" +
"public void run() {\n" +
"}\n" +
"});",
"foo(new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" }\n" +
" },\n" +
" new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" }\n" +
" });"
);
doMethodTest(
"foo(123456789, new Runnable() {\n" +
"@Override\n" +
"public void run() {\n" +
"}\n" +
"},\n" +
"new Runnable() {\n" +
"@Override\n" +
"public void run() {\n" +
"}\n" +
"});",
"foo(123456789, new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" }\n" +
" },\n" +
" new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" }\n" +
" });"
);
doMethodTest(
"foo(new Runnable() {\n" +
"@Override\n" +
"public void run() {\n" +
"}" +
"}, 1, 2);",
"foo(new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" }\n" +
"}, 1, 2);"
);
}
public void testAnonymousClassesOnSameLineAtMethodCallExpression() {
doMethodTest(
"foo(new Runnable() {\n" +
" public void run() {\n" +
" }\n" +
" }, new Runnable() {\n" +
" public void run() {\n" +
" }\n" +
" });",
"foo(new Runnable() {\n" +
" public void run() {\n" +
" }\n" +
"}, new Runnable() {\n" +
" public void run() {\n" +
" }\n" +
"});"
);
}
public void testAlignMultipleAnonymousClasses_PassedAsMethodParameters() {
String text = "test(new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" System.out.println(\"AAA!\");\n" +
" }\n" +
"}, new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" System.out.println(\"BBB!\");\n" +
" }\n" +
"});\n";
doMethodTest(text, text);
}
public void testAlignmentAdditionalParamsWithMultipleAnonymousClasses_PassedAsMethodParameters() {
String text = "foo(1221, new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" System.out.println(\"A\");\n" +
" }\n" +
"}, new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" System.out.println(\"BB\");\n" +
" }\n" +
"});";
doMethodTest(text, text);
}
public void testAlignmentMultipleParamsWithAnonymousClass_PassedAsMethodParams() {
getSettings().ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true;
String text = "test(1000,\n" +
" new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" System.out.println(\"BBB\");\n" +
" }\n" +
" }\n" +
");";
doMethodTest(text, text);
}
public void testAlignmentMultipleAnonymousClassesOnNewLines() {
getSettings().ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true;
String text = "test(1000,\n" +
" new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" System.out.println(\"BBB\");\n" +
" }\n" +
" },\n" +
" new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
" System.out.println(\"BBB\");\n" +
" }\n" +
" }\n" +
");";
doMethodTest(text, text);
}
public void testEnforceChildrenIndent_OfAnonymousClasses_IfAnyOfParamsIsLocatedOnNewLine() {
getSettings().ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true;
String text = "test(\"Suuuuuuuuuuuuuuuuuper loooooooooooong string\",\n" +
" \"Next loooooooooooooooooooooong striiiiiiiiiiing\", new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
"\n" +
" }\n" +
" }, new Runnable() {\n" +
" @Override\n" +
" public void run() {\n" +
"\n" +
" }\n" +
" }\n" +
");\n";
doMethodTest(text, text);
}
public void testPackagePrivateAnnotation() {
// Inspired by IDEA-67294
String text =
"@Retention(RUNTIME)\n" +
"@Target({FIELD, PARAMETER, METHOD})\n" +
"@interface MyAnnotation {\n" +
"\n" +
"}";
doTextTest(text, text);
}
public void testIncompleteMethodCall() {
// Inspired by IDEA-79836.
doMethodTest(
"test(new Runnable() {\n" +
" public void run() {\n" +
" }\n" +
" }, new Runnable() {\n" +
" public void run() {\n" +
" }\n" +
" }, )",
"test(new Runnable() {\n" +
" public void run() {\n" +
" }\n" +
"}, new Runnable() {\n" +
" public void run() {\n" +
" }\n" +
"}, )"
);
}
public void testCStyleCommentIsNotMoved() {
// IDEA-87087
doClassTest(
" /*\n" +
" this is a c-style comment\n" +
" */\n" +
" // This is a line comment",
" /*\n" +
" this is a c-style comment\n" +
" */\n" +
"// This is a line comment"
);
}
public void testMultilineCommentAtFileStart() {
// IDEA-90860
String text =
"\n" +
"/*\n" +
" * comment\n" +
" */\n" +
"\n" +
"class Test {\n" +
"}";
doTextTest(text, text);
}
public void testMultilineCommentAndTabsIndent() {
// IDEA-91703
String initial =
"\t/*\n" +
"\t\t* comment\n" +
"\t */\n" +
"class Test {\n" +
"}";
String expected =
"/*\n" +
" * comment\n" +
" */\n" +
"class Test {\n" +
"}";
getIndentOptions().USE_TAB_CHARACTER = true;
doTextTest(initial, expected);
}
public void testLambdaIndentation() {
String before = "Runnable r = () ->\n" +
"{\n" +
" System.out.println(\"olo\");\n" +
"};";
doMethodTest(before, before);
}
public void testAnnotatedParameters() {
String before = "public class Formatting {\n" +
" @RequestMapping(value = \"/\", method = GET)\n" +
" public HttpEntity<String> helloWorld(@RequestParam(\"name\") String name, @PageableDefault(page = 0, size = 10)\n" +
" Pageable pageable) {\n" +
" // I'd expect the line above to be indented by 4 spaces\n" +
" return ResponseEntity.ok(\"Hello \" + name);\n" +
" }\n" +
"}";
String after = "public class Formatting {\n" +
" @RequestMapping(value = \"/\", method = GET)\n" +
" public HttpEntity<String> helloWorld(@RequestParam(\"name\") String name, @PageableDefault(page = 0, size = 10)\n" +
" Pageable pageable) {\n" +
" // I'd expect the line above to be indented by 4 spaces\n" +
" return ResponseEntity.ok(\"Hello \" + name);\n" +
" }\n" +
"}";
doTextTest(before, after);
}
public void testTextBlock() {
String before = "class Formatting {\n" +
" void test() {\n" +
" String block = \"\"\"\n" +
" \n" +
" text\n" +
"block\"\"\";\n" +
" " +
" }\n" +
"}";
String after = "class Formatting {\n" +
" void test() {\n" +
" String block = \"\"\"\n" +
" \n" +
" text\n" +
" block\"\"\";\n" +
" " +
"}\n" +
"}";
doTextTest(before, after);
}
}
|
// Template Source: BaseEntityRequest.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.models.WorkbookRange;
import com.microsoft.graph.models.WorkbookRangeView;
import com.microsoft.graph.requests.WorkbookRangeFormatRequestBuilder;
import com.microsoft.graph.requests.WorkbookRangeSortRequestBuilder;
import com.microsoft.graph.requests.WorkbookWorksheetRequestBuilder;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseRequest;
import com.microsoft.graph.http.HttpMethod;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Workbook Range Request.
*/
public class WorkbookRangeRequest extends BaseRequest<WorkbookRange> {
/**
* The request for the WorkbookRange
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public WorkbookRangeRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions, WorkbookRange.class);
}
/**
* Gets the WorkbookRange from the service
*
* @return a future with the result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<WorkbookRange> getAsync() {
return sendAsync(HttpMethod.GET, null);
}
/**
* Gets the WorkbookRange from the service
*
* @return the WorkbookRange from the request
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
@Nullable
public WorkbookRange get() throws ClientException {
return send(HttpMethod.GET, null);
}
/**
* Delete this item from the service
*
* @return a future with the deletion result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<WorkbookRange> deleteAsync() {
return sendAsync(HttpMethod.DELETE, null);
}
/**
* Delete this item from the service
* @return the resulting response if the service returns anything on deletion
*
* @throws ClientException if there was an exception during the delete operation
*/
@Nullable
public WorkbookRange delete() throws ClientException {
return send(HttpMethod.DELETE, null);
}
/**
* Patches this WorkbookRange with a source
*
* @param sourceWorkbookRange the source object with updates
* @return a future with the result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<WorkbookRange> patchAsync(@Nonnull final WorkbookRange sourceWorkbookRange) {
return sendAsync(HttpMethod.PATCH, sourceWorkbookRange);
}
/**
* Patches this WorkbookRange with a source
*
* @param sourceWorkbookRange the source object with updates
* @return the updated WorkbookRange
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
@Nullable
public WorkbookRange patch(@Nonnull final WorkbookRange sourceWorkbookRange) throws ClientException {
return send(HttpMethod.PATCH, sourceWorkbookRange);
}
/**
* Creates a WorkbookRange with a new object
*
* @param newWorkbookRange the new object to create
* @return a future with the result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<WorkbookRange> postAsync(@Nonnull final WorkbookRange newWorkbookRange) {
return sendAsync(HttpMethod.POST, newWorkbookRange);
}
/**
* Creates a WorkbookRange with a new object
*
* @param newWorkbookRange the new object to create
* @return the created WorkbookRange
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
@Nullable
public WorkbookRange post(@Nonnull final WorkbookRange newWorkbookRange) throws ClientException {
return send(HttpMethod.POST, newWorkbookRange);
}
/**
* Creates a WorkbookRange with a new object
*
* @param newWorkbookRange the object to create/update
* @return a future with the result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<WorkbookRange> putAsync(@Nonnull final WorkbookRange newWorkbookRange) {
return sendAsync(HttpMethod.PUT, newWorkbookRange);
}
/**
* Creates a WorkbookRange with a new object
*
* @param newWorkbookRange the object to create/update
* @return the created WorkbookRange
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
@Nullable
public WorkbookRange put(@Nonnull final WorkbookRange newWorkbookRange) throws ClientException {
return send(HttpMethod.PUT, newWorkbookRange);
}
/**
* Sets the select clause for the request
*
* @param value the select clause
* @return the updated request
*/
@Nonnull
public WorkbookRangeRequest select(@Nonnull final String value) {
addSelectOption(value);
return this;
}
/**
* Sets the expand clause for the request
*
* @param value the expand clause
* @return the updated request
*/
@Nonnull
public WorkbookRangeRequest expand(@Nonnull final String value) {
addExpandOption(value);
return this;
}
}
|
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package javafx.beans.binding;
import javafx.beans.value.ObservableLongValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import com.sun.javafx.collections.annotations.ReturnsUnmodifiableCollection;
import javafx.beans.value.ObservableValue;
/**
* A {@code LongExpression} is a {@link javafx.beans.value.ObservableLongValue}
* plus additional convenience methods to generate bindings in a fluent style.
* <p>
* A concrete sub-class of {@code LongExpression} has to implement the method
* {@link javafx.beans.value.ObservableLongValue#get()}, which provides the
* actual value of this expression.
* @since JavaFX 2.0
*/
public abstract class LongExpression extends NumberExpressionBase implements
ObservableLongValue {
@Override
public int intValue() {
return (int) get();
}
@Override
public long longValue() {
return get();
}
@Override
public float floatValue() {
return (float) get();
}
@Override
public double doubleValue() {
return (double) get();
}
@Override
public Long getValue() {
return get();
}
/**
* Returns a {@code LongExpression} that wraps a
* {@link javafx.beans.value.ObservableLongValue}. If the
* {@code ObservableLongValue} is already a {@code LongExpression}, it will
* be returned. Otherwise a new {@link javafx.beans.binding.LongBinding} is
* created that is bound to the {@code ObservableLongValue}.
*
* @param value
* The source {@code ObservableLongValue}
* @return A {@code LongExpression} that wraps the
* {@code ObservableLongValue} if necessary
* @throws NullPointerException
* if {@code value} is {@code null}
*/
public static LongExpression longExpression(final ObservableLongValue value) {
if (value == null) {
throw new NullPointerException("Value must be specified.");
}
return (value instanceof LongExpression) ? (LongExpression) value
: new LongBinding() {
{
super.bind(value);
}
@Override
public void dispose() {
super.unbind(value);
}
@Override
protected long computeValue() {
return value.get();
}
@Override
@ReturnsUnmodifiableCollection
public ObservableList<ObservableLongValue> getDependencies() {
return FXCollections.singletonObservableList(value);
}
};
}
/**
* Returns a {@code LongExpression} that wraps an
* {@link javafx.beans.value.ObservableValue}. If the
* {@code ObservableValue} is already a {@code LongExpression}, it
* will be returned. Otherwise a new
* {@link javafx.beans.binding.LongBinding} is created that is bound to
* the {@code ObservableValue}.
*
* <p>
* Note: this method can be used to convert an {@link ObjectExpression} or
* {@link javafx.beans.property.ObjectProperty} of specific number type to LongExpression, which
* is essentially an {@code ObservableValue<Number>}. See sample below.
*
* <blockquote><pre>
* LongProperty longProperty = new SimpleLongProperty(1L);
* ObjectProperty<Long> objectProperty = new SimpleObjectProperty<>(2L);
* BooleanBinding binding = longProperty.greaterThan(LongExpression.longExpression(objectProperty));
* </pre></blockquote>
*
* Note: null values will be interpreted as 0L
*
* @param value
* The source {@code ObservableValue}
* @return A {@code LongExpression} that wraps the
* {@code ObservableValue} if necessary
* @throws NullPointerException
* if {@code value} is {@code null}
* @since JavaFX 8.0
*/
public static <T extends Number> LongExpression longExpression(final ObservableValue<T> value) {
if (value == null) {
throw new NullPointerException("Value must be specified.");
}
return (value instanceof LongExpression) ? (LongExpression) value
: new LongBinding() {
{
super.bind(value);
}
@Override
public void dispose() {
super.unbind(value);
}
@Override
protected long computeValue() {
final T val = value.getValue();
return val == null ? 0L : val.longValue();
}
@Override
@ReturnsUnmodifiableCollection
public ObservableList<ObservableValue<T>> getDependencies() {
return FXCollections.singletonObservableList(value);
}
};
}
@Override
public LongBinding negate() {
return (LongBinding) Bindings.negate(this);
}
@Override
public DoubleBinding add(final double other) {
return Bindings.add(this, other);
}
@Override
public FloatBinding add(final float other) {
return (FloatBinding) Bindings.add(this, other);
}
@Override
public LongBinding add(final long other) {
return (LongBinding) Bindings.add(this, other);
}
@Override
public LongBinding add(final int other) {
return (LongBinding) Bindings.add(this, other);
}
@Override
public DoubleBinding subtract(final double other) {
return Bindings.subtract(this, other);
}
@Override
public FloatBinding subtract(final float other) {
return (FloatBinding) Bindings.subtract(this, other);
}
@Override
public LongBinding subtract(final long other) {
return (LongBinding) Bindings.subtract(this, other);
}
@Override
public LongBinding subtract(final int other) {
return (LongBinding) Bindings.subtract(this, other);
}
@Override
public DoubleBinding multiply(final double other) {
return Bindings.multiply(this, other);
}
@Override
public FloatBinding multiply(final float other) {
return (FloatBinding) Bindings.multiply(this, other);
}
@Override
public LongBinding multiply(final long other) {
return (LongBinding) Bindings.multiply(this, other);
}
@Override
public LongBinding multiply(final int other) {
return (LongBinding) Bindings.multiply(this, other);
}
@Override
public DoubleBinding divide(final double other) {
return Bindings.divide(this, other);
}
@Override
public FloatBinding divide(final float other) {
return (FloatBinding) Bindings.divide(this, other);
}
@Override
public LongBinding divide(final long other) {
return (LongBinding) Bindings.divide(this, other);
}
@Override
public LongBinding divide(final int other) {
return (LongBinding) Bindings.divide(this, other);
}
/**
* Creates an {@link javafx.beans.binding.ObjectExpression} that holds the value
* of this {@code LongExpression}. If the
* value of this {@code LongExpression} changes, the value of the
* {@code ObjectExpression} will be updated automatically.
*
* @return the new {@code ObjectExpression}
* @since JavaFX 8.0
*/
public ObjectExpression<Long> asObject() {
return new ObjectBinding<Long>() {
{
bind(LongExpression.this);
}
@Override
public void dispose() {
unbind(LongExpression.this);
}
@Override
protected Long computeValue() {
return LongExpression.this.getValue();
}
};
}
}
|
package com.mimose.component.deduplicate.constants;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author mimose
* @description constant class
* @date 2021/3/25
*/
public final class Constant {
public static final String LINE_SEPARATOR = "-";
public static final String DEDUPLICATE_TOKEN_HEADER = "deduplicateToken";
public static final Integer ZERO = 0;
public static final String EMPTY_STR = "";
public static final Map EMPTY_MAP = Collections.emptyMap();
public static final List EMPTY_LIST = Collections.emptyList();
public static final Set EMPTY_SET= Collections.emptySet();
}
|
/*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.ballerina.stdlib.graphql.runtime.schema;
import io.ballerina.runtime.api.TypeTags;
import io.ballerina.runtime.api.creators.ValueCreator;
import io.ballerina.runtime.api.types.ArrayType;
import io.ballerina.runtime.api.types.Field;
import io.ballerina.runtime.api.types.MapType;
import io.ballerina.runtime.api.types.MethodType;
import io.ballerina.runtime.api.types.Parameter;
import io.ballerina.runtime.api.types.RecordType;
import io.ballerina.runtime.api.types.RemoteMethodType;
import io.ballerina.runtime.api.types.ResourceMethodType;
import io.ballerina.runtime.api.types.ServiceType;
import io.ballerina.runtime.api.types.TableType;
import io.ballerina.runtime.api.types.Type;
import io.ballerina.runtime.api.types.UnionType;
import io.ballerina.stdlib.graphql.runtime.schema.types.SchemaType;
import io.ballerina.stdlib.graphql.runtime.schema.types.TypeKind;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.MUTATION;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.QUERY;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.SCHEMA_RECORD;
import static io.ballerina.stdlib.graphql.runtime.schema.Utils.getEffectiveType;
import static io.ballerina.stdlib.graphql.runtime.schema.Utils.getMemberTypes;
import static io.ballerina.stdlib.graphql.runtime.schema.Utils.getScalarTypeName;
import static io.ballerina.stdlib.graphql.runtime.schema.Utils.getTypeName;
import static io.ballerina.stdlib.graphql.runtime.schema.Utils.getTypeNameFromType;
import static io.ballerina.stdlib.graphql.runtime.schema.Utils.isEnum;
import static io.ballerina.stdlib.graphql.runtime.utils.ModuleUtils.getModule;
import static io.ballerina.stdlib.graphql.runtime.utils.Utils.ERROR_TYPE;
import static io.ballerina.stdlib.graphql.runtime.utils.Utils.UPLOAD;
import static io.ballerina.stdlib.graphql.runtime.utils.Utils.createError;
import static io.ballerina.stdlib.graphql.runtime.utils.Utils.isContext;
import static io.ballerina.stdlib.graphql.runtime.utils.Utils.isFileUpload;
import static io.ballerina.stdlib.graphql.runtime.utils.Utils.removeFirstElementFromArray;
/**
* Finds types used in a Ballerina GraphQL service to Generate the Schema.
*/
public class TypeFinder {
private final ServiceType serviceType;
Map<String, SchemaType> typeMap;
public TypeFinder(ServiceType serviceType) {
this.serviceType = serviceType;
this.typeMap = new HashMap<>();
}
public Map<String, SchemaType> getTypeMap() {
return this.typeMap;
}
public void populateTypes() {
this.createTypesFromRootService();
this.getDefaultTypes();
}
private void getDefaultTypes() {
Type schemaRecordType = ValueCreator.createRecordValue(getModule(), SCHEMA_RECORD).getType();
getSchemaTypeFromBalType(schemaRecordType);
}
private void createTypesFromRootService() {
this.createSchemaType(QUERY, TypeKind.OBJECT, serviceType);
for (ResourceMethodType resourceMethod : this.serviceType.getResourceMethods()) {
getTypesFromResourceMethod(resourceMethod, resourceMethod.getResourcePath());
}
if (this.serviceType.getRemoteMethods().length > 0) {
this.createSchemaType(MUTATION, TypeKind.OBJECT, serviceType);
for (RemoteMethodType remoteMethod : serviceType.getRemoteMethods()) {
getTypesFromRemoteMethod(remoteMethod);
}
}
}
private void getTypesFromService(String name, ServiceType serviceType) {
this.createSchemaType(name, TypeKind.OBJECT, serviceType);
for (ResourceMethodType resourceMethod : serviceType.getResourceMethods()) {
getTypesFromResourceMethod(resourceMethod, resourceMethod.getResourcePath());
}
}
private void getTypesFromResourceMethod(ResourceMethodType resourceMethod, String[] resourcePath) {
if (resourcePath.length > 1) {
getTypesFromHierarchicalResource(resourceMethod, resourcePath);
} else {
getInputTypesFromMethod(resourceMethod);
getSchemaTypeFromBalType(resourceMethod.getType().getReturnType());
}
}
private void getTypesFromRemoteMethod(RemoteMethodType remoteMethod) {
getInputTypesFromMethod(remoteMethod);
getSchemaTypeFromBalType(remoteMethod.getType().getReturnType());
}
private void getTypesFromHierarchicalResource(ResourceMethodType resourceMethod, String[] resourcePath) {
String name = resourcePath[0];
this.createSchemaType(name, TypeKind.OBJECT, resourceMethod);
String[] remainingPaths = removeFirstElementFromArray(resourcePath);
this.getTypesFromResourceMethod(resourceMethod, remainingPaths);
}
private void getInputTypesFromMethod(MethodType methodType) {
for (Parameter parameter : methodType.getParameters()) {
getInputTypeFromType(parameter.type);
}
}
private void getInputTypeFromType(Type type) {
if (this.typeMap.containsKey(type.getName())) {
return;
}
if (isFileUpload(type)) {
this.createSchemaType(UPLOAD, TypeKind.SCALAR, type);
} else if (type.getTag() == TypeTags.UNION_TAG) {
UnionType unionType = (UnionType) type;
String typeName = getTypeName(unionType);
if (isEnum(unionType)) {
this.createSchemaType(typeName, TypeKind.ENUM, unionType);
} else {
Type effectiveType = getMemberTypes(unionType).get(0);
getInputTypeFromType(effectiveType);
}
} else if (type.getTag() == TypeTags.RECORD_TYPE_TAG) {
RecordType recordType = (RecordType) type;
this.createSchemaType(recordType.getName(), TypeKind.INPUT_OBJECT, recordType);
for (Field field : recordType.getFields().values()) {
getInputTypeFromType(field.getFieldType());
}
} else if (type.getTag() == TypeTags.INTERSECTION_TAG) {
Type effectiveType = getEffectiveType(type);
getInputTypeFromType(effectiveType);
} else if (type.getTag() == TypeTags.ARRAY_TAG) {
ArrayType arrayType = (ArrayType) type;
getInputTypeFromType(arrayType.getElementType());
} else if (type.getTag() < TypeTags.JSON_TAG) {
getSchemaTypeFromBalType(type);
}
}
private void getSchemaTypeFromBalType(Type type) {
int tag = type.getTag();
if (this.typeMap.containsKey(type.getName())) {
return;
}
if (tag < TypeTags.JSON_TAG) {
String name = getScalarTypeName(tag);
this.createSchemaType(name, TypeKind.SCALAR, type);
} else if (tag == TypeTags.RECORD_TYPE_TAG) {
RecordType recordType = (RecordType) type;
this.createSchemaType(recordType.getName(), TypeKind.OBJECT, recordType);
for (Field field : recordType.getFields().values()) {
getSchemaTypeFromBalType(field.getFieldType());
}
} else if (tag == TypeTags.SERVICE_TAG) {
ServiceType serviceType = (ServiceType) type;
getTypesFromService(serviceType.getName(), serviceType);
} else if (tag == TypeTags.ARRAY_TAG) {
ArrayType arrayType = (ArrayType) type;
Type elementType = arrayType.getElementType();
getSchemaTypeFromBalType(elementType);
} else if (tag == TypeTags.TABLE_TAG) {
TableType tableType = (TableType) type;
Type constrainedType = tableType.getConstrainedType();
getSchemaTypeFromBalType(constrainedType);
} else if (tag == TypeTags.UNION_TAG) {
UnionType unionType = (UnionType) type;
getTypesFromUnionType(unionType);
} else if (tag == TypeTags.MAP_TAG) {
MapType mapType = (MapType) type;
Type constrainedType = mapType.getConstrainedType();
getSchemaTypeFromBalType(constrainedType);
} else if (tag == TypeTags.INTERSECTION_TAG) {
Type effectiveType = getEffectiveType(type);
getSchemaTypeFromBalType(effectiveType);
} else if (isContext(type)) {
// Do nothing
} else {
String message = "Unsupported type found in GraphQL service: " + type.getName();
throw createError(message, ERROR_TYPE);
}
}
private void getTypesFromUnionType(UnionType unionType) {
if (isEnum(unionType)) {
this.createSchemaType(getTypeNameFromType(unionType), TypeKind.ENUM, unionType);
} else {
List<Type> memberTypes = getMemberTypes(unionType);
if (memberTypes.size() > 1) {
String typeName = getTypeName(unionType);
this.createSchemaType(typeName, TypeKind.UNION, unionType);
}
for (Type type : memberTypes) {
getSchemaTypeFromBalType(type);
}
}
}
private void createSchemaType(String name, TypeKind typeKind, Type type) {
if (!this.typeMap.containsKey(name)) {
SchemaType schemaType = new SchemaType(name, typeKind, type);
this.typeMap.put(name, schemaType);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.