repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
sdgdsffdsfff/nutz
src/org/nutz/lang/util/MultiLineProperties.java
3986
package org.nutz.lang.util; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.nutz.lang.Strings; /** * 可支持直接书写多行文本的 Properties 文件 * * @author zozoh(zozohtnt@gmail.com) */ public class MultiLineProperties implements Map<String, String> { public MultiLineProperties(Reader reader) throws IOException { this(); load(reader); } public MultiLineProperties() { maps = new LinkedHashMap<String, String>(); } protected Map<String, String> maps; /** * <b>载入并销毁之前的记录</b> * * @param reader * @throws IOException */ public synchronized void load(Reader reader) throws IOException { load(reader, false); } public synchronized void load(Reader reader, boolean clear) throws IOException { if (clear) this.clear(); BufferedReader tr = null; if (reader instanceof BufferedReader) tr = (BufferedReader) reader; else tr = new BufferedReader(reader); String s; while (null != (s = tr.readLine())) { if (Strings.isBlank(s)) continue; if (s.length() > 0 && s.trim().charAt(0) == '#') // 只要第一个非空白字符是#,就认为是注释 continue; int pos; char c = '0'; for (pos = 0; pos < s.length(); pos++) { c = s.charAt(pos); if (c == '=' || c == ':') break; } if (c == '=') { String name = s.substring(0, pos); maps.put(Strings.trim(name), s.substring(pos + 1)); } else if (c == ':') { String name = s.substring(0, pos); StringBuffer sb = new StringBuffer(); sb.append(s.substring(pos + 1)); String ss; while (null != (ss = tr.readLine())) { if (ss.length() > 0 && ss.charAt(0) == '#') break; sb.append("\r\n" + ss); } maps.put(Strings.trim(name), sb.toString()); if (null == ss) return; } else { maps.put(Strings.trim(s), null); } } } public synchronized void clear() { maps.clear(); } public boolean containsKey(Object key) { return maps.containsKey(key); } public boolean containsValue(Object value) { return maps.containsValue(value); } public Set<Entry<String, String>> entrySet() { return maps.entrySet(); } @Override public boolean equals(Object o) { return maps.equals(o); } @Override public int hashCode() { return maps.hashCode(); } public boolean isEmpty() { return maps.isEmpty(); } public Set<String> keySet() { return maps.keySet(); } public List<String> keys() { return new ArrayList<String>(maps.keySet()); } public synchronized String put(String key, String value) { return maps.put(key, value); } @SuppressWarnings({"unchecked", "rawtypes"}) public synchronized void putAll(Map t) { maps.putAll(t); } public synchronized String remove(Object key) { return maps.remove(key); } public int size() { return maps.size(); } public Collection<String> values() { return maps.values(); } public String get(Object key) { return maps.get(key); } }
apache-2.0
congdepeng/java-guava-lib-demo
guava-libraries/guava-gwt/src-super/com/google/common/math/super/com/google/common/math/LongMath.java
12327
/* * Copyright (C) 2011 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.math; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.math.MathPreconditions.checkNonNegative; import static com.google.common.math.MathPreconditions.checkPositive; import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary; import static java.lang.Math.min; import static java.math.RoundingMode.HALF_EVEN; import static java.math.RoundingMode.HALF_UP; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; import java.math.RoundingMode; /** * A class for arithmetic on values of type {@code long}. Where possible, methods are defined and * named analogously to their {@code BigInteger} counterparts. * * <p>The implementations of many methods in this class are based on material from Henry S. Warren, * Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002). * * <p>Similar functionality for {@code int} and for {@link BigInteger} can be found in * {@link IntMath} and {@link BigIntegerMath} respectively. For other common operations on * {@code long} values, see {@link com.google.common.primitives.Longs}. * * @author Louis Wasserman * @since 11.0 */ @GwtCompatible(emulated = true) public final class LongMath { // NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, || /** * Returns {@code true} if {@code x} represents a power of two. * * <p>This differs from {@code Long.bitCount(x) == 1}, because * {@code Long.bitCount(Long.MIN_VALUE) == 1}, but {@link Long#MIN_VALUE} is not a power of two. */ public static boolean isPowerOfTwo(long x) { return x > 0 & (x & (x - 1)) == 0; } /** * Returns 1 if {@code x < y} as unsigned longs, and 0 otherwise. Assumes that x - y fits into a * signed long. The implementation is branch-free, and benchmarks suggest it is measurably * faster than the straightforward ternary expression. */ @VisibleForTesting static int lessThanBranchFree(long x, long y) { // Returns the sign bit of x - y. return (int) (~~(x - y) >>> (Long.SIZE - 1)); } /** * Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not a power of two */ @SuppressWarnings("fallthrough") // TODO(kevinb): remove after this warning is disabled globally public static int log2(long x, RoundingMode mode) { checkPositive("x", x); switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through case DOWN: case FLOOR: return (Long.SIZE - 1) - Long.numberOfLeadingZeros(x); case UP: case CEILING: return Long.SIZE - Long.numberOfLeadingZeros(x - 1); case HALF_DOWN: case HALF_UP: case HALF_EVEN: // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5 int leadingZeros = Long.numberOfLeadingZeros(x); long cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros; // floor(2^(logFloor + 0.5)) int logFloor = (Long.SIZE - 1) - leadingZeros; return logFloor + lessThanBranchFree(cmp, x); default: throw new AssertionError("impossible"); } } /** The biggest half power of two that fits into an unsigned long */ @VisibleForTesting static final long MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333F9DE6484L; // maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i))) @VisibleForTesting static final byte[] maxLog10ForLeadingZeros = { 19, 18, 18, 18, 18, 17, 17, 17, 16, 16, 16, 15, 15, 15, 15, 14, 14, 14, 13, 13, 13, 12, 12, 12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0 }; // halfPowersOf10[i] = largest long less than 10^(i + 0.5) /** * Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if * {@code a == 0 && b == 0}. * * @throws IllegalArgumentException if {@code a < 0} or {@code b < 0} */ public static long gcd(long a, long b) { /* * The reason we require both arguments to be >= 0 is because otherwise, what do you return on * gcd(0, Long.MIN_VALUE)? BigInteger.gcd would return positive 2^63, but positive 2^63 isn't * an int. */ checkNonNegative("a", a); checkNonNegative("b", b); if (a == 0) { // 0 % b == 0, so b divides a, but the converse doesn't hold. // BigInteger.gcd is consistent with this decision. return b; } else if (b == 0) { return a; // similar logic } /* * Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm. * This is >60% faster than the Euclidean algorithm in benchmarks. */ int aTwos = Long.numberOfTrailingZeros(a); a >>= aTwos; // divide out all 2s int bTwos = Long.numberOfTrailingZeros(b); b >>= bTwos; // divide out all 2s while (a != b) { // both a, b are odd // The key to the binary GCD algorithm is as follows: // Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b). // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two. // We bend over backwards to avoid branching, adapting a technique from // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax long delta = a - b; // can't overflow, since a and b are nonnegative long minDeltaOrZero = delta & (delta >> (Long.SIZE - 1)); // equivalent to Math.min(delta, 0) a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b) // a is now nonnegative and even b += minDeltaOrZero; // sets b to min(old a, b) a >>= Long.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b } return a << min(aTwos, bTwos); } @VisibleForTesting static final long FLOOR_SQRT_MAX_LONG = 3037000499L; static final long[] factorials = { 1L, 1L, 1L * 2, 1L * 2 * 3, 1L * 2 * 3 * 4, 1L * 2 * 3 * 4 * 5, 1L * 2 * 3 * 4 * 5 * 6, 1L * 2 * 3 * 4 * 5 * 6 * 7, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20 }; /** * Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and * {@code k}, or {@link Long#MAX_VALUE} if the result does not fit in a {@code long}. * * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n} */ public static long binomial(int n, int k) { checkNonNegative("n", n); checkNonNegative("k", k); checkArgument(k <= n, "k (%s) > n (%s)", k, n); if (k > (n >> 1)) { k = n - k; } switch (k) { case 0: return 1; case 1: return n; default: if (n < factorials.length) { return factorials[n] / (factorials[k] * factorials[n - k]); } else if (k >= biggestBinomials.length || n > biggestBinomials[k]) { return Long.MAX_VALUE; } else if (k < biggestSimpleBinomials.length && n <= biggestSimpleBinomials[k]) { // guaranteed not to overflow long result = n--; for (int i = 2; i <= k; n--, i++) { result *= n; result /= i; } return result; } else { int nBits = LongMath.log2(n, RoundingMode.CEILING); long result = 1; long numerator = n--; long denominator = 1; int numeratorBits = nBits; // This is an upper bound on log2(numerator, ceiling). /* * We want to do this in long math for speed, but want to avoid overflow. We adapt the * technique previously used by BigIntegerMath: maintain separate numerator and * denominator accumulators, multiplying the fraction into result when near overflow. */ for (int i = 2; i <= k; i++, n--) { if (numeratorBits + nBits < Long.SIZE - 1) { // It's definitely safe to multiply into numerator and denominator. numerator *= n; denominator *= i; numeratorBits += nBits; } else { // It might not be safe to multiply into numerator and denominator, // so multiply (numerator / denominator) into result. result = multiplyFraction(result, numerator, denominator); numerator = n; denominator = i; numeratorBits = nBits; } } return multiplyFraction(result, numerator, denominator); } } } /** * Returns (x * numerator / denominator), which is assumed to come out to an integral value. */ static long multiplyFraction(long x, long numerator, long denominator) { if (x == 1) { return numerator / denominator; } long commonDivisor = gcd(x, denominator); x /= commonDivisor; denominator /= commonDivisor; // We know gcd(x, denominator) = 1, and x * numerator / denominator is exact, // so denominator must be a divisor of numerator. return x * (numerator / denominator); } /* * binomial(biggestBinomials[k], k) fits in a long, but not * binomial(biggestBinomials[k] + 1, k). */ static final int[] biggestBinomials = {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 3810779, 121977, 16175, 4337, 1733, 887, 534, 361, 265, 206, 169, 143, 125, 111, 101, 94, 88, 83, 79, 76, 74, 72, 70, 69, 68, 67, 67, 66, 66, 66, 66}; /* * binomial(biggestSimpleBinomials[k], k) doesn't need to use the slower GCD-based impl, * but binomial(biggestSimpleBinomials[k] + 1, k) does. */ @VisibleForTesting static final int[] biggestSimpleBinomials = {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 2642246, 86251, 11724, 3218, 1313, 684, 419, 287, 214, 169, 139, 119, 105, 95, 87, 81, 76, 73, 70, 68, 66, 64, 63, 62, 62, 61, 61, 61}; // These values were generated by using checkedMultiply to see when the simple multiply/divide // algorithm would lead to an overflow. static boolean fitsInInt(long x) { return (int) x == x; } /** * Returns the arithmetic mean of {@code x} and {@code y}, rounded toward * negative infinity. This method is resilient to overflow. * * @since 14.0 */ public static long mean(long x, long y) { // Efficient method for computing the arithmetic mean. // The alternative (x + y) / 2 fails for large values. // The alternative (x + y) >>> 1 fails for negative values. return (x & y) + ((x ^ y) >> 1); } private LongMath() {} }
apache-2.0
smmribeiro/intellij-community
java/compiler/impl/src/com/intellij/packaging/impl/elements/LibraryElementType.java
3193
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.packaging.impl.elements; import com.intellij.openapi.compiler.JavaCompilerBundle; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; import com.intellij.packaging.artifacts.Artifact; import com.intellij.packaging.elements.ComplexPackagingElementType; import com.intellij.packaging.elements.CompositePackagingElement; import com.intellij.packaging.ui.ArtifactEditorContext; import com.intellij.util.PlatformIcons; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.ArrayList; import java.util.List; public class LibraryElementType extends ComplexPackagingElementType<LibraryPackagingElement> { public static final LibraryElementType LIBRARY_ELEMENT_TYPE = new LibraryElementType(); LibraryElementType() { super("library", JavaCompilerBundle.messagePointer("element.type.name.library.files")); } @Override public Icon getCreateElementIcon() { return PlatformIcons.LIBRARY_ICON; } @Override public boolean canCreate(@NotNull ArtifactEditorContext context, @NotNull Artifact artifact) { return !getAllLibraries(context).isEmpty(); } @Override @NotNull public List<? extends LibraryPackagingElement> chooseAndCreate(@NotNull ArtifactEditorContext context, @NotNull Artifact artifact, @NotNull CompositePackagingElement<?> parent) { final List<Library> selected = context.chooseLibraries(JavaCompilerBundle.message("dialog.title.packaging.choose.library")); final List<LibraryPackagingElement> elements = new ArrayList<>(); for (Library library : selected) { elements.add(new LibraryPackagingElement(library.getTable().getTableLevel(), library.getName(), null)); } return elements; } private static List<Library> getAllLibraries(ArtifactEditorContext context) { List<Library> libraries = new ArrayList<>(); ContainerUtil.addAll(libraries, LibraryTablesRegistrar.getInstance().getLibraryTable().getLibraries()); ContainerUtil.addAll(libraries, LibraryTablesRegistrar.getInstance().getLibraryTable(context.getProject()).getLibraries()); return libraries; } @Override @NotNull public LibraryPackagingElement createEmpty(@NotNull Project project) { return new LibraryPackagingElement(); } @Override public String getShowContentActionText() { return JavaCompilerBundle.message("show.library.files"); } }
apache-2.0
nishantmonu51/druid
indexing-service/src/main/java/org/apache/druid/indexing/common/actions/SegmentInsertAction.java
2825
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.indexing.common.actions; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.collect.ImmutableSet; import org.apache.druid.indexing.common.task.Task; import org.apache.druid.segment.SegmentUtils; import org.apache.druid.timeline.DataSegment; import java.util.Set; /** * Insert segments into metadata storage. The segment versions must all be less than or equal to a lock held by * your task for the segment intervals. * <p/> * Word of warning: Very large "segments" sets can cause oversized audit log entries, which is bad because it means * that the task cannot actually complete. Callers should avoid this by avoiding inserting too many segments in the * same action. */ public class SegmentInsertAction implements TaskAction<Set<DataSegment>> { private final Set<DataSegment> segments; @JsonCreator public SegmentInsertAction( @JsonProperty("segments") Set<DataSegment> segments ) { this.segments = ImmutableSet.copyOf(segments); } @JsonProperty public Set<DataSegment> getSegments() { return segments; } @Override public TypeReference<Set<DataSegment>> getReturnTypeReference() { return new TypeReference<Set<DataSegment>>() { }; } /** * Behaves similarly to * {@link org.apache.druid.indexing.overlord.IndexerMetadataStorageCoordinator#announceHistoricalSegments}, * with startMetadata and endMetadata both null. */ @Override public Set<DataSegment> perform(Task task, TaskActionToolbox toolbox) { return SegmentTransactionalInsertAction.appendAction(segments, null, null).perform(task, toolbox).getSegments(); } @Override public boolean isAudited() { return true; } @Override public String toString() { return "SegmentInsertAction{" + "segments=" + SegmentUtils.commaSeparatedIdentifiers(segments) + '}'; } }
apache-2.0
DavidBate/taokeeper
taokeeper-common/src/main/java/org/I0Itec/zkclient/ContentWatcher.java
2789
/** * Copyright 2010 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.I0Itec.zkclient; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.I0Itec.zkclient.exception.ZkNoNodeException; import org.apache.log4j.Logger; /** * @param <T> * The data type that is being watched. */ public final class ContentWatcher<T extends Object> implements IZkDataListener { private static final Logger LOG = Logger.getLogger(ContentWatcher.class); private Lock _contentLock = new ReentrantLock(true); private Condition _contentAvailable = _contentLock.newCondition(); private Holder<T> _content; private String _fileName; private ZkClient _zkClient; public ContentWatcher(ZkClient zkClient, String fileName) { _fileName = fileName; _zkClient = zkClient; } public void start() { _zkClient.subscribeDataChanges(_fileName, this); readData(); LOG.debug("Started ContentWatcher"); } @SuppressWarnings("unchecked") private void readData() { try { setContent((T) _zkClient.readData(_fileName)); } catch (ZkNoNodeException e) { // ignore if the node has not yet been created } } public void stop() { _zkClient.unsubscribeDataChanges(_fileName, this); } public void setContent(T data) { LOG.debug("Received new data: " + data); _contentLock.lock(); try { _content = new Holder<T>(data); _contentAvailable.signalAll(); } finally { _contentLock.unlock(); } } @SuppressWarnings("unchecked") @Override public void handleDataChange(String dataPath, Object data) { setContent((T) data); } @Override public void handleDataDeleted(String dataPath) { // ignore } public T getContent() throws InterruptedException { _contentLock.lock(); try { while (_content == null) { _contentAvailable.await(); } return _content.get(); } finally { _contentLock.unlock(); } } }
apache-2.0
minifirocks/nifi-minifi-cpp
thirdparty/rocksdb/java/src/main/java/org/rocksdb/util/Environment.java
2597
package org.rocksdb.util; public class Environment { private static String OS = System.getProperty("os.name").toLowerCase(); private static String ARCH = System.getProperty("os.arch").toLowerCase(); public static boolean isPowerPC() { return ARCH.contains("ppc"); } public static boolean isWindows() { return (OS.contains("win")); } public static boolean isMac() { return (OS.contains("mac")); } public static boolean isAix() { return OS.contains("aix"); } public static boolean isUnix() { return OS.contains("nix") || OS.contains("nux"); } public static boolean isSolaris() { return OS.contains("sunos"); } public static boolean is64Bit() { if (ARCH.indexOf("sparcv9") >= 0) { return true; } return (ARCH.indexOf("64") > 0); } public static String getSharedLibraryName(final String name) { return name + "jni"; } public static String getSharedLibraryFileName(final String name) { return appendLibOsSuffix("lib" + getSharedLibraryName(name), true); } public static String getJniLibraryName(final String name) { if (isUnix()) { final String arch = is64Bit() ? "64" : "32"; if(isPowerPC()) { return String.format("%sjni-linux-%s", name, ARCH); } else { return String.format("%sjni-linux%s", name, arch); } } else if (isMac()) { return String.format("%sjni-osx", name); } else if (isAix() && is64Bit()) { return String.format("%sjni-aix64", name); } else if (isSolaris()) { final String arch = is64Bit() ? "64" : "32"; return String.format("%sjni-solaris%s", name, arch); } else if (isWindows() && is64Bit()) { return String.format("%sjni-win64", name); } throw new UnsupportedOperationException(String.format("Cannot determine JNI library name for ARCH='%s' OS='%s' name='%s'", ARCH, OS, name)); } public static String getJniLibraryFileName(final String name) { return appendLibOsSuffix("lib" + getJniLibraryName(name), false); } private static String appendLibOsSuffix(final String libraryFileName, final boolean shared) { if (isUnix() || isAix() || isSolaris()) { return libraryFileName + ".so"; } else if (isMac()) { return libraryFileName + (shared ? ".dylib" : ".jnilib"); } else if (isWindows()) { return libraryFileName + ".dll"; } throw new UnsupportedOperationException(); } public static String getJniLibraryExtension() { if (isWindows()) { return ".dll"; } return (isMac()) ? ".jnilib" : ".so"; } }
apache-2.0
DevFactory/java-design-patterns
mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java
2258
/** * The MIT License * Copyright (c) 2014 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.mediator; import org.junit.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; /** * Date: 12/19/15 - 10:00 PM * * @author Jeroen Meulemeester */ public class PartyImplTest { /** * Verify if a member is notified when it's joining a party. Generate an action and see if the * other member gets it. Also check members don't get their own actions. */ @Test public void testPartyAction() { final PartyMember partyMember1 = mock(PartyMember.class); final PartyMember partyMember2 = mock(PartyMember.class); final PartyImpl party = new PartyImpl(); party.addMember(partyMember1); party.addMember(partyMember2); verify(partyMember1).joinedParty(party); verify(partyMember2).joinedParty(party); party.act(partyMember1, Action.GOLD); verifyZeroInteractions(partyMember1); verify(partyMember2).partyAction(Action.GOLD); verifyNoMoreInteractions(partyMember1, partyMember2); } }
mit
m-altieri/speedhouse
speedhouse/lib/jfreechart_src/org/jfree/chart/fx/interaction/ScrollHandlerFX.java
5041
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2014, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------- * ScrollHandlerFX.java * -------------------- * (C) Copyright 2014, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes: * -------- * 25-Jun-2014 : Version 1 (DG); * */ package org.jfree.chart.fx.interaction; import java.awt.geom.Point2D; import javafx.scene.input.ScrollEvent; import org.jfree.chart.ChartRenderingInfo; import org.jfree.chart.JFreeChart; import org.jfree.chart.fx.ChartCanvas; import org.jfree.chart.plot.PiePlot; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.Zoomable; /** * Handles scroll events (mouse wheel etc) on a {@link ChartCanvas}. * * <p>THE API FOR THIS CLASS IS SUBJECT TO CHANGE IN FUTURE RELEASES. This is * so that we can incorporate feedback on the (new) JavaFX support in * JFreeChart.</p> * * @since 1.0.18 */ public class ScrollHandlerFX extends AbstractMouseHandlerFX implements MouseHandlerFX { /** The zoom factor. */ private double zoomFactor = 0.1; /** * Creates a new instance with the specified ID. * * @param id the handler ID (<code>null</code> not permitted). */ public ScrollHandlerFX(String id) { super(id, false, false, false, false); this.zoomFactor = 0.1; }; /** * Returns the zoom factor. The default value is 0.10 (ten percent). * * @return The zoom factor. */ public double getZoomFactor() { return this.zoomFactor; } /** * Sets the zoom factor (a percentage amount by which the mouse wheel * movement will change the chart size). * * @param zoomFactor the zoom factor. */ public void setZoomFactor(double zoomFactor) { this.zoomFactor = zoomFactor; } @Override public void handleScroll(ChartCanvas canvas, ScrollEvent e) { JFreeChart chart = canvas.getChart(); Plot plot = chart.getPlot(); if (plot instanceof Zoomable) { Zoomable zoomable = (Zoomable) plot; handleZoomable(canvas, zoomable, e); } else if (plot instanceof PiePlot) { PiePlot pp = (PiePlot) plot; pp.handleMouseWheelRotation((int) e.getDeltaY()); } } /** * Handle the case where a plot implements the {@link Zoomable} interface. * * @param zoomable the zoomable plot. * @param e the mouse wheel event. */ private void handleZoomable(ChartCanvas canvas, Zoomable zoomable, ScrollEvent e) { // don't zoom unless the mouse pointer is in the plot's data area ChartRenderingInfo info = canvas.getRenderingInfo(); PlotRenderingInfo pinfo = info.getPlotInfo(); Point2D p = new Point2D.Double(e.getX(), e.getY()); if (pinfo.getDataArea().contains(p)) { Plot plot = (Plot) zoomable; // do not notify while zooming each axis boolean notifyState = plot.isNotify(); plot.setNotify(false); int clicks = (int) e.getDeltaY(); double zf = 1.0 + this.zoomFactor; if (clicks < 0) { zf = 1.0 / zf; } if (true) { //this.chartPanel.isDomainZoomable()) { zoomable.zoomDomainAxes(zf, pinfo, p, true); } if (true) { //this.chartPanel.isRangeZoomable()) { zoomable.zoomRangeAxes(zf, pinfo, p, true); } plot.setNotify(notifyState); // this generates the change event too } } }
mit
md-5/jdk10
test/jdk/javax/imageio/stream/StreamFlush.java
4104
/* * Copyright (c) 2001, 2017, 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 4414990 4415041 * @summary Checks that the output is flushed properly when using various * ImageOutputStreams and writers */ import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import javax.imageio.ImageIO; import javax.imageio.stream.ImageOutputStream; public class StreamFlush { public static void main(String[] args) throws IOException { ImageIO.setUseCache(true); // Create a FileImageOutputStream from a FileOutputStream File temp1 = File.createTempFile("imageio", ".tmp"); temp1.deleteOnExit(); ImageOutputStream fios = ImageIO.createImageOutputStream(temp1); // Create a FileCacheImageOutputStream from a BufferedOutputStream File temp2 = File.createTempFile("imageio", ".tmp"); temp2.deleteOnExit(); FileOutputStream fos2 = new FileOutputStream(temp2); BufferedOutputStream bos = new BufferedOutputStream(fos2); ImageOutputStream fcios1 = ImageIO.createImageOutputStream(bos); // Create a FileCacheImageOutputStream from a ByteArrayOutputStream ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageOutputStream fcios2 = ImageIO.createImageOutputStream(baos); BufferedImage bi = new BufferedImage(10, 10, BufferedImage.TYPE_3BYTE_BGR); ImageIO.write(bi, "jpg", fios); // No bug, check it anyway ImageIO.write(bi, "png", fcios1); // Bug 4414990 ImageIO.write(bi, "jpg", fcios2); // Bug 4415041 // It should not be necessary to flush any of the streams // If flushing does make a difference, it indicates a bug // in the writer or the stream implementation // Get length of temp1 before and after flushing long file1NoFlushLength = temp1.length(); fios.flush(); long file1FlushLength = temp1.length(); // Get length of temp2 before and after flushing long file2NoFlushLength = temp2.length(); fcios1.flush(); bos.flush(); long file2FlushLength = temp2.length(); byte[] b0 = baos.toByteArray(); int cacheNoFlushLength = b0.length; fcios2.flush(); byte[] b1 = baos.toByteArray(); int cacheFlushLength = b1.length; if (file1NoFlushLength != file1FlushLength) { // throw new RuntimeException System.out.println ("FileImageOutputStream not flushed!"); } if (file2NoFlushLength != file2FlushLength) { // throw new RuntimeException System.out.println ("FileCacheImageOutputStream/BufferedOutputStream not flushed!"); } if (cacheNoFlushLength != cacheFlushLength) { // throw new RuntimeException System.out.println ("FileCacheImageOutputStream/ByteArrayOutputStream not flushed!"); } } }
gpl-2.0
tobwiens/scheduling
common/common-client/src/main/java/org/ow2/proactive/utils/OperatingSystemFamily.java
1216
/* * ProActive Parallel Suite(TM): * The Open Source library for parallel and distributed * Workflows & Scheduling, Orchestration, Cloud Automation * and Big Data Analysis on Enterprise Grids & Clouds. * * Copyright (c) 2007 - 2017 ActiveEon * Contact: contact@activeeon.com * * This library is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation: version 3 of * the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. */ package org.ow2.proactive.utils; /** * OperatingSystemFamily * * @author The ProActive Team */ public enum OperatingSystemFamily { LINUX, WINDOWS, UNIX, DEC_OS, MAC; }
agpl-3.0
Buzzardo/spring-boot
spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsRegistrarConfiguration.java
3324
/* * Copyright 2012-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 * * 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.boot.actuate.autoconfigure.metrics.cache; import java.util.Collection; import java.util.Map; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tag; import org.springframework.boot.actuate.metrics.cache.CacheMeterBinderProvider; import org.springframework.boot.actuate.metrics.cache.CacheMetricsRegistrar; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; /** * Configure a {@link CacheMetricsRegistrar} and register all available {@link Cache * caches}. * * @author Stephane Nicoll */ @Configuration(proxyBeanMethods = false) @ConditionalOnBean({ CacheMeterBinderProvider.class, MeterRegistry.class }) class CacheMetricsRegistrarConfiguration { private static final String CACHE_MANAGER_SUFFIX = "cacheManager"; private final MeterRegistry registry; private final CacheMetricsRegistrar cacheMetricsRegistrar; private final Map<String, CacheManager> cacheManagers; CacheMetricsRegistrarConfiguration(MeterRegistry registry, Collection<CacheMeterBinderProvider<?>> binderProviders, Map<String, CacheManager> cacheManagers) { this.registry = registry; this.cacheManagers = cacheManagers; this.cacheMetricsRegistrar = new CacheMetricsRegistrar(this.registry, binderProviders); bindCachesToRegistry(); } @Bean CacheMetricsRegistrar cacheMetricsRegistrar() { return this.cacheMetricsRegistrar; } private void bindCachesToRegistry() { this.cacheManagers.forEach(this::bindCacheManagerToRegistry); } private void bindCacheManagerToRegistry(String beanName, CacheManager cacheManager) { cacheManager.getCacheNames() .forEach((cacheName) -> bindCacheToRegistry(beanName, cacheManager.getCache(cacheName))); } private void bindCacheToRegistry(String beanName, Cache cache) { Tag cacheManagerTag = Tag.of("cacheManager", getCacheManagerName(beanName)); this.cacheMetricsRegistrar.bindCacheToRegistry(cache, cacheManagerTag); } /** * Get the name of a {@link CacheManager} based on its {@code beanName}. * @param beanName the name of the {@link CacheManager} bean * @return a name for the given cache manager */ private String getCacheManagerName(String beanName) { if (beanName.length() > CACHE_MANAGER_SUFFIX.length() && StringUtils.endsWithIgnoreCase(beanName, CACHE_MANAGER_SUFFIX)) { return beanName.substring(0, beanName.length() - CACHE_MANAGER_SUFFIX.length()); } return beanName; } }
apache-2.0
hsbhathiya/stratos
components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/data/publisher/exception/DataPublisherException.java
1104
/* * 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.stratos.cartridge.agent.data.publisher.exception; public class DataPublisherException extends Exception { public DataPublisherException(String msg) { super(msg); } public DataPublisherException(String msg, Exception ex) { super(msg, ex); } }
apache-2.0
siosio/intellij-community
java/java-tests/testData/compiler/notNullVerification/mixed/Nullable.java
283
package org.jetbrains.annotations; import java.lang.annotation.*; @Retention(RetentionPolicy.CLASS) @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.TYPE_USE}) public @interface Nullable { String value() default ""; }
apache-2.0
asedunov/intellij-community
platform/core-api/src/com/intellij/pom/Navigatable.java
1619
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.pom; /** * Represents an instance which can be shown in the IDE (e.g. a file, a specific location inside a file, etc). * <p/> * Many {@link com.intellij.psi.PsiElement}s implement this interface (see {@link com.intellij.psi.NavigatablePsiElement}). To create an * instance which opens a file in editor and put caret to a specific location use {@link com.intellij.openapi.fileEditor.OpenFileDescriptor}. */ public interface Navigatable { /** * Open editor and select/navigate to the object there if possible. * Just do nothing if navigation is not possible like in case of a package * * @param requestFocus {@code true} if focus requesting is necessary */ void navigate(boolean requestFocus); /** * @return {@code false} if navigation is not possible for any reason. */ boolean canNavigate(); /** * @return {@code false} if navigation to source is not possible for any reason. * Source means some kind of editor */ boolean canNavigateToSource(); }
apache-2.0
ruks/carbon-apimgt
components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/utils/OpenAPIUtils.java
12297
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.apimgt.gateway.utils; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.synapse.MessageContext; import org.apache.synapse.core.axis2.Axis2MessageContext; import org.wso2.carbon.apimgt.impl.APIConstants; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.PathItem; import io.swagger.v3.oas.models.security.SecurityRequirement; public class OpenAPIUtils { /** * Return the resource authentication scheme of the API resource. * * @param openAPI OpenAPI of the API * @param synCtx The message containing resource request * @return the resource authentication scheme */ public static String getResourceAuthenticationScheme(OpenAPI openAPI, MessageContext synCtx) { String authType = null; Map<String, Object> vendorExtensions = getPathItemExtensions(synCtx, openAPI); if (vendorExtensions != null) { authType = (String) vendorExtensions.get(APIConstants.SWAGGER_X_AUTH_TYPE); } if (StringUtils.isNotBlank(authType)) { if (APIConstants.OASResourceAuthTypes.APPLICATION_OR_APPLICATION_USER.equals(authType)) { authType = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN; } else if (APIConstants.OASResourceAuthTypes.APPLICATION_USER.equals(authType)) { authType = APIConstants.AUTH_APPLICATION_USER_LEVEL_TOKEN; } else if (APIConstants.OASResourceAuthTypes.NONE.equals(authType)) { authType = APIConstants.AUTH_NO_AUTHENTICATION; } else if (APIConstants.OASResourceAuthTypes.APPLICATION.equals(authType)) { authType = APIConstants.AUTH_APPLICATION_LEVEL_TOKEN; } else { authType = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN; } return authType; } //Return 'Any' type (meaning security is on) if the authType is null or empty. return APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN; } /** * Return the scopes bound to the API resource. * * @param openAPI OpenAPI of the API * @param synCtx The message containing resource request * @return the scopes */ public static List<String> getScopesOfResource(OpenAPI openAPI, MessageContext synCtx) { Map<String, Object> vendorExtensions = getPathItemExtensions(synCtx, openAPI); if (vendorExtensions != null) { String resourceScope = (String) vendorExtensions.get(APIConstants.SWAGGER_X_SCOPE); if (resourceScope == null) { // If x-scope not found in swagger, check for the scopes in security List<String> securityScopes = getPathItemSecurityScopes(synCtx, openAPI); if (securityScopes == null || securityScopes.isEmpty()) { return null; } else { return securityScopes; } } else { List<String> scopeList = new ArrayList<>(); scopeList.add(resourceScope); return scopeList; } } return null; } /** * Return the roles of a given scope attached to a resource using the API swagger. * * @param openAPI OpenAPI of the API * @param synCtx The message containing resource request * @param resourceScope The scope of the resource * @return the roles of the scope in the comma separated format */ public static String getRolesOfScope(OpenAPI openAPI, MessageContext synCtx, String resourceScope) { String resourceRoles = null; Map<String, Object> vendorExtensions = getPathItemExtensions(synCtx, openAPI); if (vendorExtensions != null) { if (StringUtils.isNotBlank(resourceScope)) { if (openAPI.getExtensions() != null && openAPI.getExtensions().get(APIConstants.SWAGGER_X_WSO2_SECURITY) != null) { LinkedHashMap swaggerWSO2Security = (LinkedHashMap) openAPI.getExtensions() .get(APIConstants.SWAGGER_X_WSO2_SECURITY); if (swaggerWSO2Security != null && swaggerWSO2Security.get(APIConstants.SWAGGER_OBJECT_NAME_APIM) != null) { LinkedHashMap swaggerObjectAPIM = (LinkedHashMap) swaggerWSO2Security .get(APIConstants.SWAGGER_OBJECT_NAME_APIM); if (swaggerObjectAPIM != null && swaggerObjectAPIM.get(APIConstants.SWAGGER_X_WSO2_SCOPES) != null) { ArrayList<LinkedHashMap> apiScopes = (ArrayList<LinkedHashMap>) swaggerObjectAPIM.get(APIConstants.SWAGGER_X_WSO2_SCOPES); for (LinkedHashMap scope: apiScopes) { if (resourceScope.equals(scope.get(APIConstants.SWAGGER_SCOPE_KEY))) { resourceRoles = (String) scope.get(APIConstants.SWAGGER_ROLES); break; } } } } } } } if (resourceRoles == null) { LinkedHashMap<String, Object> scopeBindings = null; Map<String, Object> extensions = openAPI.getComponents().getSecuritySchemes() .get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY).getExtensions(); if (extensions != null && extensions.get(APIConstants.SWAGGER_X_SCOPES_BINDINGS) != null) { scopeBindings = (LinkedHashMap<String, Object>) extensions.get(APIConstants.SWAGGER_X_SCOPES_BINDINGS); } else { scopeBindings = (LinkedHashMap<String, Object>) openAPI.getComponents().getSecuritySchemes(). get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY).getFlows().getImplicit().getExtensions(). get(APIConstants.SWAGGER_X_SCOPES_BINDINGS); } if (scopeBindings != null) { return (String) scopeBindings.get(resourceScope); } } return null; } /** * Return the throttling tier of the API resource. * * @param openAPI OpenAPI of the API * @param synCtx The message containing resource request * @return the resource throttling tier */ public static String getResourceThrottlingTier(OpenAPI openAPI, MessageContext synCtx) { String throttlingTier = null; Map<String, Object> vendorExtensions = getPathItemExtensions(synCtx, openAPI); if (vendorExtensions != null) { throttlingTier = (String) vendorExtensions.get(APIConstants.SWAGGER_X_THROTTLING_TIER); } if (StringUtils.isNotBlank(throttlingTier)) { return throttlingTier; } return APIConstants.UNLIMITED_TIER; } /** * Check whether the tier for the API is content aware or not. * @param openAPI OpenAPI of the API * @param synCtx The message containing resource request * @return whether tier is content aware or not. */ public static boolean isContentAwareTierAvailable(OpenAPI openAPI, MessageContext synCtx) { boolean status = false; Map<String, Object> vendorExtensions; if (openAPI != null) { vendorExtensions = openAPI.getExtensions(); if (vendorExtensions != null && vendorExtensions.get(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH) != null && (boolean) vendorExtensions.get(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH)) { // check for api level policy status = true; } // if there is api level policy. no need to check for resource level. if not, check for resource level if(!status) { vendorExtensions = getPathItemExtensions(synCtx, openAPI); if (vendorExtensions != null && vendorExtensions.get(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH) != null && (boolean) vendorExtensions.get(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH)) { // check for resource level policy status = true; } } } return status; } private static Map<String, Object> getPathItemExtensions(MessageContext synCtx, OpenAPI openAPI) { if (openAPI != null) { String apiElectedResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE); org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) synCtx).getAxis2MessageContext(); String httpMethod = (String) axis2MessageContext.getProperty(APIConstants.DigestAuthConstants.HTTP_METHOD); PathItem path = openAPI.getPaths().get(apiElectedResource); if (path != null) { switch (httpMethod) { case APIConstants.HTTP_GET: return path.getGet().getExtensions(); case APIConstants.HTTP_POST: return path.getPost().getExtensions(); case APIConstants.HTTP_PUT: return path.getPut().getExtensions(); case APIConstants.HTTP_DELETE: return path.getDelete().getExtensions(); case APIConstants.HTTP_HEAD: return path.getHead().getExtensions(); case APIConstants.HTTP_OPTIONS: return path.getOptions().getExtensions(); case APIConstants.HTTP_PATCH: return path.getPatch().getExtensions(); } } } return null; } private static List<String> getPathItemSecurityScopes(MessageContext synCtx, OpenAPI openAPI) { if (openAPI != null) { String apiElectedResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE); org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) synCtx).getAxis2MessageContext(); String httpMethod = (String) axis2MessageContext.getProperty(APIConstants.DigestAuthConstants.HTTP_METHOD); PathItem path = openAPI.getPaths().get(apiElectedResource); if (path != null) { Operation operation = path.readOperationsMap().get(PathItem.HttpMethod.valueOf(httpMethod)); return getDefaultSecurityScopes(operation.getSecurity()); } } return null; } /** * Extract the scopes of "default" security definition * * @param requirements security requirements of the operation * @return extracted scopes of "default" security definition */ private static List<String> getDefaultSecurityScopes(List<SecurityRequirement> requirements) { if (requirements != null) { for (SecurityRequirement requirement: requirements) { if (requirement.get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY) != null) { return requirement.get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY); } } } return new ArrayList<>(); } }
apache-2.0
MetSystem/jbpm
jbpm-flow/src/main/java/org/jbpm/ruleflow/core/factory/BoundaryEventNodeFactory.java
4212
/** * Copyright 2010 JBoss 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.jbpm.ruleflow.core.factory; import org.jbpm.process.core.event.EventFilter; import org.jbpm.process.core.event.EventTransformer; import org.jbpm.process.core.event.EventTypeFilter; import org.jbpm.ruleflow.core.RuleFlowNodeContainerFactory; import org.jbpm.workflow.core.Node; import org.jbpm.workflow.core.NodeContainer; import org.jbpm.workflow.core.node.BoundaryEventNode; public class BoundaryEventNodeFactory extends NodeFactory { private NodeContainer nodeContainer; private String attachedToUniqueId; public BoundaryEventNodeFactory(RuleFlowNodeContainerFactory nodeContainerFactory, NodeContainer nodeContainer, long id) { super(nodeContainerFactory, nodeContainer, id); this.nodeContainer = nodeContainer; } public BoundaryEventNodeFactory attachedTo(long attachedToId) { attachedToUniqueId = (String)nodeContainer.getNode(attachedToId).getMetaData().get("UniqueId"); getBoundaryEventNode().setAttachedToNodeId(attachedToUniqueId); getBoundaryEventNode().setMetaData("AttachedTo", attachedToUniqueId); return this; } protected Node createNode() { return new BoundaryEventNode(); } protected BoundaryEventNode getBoundaryEventNode() { return(BoundaryEventNode) getNode(); } public BoundaryEventNodeFactory name(String name) { getNode().setName(name); return this; } public BoundaryEventNodeFactory variableName(String variableName) { getBoundaryEventNode().setVariableName(variableName); return this; } public BoundaryEventNodeFactory eventFilter(EventFilter eventFilter) { getBoundaryEventNode().addEventFilter(eventFilter); return this; } public BoundaryEventNodeFactory eventType(String eventType) { EventTypeFilter filter = new EventTypeFilter(); filter.setType(eventType); return eventFilter(filter); } public BoundaryEventNodeFactory eventType(String eventTypePrefix, String eventTypeSurffix) { if (attachedToUniqueId == null) { throw new IllegalStateException("attachedTo() must be called before"); } EventTypeFilter filter = new EventTypeFilter(); filter.setType(eventTypePrefix + "-" + attachedToUniqueId + "-" + eventTypeSurffix); return eventFilter(filter); } public BoundaryEventNodeFactory timeCycle(String timeCycle) { eventType("Timer", timeCycle); setMetaData("TimeCycle", timeCycle); return this; } public BoundaryEventNodeFactory timeCycle(String timeCycle, String language) { eventType("Timer", timeCycle); setMetaData("TimeCycle", timeCycle); setMetaData("Language", language); return this; } public BoundaryEventNodeFactory timeDuration(String timeDuration) { eventType("Timer", timeDuration); setMetaData("TimeDuration", timeDuration); return this; } public BoundaryEventNodeFactory cancelActivity(boolean cancelActivity) { setMetaData("CancelActivity", cancelActivity); return this; } public BoundaryEventNodeFactory eventTransformer(EventTransformer transformer) { getBoundaryEventNode().setEventTransformer(transformer); return this; } public BoundaryEventNodeFactory scope(String scope) { getBoundaryEventNode().setScope(scope); return this; } public BoundaryEventNodeFactory setMetaData(String name,Object value) { getBoundaryEventNode().setMetaData(name, value); return this; } }
apache-2.0
Darsstar/framework
uitest/src/main/java/com/vaadin/tests/elements/radiobuttongroup/RadioButtonGroupSetValue.java
969
package com.vaadin.tests.elements.radiobuttongroup; import java.util.ArrayList; import java.util.List; import com.vaadin.data.provider.ListDataProvider; import com.vaadin.server.VaadinRequest; import com.vaadin.tests.components.AbstractTestUI; import com.vaadin.ui.RadioButtonGroup; public class RadioButtonGroupSetValue extends AbstractTestUI { @Override protected void setup(VaadinRequest request) { RadioButtonGroup<String> group = new RadioButtonGroup<String>(); List<String> options = new ArrayList<String>(); options.add("item1"); options.add("item2"); options.add("item3"); group.setDataProvider(new ListDataProvider<String>(options)); addComponent(group); } @Override protected String getTestDescription() { return "Test RadioButtonGroup element setValue() and SelectByText()"; } @Override protected Integer getTicketNumber() { return null; } }
apache-2.0
dugilos/nar-maven-plugin
src/main/java/com/github/maven_nar/cpptasks/parser/LetterState.java
2232
/* * #%L * Native ARchive plugin for Maven * %% * Copyright (C) 2002 - 2014 NAR Maven Plugin developers. * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.github.maven_nar.cpptasks.parser; /** * This parser state checks consumed characters against a specific character. * * @author Curt Arnold */ public final class LetterState extends AbstractParserState { /** * Next state if a match is found. */ private final AbstractParserState nextState; /** * Next state if not match is found. */ private final AbstractParserState noMatchState; /** * Character to match. */ private final char thisLetter; /** * Constructor. * * @param parser * parser * @param matchLetter * letter to match * @param nextStateArg * next state if a match on the letter * @param noMatchStateArg * state if no match on letter */ public LetterState(final AbstractParser parser, final char matchLetter, final AbstractParserState nextStateArg, final AbstractParserState noMatchStateArg) { super(parser); this.thisLetter = matchLetter; this.nextState = nextStateArg; this.noMatchState = noMatchStateArg; } /** * Consumes a character and returns the next state for the parser. * * @param ch * next character * @return the configured nextState if ch is the expected character or the * configure noMatchState otherwise. */ @Override public AbstractParserState consume(final char ch) { if (ch == this.thisLetter) { return this.nextState; } if (ch == '\n') { getParser().getNewLineState(); } return this.noMatchState; } }
apache-2.0
ananthc/apex-malhar
examples/frauddetect/src/main/java/org/apache/apex/examples/frauddetect/TransactionStatsData.java
1212
/** * 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.apex.examples.frauddetect; /** * POJO to capture transaction data related to min, max, sma, std-dev, variance. * * @since 0.9.0 */ public class TransactionStatsData { public String merchantId; public int terminalId; public int zipCode; public MerchantTransaction.MerchantType merchantType; public long min; public long max; public double sma; public long time; }
apache-2.0
abstractj/keycloak
services/src/main/java/org/keycloak/storage/UserStorageManager.java
33353
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.storage; import org.jboss.logging.Logger; import org.keycloak.component.ComponentFactory; import org.keycloak.component.ComponentModel; import org.keycloak.models.ClientModel; import org.keycloak.models.ClientScopeModel; import org.keycloak.models.FederatedIdentityModel; import org.keycloak.models.GroupModel; import org.keycloak.models.IdentityProviderModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.ModelException; import org.keycloak.models.ProtocolMapperModel; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserConsentModel; import org.keycloak.models.UserManager; import org.keycloak.models.UserModel; import org.keycloak.models.UserProvider; import org.keycloak.models.cache.CachedUserModel; import org.keycloak.models.cache.OnUserCache; import org.keycloak.models.cache.UserCache; import org.keycloak.models.utils.ComponentUtil; import org.keycloak.models.utils.ReadOnlyUserModelDelegate; import org.keycloak.services.managers.UserStorageSyncManager; import org.keycloak.storage.client.ClientStorageProvider; import org.keycloak.storage.federated.UserFederatedStorageProvider; import org.keycloak.storage.user.ImportedUserValidation; import org.keycloak.storage.user.UserBulkUpdateProvider; import org.keycloak.storage.user.UserLookupProvider; import org.keycloak.storage.user.UserQueryProvider; import org.keycloak.storage.user.UserRegistrationProvider; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; import static org.keycloak.models.utils.KeycloakModelUtils.runJobInTransaction; import static org.keycloak.utils.StreamsUtil.distinctByKey; import static org.keycloak.utils.StreamsUtil.paginatedStream; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ public class UserStorageManager extends AbstractStorageManager<UserStorageProvider, UserStorageProviderModel> implements UserProvider.Streams, OnUserCache, OnCreateComponent, OnUpdateComponent { private static final Logger logger = Logger.getLogger(UserStorageManager.class); public UserStorageManager(KeycloakSession session) { super(session, UserStorageProviderFactory.class, UserStorageProvider.class, UserStorageProviderModel::new, "user"); } protected UserProvider localStorage() { return session.userLocalStorage(); } private UserFederatedStorageProvider getFederatedStorage() { return session.userFederatedStorage(); } /** * Allows a UserStorageProvider to proxy and/or synchronize an imported user. * * @param realm * @param user * @return */ protected UserModel importValidation(RealmModel realm, UserModel user) { if (user == null || user.getFederationLink() == null) return user; UserStorageProviderModel model = getStorageProviderModel(realm, user.getFederationLink()); if (model == null) { // remove linked user with unknown storage provider. logger.debugf("Removed user with federation link of unknown storage provider '%s'", user.getUsername()); deleteInvalidUser(realm, user); return null; } if (!model.isEnabled()) { return new ReadOnlyUserModelDelegate(user) { @Override public boolean isEnabled() { return false; } }; } ImportedUserValidation importedUserValidation = getStorageProviderInstance(model, ImportedUserValidation.class, true); if (importedUserValidation == null) return user; UserModel validated = importedUserValidation.validate(realm, user); if (validated == null) { deleteInvalidUser(realm, user); return null; } else { return validated; } } protected void deleteInvalidUser(final RealmModel realm, final UserModel user) { String userId = user.getId(); String userName = user.getUsername(); UserCache userCache = session.userCache(); if (userCache != null) { userCache.evict(realm, user); } // This needs to be running in separate transaction because removing the user may end up with throwing // PessimisticLockException which also rollbacks Jpa transaction, hence when it is running in current transaction // it will become not usable for all consequent jpa calls. It will end up with Transaction is in rolled back // state error runJobInTransaction(session.getKeycloakSessionFactory(), session -> { RealmModel realmModel = session.realms().getRealm(realm.getId()); if (realmModel == null) return; UserModel deletedUser = session.userLocalStorage().getUserById(realmModel, userId); if (deletedUser != null) { try { new UserManager(session).removeUser(realmModel, deletedUser, session.userLocalStorage()); logger.debugf("Removed invalid user '%s'", userName); } catch (ModelException ex) { // Ignore exception, possible cause may be concurrent deleteInvalidUser calls which means // ModelException exception may be ignored because users will be removed with next call or is // already removed logger.debugf(ex, "ModelException thrown during deleteInvalidUser with username '%s'", userName); } } }); } protected Stream<UserModel> importValidation(RealmModel realm, Stream<UserModel> users) { return users.map(user -> importValidation(realm, user)).filter(Objects::nonNull); } @FunctionalInterface interface PaginatedQuery { Stream<UserModel> query(Object provider, Integer firstResult, Integer maxResults); } @FunctionalInterface interface CountQuery { int query(Object provider, Integer firstResult, Integer maxResult); } protected Stream<UserModel> query(PaginatedQuery pagedQuery, RealmModel realm, Integer firstResult, Integer maxResults) { return query(pagedQuery, ((provider, first, max) -> (int) pagedQuery.query(provider, first, max).count()), realm, firstResult, maxResults); } protected Stream<UserModel> query(PaginatedQuery pagedQuery, CountQuery countQuery, RealmModel realm, Integer firstResult, Integer maxResults) { if (maxResults != null && maxResults == 0) return Stream.empty(); Stream<Object> providersStream = Stream.concat(Stream.of((Object) localStorage()), getEnabledStorageProviders(realm, UserQueryProvider.class)); UserFederatedStorageProvider federatedStorageProvider = getFederatedStorage(); if (federatedStorageProvider != null) { providersStream = Stream.concat(providersStream, Stream.of(federatedStorageProvider)); } final AtomicInteger currentFirst; if (firstResult == null || firstResult <= 0) { // We don't want to skip any users so we don't need to do firstResult filtering currentFirst = new AtomicInteger(0); } else { AtomicBoolean droppingProviders = new AtomicBoolean(true); currentFirst = new AtomicInteger(firstResult); providersStream = providersStream .filter(provider -> { // This is basically dropWhile if (!droppingProviders.get()) return true; // We have already gathered enough users to pass firstResult number in previous providers, we can take all following providers long expectedNumberOfUsersForProvider = countQuery.query(provider, 0, currentFirst.get() + 1); // check how many users we can obtain from this provider if (expectedNumberOfUsersForProvider == currentFirst.get()) { // This provider provides exactly the amount of users we need for passing firstResult, we can set currentFirst to 0 and drop this provider currentFirst.set(0); droppingProviders.set(false); return false; } if (expectedNumberOfUsersForProvider > currentFirst.get()) { // If we can obtain enough enough users from this provider to fulfill our need we can stop dropping providers droppingProviders.set(false); return true; // don't filter out this provider because we are going to return some users from it } // This provider cannot provide enough users to pass firstResult so we are going to filter it out and change firstResult for next provider currentFirst.set((int) (currentFirst.get() - expectedNumberOfUsersForProvider)); return false; }); } // Actual user querying if (maxResults == null || maxResults < 0) { // No maxResult set, we want all users return providersStream .flatMap(provider -> pagedQuery.query(provider, currentFirst.getAndSet(0), null)); } else { final AtomicInteger currentMax = new AtomicInteger(maxResults); // Query users with currentMax variable counting how many users we return return providersStream .filter(provider -> currentMax.get() != 0) // If we reach currentMax == 0, we can skip querying all following providers .flatMap(provider -> pagedQuery.query(provider, currentFirst.getAndSet(0), currentMax.get())) .peek(userModel -> { currentMax.updateAndGet(i -> i > 0 ? i - 1 : i); }); } } // removeDuplicates method may cause concurrent issues, it should not be used on parallel streams private static Stream<UserModel> removeDuplicates(Stream<UserModel> withDuplicates) { return withDuplicates.filter(distinctByKey(UserModel::getId)); } /** {@link UserRegistrationProvider} methods implementations start here */ @Override public UserModel addUser(RealmModel realm, String username) { return getEnabledStorageProviders(realm, UserRegistrationProvider.class) .map(provider -> provider.addUser(realm, username)) .filter(Objects::nonNull) .findFirst() .orElseGet(() -> localStorage().addUser(realm, username.toLowerCase())); } @Override public boolean removeUser(RealmModel realm, UserModel user) { if (getFederatedStorage() != null) getFederatedStorage().preRemove(realm, user); StorageId storageId = new StorageId(user.getId()); if (storageId.getProviderId() == null) { String federationLink = user.getFederationLink(); boolean linkRemoved = federationLink == null || Optional.ofNullable( getStorageProviderInstance(realm, federationLink, UserRegistrationProvider.class)) .map(provider -> provider.removeUser(realm, user)) .orElse(false); return localStorage().removeUser(realm, user) && linkRemoved; } UserRegistrationProvider registry = getStorageProviderInstance(realm, storageId.getProviderId(), UserRegistrationProvider.class); if (registry == null) { throw new ModelException("Could not resolve UserRegistrationProvider: " + storageId.getProviderId()); } return registry.removeUser(realm, user); } /** {@link UserRegistrationProvider} methods implementations end here {@link UserLookupProvider} methods implementations start here */ @Override public UserModel getUserById(RealmModel realm, String id) { StorageId storageId = new StorageId(id); if (storageId.getProviderId() == null) { UserModel user = localStorage().getUserById(realm, id); return importValidation(realm, user); } UserLookupProvider provider = getStorageProviderInstance(realm, storageId.getProviderId(), UserLookupProvider.class); if (provider == null) return null; return provider.getUserById(realm, id); } @Override public UserModel getUserByUsername(RealmModel realm, String username) { UserModel user = localStorage().getUserByUsername(realm, username); if (user != null) { return importValidation(realm, user); } return mapEnabledStorageProvidersWithTimeout(realm, UserLookupProvider.class, provider -> provider.getUserByUsername(realm, username)).findFirst().orElse(null); } @Override public UserModel getUserByEmail(RealmModel realm, String email) { UserModel user = localStorage().getUserByEmail(realm, email); if (user != null) { user = importValidation(realm, user); // Case when email was changed directly in the userStorage and doesn't correspond anymore to the email from local DB if (email.equalsIgnoreCase(user.getEmail())) { return user; } } return mapEnabledStorageProvidersWithTimeout(realm, UserLookupProvider.class, provider -> provider.getUserByEmail(realm, email)).findFirst().orElse(null); } /** {@link UserLookupProvider} methods implementations end here {@link UserQueryProvider} methods implementation start here */ @Override public Stream<UserModel> getGroupMembersStream(final RealmModel realm, final GroupModel group, Integer firstResult, Integer maxResults) { Stream<UserModel> results = query((provider, firstResultInQuery, maxResultsInQuery) -> { if (provider instanceof UserQueryProvider) { return ((UserQueryProvider)provider).getGroupMembersStream(realm, group, firstResultInQuery, maxResultsInQuery); } else if (provider instanceof UserFederatedStorageProvider) { return ((UserFederatedStorageProvider)provider).getMembershipStream(realm, group, firstResultInQuery, maxResultsInQuery). map(id -> getUserById(realm, id)); } return Stream.empty(); }, realm, firstResult, maxResults); return importValidation(realm, results); } @Override public Stream<UserModel> getRoleMembersStream(final RealmModel realm, final RoleModel role, Integer firstResult, Integer maxResults) { Stream<UserModel> results = query((provider, firstResultInQuery, maxResultsInQuery) -> { if (provider instanceof UserQueryProvider) { return ((UserQueryProvider)provider).getRoleMembersStream(realm, role, firstResultInQuery, maxResultsInQuery); } return Stream.empty(); }, realm, firstResult, maxResults); return importValidation(realm, results); } @Override public Stream<UserModel> getUsersStream(RealmModel realm) { return getUsersStream(realm, null, null, false); } @Override public Stream<UserModel> getUsersStream(RealmModel realm, Integer firstResult, Integer maxResults) { return getUsersStream(realm, firstResult, maxResults, false); } @Override public Stream<UserModel> getUsersStream(final RealmModel realm, Integer firstResult, Integer maxResults, final boolean includeServiceAccounts) { Stream<UserModel> results = query((provider, firstResultInQuery, maxResultsInQuery) -> { if (provider instanceof UserProvider) { // it is local storage return ((UserProvider) provider).getUsersStream(realm, firstResultInQuery, maxResultsInQuery, includeServiceAccounts); } else if (provider instanceof UserQueryProvider) { return ((UserQueryProvider)provider).getUsersStream(realm); } return Stream.empty(); } , realm, firstResult, maxResults); return importValidation(realm, results); } @Override public int getUsersCount(RealmModel realm, boolean includeServiceAccount) { int localStorageUsersCount = localStorage().getUsersCount(realm, includeServiceAccount); int storageProvidersUsersCount = mapEnabledStorageProvidersWithTimeout(realm, UserQueryProvider.class, userQueryProvider -> userQueryProvider.getUsersCount(realm)) .reduce(0, Integer::sum); return localStorageUsersCount + storageProvidersUsersCount; } @Override public int getUsersCount(RealmModel realm) { return getUsersCount(realm, false); } @Override // TODO: missing storageProviders count? public int getUsersCount(RealmModel realm, Set<String> groupIds) { return localStorage().getUsersCount(realm, groupIds); } @Override // TODO: missing storageProviders count? public int getUsersCount(RealmModel realm, String search) { return localStorage().getUsersCount(realm, search); } @Override // TODO: missing storageProviders count? public int getUsersCount(RealmModel realm, String search, Set<String> groupIds) { return localStorage().getUsersCount(realm, search, groupIds); } @Override // TODO: missing storageProviders count? public int getUsersCount(RealmModel realm, Map<String, String> params) { return localStorage().getUsersCount(realm, params); } @Override // TODO: missing storageProviders count? public int getUsersCount(RealmModel realm, Map<String, String> params, Set<String> groupIds) { return localStorage().getUsersCount(realm, params, groupIds); } @Override public Stream<UserModel> searchForUserStream(RealmModel realm, String search, Integer firstResult, Integer maxResults) { Stream<UserModel> results = query((provider, firstResultInQuery, maxResultsInQuery) -> { if (provider instanceof UserQueryProvider) { return ((UserQueryProvider)provider).searchForUserStream(realm, search, firstResultInQuery, maxResultsInQuery); } return Stream.empty(); }, (provider, firstResultInQuery, maxResultsInQuery) -> { if (provider instanceof UserQueryProvider) { return ((UserQueryProvider)provider).getUsersCount(realm, search); } return 0; }, realm, firstResult, maxResults); return importValidation(realm, results); } @Override public Stream<UserModel> searchForUserStream(RealmModel realm, Map<String, String> attributes, Integer firstResult, Integer maxResults) { Stream<UserModel> results = query((provider, firstResultInQuery, maxResultsInQuery) -> { if (provider instanceof UserQueryProvider) { if (attributes.containsKey(UserModel.SEARCH)) { return ((UserQueryProvider)provider).searchForUserStream(realm, attributes.get(UserModel.SEARCH), firstResultInQuery, maxResultsInQuery); } else { return ((UserQueryProvider)provider).searchForUserStream(realm, attributes, firstResultInQuery, maxResultsInQuery); } } return Stream.empty(); }, (provider, firstResultInQuery, maxResultsInQuery) -> { if (provider instanceof UserQueryProvider) { if (attributes.containsKey(UserModel.SEARCH)) { return ((UserQueryProvider)provider).getUsersCount(realm, attributes.get(UserModel.SEARCH)); } else { return ((UserQueryProvider)provider).getUsersCount(realm, attributes); } } return 0; } , realm, firstResult, maxResults); return importValidation(realm, results); } @Override public Stream<UserModel> searchForUserByUserAttributeStream(RealmModel realm, String attrName, String attrValue) { Stream<UserModel> results = query((provider, firstResultInQuery, maxResultsInQuery) -> { if (provider instanceof UserQueryProvider) { return paginatedStream(((UserQueryProvider)provider).searchForUserByUserAttributeStream(realm, attrName, attrValue), firstResultInQuery, maxResultsInQuery); } else if (provider instanceof UserFederatedStorageProvider) { return paginatedStream(((UserFederatedStorageProvider)provider).getUsersByUserAttributeStream(realm, attrName, attrValue) .map(id -> getUserById(realm, id)) .filter(Objects::nonNull), firstResultInQuery, maxResultsInQuery); } return Stream.empty(); }, realm, null, null); // removeDuplicates method may cause concurrent issues, it should not be used on parallel streams results = removeDuplicates(results); return importValidation(realm, results); } /** {@link UserQueryProvider} methods implementation end here {@link UserBulkUpdateProvider} methods implementation start here */ @Override public void grantToAllUsers(RealmModel realm, RoleModel role) { localStorage().grantToAllUsers(realm, role); consumeEnabledStorageProvidersWithTimeout(realm, UserBulkUpdateProvider.class, provider -> provider.grantToAllUsers(realm, role)); } /** {@link UserBulkUpdateProvider} methods implementation end here {@link UserStorageProvider} methods implementations start here -> no StorageProviders involved */ @Override public void preRemove(RealmModel realm) { localStorage().preRemove(realm); if (getFederatedStorage() != null) { getFederatedStorage().preRemove(realm); } consumeEnabledStorageProvidersWithTimeout(realm, UserStorageProvider.class, provider -> provider.preRemove(realm)); } @Override public void preRemove(RealmModel realm, GroupModel group) { localStorage().preRemove(realm, group); if (getFederatedStorage() != null) { getFederatedStorage().preRemove(realm, group); } consumeEnabledStorageProvidersWithTimeout(realm, UserStorageProvider.class, provider -> provider.preRemove(realm, group)); } @Override public void preRemove(RealmModel realm, RoleModel role) { localStorage().preRemove(realm, role); if (getFederatedStorage() != null) { getFederatedStorage().preRemove(realm, role); } consumeEnabledStorageProvidersWithTimeout(realm, UserStorageProvider.class, provider -> provider.preRemove(realm, role)); } /** {@link UserStorageProvider} methods implementation end here {@link UserProvider} methods implementations start here -> no StorageProviders involved */ @Override public UserModel addUser(RealmModel realm, String id, String username, boolean addDefaultRoles, boolean addDefaultRequiredActions) { return localStorage().addUser(realm, id, username.toLowerCase(), addDefaultRoles, addDefaultRequiredActions); } @Override public void addFederatedIdentity(RealmModel realm, UserModel user, FederatedIdentityModel socialLink) { if (StorageId.isLocalStorage(user)) { localStorage().addFederatedIdentity(realm, user, socialLink); } else { getFederatedStorage().addFederatedIdentity(realm, user.getId(), socialLink); } } @Override public void updateFederatedIdentity(RealmModel realm, UserModel federatedUser, FederatedIdentityModel federatedIdentityModel) { if (StorageId.isLocalStorage(federatedUser)) { localStorage().updateFederatedIdentity(realm, federatedUser, federatedIdentityModel); } else { getFederatedStorage().updateFederatedIdentity(realm, federatedUser.getId(), federatedIdentityModel); } } @Override public boolean removeFederatedIdentity(RealmModel realm, UserModel user, String socialProvider) { if (StorageId.isLocalStorage(user)) { return localStorage().removeFederatedIdentity(realm, user, socialProvider); } else { return getFederatedStorage().removeFederatedIdentity(realm, user.getId(), socialProvider); } } @Override public void preRemove(RealmModel realm, IdentityProviderModel provider) { localStorage().preRemove(realm, provider); getFederatedStorage().preRemove(realm, provider); } @Override public void addConsent(RealmModel realm, String userId, UserConsentModel consent) { if (StorageId.isLocalStorage(userId)) { localStorage().addConsent(realm, userId, consent); } else { getFederatedStorage().addConsent(realm, userId, consent); } } @Override public UserConsentModel getConsentByClient(RealmModel realm, String userId, String clientInternalId) { if (StorageId.isLocalStorage(userId)) { return localStorage().getConsentByClient(realm, userId, clientInternalId); } else { return getFederatedStorage().getConsentByClient(realm, userId, clientInternalId); } } @Override public Stream<UserConsentModel> getConsentsStream(RealmModel realm, String userId) { if (StorageId.isLocalStorage(userId)) { return localStorage().getConsentsStream(realm, userId); } else { return getFederatedStorage().getConsentsStream(realm, userId); } } @Override public void updateConsent(RealmModel realm, String userId, UserConsentModel consent) { if (StorageId.isLocalStorage(userId)) { localStorage().updateConsent(realm, userId, consent); } else { getFederatedStorage().updateConsent(realm, userId, consent); } } @Override public boolean revokeConsentForClient(RealmModel realm, String userId, String clientInternalId) { if (StorageId.isLocalStorage(userId)) { return localStorage().revokeConsentForClient(realm, userId, clientInternalId); } else { return getFederatedStorage().revokeConsentForClient(realm, userId, clientInternalId); } } @Override public void setNotBeforeForUser(RealmModel realm, UserModel user, int notBefore) { if (StorageId.isLocalStorage(user)) { localStorage().setNotBeforeForUser(realm, user, notBefore); } else { getFederatedStorage().setNotBeforeForUser(realm, user.getId(), notBefore); } } @Override public int getNotBeforeOfUser(RealmModel realm, UserModel user) { if (StorageId.isLocalStorage(user)) { return localStorage().getNotBeforeOfUser(realm, user); } else { return getFederatedStorage().getNotBeforeOfUser(realm, user.getId()); } } @Override public UserModel getUserByFederatedIdentity(RealmModel realm, FederatedIdentityModel socialLink) { UserModel user = localStorage().getUserByFederatedIdentity(realm, socialLink); if (user != null) { return importValidation(realm, user); } if (getFederatedStorage() == null) return null; String id = getFederatedStorage().getUserByFederatedIdentity(socialLink, realm); if (id != null) return getUserById(realm, id); return null; } @Override public UserModel getServiceAccount(ClientModel client) { return localStorage().getServiceAccount(client); } @Override public Stream<FederatedIdentityModel> getFederatedIdentitiesStream(RealmModel realm, UserModel user) { if (user == null) throw new IllegalStateException("Federated user no longer valid"); Stream<FederatedIdentityModel> stream = StorageId.isLocalStorage(user) ? localStorage().getFederatedIdentitiesStream(realm, user) : Stream.empty(); if (getFederatedStorage() != null) stream = Stream.concat(stream, getFederatedStorage().getFederatedIdentitiesStream(user.getId(), realm)); return stream.distinct(); } @Override public FederatedIdentityModel getFederatedIdentity(RealmModel realm, UserModel user, String socialProvider) { if (user == null) throw new IllegalStateException("Federated user no longer valid"); if (StorageId.isLocalStorage(user)) { FederatedIdentityModel model = localStorage().getFederatedIdentity(realm, user, socialProvider); if (model != null) return model; } if (getFederatedStorage() != null) return getFederatedStorage().getFederatedIdentity(user.getId(), socialProvider, realm); else return null; } @Override public void preRemove(RealmModel realm, ClientModel client) { localStorage().preRemove(realm, client); if (getFederatedStorage() != null) getFederatedStorage().preRemove(realm, client); } @Override public void preRemove(ProtocolMapperModel protocolMapper) { localStorage().preRemove(protocolMapper); if (getFederatedStorage() != null) getFederatedStorage().preRemove(protocolMapper); } @Override public void preRemove(ClientScopeModel clientScope) { localStorage().preRemove(clientScope); if (getFederatedStorage() != null) getFederatedStorage().preRemove(clientScope); } @Override public void preRemove(RealmModel realm, ComponentModel component) { if (component.getProviderType().equals(ClientStorageProvider.class.getName())) { localStorage().preRemove(realm, component); if (getFederatedStorage() != null) getFederatedStorage().preRemove(realm, component); return; } if (!component.getProviderType().equals(UserStorageProvider.class.getName())) return; localStorage().preRemove(realm, component); if (getFederatedStorage() != null) getFederatedStorage().preRemove(realm, component); new UserStorageSyncManager().notifyToRefreshPeriodicSync(session, realm, new UserStorageProviderModel(component), true); } @Override public void removeImportedUsers(RealmModel realm, String storageProviderId) { localStorage().removeImportedUsers(realm, storageProviderId); } @Override public void unlinkUsers(RealmModel realm, String storageProviderId) { localStorage().unlinkUsers(realm, storageProviderId); } /** {@link UserProvider} methods implementations end here */ @Override public void close() { } @Override public void onCreate(KeycloakSession session, RealmModel realm, ComponentModel model) { ComponentFactory factory = ComponentUtil.getComponentFactory(session, model); if (!(factory instanceof UserStorageProviderFactory)) return; new UserStorageSyncManager().notifyToRefreshPeriodicSync(session, realm, new UserStorageProviderModel(model), false); } @Override public void onUpdate(KeycloakSession session, RealmModel realm, ComponentModel oldModel, ComponentModel newModel) { ComponentFactory factory = ComponentUtil.getComponentFactory(session, newModel); if (!(factory instanceof UserStorageProviderFactory)) return; UserStorageProviderModel old = new UserStorageProviderModel(oldModel); UserStorageProviderModel newP= new UserStorageProviderModel(newModel); if (old.getChangedSyncPeriod() != newP.getChangedSyncPeriod() || old.getFullSyncPeriod() != newP.getFullSyncPeriod() || old.isImportEnabled() != newP.isImportEnabled()) { new UserStorageSyncManager().notifyToRefreshPeriodicSync(session, realm, new UserStorageProviderModel(newModel), false); } } @Override public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) { if (StorageId.isLocalStorage(user)) { if (session.userLocalStorage() instanceof OnUserCache) { ((OnUserCache)session.userLocalStorage()).onCache(realm, user, delegate); } } else { OnUserCache provider = getStorageProviderInstance(realm, StorageId.resolveProviderId(user), OnUserCache.class); if (provider != null ) { provider.onCache(realm, user, delegate); } } } }
apache-2.0
skyseazcq/ninja-1
ninja-servlet/src/main/java/ninja/servlet/util/ResponseExtractor.java
1447
/** * Copyright (C) 2012-2015 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 ninja.servlet.util; import javax.servlet.http.HttpServletResponse; import ninja.Context; import ninja.params.ArgumentExtractor; import ninja.servlet.ContextImpl; public class ResponseExtractor implements ArgumentExtractor<HttpServletResponse> { @Override public HttpServletResponse extract(Context context) { if (context instanceof ContextImpl) { return ((ContextImpl) context).getHttpServletResponse(); } else { throw new RuntimeException( "RequestExtractor only works with Servlet container implementation of Context."); } } @Override public Class<HttpServletResponse> getExtractedType() { return HttpServletResponse.class; } @Override public String getFieldName() { return null; } }
apache-2.0
packet-tracker/onos
cli/src/main/java/org/onosproject/cli/net/AddTestFlowsCommand.java
6507
/* * Copyright 2014-2015 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.cli.net; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.Stopwatch; import com.google.common.collect.Lists; import org.apache.commons.lang.math.RandomUtils; import org.apache.karaf.shell.commands.Argument; import org.apache.karaf.shell.commands.Command; import org.onlab.packet.MacAddress; import org.onosproject.cli.AbstractShellCommand; import org.onosproject.core.ApplicationId; import org.onosproject.core.CoreService; import org.onosproject.net.Device; import org.onosproject.net.PortNumber; import org.onosproject.net.device.DeviceService; import org.onosproject.net.flow.DefaultFlowRule; import org.onosproject.net.flow.DefaultTrafficSelector; import org.onosproject.net.flow.DefaultTrafficTreatment; import org.onosproject.net.flow.FlowRule; import org.onosproject.net.flow.FlowRuleOperations; import org.onosproject.net.flow.FlowRuleOperationsContext; import org.onosproject.net.flow.FlowRuleService; import org.onosproject.net.flow.TrafficSelector; import org.onosproject.net.flow.TrafficTreatment; import java.util.ArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * Installs bulk flows. */ @Command(scope = "onos", name = "add-test-flows", description = "Installs a number of test flow rules - for testing only") public class AddTestFlowsCommand extends AbstractShellCommand { private CountDownLatch latch; @Argument(index = 0, name = "flowPerDevice", description = "Number of flows to add per device", required = true, multiValued = false) String flows = null; @Argument(index = 1, name = "numOfRuns", description = "Number of iterations", required = true, multiValued = false) String numOfRuns = null; @Override protected void execute() { FlowRuleService flowService = get(FlowRuleService.class); DeviceService deviceService = get(DeviceService.class); CoreService coreService = get(CoreService.class); ApplicationId appId = coreService.registerApplication("onos.test.flow.installer"); int flowsPerDevice = Integer.parseInt(flows); int num = Integer.parseInt(numOfRuns); ArrayList<Long> results = Lists.newArrayList(); Iterable<Device> devices = deviceService.getDevices(); TrafficTreatment treatment = DefaultTrafficTreatment.builder() .setOutput(PortNumber.portNumber(RandomUtils.nextInt())).build(); TrafficSelector.Builder sbuilder; FlowRuleOperations.Builder rules = FlowRuleOperations.builder(); FlowRuleOperations.Builder remove = FlowRuleOperations.builder(); for (Device d : devices) { for (int i = 0; i < flowsPerDevice; i++) { sbuilder = DefaultTrafficSelector.builder(); sbuilder.matchEthSrc(MacAddress.valueOf(RandomUtils.nextInt() * i)) .matchEthDst(MacAddress.valueOf((Integer.MAX_VALUE - i) * RandomUtils.nextInt())); int randomPriority = RandomUtils.nextInt(); FlowRule addRule = DefaultFlowRule.builder() .forDevice(d.id()) .withSelector(sbuilder.build()) .withTreatment(treatment) .withPriority(randomPriority) .fromApp(appId) .makeTemporary(10) .build(); FlowRule removeRule = DefaultFlowRule.builder() .forDevice(d.id()) .withSelector(sbuilder.build()) .withTreatment(treatment) .withPriority(randomPriority) .fromApp(appId) .makeTemporary(10) .build(); rules.add(addRule); remove.remove(removeRule); } } for (int i = 0; i < num; i++) { latch = new CountDownLatch(2); flowService.apply(rules.build(new FlowRuleOperationsContext() { private final Stopwatch timer = Stopwatch.createStarted(); @Override public void onSuccess(FlowRuleOperations ops) { timer.stop(); results.add(timer.elapsed(TimeUnit.MILLISECONDS)); if (results.size() == num) { if (outputJson()) { print("%s", json(new ObjectMapper(), true, results)); } else { printTime(true, results); } } latch.countDown(); } })); flowService.apply(remove.build(new FlowRuleOperationsContext() { @Override public void onSuccess(FlowRuleOperations ops) { latch.countDown(); } })); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } } private Object json(ObjectMapper mapper, boolean isSuccess, ArrayList<Long> elapsed) { ObjectNode result = mapper.createObjectNode(); result.put("Success", isSuccess); ArrayNode node = result.putArray("elapsed-time"); for (Long v : elapsed) { node.add(v); } return result; } private void printTime(boolean isSuccess, ArrayList<Long> elapsed) { print("Run is %s.", isSuccess ? "success" : "failure"); for (int i = 0; i < elapsed.size(); i++) { print(" Run %s : %s", i, elapsed.get(i)); } } }
apache-2.0
rmarting/camel
components/camel-lra/src/main/java/org/apache/camel/service/lra/LRAConstants.java
1666
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.service.lra; /** * */ public final class LRAConstants { public static final String DEFAULT_COORDINATOR_CONTEXT_PATH = "/lra-coordinator"; public static final String DEFAULT_LOCAL_PARTICIPANT_CONTEXT_PATH = "/lra-participant"; static final String COORDINATOR_PATH_START = "/start"; static final String COORDINATOR_PATH_CLOSE = "/close"; static final String COORDINATOR_PATH_CANCEL = "/cancel"; static final String PARTICIPANT_PATH_COMPENSATE = "/compensate"; static final String PARTICIPANT_PATH_COMPLETE = "/complete"; static final String HEADER_LINK = "Link"; static final String HEADER_TIME_LIMIT = "TimeLimit"; static final String URL_COMPENSATION_KEY = "Camel-Saga-Compensate"; static final String URL_COMPLETION_KEY = "Camel-Saga-Complete"; private LRAConstants() { } }
apache-2.0
ipros-team/presto
presto-tpch/src/main/java/com/facebook/presto/tpch/TpchSplitManager.java
2821
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.tpch; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.ConnectorSplit; import com.facebook.presto.spi.ConnectorSplitSource; import com.facebook.presto.spi.ConnectorTableLayoutHandle; import com.facebook.presto.spi.FixedSplitSource; import com.facebook.presto.spi.Node; import com.facebook.presto.spi.NodeManager; import com.facebook.presto.spi.connector.ConnectorSplitManager; import com.facebook.presto.spi.connector.ConnectorTransactionHandle; import com.google.common.collect.ImmutableList; import java.util.Set; import static com.facebook.presto.tpch.Types.checkType; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; public class TpchSplitManager implements ConnectorSplitManager { private final String connectorId; private final NodeManager nodeManager; private final int splitsPerNode; public TpchSplitManager(String connectorId, NodeManager nodeManager, int splitsPerNode) { this.connectorId = connectorId; this.nodeManager = nodeManager; checkArgument(splitsPerNode > 0, "splitsPerNode must be at least 1"); this.splitsPerNode = splitsPerNode; } @Override public ConnectorSplitSource getSplits(ConnectorTransactionHandle transaction, ConnectorSession session, ConnectorTableLayoutHandle layout) { TpchTableHandle tableHandle = checkType(layout, TpchTableLayoutHandle.class, "layout").getTable(); Set<Node> nodes = nodeManager.getActiveDatasourceNodes(connectorId); checkState(!nodes.isEmpty(), "No TPCH nodes available"); int totalParts = nodes.size() * splitsPerNode; int partNumber = 0; // Split the data using split and skew by the number of nodes available. ImmutableList.Builder<ConnectorSplit> splits = ImmutableList.builder(); for (Node node : nodes) { for (int i = 0; i < splitsPerNode; i++) { splits.add(new TpchSplit(tableHandle, partNumber, totalParts, ImmutableList.of(node.getHostAndPort()))); partNumber++; } } return new FixedSplitSource(connectorId, splits.build()); } }
apache-2.0
siosio/intellij-community
platform/external-system-rt/src/com/intellij/openapi/externalSystem/model/project/ExternalSystemSourceType.java
2489
package com.intellij.openapi.externalSystem.model.project; import org.jetbrains.annotations.Nullable; /** * Enumerates module source types. * * @author Denis Zhdanov */ public enum ExternalSystemSourceType implements IExternalSystemSourceType { SOURCE(false, false, false, false), TEST(true, false, false, false), EXCLUDED(false, false, false, true), SOURCE_GENERATED(false, true, false, false), TEST_GENERATED(true, true, false, false), RESOURCE(false, false, true, false), TEST_RESOURCE(true, false, true, false), RESOURCE_GENERATED(false, true, true, false), TEST_RESOURCE_GENERATED(true, true, true, false); private final boolean isTest; private final boolean isGenerated; private final boolean isResource; private final boolean isExcluded; ExternalSystemSourceType(boolean test, boolean generated, boolean resource, boolean excluded) { isTest = test; isGenerated = generated; isResource = resource; isExcluded = excluded; } @Override public boolean isTest() { return isTest; } @Override public boolean isGenerated() { return isGenerated; } @Override public boolean isResource() { return isResource; } @Override public boolean isExcluded() { return isExcluded; } public static ExternalSystemSourceType from(IExternalSystemSourceType sourceType) { for (ExternalSystemSourceType systemSourceType : ExternalSystemSourceType.values()) { if (systemSourceType.isGenerated == sourceType.isGenerated() && systemSourceType.isResource == sourceType.isResource() && systemSourceType.isTest == sourceType.isTest() && systemSourceType.isExcluded == sourceType.isExcluded()) { return systemSourceType; } } throw new IllegalArgumentException("Invalid source type: " + sourceType); } @Nullable public static ExternalSystemSourceType from(boolean isTest, boolean isGenerated, boolean isResource, boolean isExcluded) { for (ExternalSystemSourceType systemSourceType : ExternalSystemSourceType.values()) { if (systemSourceType.isGenerated == isGenerated && systemSourceType.isResource == isResource && systemSourceType.isTest == isTest && systemSourceType.isExcluded == isExcluded) { return systemSourceType; } } return null; } }
apache-2.0
nikhilvibhav/camel
components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileMoveExistingStrategy.java
2074
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.file.strategy; import org.apache.camel.component.file.GenericFileEndpoint; import org.apache.camel.component.file.GenericFileOperationFailedException; import org.apache.camel.component.file.GenericFileOperations; /** * This is the interface to be implemented when a custom implementation needs to be provided in case of fileExists=Move * is in use while moving any existing file in producer endpoints. */ public interface FileMoveExistingStrategy { /** * Moves any existing file due fileExists=Move is in use. * * @param endpoint the given endpoint of the component * @param operations file operations API of the relevant component's API * @return result of the file opeartion can be returned note that for now, implemetion classes for file * component and ftp components, always returned true. However,if such a need of direct usage of * File API returning true|false, you can use that return value for implementation's return * value. */ boolean moveExistingFile(GenericFileEndpoint endpoint, GenericFileOperations operations, String fileName) throws GenericFileOperationFailedException; }
apache-2.0
nikhilvibhav/camel
components/camel-cxf/src/main/java/org/apache/camel/component/cxf/jaxrs/HostnameVerifierCxfRsConfigurer.java
2125
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.cxf.jaxrs; import javax.net.ssl.HostnameVerifier; import org.apache.camel.component.cxf.common.AbstractHostnameVerifierEndpointConfigurer; import org.apache.cxf.endpoint.Server; import org.apache.cxf.jaxrs.AbstractJAXRSFactoryBean; import org.apache.cxf.jaxrs.client.Client; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.transport.http.HTTPConduit; public final class HostnameVerifierCxfRsConfigurer extends AbstractHostnameVerifierEndpointConfigurer implements CxfRsConfigurer { private HostnameVerifierCxfRsConfigurer(HostnameVerifier hostnameVerifier) { super(hostnameVerifier); } public static CxfRsConfigurer create(HostnameVerifier hostnameVerifier) { if (hostnameVerifier == null) { return new ChainedCxfRsConfigurer.NullCxfRsConfigurer(); } else { return new HostnameVerifierCxfRsConfigurer(hostnameVerifier); } } @Override public void configure(AbstractJAXRSFactoryBean factoryBean) { } @Override public void configureClient(Client client) { HTTPConduit httpConduit = (HTTPConduit) WebClient.getConfig(client).getConduit(); setupHttpConduit(httpConduit); } @Override public void configureServer(Server server) { } }
apache-2.0
mplushnikov/lombok-intellij-plugin
testData/intention/replaceLombok/NotReplaceIncorrectAccessors.java
264
public class ReplaceGetterFromField { private int fi<caret>eld; public int getField() { System.out.println("some stub"); return 0; } public void setField(int field) { System.out.println("Additional monitoring"); this.field = field; } }
bsd-3-clause
tsuna/asynchbase
src/UnknownRowLockException.java
2802
/* * Copyright (C) 2010-2012 The Async HBase Authors. All rights reserved. * This file is part of Async HBase. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the StumbleUpon nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.hbase.async; /** * Exception thrown when we try to use an invalid or expired {@link RowLock}. */ public final class UnknownRowLockException extends NonRecoverableException implements HasFailedRpcException { static final String REMOTE_CLASS = "org.apache.hadoop.hbase.UnknownRowLockException"; final HBaseRpc failed_rpc; /** * Constructor. * @param msg The message of the exception, potentially with a stack trace. * @param failed_rpc The RPC that caused this exception, if known, or null. */ UnknownRowLockException(final String msg, final HBaseRpc failed_rpc) { super(msg + "\nCaused by RPC: " + failed_rpc); this.failed_rpc = failed_rpc; } public HBaseRpc getFailedRpc() { return failed_rpc; } @Override UnknownRowLockException make(final Object msg, final HBaseRpc rpc) { if (msg == this || msg instanceof UnknownRowLockException) { final UnknownRowLockException e = (UnknownRowLockException) msg; return new UnknownRowLockException(e.getMessage(), rpc); } return new UnknownRowLockException(msg.toString(), rpc); } private static final long serialVersionUID = 1281540942; }
bsd-3-clause
plumer/codana
tomcat_files/7.0.61/SmapGenerator.java
5996
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper.compiler; import java.util.ArrayList; import java.util.List; /** * Represents a source map (SMAP), which serves to associate lines * of the input JSP file(s) to lines in the generated servlet in the * final .class file, according to the JSR-045 spec. * * @author Shawn Bayern */ public class SmapGenerator { //********************************************************************* // Overview /* * The SMAP syntax is reasonably straightforward. The purpose of this * class is currently twofold: * - to provide a simple but low-level Java interface to build * a logical SMAP * - to serialize this logical SMAP for eventual inclusion directly * into a .class file. */ //********************************************************************* // Private state private String outputFileName; private String defaultStratum = "Java"; private List<SmapStratum> strata = new ArrayList<SmapStratum>(); private List<String> embedded = new ArrayList<String>(); private boolean doEmbedded = true; //********************************************************************* // Methods for adding mapping data /** * Sets the filename (without path information) for the generated * source file. E.g., "foo$jsp.java". */ public synchronized void setOutputFileName(String x) { outputFileName = x; } /** * Adds the given SmapStratum object, representing a Stratum with * logically associated FileSection and LineSection blocks, to * the current SmapGenerator. If <tt>default</tt> is true, this * stratum is made the default stratum, overriding any previously * set default. * * @param stratum the SmapStratum object to add * @param defaultStratum if <tt>true</tt>, this SmapStratum is considered * to represent the default SMAP stratum unless * overwritten */ public synchronized void addStratum(SmapStratum stratum, boolean defaultStratum) { strata.add(stratum); if (defaultStratum) this.defaultStratum = stratum.getStratumName(); } /** * Adds the given string as an embedded SMAP with the given stratum name. * * @param smap the SMAP to embed * @param stratumName the name of the stratum output by the compilation * that produced the <tt>smap</tt> to be embedded */ public synchronized void addSmap(String smap, String stratumName) { embedded.add("*O " + stratumName + "\n" + smap + "*C " + stratumName + "\n"); } /** * Instructs the SmapGenerator whether to actually print any embedded * SMAPs or not. Intended for situations without an SMAP resolver. * * @param status If <tt>false</tt>, ignore any embedded SMAPs. */ public void setDoEmbedded(boolean status) { doEmbedded = status; } //********************************************************************* // Methods for serializing the logical SMAP public synchronized String getString() { // check state and initialize buffer if (outputFileName == null) throw new IllegalStateException(); StringBuilder out = new StringBuilder(); // start the SMAP out.append("SMAP\n"); out.append(outputFileName + '\n'); out.append(defaultStratum + '\n'); // include embedded SMAPs if (doEmbedded) { int nEmbedded = embedded.size(); for (int i = 0; i < nEmbedded; i++) { out.append(embedded.get(i)); } } // print our StratumSections, FileSections, and LineSections int nStrata = strata.size(); for (int i = 0; i < nStrata; i++) { SmapStratum s = strata.get(i); out.append(s.getString()); } // end the SMAP out.append("*E\n"); return out.toString(); } @Override public String toString() { return getString(); } //********************************************************************* // For testing (and as an example of use)... public static void main(String args[]) { SmapGenerator g = new SmapGenerator(); g.setOutputFileName("foo.java"); SmapStratum s = new SmapStratum("JSP"); s.addFile("foo.jsp"); s.addFile("bar.jsp", "/foo/foo/bar.jsp"); s.addLineData(1, "foo.jsp", 1, 1, 1); s.addLineData(2, "foo.jsp", 1, 6, 1); s.addLineData(3, "foo.jsp", 2, 10, 5); s.addLineData(20, "bar.jsp", 1, 30, 1); g.addStratum(s, true); System.out.print(g); System.out.println("---"); SmapGenerator embedded = new SmapGenerator(); embedded.setOutputFileName("blargh.tier2"); s = new SmapStratum("Tier2"); s.addFile("1.tier2"); s.addLineData(1, "1.tier2", 1, 1, 1); embedded.addStratum(s, true); g.addSmap(embedded.toString(), "JSP"); System.out.println(g); } }
mit
jeffmart/incubator-trafficcontrol
traffic_router/core/src/main/java/com/comcast/cdn/traffic_control/traffic_router/core/config/WatcherConfig.java
1494
/* * * 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.comcast.cdn.traffic_control.traffic_router.core.config; import com.comcast.cdn.traffic_control.traffic_router.core.util.JsonUtils; import com.comcast.cdn.traffic_control.traffic_router.core.util.TrafficOpsUtils; import com.fasterxml.jackson.databind.JsonNode; public class WatcherConfig { private final String url; private final long interval; // this is an int instead of a long because of protected resource fetcher private final int timeout; public WatcherConfig(final String prefix, final JsonNode config, final TrafficOpsUtils trafficOpsUtils) { url = trafficOpsUtils.getUrl(prefix + ".polling.url", ""); interval = JsonUtils.optLong(config, prefix + ".polling.interval", -1L); timeout = JsonUtils.optInt(config, prefix + ".polling.timeout", -1); } public long getInterval() { return interval; } public String getUrl() { return url; } public int getTimeout() { return timeout; } }
apache-2.0
rsharipov/izpack
izpack-util/src/main/java/com/izforge/izpack/util/config/ConfigFileTask.java
2446
/* * IzPack - Copyright 2001-2010 Julien Ponge, All Rights Reserved. * * http://izpack.org/ * http://izpack.codehaus.org/ * * Copyright 2005,2009 Ivan SZKIBA * Copyright 2010,2011 Rene Krell * * 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.izforge.izpack.util.config; import java.io.File; import java.util.List; public abstract class ConfigFileTask extends SingleConfigurableTask { protected File oldFile; protected File newFile; protected File toFile; protected boolean cleanup; /** * Use this to prepend a comment to the configuration file's header */ private List<String> comment; /** * Location of the configuration file to be patched to; optional. If not set, any empty * reference file is assumed, instead. */ public void setNewFile(File file) { this.newFile = file; } /** * Location of the configuration file to be patched from; optional. If not set, attributes * defining preservations of entries and values are ignored. */ public void setOldFile(File file) { this.oldFile = file; } /** * Location of the resulting output file; required. */ public void setToFile(File file) { this.toFile = file; } /** * Whether to delete the patchfile after the operation * @param cleanup True, if the patchfile should be deleted after the operation */ public void setCleanup(boolean cleanup) { this.cleanup = cleanup; } /** * optional header comment for the file */ public void setComment(List<String> hdr) { comment = hdr; } protected List<String> getComment() { return this.comment; } @Override protected void checkAttributes() throws Exception { if (this.toFile == null) { throw new Exception("The \"file\" attribute must be set"); } } }
apache-2.0
jomarko/kie-wb-common
kie-wb-common-screens/kie-wb-common-data-modeller/kie-wb-common-data-modeller-client/src/main/java/org/kie/workbench/common/screens/datamodeller/client/widgets/editor/NewFieldPopupView.java
1758
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.screens.datamodeller.client.widgets.editor; import java.util.List; import org.uberfire.client.mvp.UberView; import org.uberfire.commons.data.Pair; public interface NewFieldPopupView extends UberView<NewFieldPopupView.Presenter> { interface Presenter { void onCreate(); void onCreateAndContinue(); void onCancel(); void onTypeChange(); } interface NewFieldPopupHandler { void onCreate( String fieldName, String fieldLabel, String type, boolean multiple ); void onCreateAndContinue( String fieldName, String fieldLabel, String type, boolean multiple ); void onCancel(); } void initTypeList( List<Pair<String, String>> options, boolean includeEmptyItem ); String getSelectedType(); String getFieldName(); String getFieldLabel(); void setErrorMessage( String errorMessage ); boolean getIsMultiple(); void setIsMultiple( boolean multiple ); void enableIsMultiple( boolean enabled ); void setFocusOnFieldName(); void clear(); void show(); void hide(); }
apache-2.0
samaitra/jena
jena-sdb/src/test/java/org/apache/jena/sdb/test/misc/TestExprMatch.java
9795
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.sdb.test.misc; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.apache.jena.sdb.exprmatch.* ; import org.apache.jena.sparql.core.Var ; import org.apache.jena.sparql.util.ExprUtils ; import org.junit.Test; public class TestExprMatch { // ---- Basic tests @Test public void match_0() { MapAction mapAction = new MapAction() ; match("?x", "?a", mapAction, null) ; } @Test public void match_1() { MapAction mapAction = new MapAction() ; MapResult mapResult = new MapResult() ; mapResult.put(Var.alloc("a"), "?x") ; match("?x", "?a", mapAction, null) ; } @Test public void match_2() { MapAction mapAction = new MapAction() ; mapAction.put(Var.alloc("a"), new ActionMatchVar()) ; MapResult mapResult = new MapResult() ; mapResult.put(Var.alloc("a"), ExprUtils.parse("?x")) ; match("?x", "?a", mapAction, mapResult) ; } @Test public void match_3() { MapAction mapAction = new MapAction() ; mapAction.put(Var.alloc("a"), new ActionMatchNoBind()) ; MapResult mapResult = new MapResult() ; match("?x", "?a", mapAction, mapResult) ; } @Test public void match_4() { MapAction mapAction = new MapAction() ; MapResult mapResult = new MapResult() ; mapResult.put(Var.alloc("a"), "1") ; // Value one match("1", "?a", mapAction, mapResult) ; } @Test public void match_5() { MapAction mapAction = new MapAction() ; noMatch("?a", "1", mapAction) ; } @Test public void struct_1() { MapAction mapAction = new MapAction() ; MapResult mapResult = new MapResult() ; match("1+2=3", "(1+2)=3", mapAction, null) ; } @Test public void struct_2() { MapAction mapAction = new MapAction() ; MapResult mapResult = new MapResult() ; match("1+2+3", "(1+2)+3", mapAction, null) ; } @Test public void struct_3() { MapAction mapAction = new MapAction() ; // Different structures. noMatch("1+2+3", "1+(2+3)", mapAction) ; } // ---- Comparison tests @Test public void cond_1() { MapAction mapAction = new MapAction() ; mapAction.put(Var.alloc("a1"), new ActionMatchVar()) ; mapAction.put(Var.alloc("a2"), new ActionMatchBind()) ; MapResult mapResult = new MapResult() ; mapResult.put(Var.alloc("a1"), "?x") ; mapResult.put(Var.alloc("a2"), "3") ; match("?x < 3", "?a1 < ?a2", mapAction, mapResult) ; } @Test public void cond_2() { MapAction mapAction = new MapAction() ; mapAction.put(Var.alloc("a1"), new ActionMatchVar()) ; mapAction.put(Var.alloc("a2"), new ActionMatchBind()) ; MapResult mapResult = new MapResult() ; mapResult.put(Var.alloc("a1"), "?x") ; mapResult.put(Var.alloc("a2"), "3") ; noMatch("?x < 3", "?a1 > ?a2", mapAction) ; } // ---- Regex tests @Test public void regex_1() { MapAction mapAction = new MapAction() ; mapAction.put(Var.alloc("a1"), new ActionMatchVar()) ; mapAction.put(Var.alloc("a2"), new ActionMatchString()) ; MapResult mapResult = new MapResult() ; mapResult.put(Var.alloc("a1"), "?x") ; mapResult.put(Var.alloc("a2"), "'smith'") ; match("regex(?x , 'smith')", "regex(?a1 , ?a2)", mapAction, mapResult) ; } @Test public void regex_2() { MapAction mapAction = new MapAction() ; mapAction.put(Var.alloc("a1"), new ActionMatchVar()) ; mapAction.put(Var.alloc("a2"), new ActionMatchString()) ; mapAction.put(Var.alloc("a3"), new ActionMatchString()) ; noMatch("regex(?x , 'smith')", "regex(?a1 , ?a2, ?a3)", mapAction) ; } @Test public void regex_3() { MapAction mapAction = new MapAction() ; mapAction.put(Var.alloc("a1"), new ActionMatchVar()) ; mapAction.put(Var.alloc("a2"), new ActionMatchString()) ; mapAction.put(Var.alloc("a3"), new ActionMatchString()) ; MapResult mapResult = new MapResult() ; mapResult.put(Var.alloc("a1"), "?x") ; mapResult.put(Var.alloc("a2"), "'smith'") ; mapResult.put(Var.alloc("a3"), "'i'") ; match("regex(?x , 'smith', 'i')", "regex(?a1, ?a2, ?a3)", mapAction, mapResult) ; } @Test public void regex_4() { MapAction mapAction = new MapAction() ; mapAction.put(Var.alloc("a1"), new ActionMatchVar()) ; mapAction.put(Var.alloc("a2"), new ActionMatchString()) ; mapAction.put(Var.alloc("a3"), new ActionMatchExact("'i'")) ; MapResult mapResult = new MapResult() ; mapResult.put(Var.alloc("a1"), "?x") ; mapResult.put(Var.alloc("a2"), "'smith'") ; mapResult.put(Var.alloc("a3"), "'i'") ; match("regex(?x , 'smith', 'i')", "regex(?a1, ?a2, ?a3)", mapAction, mapResult) ; } @Test public void regex_5() { MapAction mapAction = new MapAction() ; mapAction.put(Var.alloc("a1"), new ActionMatchVar()) ; mapAction.put(Var.alloc("a2"), new ActionMatchString()) ; noMatch("regex(?x , 'smith', 'i')", "regex(?a1, ?a2)", mapAction) ; } @Test public void regex_6() { MapAction mapAction = new MapAction() ; //mapAction.put(Var.alloc("a1"), new ActionMatch mapAction.put(Var.alloc("a2"), new ActionMatchString()) ; mapAction.put(Var.alloc("a3"), new ActionMatchExact("'i'")) ; MapResult mapResult = new MapResult() ; mapResult.put(Var.alloc("a1"), "str(?x)") ; mapResult.put(Var.alloc("a2"), "'smith'") ; mapResult.put(Var.alloc("a3"), "'i'") ; match("regex(str(?x) , 'smith', 'i')", "regex(?a1, ?a2, ?a3)", mapAction, mapResult) ; } @Test public void regex_7() { MapAction mapAction = new MapAction() ; //mapAction.put(Var.alloc("a1"), new ActionMatch mapAction.put(Var.alloc("a2"), new ActionMatchString()) ; mapAction.put(Var.alloc("a3"), new ActionMatchExact("'i'")) ; MapResult mapResult = new MapResult() ; mapResult.put(Var.alloc("a1"), "?x") ; mapResult.put(Var.alloc("a2"), "'smith'") ; mapResult.put(Var.alloc("a3"), "'i'") ; match("regex(str(?x) , 'smith', 'i')", "regex(str(?a1), ?a2, ?a3)", mapAction, mapResult) ; } @Test public void regex_8() { MapAction mapAction = new MapAction() ; //mapAction.put(Var.alloc("a1"), new ActionMatch mapAction.put(Var.alloc("a2"), new ActionMatchString()) ; mapAction.put(Var.alloc("a3"), new ActionMatchExact("'i'")) ; noMatch("regex(?x , 'smith', 'i')", "regex(str(?a1), ?a2, ?a3)", mapAction) ; } @Test public void function_1() { MapAction mapAction = new MapAction() ; mapAction.put(Var.alloc("a1"), new ActionMatchVar()) ; MapResult mapResult = new MapResult() ; mapResult.put(Var.alloc("a1"), "?x") ; match("fn:not(?x)", "fn:not(?a1)", mapAction, mapResult) ; } @Test public void function_2() { MapAction mapAction = new MapAction() ; mapAction.put(Var.alloc("a1"), new ActionMatchVar()) ; MapResult mapResult = new MapResult() ; mapResult.put(Var.alloc("a1"), "?x") ; noMatch("fn:not(?x)", "fn:notNot(?a1)", mapAction) ; } // //Run JUnit4 tests in a JUnit3 environment // public static junit.framework.Test suite() // { // return new JUnit4TestAdapter(TestExprMatch.class); // } private MapResult match(String expr, String pattern, MapAction aMap, MapResult expected) { MapResult rMap = ExprMatcher.match(expr, pattern, aMap) ; assertNotNull(rMap) ; if ( expected != null ) assertEquals(expected, rMap) ; return rMap ; } private void noMatch(String expr, String pattern, MapAction aMap) { MapResult rMap = ExprMatcher.match(expr, pattern, aMap) ; assertNull(rMap) ; } }
apache-2.0
asedunov/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/VcsLogQuickSettingsActions.java
867
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.vcs.log.ui.actions; import com.intellij.vcs.log.ui.VcsLogActionPlaces; public class VcsLogQuickSettingsActions extends VcsLogGearActionGroup { public VcsLogQuickSettingsActions() { super(VcsLogActionPlaces.SETTINGS_ACTION_GROUP); } }
apache-2.0
abstractj/keycloak
server-spi-private/src/main/java/org/keycloak/utils/CredentialHelper.java
7608
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.utils; import org.jboss.logging.Logger; import org.keycloak.authentication.Authenticator; import org.keycloak.authentication.AuthenticatorFactory; import org.keycloak.authentication.ClientAuthenticator; import org.keycloak.authentication.ClientAuthenticatorFactory; import org.keycloak.authentication.ConfigurableAuthenticatorFactory; import org.keycloak.authentication.FormAction; import org.keycloak.authentication.FormActionFactory; import org.keycloak.credential.CredentialModel; import org.keycloak.credential.CredentialProvider; import org.keycloak.models.AuthenticationExecutionModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserModel; import org.keycloak.models.credential.OTPCredentialModel; import org.keycloak.representations.idm.CredentialRepresentation; import java.util.Objects; /** * used to set an execution a state based on type. * * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ public class CredentialHelper { private static final Logger logger = Logger.getLogger(CredentialHelper.class); public static void setRequiredCredential(KeycloakSession session, String type, RealmModel realm) { AuthenticationExecutionModel.Requirement requirement = AuthenticationExecutionModel.Requirement.REQUIRED; setOrReplaceAuthenticationRequirement(session, realm, type, requirement, null); } public static void setAlternativeCredential(KeycloakSession session, String type, RealmModel realm) { AuthenticationExecutionModel.Requirement requirement = AuthenticationExecutionModel.Requirement.ALTERNATIVE; setOrReplaceAuthenticationRequirement(session, realm, type, requirement, null); } public static void setOrReplaceAuthenticationRequirement(KeycloakSession session, RealmModel realm, String type, AuthenticationExecutionModel.Requirement requirement, AuthenticationExecutionModel.Requirement currentRequirement) { realm.getAuthenticationFlowsStream().forEach(flow -> realm.getAuthenticationExecutionsStream(flow.getId()) .filter(exe -> { ConfigurableAuthenticatorFactory factory = getConfigurableAuthenticatorFactory(session, exe.getAuthenticator()); return Objects.nonNull(factory) && Objects.equals(type, factory.getReferenceCategory()); }) .filter(exe -> { if (Objects.isNull(currentRequirement) || Objects.equals(exe.getRequirement(), currentRequirement)) return true; else { logger.debugf("Skip switch authenticator execution '%s' to '%s' as it's in state %s", exe.getAuthenticator(), requirement.toString(), exe.getRequirement()); return false; } }) .forEachOrdered(exe -> { exe.setRequirement(requirement); realm.updateAuthenticatorExecution(exe); logger.debugf("Authenticator execution '%s' switched to '%s'", exe.getAuthenticator(), requirement.toString()); })); } public static ConfigurableAuthenticatorFactory getConfigurableAuthenticatorFactory(KeycloakSession session, String providerId) { ConfigurableAuthenticatorFactory factory = (AuthenticatorFactory)session.getKeycloakSessionFactory().getProviderFactory(Authenticator.class, providerId); if (factory == null) { factory = (FormActionFactory)session.getKeycloakSessionFactory().getProviderFactory(FormAction.class, providerId); } if (factory == null) { factory = (ClientAuthenticatorFactory)session.getKeycloakSessionFactory().getProviderFactory(ClientAuthenticator.class, providerId); } return factory; } /** * Create OTP credential either in userStorage or local storage (Keycloak DB) * * @return true if credential was successfully created either in the user storage or Keycloak DB. False if error happened (EG. during HOTP validation) */ public static boolean createOTPCredential(KeycloakSession session, RealmModel realm, UserModel user, String totpCode, OTPCredentialModel credentialModel) { CredentialProvider otpCredentialProvider = session.getProvider(CredentialProvider.class, "keycloak-otp"); String totpSecret = credentialModel.getOTPSecretData().getValue(); UserCredentialModel otpUserCredential = new UserCredentialModel("", realm.getOTPPolicy().getType(), totpSecret); boolean userStorageCreated = session.userCredentialManager().updateCredential(realm, user, otpUserCredential); String credentialId = null; if (userStorageCreated) { logger.debugf("Created OTP credential for user '%s' in the user storage", user.getUsername()); } else { CredentialModel createdCredential = otpCredentialProvider.createCredential(realm, user, credentialModel); credentialId = createdCredential.getId(); } //If the type is HOTP, call verify once to consume the OTP used for registration and increase the counter. UserCredentialModel credential = new UserCredentialModel(credentialId, otpCredentialProvider.getType(), totpCode); return session.userCredentialManager().isValid(realm, user, credential); } public static void deleteOTPCredential(KeycloakSession session, RealmModel realm, UserModel user, String credentialId) { CredentialProvider otpCredentialProvider = session.getProvider(CredentialProvider.class, "keycloak-otp"); boolean removed = otpCredentialProvider.deleteCredential(realm, user, credentialId); // This can usually happened when credential is stored in the userStorage. Propagate to "disable" credential in the userStorage if (!removed) { logger.debug("Removing OTP credential from userStorage"); session.userCredentialManager().disableCredentialType(realm, user, OTPCredentialModel.TYPE); } } /** * Create "dummy" representation of the credential. Typically used when credential is provided by userStorage and we don't know further * details about the credential besides the type * * @param credentialProviderType * @return dummy credential */ public static CredentialRepresentation createUserStorageCredentialRepresentation(String credentialProviderType) { CredentialRepresentation credential = new CredentialRepresentation(); credential.setId(credentialProviderType + "-id"); credential.setType(credentialProviderType); credential.setCreatedDate(-1L); credential.setPriority(0); return credential; } }
apache-2.0
chienjchienj/antlr4
tool/src/org/antlr/v4/semantics/BasicSemanticChecks.java
20118
/* * [The "BSD license"] * Copyright (c) 2012 Terence Parr * Copyright (c) 2012 Sam Harwell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.antlr.v4.semantics; import org.antlr.runtime.Token; import org.antlr.runtime.tree.CommonTree; import org.antlr.runtime.tree.Tree; import org.antlr.v4.misc.Utils; import org.antlr.v4.parse.ANTLRParser; import org.antlr.v4.parse.GrammarTreeVisitor; import org.antlr.v4.tool.ErrorManager; import org.antlr.v4.tool.ErrorType; import org.antlr.v4.tool.Grammar; import org.antlr.v4.tool.Rule; import org.antlr.v4.tool.ast.ActionAST; import org.antlr.v4.tool.ast.AltAST; import org.antlr.v4.tool.ast.BlockAST; import org.antlr.v4.tool.ast.GrammarAST; import org.antlr.v4.tool.ast.GrammarASTWithOptions; import org.antlr.v4.tool.ast.GrammarRootAST; import org.antlr.v4.tool.ast.RuleAST; import org.antlr.v4.tool.ast.RuleRefAST; import org.antlr.v4.tool.ast.TerminalAST; import org.stringtemplate.v4.misc.MultiMap; import java.io.File; import java.util.ArrayList; import java.util.List; /** No side-effects except for setting options into the appropriate node. * TODO: make the side effects into a separate pass this * * Invokes check rules for these: * * FILE_AND_GRAMMAR_NAME_DIFFER * LEXER_RULES_NOT_ALLOWED * PARSER_RULES_NOT_ALLOWED * CANNOT_ALIAS_TOKENS * ARGS_ON_TOKEN_REF * ILLEGAL_OPTION * REWRITE_OR_OP_WITH_NO_OUTPUT_OPTION * NO_RULES * REWRITE_FOR_MULTI_ELEMENT_ALT * HETERO_ILLEGAL_IN_REWRITE_ALT * AST_OP_WITH_NON_AST_OUTPUT_OPTION * AST_OP_IN_ALT_WITH_REWRITE * CONFLICTING_OPTION_IN_TREE_FILTER * WILDCARD_AS_ROOT * INVALID_IMPORT * TOKEN_VOCAB_IN_DELEGATE * IMPORT_NAME_CLASH * REPEATED_PREQUEL * TOKEN_NAMES_MUST_START_UPPER */ public class BasicSemanticChecks extends GrammarTreeVisitor { /** Set of valid imports. Maps delegate to set of delegator grammar types. * validDelegations.get(LEXER) gives list of the kinds of delegators * that can import lexers. */ public static MultiMap<Integer,Integer> validImportTypes = new MultiMap<Integer,Integer>() { { map(ANTLRParser.LEXER, ANTLRParser.LEXER); map(ANTLRParser.LEXER, ANTLRParser.COMBINED); map(ANTLRParser.PARSER, ANTLRParser.PARSER); map(ANTLRParser.PARSER, ANTLRParser.COMBINED); map(ANTLRParser.COMBINED, ANTLRParser.COMBINED); } }; public Grammar g; public RuleCollector ruleCollector; public ErrorManager errMgr; /** * When this is {@code true}, the semantic checks will report * {@link ErrorType#UNRECOGNIZED_ASSOC_OPTION} where appropriate. This may * be set to {@code false} to disable this specific check. * * <p>The default value is {@code true}.</p> */ public boolean checkAssocElementOption = true; /** * This field is used for reporting the {@link ErrorType#MODE_WITHOUT_RULES} * error when necessary. */ protected int nonFragmentRuleCount; /** * This is {@code true} from the time {@link #discoverLexerRule} is called * for a lexer rule with the {@code fragment} modifier until * {@link #exitLexerRule} is called. */ private boolean inFragmentRule; public BasicSemanticChecks(Grammar g, RuleCollector ruleCollector) { this.g = g; this.ruleCollector = ruleCollector; this.errMgr = g.tool.errMgr; } @Override public ErrorManager getErrorManager() { return errMgr; } public void process() { visitGrammar(g.ast); } // Routines to route visitor traffic to the checking routines @Override public void discoverGrammar(GrammarRootAST root, GrammarAST ID) { checkGrammarName(ID.token); } @Override public void finishPrequels(GrammarAST firstPrequel) { if ( firstPrequel==null ) return; GrammarAST parent = (GrammarAST)firstPrequel.parent; List<GrammarAST> options = parent.getAllChildrenWithType(OPTIONS); List<GrammarAST> imports = parent.getAllChildrenWithType(IMPORT); List<GrammarAST> tokens = parent.getAllChildrenWithType(TOKENS_SPEC); checkNumPrequels(options, imports, tokens); } @Override public void importGrammar(GrammarAST label, GrammarAST ID) { checkImport(ID.token); } @Override public void discoverRules(GrammarAST rules) { checkNumRules(rules); } @Override protected void enterMode(GrammarAST tree) { nonFragmentRuleCount = 0; } @Override protected void exitMode(GrammarAST tree) { if (nonFragmentRuleCount == 0) { Token token = tree.getToken(); String name = "?"; if (tree.getChildCount() > 0) { name = tree.getChild(0).getText(); if (name == null || name.isEmpty()) { name = "?"; } token = ((GrammarAST)tree.getChild(0)).getToken(); } g.tool.errMgr.grammarError(ErrorType.MODE_WITHOUT_RULES, g.fileName, token, name, g); } } @Override public void modeDef(GrammarAST m, GrammarAST ID) { if ( !g.isLexer() ) { g.tool.errMgr.grammarError(ErrorType.MODE_NOT_IN_LEXER, g.fileName, ID.token, ID.token.getText(), g); } } @Override public void discoverRule(RuleAST rule, GrammarAST ID, List<GrammarAST> modifiers, ActionAST arg, ActionAST returns, GrammarAST thrws, GrammarAST options, ActionAST locals, List<GrammarAST> actions, GrammarAST block) { // TODO: chk that all or no alts have "# label" checkInvalidRuleDef(ID.token); } @Override public void discoverLexerRule(RuleAST rule, GrammarAST ID, List<GrammarAST> modifiers, GrammarAST block) { checkInvalidRuleDef(ID.token); if (modifiers != null) { for (GrammarAST tree : modifiers) { if (tree.getType() == ANTLRParser.FRAGMENT) { inFragmentRule = true; } } } if (!inFragmentRule) { nonFragmentRuleCount++; } } @Override protected void exitLexerRule(GrammarAST tree) { inFragmentRule = false; } @Override public void ruleRef(GrammarAST ref, ActionAST arg) { checkInvalidRuleRef(ref.token); } @Override public void ruleOption(GrammarAST ID, GrammarAST valueAST) { checkOptions((GrammarAST)ID.getAncestor(RULE), ID.token, valueAST); } @Override public void blockOption(GrammarAST ID, GrammarAST valueAST) { checkOptions((GrammarAST)ID.getAncestor(BLOCK), ID.token, valueAST); } @Override public void grammarOption(GrammarAST ID, GrammarAST valueAST) { boolean ok = checkOptions(g.ast, ID.token, valueAST); //if ( ok ) g.ast.setOption(ID.getText(), value); } @Override public void defineToken(GrammarAST ID) { checkTokenDefinition(ID.token); } @Override protected void enterChannelsSpec(GrammarAST tree) { if (g.isParser()) { g.tool.errMgr.grammarError(ErrorType.CHANNELS_BLOCK_IN_PARSER_GRAMMAR, g.fileName, tree.token); } else if (g.isCombined()) { g.tool.errMgr.grammarError(ErrorType.CHANNELS_BLOCK_IN_COMBINED_GRAMMAR, g.fileName, tree.token); } } @Override public void defineChannel(GrammarAST ID) { checkChannelDefinition(ID.token); } @Override public void elementOption(GrammarASTWithOptions elem, GrammarAST ID, GrammarAST valueAST) { String v = null; boolean ok = checkElementOptions(elem, ID, valueAST); // if ( ok ) { // if ( v!=null ) { // t.setOption(ID.getText(), v); // } // else { // t.setOption(TerminalAST.defaultTokenOption, v); // } // } } @Override public void finishRule(RuleAST rule, GrammarAST ID, GrammarAST block) { if ( rule.isLexerRule() ) return; BlockAST blk = (BlockAST)rule.getFirstChildWithType(BLOCK); int nalts = blk.getChildCount(); GrammarAST idAST = (GrammarAST)rule.getChild(0); for (int i=0; i< nalts; i++) { AltAST altAST = (AltAST)blk.getChild(i); if ( altAST.altLabel!=null ) { String altLabel = altAST.altLabel.getText(); // first check that label doesn't conflict with a rule // label X or x can't be rule x. Rule r = ruleCollector.rules.get(Utils.decapitalize(altLabel)); if ( r!=null ) { g.tool.errMgr.grammarError(ErrorType.ALT_LABEL_CONFLICTS_WITH_RULE, g.fileName, altAST.altLabel.token, altLabel, r.name); } // Now verify that label X or x doesn't conflict with label // in another rule. altLabelToRuleName has both X and x mapped. String prevRuleForLabel = ruleCollector.altLabelToRuleName.get(altLabel); if ( prevRuleForLabel!=null && !prevRuleForLabel.equals(rule.getRuleName()) ) { g.tool.errMgr.grammarError(ErrorType.ALT_LABEL_REDEF, g.fileName, altAST.altLabel.token, altLabel, rule.getRuleName(), prevRuleForLabel); } } } List<GrammarAST> altLabels = ruleCollector.ruleToAltLabels.get(rule.getRuleName()); int numAltLabels = 0; if ( altLabels!=null ) numAltLabels = altLabels.size(); if ( numAltLabels>0 && nalts != numAltLabels ) { g.tool.errMgr.grammarError(ErrorType.RULE_WITH_TOO_FEW_ALT_LABELS, g.fileName, idAST.token, rule.getRuleName()); } } // Routines to do the actual work of checking issues with a grammar. // They are triggered by the visitor methods above. void checkGrammarName(Token nameToken) { String fullyQualifiedName = nameToken.getInputStream().getSourceName(); if (fullyQualifiedName == null) { // This wasn't read from a file. return; } File f = new File(fullyQualifiedName); String fileName = f.getName(); if ( g.originalGrammar!=null ) return; // don't warn about diff if this is implicit lexer if ( !Utils.stripFileExtension(fileName).equals(nameToken.getText()) && !fileName.equals(Grammar.GRAMMAR_FROM_STRING_NAME)) { g.tool.errMgr.grammarError(ErrorType.FILE_AND_GRAMMAR_NAME_DIFFER, fileName, nameToken, nameToken.getText(), fileName); } } void checkNumRules(GrammarAST rulesNode) { if ( rulesNode.getChildCount()==0 ) { GrammarAST root = (GrammarAST)rulesNode.getParent(); GrammarAST IDNode = (GrammarAST)root.getChild(0); g.tool.errMgr.grammarError(ErrorType.NO_RULES, g.fileName, null, IDNode.getText(), g); } } void checkNumPrequels(List<GrammarAST> options, List<GrammarAST> imports, List<GrammarAST> tokens) { List<Token> secondOptionTokens = new ArrayList<Token>(); if ( options!=null && options.size()>1 ) { secondOptionTokens.add(options.get(1).token); } if ( imports!=null && imports.size()>1 ) { secondOptionTokens.add(imports.get(1).token); } if ( tokens!=null && tokens.size()>1 ) { secondOptionTokens.add(tokens.get(1).token); } for (Token t : secondOptionTokens) { String fileName = t.getInputStream().getSourceName(); g.tool.errMgr.grammarError(ErrorType.REPEATED_PREQUEL, fileName, t); } } void checkInvalidRuleDef(Token ruleID) { String fileName = null; if ( ruleID.getInputStream()!=null ) { fileName = ruleID.getInputStream().getSourceName(); } if ( g.isLexer() && Character.isLowerCase(ruleID.getText().charAt(0)) ) { g.tool.errMgr.grammarError(ErrorType.PARSER_RULES_NOT_ALLOWED, fileName, ruleID, ruleID.getText()); } if ( g.isParser() && Grammar.isTokenName(ruleID.getText()) ) { g.tool.errMgr.grammarError(ErrorType.LEXER_RULES_NOT_ALLOWED, fileName, ruleID, ruleID.getText()); } } void checkInvalidRuleRef(Token ruleID) { String fileName = ruleID.getInputStream().getSourceName(); if ( g.isLexer() && Character.isLowerCase(ruleID.getText().charAt(0)) ) { g.tool.errMgr.grammarError(ErrorType.PARSER_RULE_REF_IN_LEXER_RULE, fileName, ruleID, ruleID.getText(), currentRuleName); } } void checkTokenDefinition(Token tokenID) { String fileName = tokenID.getInputStream().getSourceName(); if ( !Grammar.isTokenName(tokenID.getText()) ) { g.tool.errMgr.grammarError(ErrorType.TOKEN_NAMES_MUST_START_UPPER, fileName, tokenID, tokenID.getText()); } } void checkChannelDefinition(Token tokenID) { } @Override protected void enterLexerElement(GrammarAST tree) { } @Override protected void enterLexerCommand(GrammarAST tree) { checkElementIsOuterMostInSingleAlt(tree); if (inFragmentRule) { String fileName = tree.token.getInputStream().getSourceName(); String ruleName = currentRuleName; g.tool.errMgr.grammarError(ErrorType.FRAGMENT_ACTION_IGNORED, fileName, tree.token, ruleName); } } @Override public void actionInAlt(ActionAST action) { if (inFragmentRule) { String fileName = action.token.getInputStream().getSourceName(); String ruleName = currentRuleName; g.tool.errMgr.grammarError(ErrorType.FRAGMENT_ACTION_IGNORED, fileName, action.token, ruleName); } } /** Make sure that action is last element in outer alt; here action, a2, z, and zz are bad, but a3 is ok: (RULE A (BLOCK (ALT {action} 'a'))) (RULE B (BLOCK (ALT (BLOCK (ALT {a2} 'x') (ALT 'y')) {a3}))) (RULE C (BLOCK (ALT 'd' {z}) (ALT 'e' {zz}))) */ protected void checkElementIsOuterMostInSingleAlt(GrammarAST tree) { CommonTree alt = tree.parent; CommonTree blk = alt.parent; boolean outerMostAlt = blk.parent.getType() == RULE; Tree rule = tree.getAncestor(RULE); String fileName = tree.getToken().getInputStream().getSourceName(); if ( !outerMostAlt || blk.getChildCount()>1 ) { ErrorType e = ErrorType.LEXER_COMMAND_PLACEMENT_ISSUE; g.tool.errMgr.grammarError(e, fileName, tree.getToken(), rule.getChild(0).getText()); } } @Override public void label(GrammarAST op, GrammarAST ID, GrammarAST element) { switch (element.getType()) { // token atoms case TOKEN_REF: case STRING_LITERAL: case RANGE: // token sets case SET: case NOT: // rule atoms case RULE_REF: case WILDCARD: return; default: String fileName = ID.token.getInputStream().getSourceName(); g.tool.errMgr.grammarError(ErrorType.LABEL_BLOCK_NOT_A_SET, fileName, ID.token, ID.getText()); break; } } @Override protected void enterLabeledLexerElement(GrammarAST tree) { Token label = ((GrammarAST)tree.getChild(0)).getToken(); g.tool.errMgr.grammarError(ErrorType.V3_LEXER_LABEL, g.fileName, label, label.getText()); } /** Check option is appropriate for grammar, rule, subrule */ boolean checkOptions(GrammarAST parent, Token optionID, GrammarAST valueAST) { boolean ok = true; if ( parent.getType()==ANTLRParser.BLOCK ) { if ( g.isLexer() && !Grammar.LexerBlockOptions.contains(optionID.getText()) ) { // block g.tool.errMgr.grammarError(ErrorType.ILLEGAL_OPTION, g.fileName, optionID, optionID.getText()); ok = false; } if ( !g.isLexer() && !Grammar.ParserBlockOptions.contains(optionID.getText()) ) { // block g.tool.errMgr.grammarError(ErrorType.ILLEGAL_OPTION, g.fileName, optionID, optionID.getText()); ok = false; } } else if ( parent.getType()==ANTLRParser.RULE ) { if ( !Grammar.ruleOptions.contains(optionID.getText()) ) { // rule g.tool.errMgr.grammarError(ErrorType.ILLEGAL_OPTION, g.fileName, optionID, optionID.getText()); ok = false; } } else if ( parent.getType()==ANTLRParser.GRAMMAR && !legalGrammarOption(optionID.getText()) ) { // grammar g.tool.errMgr.grammarError(ErrorType.ILLEGAL_OPTION, g.fileName, optionID, optionID.getText()); ok = false; } return ok; } /** Check option is appropriate for elem; parent of ID is ELEMENT_OPTIONS */ boolean checkElementOptions(GrammarASTWithOptions elem, GrammarAST ID, GrammarAST valueAST) { if (checkAssocElementOption && ID != null && "assoc".equals(ID.getText())) { if (elem.getType() != ANTLRParser.ALT) { Token optionID = ID.token; String fileName = optionID.getInputStream().getSourceName(); g.tool.errMgr.grammarError(ErrorType.UNRECOGNIZED_ASSOC_OPTION, fileName, optionID, currentRuleName); } } if ( elem instanceof RuleRefAST ) { return checkRuleRefOptions((RuleRefAST)elem, ID, valueAST); } if ( elem instanceof TerminalAST ) { return checkTokenOptions((TerminalAST)elem, ID, valueAST); } if ( elem.getType()==ANTLRParser.ACTION ) { return false; } if ( elem.getType()==ANTLRParser.SEMPRED ) { Token optionID = ID.token; String fileName = optionID.getInputStream().getSourceName(); if ( valueAST!=null && !Grammar.semPredOptions.contains(optionID.getText()) ) { g.tool.errMgr.grammarError(ErrorType.ILLEGAL_OPTION, fileName, optionID, optionID.getText()); return false; } } return false; } boolean checkRuleRefOptions(RuleRefAST elem, GrammarAST ID, GrammarAST valueAST) { Token optionID = ID.token; String fileName = optionID.getInputStream().getSourceName(); // don't care about id<SimpleValue> options if ( valueAST!=null && !Grammar.ruleRefOptions.contains(optionID.getText()) ) { g.tool.errMgr.grammarError(ErrorType.ILLEGAL_OPTION, fileName, optionID, optionID.getText()); return false; } // TODO: extra checks depending on rule kind? return true; } boolean checkTokenOptions(TerminalAST elem, GrammarAST ID, GrammarAST valueAST) { Token optionID = ID.token; String fileName = optionID.getInputStream().getSourceName(); // don't care about ID<ASTNodeName> options if ( valueAST!=null && !Grammar.tokenOptions.contains(optionID.getText()) ) { g.tool.errMgr.grammarError(ErrorType.ILLEGAL_OPTION, fileName, optionID, optionID.getText()); return false; } // TODO: extra checks depending on terminal kind? return true; } boolean legalGrammarOption(String key) { switch ( g.getType() ) { case ANTLRParser.LEXER : return Grammar.lexerOptions.contains(key); case ANTLRParser.PARSER : return Grammar.parserOptions.contains(key); default : return Grammar.parserOptions.contains(key); } } void checkImport(Token importID) { Grammar delegate = g.getImportedGrammar(importID.getText()); if ( delegate==null ) return; List<Integer> validDelegators = validImportTypes.get(delegate.getType()); if ( validDelegators!=null && !validDelegators.contains(g.getType()) ) { g.tool.errMgr.grammarError(ErrorType.INVALID_IMPORT, g.fileName, importID, g, delegate); } if ( g.isCombined() && (delegate.name.equals(g.name+Grammar.getGrammarTypeToFileNameSuffix(ANTLRParser.LEXER))|| delegate.name.equals(g.name+Grammar.getGrammarTypeToFileNameSuffix(ANTLRParser.PARSER))) ) { g.tool.errMgr.grammarError(ErrorType.IMPORT_NAME_CLASH, g.fileName, importID, g, delegate); } } }
bsd-3-clause
clinique/openhab2
bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/PentairBindingConstants.java
4844
/** * Copyright (c) 2010-2019 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.pentair.internal; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.smarthome.core.thing.ThingTypeUID; /** * The {@link PentairBindingConstants} class defines common constants, which are * used across the whole binding. * * @author Jeff James - Initial contribution */ @NonNullByDefault public class PentairBindingConstants { public static final String BINDING_ID = "pentair"; // List of Bridge Types public static final String IP_BRIDGE = "ip_bridge"; public static final String SERIAL_BRIDGE = "serial_bridge"; // List of all Device Types public static final String EASYTOUCH = "easytouch"; public static final String INTELLIFLO = "intelliflo"; public static final String INTELLICHLOR = "intellichlor"; // List of all Bridge Thing Type UIDs public static final ThingTypeUID IP_BRIDGE_THING_TYPE = new ThingTypeUID(BINDING_ID, IP_BRIDGE); public static final ThingTypeUID SERIAL_BRIDGE_THING_TYPE = new ThingTypeUID(BINDING_ID, SERIAL_BRIDGE); // List of all Thing Type UIDs public static final ThingTypeUID INTELLIFLO_THING_TYPE = new ThingTypeUID(BINDING_ID, INTELLIFLO); public static final ThingTypeUID EASYTOUCH_THING_TYPE = new ThingTypeUID(BINDING_ID, EASYTOUCH); public static final ThingTypeUID INTELLICHLOR_THING_TYPE = new ThingTypeUID(BINDING_ID, INTELLICHLOR); // List of all Channel ids public static final String EASYTOUCH_POOLTEMP = "pooltemp"; public static final String EASYTOUCH_SPATEMP = "spatemp"; public static final String EASYTOUCH_AIRTEMP = "airtemp"; public static final String EASYTOUCH_SOLARTEMP = "solartemp"; public static final String EASYTOUCH_SPAHEATMODE = "spaheatmode"; public static final String EASYTOUCH_SPAHEATMODESTR = "spaheatmodestr"; public static final String EASYTOUCH_POOLHEATMODE = "poolheatmode"; public static final String EASYTOUCH_POOLHEATMODESTR = "poolheatmodestr"; public static final String EASYTOUCH_HEATACTIVE = "heatactive"; public static final String EASYTOUCH_POOLSETPOINT = "poolsetpoint"; public static final String EASYTOUCH_SPASETPOINT = "spasetpoint"; public static final String EASYTOUCH_POOL = "pool"; public static final String EASYTOUCH_SPA = "spa"; public static final String EASYTOUCH_AUX1 = "aux1"; public static final String EASYTOUCH_AUX2 = "aux2"; public static final String EASYTOUCH_AUX3 = "aux3"; public static final String EASYTOUCH_AUX4 = "aux4"; public static final String EASYTOUCH_AUX5 = "aux5"; public static final String EASYTOUCH_AUX6 = "aux6"; public static final String EASYTOUCH_AUX7 = "aux7"; public static final String EASYTOUCH_FEATURE1 = "feature1"; public static final String EASYTOUCH_FEATURE2 = "feature2"; public static final String EASYTOUCH_FEATURE3 = "feature3"; public static final String EASYTOUCH_FEATURE4 = "feature4"; public static final String EASYTOUCH_FEATURE5 = "feature5"; public static final String EASYTOUCH_FEATURE6 = "feature6"; public static final String EASYTOUCH_FEATURE7 = "feature7"; public static final String EASYTOUCH_FEATURE8 = "feature8"; public static final String INTELLICHLOR_SALTOUTPUT = "saltoutput"; public static final String INTELLICHLOR_SALINITY = "salinity"; public static final String INTELLIFLO_RUN = "run"; public static final String INTELLIFLO_MODE = "mode"; public static final String INTELLIFLO_DRIVESTATE = "drivestate"; public static final String INTELLIFLO_POWER = "power"; public static final String INTELLIFLO_RPM = "rpm"; public static final String INTELLIFLO_PPC = "ppc"; public static final String INTELLIFLO_ERROR = "error"; public static final String INTELLIFLO_TIMER = "timer"; public static final String DIAG = "diag"; // Custom Properties public static final String PROPERTY_ADDRESS = "localhost"; public static final Integer PROPERTY_PORT = 10000; // Set of all supported Thing Type UIDs public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections .unmodifiableSet(Stream.of(IP_BRIDGE_THING_TYPE, SERIAL_BRIDGE_THING_TYPE, EASYTOUCH_THING_TYPE, INTELLIFLO_THING_TYPE, INTELLICHLOR_THING_TYPE).collect(Collectors.toSet())); }
epl-1.0
erpcya/adempierePOS
posterita/posterita/src/main/org/posterita/beans/PaymentAllocationBean.java
3364
/** * Product: Posterita Web-Based POS and Adempiere Plugin * Copyright (C) 2007 Posterita Ltd * This file is part of POSterita * * POSterita is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * Created on Oct 30, 2006 */ package org.posterita.beans; import java.math.BigDecimal; public class PaymentAllocationBean extends UDIBean { public Integer getCreditMemoId() { return creditMemoId; } public void setCreditMemoId(Integer creditMemoId) { this.creditMemoId = creditMemoId; } public String getCreditMemoNumber() { return creditMemoNumber; } public void setCreditMemoNumber(String creditMemoNumber) { this.creditMemoNumber = creditMemoNumber; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public Integer getBpartnerId() { return bpartnerId; } public void setBpartnerId(Integer bpartnerId) { this.bpartnerId = bpartnerId; } public Integer getCashLineId() { return cashLineId; } public void setCashLineId(Integer cashLineId) { this.cashLineId = cashLineId; } public BigDecimal getDiscountAmt() { return discountAmt; } public void setDiscountAmt(BigDecimal discountAmt) { this.discountAmt = discountAmt; } public String getDocumentNo() { return documentNo; } public void setDocumentNo(String documentNo) { this.documentNo = documentNo; } public Integer getInvoiceId() { return invoiceId; } public void setInvoiceId(Integer invoiceId) { this.invoiceId = invoiceId; } public String getInvoiceNo() { return invoiceNo; } public void setInvoiceNo(String invoiceNo) { this.invoiceNo = invoiceNo; } public Integer getOrderId() { return orderId; } public void setOrderId(Integer orderId) { this.orderId = orderId; } public BigDecimal getOverUnderPayment() { return overUnderPayment; } public void setOverUnderPayment(BigDecimal overUnderPayment) { this.overUnderPayment = overUnderPayment; } public String getPartnerName() { return partnerName; } public void setPartnerName(String partnerName) { this.partnerName = partnerName; } public Integer getPaymentId() { return paymentId; } public void setPaymentId(Integer paymentId) { this.paymentId = paymentId; } public BigDecimal getWriteOffAmt() { return writeOffAmt; } public void setWriteOffAmt(BigDecimal writeOffAmt) { this.writeOffAmt = writeOffAmt; } public Boolean getIsCustomer() { return isCustomer; } public void setIsCustomer(Boolean isCustomer) { this.isCustomer = isCustomer; } public Boolean getIsVendor() { return isVendor; } public void setIsVendor(Boolean isVendor) { this.isVendor = isVendor; } }
gpl-2.0
siosio/intellij-community
java/java-tests/testData/psi/resolve/var15/DuplicateStaticImport.java
218
import static java.lang.System.out; import static java.lang.System.out; class DuplicateStaticImport { public static void main(String[] args) { <caret>out.println(""); // cannot resolve symbol 'out' } }
apache-2.0
siosio/intellij-community
java/java-structure-view/src/com/intellij/ide/structureView/impl/java/KindSorter.java
2619
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.structureView.impl.java; import com.intellij.ide.util.treeView.smartTree.ActionPresentation; import com.intellij.ide.util.treeView.smartTree.Sorter; import com.intellij.psi.PsiMethod; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.util.Comparator; public class KindSorter implements Sorter { public static final Sorter INSTANCE = new KindSorter(false); public static final Sorter POPUP_INSTANCE = new KindSorter(true); public KindSorter(boolean isPopup) { this.isPopup = isPopup; } @NonNls public static final String ID = "KIND"; private final boolean isPopup; private final Comparator COMPARATOR = new Comparator() { @Override public int compare(final Object o1, final Object o2) { return getWeight(o1) - getWeight(o2); } private int getWeight(final Object value) { if (value instanceof JavaAnonymousClassTreeElement) { return 55; } if (value instanceof JavaClassTreeElement) { return isPopup ? 53 : 10; } if (value instanceof ClassInitializerTreeElement) { return 15; } if (value instanceof SuperTypeGroup) { return 20; } if (value instanceof PsiMethodTreeElement) { final PsiMethodTreeElement methodTreeElement = (PsiMethodTreeElement)value; final PsiMethod method = methodTreeElement.getMethod(); return method != null && method.isConstructor() ? 30 : 35; } if (value instanceof PropertyGroup) { return 40; } if (value instanceof PsiFieldTreeElement) { return 50; } return 60; } }; @Override @NotNull public Comparator getComparator() { return COMPARATOR; } @Override public boolean isVisible() { return false; } @Override @NotNull public ActionPresentation getPresentation() { throw new IllegalStateException(); } @Override @NotNull public String getName() { return ID; } }
apache-2.0
siosio/intellij-community
java/java-tests/testSrc/com/intellij/java/refactoring/inline/InlineMethodMultifileTest.java
1694
// 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.java.refactoring.inline; import com.intellij.JavaTestUtil; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiMethod; import com.intellij.refactoring.LightMultiFileTestCase; import com.intellij.refactoring.MockInlineMethodOptions; import com.intellij.refactoring.inline.InlineMethodProcessor; import com.intellij.refactoring.inline.InlineOptions; import com.intellij.refactoring.util.InlineUtil; public class InlineMethodMultifileTest extends LightMultiFileTestCase { @Override protected String getTestDataPath() { return JavaTestUtil.getJavaTestDataPath() + "/refactoring/inlineMethod/multifile/"; } public void testRemoveStaticImports() { doTest("Foo", "foo"); } public void testPreserveStaticImportsIfOverloaded() { doTest("Foo", "foo"); } public void testDecodeQualifierInMethodReference() { doTest("Foo", "foo"); } private void doTest(String className, String methodName) { doTest(() -> { PsiClass aClass = myFixture.findClass(className); assertNotNull(aClass); PsiMethod method = aClass.findMethodsByName(methodName, false)[0]; final boolean condition = InlineMethodProcessor.checkBadReturns(method) && !InlineUtil.allUsagesAreTailCalls(method); assertFalse("Bad returns found", condition); InlineOptions options = new MockInlineMethodOptions(); final InlineMethodProcessor processor = new InlineMethodProcessor(getProject(), method, null, getEditor(), options.isInlineThisOnly()); processor.run(); }); } }
apache-2.0
Salaboy/jbpm
jbpm-services/jbpm-services-ejb/jbpm-services-ejb-impl/src/test/java/org/jbpm/services/ejb/test/identity/TestIdentityProvider.java
1343
/* * Copyright 2014 JBoss by Red Hat. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.services.ejb.test.identity; import java.util.ArrayList; import java.util.List; import javax.enterprise.context.ApplicationScoped; import org.kie.internal.identity.IdentityProvider; @ApplicationScoped public class TestIdentityProvider implements IdentityProvider { private String name = "testUser"; private List<String> roles = new ArrayList<String>(); public String getName() { return name; } public List<String> getRoles() { return roles; } @Override public boolean hasRole(String role) { return roles.contains(role); } // just for testing public void setRoles(List<String> roles) { this.roles = roles; } public void setName(String name) { this.name = name; } }
apache-2.0
thomasdarimont/keycloak
server-spi-private/src/main/java/org/keycloak/protocol/LoginProtocol.java
3730
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.protocol; import org.keycloak.events.EventBuilder; import org.keycloak.models.AuthenticatedClientSessionModel; import org.keycloak.models.ClientModel; import org.keycloak.models.ClientSessionContext; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.UserSessionModel; import org.keycloak.provider.Provider; import org.keycloak.sessions.AuthenticationSessionModel; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ public interface LoginProtocol extends Provider { enum Error { /** * Login cancelled by the user */ CANCELLED_BY_USER, /** * Applications-initiated action was canceled by the user */ CANCELLED_AIA, /** * Applications-initiated action was canceled by the user. Do not send error. */ CANCELLED_AIA_SILENT, /** * Consent denied by the user */ CONSENT_DENIED, /** * Passive authentication mode requested but nobody is logged in */ PASSIVE_LOGIN_REQUIRED, /** * Passive authentication mode requested, user is logged in, but some other user interaction is necessary (eg. some required login actions exist or Consent approval is necessary for logged in * user) */ PASSIVE_INTERACTION_REQUIRED; } LoginProtocol setSession(KeycloakSession session); LoginProtocol setRealm(RealmModel realm); LoginProtocol setUriInfo(UriInfo uriInfo); LoginProtocol setHttpHeaders(HttpHeaders headers); LoginProtocol setEventBuilder(EventBuilder event); Response authenticated(AuthenticationSessionModel authSession, UserSessionModel userSession, ClientSessionContext clientSessionCtx); Response sendError(AuthenticationSessionModel authSession, Error error); Response backchannelLogout(UserSessionModel userSession, AuthenticatedClientSessionModel clientSession); Response frontchannelLogout(UserSessionModel userSession, AuthenticatedClientSessionModel clientSession); Response finishLogout(UserSessionModel userSession); /** * @param userSession * @param authSession * @return true if SSO cookie authentication can't be used. User will need to "actively" reauthenticate */ boolean requireReauthentication(UserSessionModel userSession, AuthenticationSessionModel authSession); /** * Send not-before revocation policy to the given client. * @param realm * @param resource * @param notBefore * @param managementUrl * @return {@code true} if revocation policy was successfully updated at the client, {@code false} otherwise. */ default boolean sendPushRevocationPolicyRequest(RealmModel realm, ClientModel resource, int notBefore, String managementUrl) { return false; } }
apache-2.0
shaotuanchen/sunflower_exp
tools/source/gcc-4.2.4/libjava/classpath/gnu/java/util/regex/UncheckedRE.java
4719
/* gnu/regexp/UncheckedRE.java Copyright (C) 2001, 2004 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.java.util.regex; /** * UncheckedRE is a subclass of RE that allows programmers an easier means * of programmatically precompiling regular expressions. It is constructed * and used in exactly the same manner as an instance of the RE class; the * only difference is that its constructors do not throw REException. * Instead, if a syntax error is encountered during construction, a * RuntimeException will be thrown. * <P> * Note that this makes UncheckedRE dangerous if constructed with * dynamic data. Do not use UncheckedRE unless you are completely sure * that all input being passed to it contains valid, well-formed * regular expressions for the syntax specified. * * @author <A HREF="mailto:wes@cacas.org">Wes Biggs</A> * @see gnu.java.util.regex.RE * @since gnu.regexp 1.1.4 */ public final class UncheckedRE extends RE { /** * Constructs a regular expression pattern buffer without any compilation * flags set, and using the default syntax (RESyntax.RE_SYNTAX_PERL5). * * @param pattern A regular expression pattern, in the form of a String, * StringBuffer or char[]. Other input types will be converted to * strings using the toString() method. * @exception RuntimeException The input pattern could not be parsed. * @exception NullPointerException The pattern was null. */ public UncheckedRE(Object pattern) { this(pattern,0,RESyntax.RE_SYNTAX_PERL5); } /** * Constructs a regular expression pattern buffer using the specified * compilation flags and the default syntax (RESyntax.RE_SYNTAX_PERL5). * * @param pattern A regular expression pattern, in the form of a String, * StringBuffer, or char[]. Other input types will be converted to * strings using the toString() method. * @param cflags The logical OR of any combination of the compilation flags in the RE class. * @exception RuntimeException The input pattern could not be parsed. * @exception NullPointerException The pattern was null. */ public UncheckedRE(Object pattern, int cflags) { this(pattern,cflags,RESyntax.RE_SYNTAX_PERL5); } /** * Constructs a regular expression pattern buffer using the specified * compilation flags and regular expression syntax. * * @param pattern A regular expression pattern, in the form of a String, * StringBuffer, or char[]. Other input types will be converted to * strings using the toString() method. * @param cflags The logical OR of any combination of the compilation flags in the RE class. * @param syntax The type of regular expression syntax to use. * @exception RuntimeException The input pattern could not be parsed. * @exception NullPointerException The pattern was null. */ public UncheckedRE(Object pattern, int cflags, RESyntax syntax) { try { initialize(pattern,cflags,syntax,0,0); } catch (REException e) { throw new RuntimeException(e.getMessage()); } } }
bsd-3-clause
wstrzelczyk/modules
commcare/src/test/java/org/motechproject/commcare/testutil/RequestTestUtils.java
869
package org.motechproject.commcare.testutil; import org.motechproject.commcare.request.StockTransactionRequest; /** * Utility class for preparing sample stock transactions request. */ public class RequestTestUtils { public static final String CASE_ID = "caseId"; public static final String SECTION_ID = "s1"; public static final String START_DATE = "startDate"; public static final String END_DATE = "endDate"; /** * Prepares a sample stock transaction request. * * @return the sample request */ public static StockTransactionRequest prepareRequest() { StockTransactionRequest request = new StockTransactionRequest(); request.setCaseId(CASE_ID); request.setSectionId(SECTION_ID); request.setStartDate(START_DATE); request.setEndDate(END_DATE); return request; } }
bsd-3-clause
andre-nunes/fenixedu-academic
src/main/java/org/fenixedu/academic/dto/InfoCoordinator.java
2180
/** * Copyright © 2002 Instituto Superior Técnico * * This file is part of FenixEdu Academic. * * FenixEdu Academic is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FenixEdu Academic is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>. */ /* * Created on 27/Out/2003 * */ package org.fenixedu.academic.dto; import org.fenixedu.academic.domain.Coordinator; /** * fenix-head Dominio * * @author João Mota 27/Out/2003 * */ public class InfoCoordinator extends InfoObject { private final Coordinator coordinator; public Coordinator getCoordinator() { return coordinator; } public InfoCoordinator(final Coordinator coordinator) { this.coordinator = coordinator; } public InfoExecutionDegree getInfoExecutionDegree() { return InfoExecutionDegree.newInfoFromDomain(getCoordinator().getExecutionDegree()); } public InfoTeacher getInfoTeacher() { return InfoTeacher.newInfoFromDomain(getCoordinator().getPerson().getTeacher()); } public InfoPerson getInfoPerson() { return InfoPerson.newInfoFromDomain(getCoordinator().getPerson()); } public Boolean getResponsible() { return getCoordinator().getResponsible(); } public static InfoCoordinator newInfoFromDomain(final Coordinator coordinator) { return coordinator == null ? null : new InfoCoordinator(coordinator); } @Override public String getExternalId() { return getCoordinator().getExternalId(); } @Override public void setExternalId(String integer) { throw new Error("Method should not be called!"); } }
lgpl-3.0
ouit0408/sakai
login/login-tool/tool/src/java/org/sakaiproject/login/tool/ContainerLogin.java
4830
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2005, 2006, 2008 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-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.sakaiproject.login.tool; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.event.cover.UsageSessionService; import org.sakaiproject.tool.api.Session; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.user.api.Authentication; import org.sakaiproject.user.api.AuthenticationException; import org.sakaiproject.user.api.Evidence; import org.sakaiproject.user.cover.AuthenticationManager; import org.sakaiproject.util.ExternalTrustedEvidence; /** * <p> * ContainerLogin ... * </p> */ public class ContainerLogin extends HttpServlet { private static final long serialVersionUID = -3589514330633190919L; /** Our log (commons). */ private static Logger M_log = LoggerFactory.getLogger(ContainerLogin.class); private String defaultReturnUrl; /** * Access the Servlet's information display. * * @return servlet information. */ public String getServletInfo() { return "Sakai Container Login"; } /** * Initialize the servlet. * * @param config * The servlet config. * @throws ServletException */ public void init(ServletConfig config) throws ServletException { super.init(config); M_log.info("init()"); defaultReturnUrl = ServerConfigurationService.getString("portalPath", "/portal"); } /** * Shutdown the servlet. */ public void destroy() { M_log.info("destroy()"); super.destroy(); } /** * Respond to requests. * * @param req * The servlet request. * @param res * The servlet response. * @throws ServletException. * @throws IOException. */ protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // get the session Session session = SessionManager.getCurrentSession(); // check the remote user for authentication String remoteUser = req.getRemoteUser(); try { Evidence e = new ExternalTrustedEvidence(remoteUser); Authentication a = AuthenticationManager.authenticate(e); // login the user if (UsageSessionService.login(a.getUid(), a.getEid(), req.getRemoteAddr(), req.getHeader("user-agent"), UsageSessionService.EVENT_LOGIN_CONTAINER)) { // get the return URL String url = getUrl(session, Tool.HELPER_DONE_URL); // cleanup session session.removeAttribute(Tool.HELPER_MESSAGE); session.removeAttribute(Tool.HELPER_DONE_URL); // Mark as successfully authenticated session.setAttribute(SkinnableLogin.ATTR_CONTAINER_SUCCESS, SkinnableLogin.ATTR_CONTAINER_SUCCESS); // redirect to the done URL res.sendRedirect(res.encodeRedirectURL(url)); return; } } catch (AuthenticationException ex) { M_log.warn("Authentication Failed for: "+ remoteUser+ ". "+ ex.getMessage()); } // mark the session and redirect (for login failure or authentication exception) session.setAttribute(SkinnableLogin.ATTR_CONTAINER_CHECKED, SkinnableLogin.ATTR_CONTAINER_CHECKED); res.sendRedirect(res.encodeRedirectURL(getUrl(session, SkinnableLogin.ATTR_RETURN_URL))); } /** * Gets a URL from the session, if not found returns the portal URL. * @param session The users HTTP session. * @param sessionAttribute The attribute the URL is stored under. * @return The URL. */ private String getUrl(Session session, String sessionAttribute) { String url = (String) session.getAttribute(sessionAttribute); if (url == null || url.length() == 0) { M_log.debug("No "+ sessionAttribute + " URL, redirecting to portal URL."); url = defaultReturnUrl; } return url; } }
apache-2.0
skyseazcq/ninja-1
ninja-core/src/main/java/ninja/template/TemplateEngineXml.java
1980
/** * Copyright (C) 2012-2015 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 ninja.template; import java.io.IOException; import java.io.OutputStream; import javax.inject.Singleton; import ninja.Context; import ninja.Result; import ninja.utils.ResponseStreams; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.google.inject.Inject; @Singleton public class TemplateEngineXml implements TemplateEngine { private static final Logger logger = LoggerFactory.getLogger(TemplateEngineXml.class); private final XmlMapper xmlMapper; @Inject public TemplateEngineXml(XmlMapper xmlMapper) { this.xmlMapper = xmlMapper; } @Override public void invoke(Context context, Result result) { ResponseStreams responseStreams = context.finalizeHeaders(result); try (OutputStream outputStream = responseStreams.getOutputStream()) { xmlMapper.writeValue(outputStream, result.getRenderable()); } catch (IOException e) { logger.error("Error while rendering json", e); } } @Override public String getContentType() { return Result.APPLICATION_XML; } @Override public String getSuffixOfTemplatingEngine() { // intentionally returns null... return null; } }
apache-2.0
afinka77/ignite
modules/core/src/test/java/org/apache/ignite/internal/processors/cache/CachePutEventListenerErrorSelfTest.java
6263
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cache; import java.util.UUID; import javax.cache.CacheException; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.Ignition; import org.apache.ignite.cache.CacheAtomicityMode; import org.apache.ignite.cache.CacheMemoryMode; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.events.Event; import org.apache.ignite.events.EventType; import org.apache.ignite.lang.IgniteBiPredicate; import org.apache.ignite.lang.IgnitePredicate; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; /** * Test for cache put with error in event listener. */ public class CachePutEventListenerErrorSelfTest extends GridCommonAbstractTest { /** */ private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true); /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); TcpDiscoverySpi disco = new TcpDiscoverySpi(); disco.setIpFinder(IP_FINDER); cfg.setDiscoverySpi(disco); cfg.setIncludeEventTypes(EventType.EVT_CACHE_OBJECT_PUT); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { startGridsMultiThreaded(3); Ignition.setClientMode(true); try { Ignite ignite = startGrid("client"); ignite.events().remoteListen( new IgniteBiPredicate<UUID, Event>() { @Override public boolean apply(UUID uuid, Event evt) { return true; } }, new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { throw new NoClassDefFoundError("XXX"); } }, EventType.EVT_CACHE_OBJECT_PUT ); } finally { Ignition.setClientMode(false); } } /** {@inheritDoc} */ @Override protected void afterTestsStopped() throws Exception { stopAllGrids(); } /** * @throws Exception If failed. */ public void testPartitionedAtomicOnHeap() throws Exception { doTest(CacheMode.PARTITIONED, CacheAtomicityMode.ATOMIC, CacheMemoryMode.ONHEAP_TIERED); } /** * @throws Exception If failed. */ public void testPartitionedAtomicOffHeap() throws Exception { doTest(CacheMode.PARTITIONED, CacheAtomicityMode.ATOMIC, CacheMemoryMode.OFFHEAP_TIERED); } /** * @throws Exception If failed. */ public void testPartitionedTransactionalOnHeap() throws Exception { doTest(CacheMode.PARTITIONED, CacheAtomicityMode.TRANSACTIONAL, CacheMemoryMode.ONHEAP_TIERED); } /** * @throws Exception If failed. */ public void testPartitionedTransactionalOffHeap() throws Exception { doTest(CacheMode.PARTITIONED, CacheAtomicityMode.TRANSACTIONAL, CacheMemoryMode.OFFHEAP_TIERED); } /** * @throws Exception If failed. */ public void testReplicatedAtomicOnHeap() throws Exception { doTest(CacheMode.REPLICATED, CacheAtomicityMode.ATOMIC, CacheMemoryMode.ONHEAP_TIERED); } /** * @throws Exception If failed. */ public void testReplicatedAtomicOffHeap() throws Exception { doTest(CacheMode.REPLICATED, CacheAtomicityMode.ATOMIC, CacheMemoryMode.OFFHEAP_TIERED); } /** * @throws Exception If failed. */ public void testReplicatedTransactionalOnHeap() throws Exception { doTest(CacheMode.REPLICATED, CacheAtomicityMode.TRANSACTIONAL, CacheMemoryMode.ONHEAP_TIERED); } /** * @throws Exception If failed. */ public void testReplicatedTransactionalOffHeap() throws Exception { doTest(CacheMode.REPLICATED, CacheAtomicityMode.TRANSACTIONAL, CacheMemoryMode.OFFHEAP_TIERED); } /** * @param cacheMode Cache mode. * @param atomicityMode Atomicity mode. * @param memMode Memory mode. * @throws Exception If failed. */ private void doTest(CacheMode cacheMode, CacheAtomicityMode atomicityMode, CacheMemoryMode memMode) throws Exception { Ignite ignite = grid("client"); try { CacheConfiguration<Integer, Integer> cfg = defaultCacheConfiguration(); cfg.setName("cache"); cfg.setCacheMode(cacheMode); cfg.setAtomicityMode(atomicityMode); cfg.setMemoryMode(memMode); IgniteCache<Integer, Integer> cache = ignite.createCache(cfg).withAsync(); cache.put(0, 0); try { cache.future().get(2000); assert false : "Exception was not thrown"; } catch (CacheException e) { info("Caught expected exception: " + e); } } finally { ignite.destroyCache("cache"); } } }
apache-2.0
bhutchinson/rice
rice-middleware/core/api/src/main/java/org/kuali/rice/core/api/impex/xml/ZipXmlDoc.java
1779
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.core.api.impex.xml; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * An XmlDoc implementation backed by a ZipEntry in a ZipFile * @see org.kuali.rice.core.api.impex.xml.batch.XmlDoc * @see org.kuali.rice.core.api.impex.xml.impl.impex.BaseXmlDoc * @see org.kuali.rice.core.api.impex.xml.ZipXmlDocCollection * @author Kuali Rice Team (rice.collab@kuali.org) */ class ZipXmlDoc extends BaseXmlDoc { private ZipFile zipFile; private ZipEntry zipEntry; public ZipXmlDoc(ZipFile zipFile, ZipEntry zipEntry, XmlDocCollection collection) { super(collection); this.zipFile = zipFile; this.zipEntry = zipEntry; } public String getName() { return zipEntry.getName(); } public InputStream getStream() throws IOException { return zipFile.getInputStream(zipEntry); } public int hashCode() { return zipEntry.hashCode(); } public boolean equals(Object o) { if (!(o instanceof ZipXmlDoc)) return false; return zipEntry.equals(((ZipXmlDoc) o).zipEntry); } }
apache-2.0
alficles/incubator-trafficcontrol
traffic_monitor_java/src/main/java/com/comcast/cdn/traffic_control/traffic_monitor/MonitorApplication.java
3690
/* * * 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.comcast.cdn.traffic_control.traffic_monitor; import org.apache.log4j.Logger; import org.apache.wicket.Application; import org.apache.wicket.Page; import org.apache.wicket.Session; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.request.Request; import org.apache.wicket.request.Response; import org.apache.wicket.util.time.Duration; import com.comcast.cdn.traffic_control.traffic_monitor.config.ConfigHandler; import com.comcast.cdn.traffic_control.traffic_monitor.config.RouterConfig; import com.comcast.cdn.traffic_control.traffic_monitor.health.CacheWatcher; import com.comcast.cdn.traffic_control.traffic_monitor.health.DsWatcher; import com.comcast.cdn.traffic_control.traffic_monitor.health.HealthDeterminer; import com.comcast.cdn.traffic_control.traffic_monitor.health.PeerWatcher; import com.comcast.cdn.traffic_control.traffic_monitor.health.TmWatcher; import com.comcast.cdn.traffic_control.traffic_monitor.publish.CrStates; public class MonitorApplication extends WebApplication { private static final Logger LOGGER = Logger.getLogger(MonitorApplication.class); private CacheWatcher cw; private TmWatcher tmw; private PeerWatcher pw; private DsWatcher dsw; private static long startTime; public static MonitorApplication get() { return (MonitorApplication) Application.get(); } /** * @see org.apache.wicket.Application#getHomePage() */ @Override public Class<? extends Page> getHomePage() { return Index.class; } /** * @see org.apache.wicket.Application#init() */ @Override public void init() { super.init(); if (!ConfigHandler.getInstance().configFileExists()) { LOGGER.fatal("Cannot find configuration file: " + ConfigHandler.getInstance().getConfigFile()); // This will only stop Tomcat if the security manager allows it // https://tomcat.apache.org/tomcat-6.0-doc/security-manager-howto.html System.exit(1); } getResourceSettings().setResourcePollFrequency(Duration.ONE_SECOND); // This allows us to override the Host header sent via URLConnection System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); final HealthDeterminer hd = new HealthDeterminer(); tmw = new TmWatcher(hd); cw = new CacheWatcher(); cw.init(hd); dsw = new DsWatcher(); dsw.init(hd); pw = new PeerWatcher(); pw.init(); tmw.addTmListener(RouterConfig.getTmListener(hd)); tmw.init(); CrStates.init(cw, pw, hd); mountPackage("/publish", CrStates.class); startTime = System.currentTimeMillis(); } @Override public Session newSession(final Request request, final Response response) { return new MonitorSession(request); } public void onDestroy() { final boolean forceDown = ConfigHandler.getInstance().getConfig().shouldForceSystemExit(); ConfigHandler.getInstance().destroy(); LOGGER.warn("MonitorApplication: shutting down "); tmw.destroy(); if (forceDown) { LOGGER.warn("MonitorApplication: System.exit"); System.exit(0); } cw.destroy(); dsw.destroy(); pw.destroy(); } public static long getUptime() { return System.currentTimeMillis() - startTime; } }
apache-2.0
samaitra/jena
jena-core/src/main/java/org/apache/jena/rdfxml/xmlinput/impl/Names.java
2344
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.rdfxml.xmlinput.impl; public interface Names { String rdfns = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" .intern(); String xmlns = "http://www.w3.org/XML/1998/namespace".intern(); String xmlnsns = "http://www.w3.org/2000/xmlns/"; int A_XMLBASE = 1; int A_XMLLANG = 2; int A_XML_OTHER = 4; int A_XMLNS = 32768; int A_ID = 8; int A_ABOUT = 16; int A_NODEID = 32; int A_RESOURCE = 64; int A_PARSETYPE = 128; int A_DATATYPE = 256; int A_TYPE = 512; int A_DEPRECATED = 1024; int A_BAGID = 16384; int E_LI = 2048; int E_RDF = 4096; int E_DESCRIPTION = 8192; // see sections 7.2.[2-5] of RDF Syntax (Revised) int CoreAndOldTerms = E_RDF | A_DEPRECATED | A_ABOUT | A_ID | A_NODEID | A_RESOURCE | A_PARSETYPE | A_DATATYPE | A_BAGID; int A_BADATTRS = CoreAndOldTerms | E_LI | E_DESCRIPTION; ANode RDF_STATEMENT = URIReference.createNoChecks(rdfns + "Statement"); ANode RDF_TYPE = URIReference.createNoChecks((rdfns + "type")); ANode RDF_SUBJECT = URIReference.createNoChecks((rdfns + "subject")); ANode RDF_PREDICATE = URIReference.createNoChecks(rdfns + "predicate"); ANode RDF_OBJECT = URIReference.createNoChecks((rdfns + "object")); ANode RDF_NIL = URIReference.createNoChecks(rdfns+"nil"); ANode RDF_FIRST = URIReference.createNoChecks(rdfns+"first"); ANode RDF_REST = URIReference.createNoChecks(rdfns+"rest"); }
apache-2.0
roele/sling
installer/providers/jcr/src/test/java/org/apache/sling/installer/provider/jcr/impl/ScanningLoopTest.java
6177
/* * 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.sling.installer.provider.jcr.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import javax.jcr.Node; import org.junit.Test; /** Verify that JcrInstaller scans folders only when needed */ public class ScanningLoopTest extends JcrInstallTestBase { private void assertCounter(int index, long value) { String label; switch (index ) { case JcrInstaller.RUN_LOOP_COUNTER: label = "RUN_LOOP_COUNTER"; break; case JcrInstaller.SCAN_FOLDERS_COUNTER: label = "SCAN_FOLDERS_COUNTER"; break; case JcrInstaller.UPDATE_FOLDERS_LIST_COUNTER: label = "UPDATE_FOLDERS_LIST_COUNTER"; break; default: label = "Unknown (" + index +")"; break; } assertEquals("Counter " + label, value, installer.getCounterValue(index)); } private void assertIdle() throws Exception { final long sf = installer.getCounterValue(JcrInstaller.SCAN_FOLDERS_COUNTER); final long uc = installer.getCounterValue(JcrInstaller.UPDATE_FOLDERS_LIST_COUNTER); Thread.sleep(JcrInstaller.RUN_LOOP_DELAY_MSEC * 2); assertCounter(JcrInstaller.SCAN_FOLDERS_COUNTER, sf); assertCounter(JcrInstaller.UPDATE_FOLDERS_LIST_COUNTER, uc); } private void assertEvents(String info, long oldCount, int counterIndex) { final long newCount = installer.getCounterValue(counterIndex); assertTrue(info + " (old=" + oldCount + ", new=" + newCount + ")", newCount > oldCount); } @Test public void testIdleState() throws Exception { Thread.sleep(JcrInstaller.RUN_LOOP_DELAY_MSEC * 4); assertIdle(); } @Test public void testDefaultScanPauseFalse() throws Exception{ assertFalse(installer.scanningIsPaused(installer.getConfiguration(), installer.getSession())); } @Test public void testPauseScan() throws Exception{ assertFalse(installer.scanningIsPaused(installer.getConfiguration(), installer.getSession())); Node n = contentHelper.createFolder(JcrInstaller.PAUSE_SCAN_NODE_PATH); Node testNode = n.addNode("foo.example.pause"); session.save(); eventHelper.waitForEvents(TIMEOUT); assertTrue(installer.scanningIsPaused(installer.getConfiguration(), installer.getSession())); final long sf = installer.getCounterValue(JcrInstaller.SCAN_FOLDERS_COUNTER); final long uc = installer.getCounterValue(JcrInstaller.UPDATE_FOLDERS_LIST_COUNTER); Thread.sleep(JcrInstaller.RUN_LOOP_DELAY_MSEC * 2); //Counters should not have changed as no scanning being performed assertEquals(sf, installer.getCounterValue(JcrInstaller.SCAN_FOLDERS_COUNTER)); //Now lets resume again testNode.remove(); session.save(); Thread.sleep(JcrInstaller.RUN_LOOP_DELAY_MSEC * 2); //Now counters should have changed assertIdle(); } @Test public void testAddBundle() throws Exception { contentHelper.createOrUpdateFile(contentHelper.FAKE_RESOURCES[0]); eventHelper.waitForEvents(TIMEOUT); Thread.sleep(JcrInstaller.RUN_LOOP_DELAY_MSEC * 2); assertIdle(); } @Test public void testAddContentOutside() throws Exception { final long sf = installer.getCounterValue(JcrInstaller.SCAN_FOLDERS_COUNTER); final long uc = installer.getCounterValue(JcrInstaller.UPDATE_FOLDERS_LIST_COUNTER); contentHelper.createOrUpdateFile("/" + System.currentTimeMillis()); eventHelper.waitForEvents(TIMEOUT); Thread.sleep(JcrInstaller.RUN_LOOP_DELAY_MSEC * 2); // Adding a file outside /libs or /apps must not "wake up" the scan loop assertCounter(JcrInstaller.SCAN_FOLDERS_COUNTER, sf); assertCounter(JcrInstaller.UPDATE_FOLDERS_LIST_COUNTER, uc); } @Test public void testDeleteFile() throws Exception { contentHelper.setupContent(); eventHelper.waitForEvents(TIMEOUT); Thread.sleep(JcrInstaller.RUN_LOOP_DELAY_MSEC * 2); assertIdle(); final long sf = installer.getCounterValue(JcrInstaller.SCAN_FOLDERS_COUNTER); contentHelper.delete(contentHelper.FAKE_RESOURCES[0]); eventHelper.waitForEvents(TIMEOUT); Thread.sleep(JcrInstaller.RUN_LOOP_DELAY_MSEC * 2); assertEvents("Expected at least one folder scan event", sf, JcrInstaller.SCAN_FOLDERS_COUNTER); assertIdle(); } @Test public void testDeleteLibsFolder() throws Exception { contentHelper.setupContent(); eventHelper.waitForEvents(TIMEOUT); Thread.sleep(JcrInstaller.RUN_LOOP_DELAY_MSEC * 2); assertIdle(); final long uc = installer.getCounterValue(JcrInstaller.UPDATE_FOLDERS_LIST_COUNTER); contentHelper.delete("/libs"); eventHelper.waitForEvents(TIMEOUT); Thread.sleep(JcrInstaller.RUN_LOOP_DELAY_MSEC * 2); assertEvents("Expected at least one folders list update event", uc, JcrInstaller.UPDATE_FOLDERS_LIST_COUNTER); assertIdle(); } }
apache-2.0
apache/flink
flink-core/src/test/java/org/apache/flink/api/common/typeutils/base/BigIntSerializerTest.java
1893
/* * 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.api.common.typeutils.base; import org.apache.flink.api.common.typeutils.SerializerTestBase; import org.apache.flink.api.common.typeutils.TypeSerializer; import java.math.BigInteger; import java.util.Random; /** A test for the {@link BigIntSerializer}. */ public class BigIntSerializerTest extends SerializerTestBase<BigInteger> { @Override protected TypeSerializer<BigInteger> createSerializer() { return new BigIntSerializer(); } @Override protected int getLength() { return -1; } @Override protected Class<BigInteger> getTypeClass() { return BigInteger.class; } @Override protected BigInteger[] getTestData() { Random rnd = new Random(874597969123412341L); return new BigInteger[] { BigInteger.ZERO, BigInteger.ONE, BigInteger.TEN, new BigInteger(1000, rnd), new BigInteger("8745979691234123413478523984729447"), BigInteger.valueOf(-1), BigInteger.valueOf(-10000) }; } }
apache-2.0
codepoke/libgdx
extensions/gdx-bullet/jni/swig-src/linearmath/com/badlogic/gdx/physics/bullet/linearmath/btClock.java
2233
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 3.0.10 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package com.badlogic.gdx.physics.bullet.linearmath; import com.badlogic.gdx.physics.bullet.BulletBase; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Matrix3; import com.badlogic.gdx.math.Matrix4; public class btClock extends BulletBase { private long swigCPtr; protected btClock(final String className, long cPtr, boolean cMemoryOwn) { super(className, cPtr, cMemoryOwn); swigCPtr = cPtr; } /** Construct a new btClock, normally you should not need this constructor it's intended for low-level usage. */ public btClock(long cPtr, boolean cMemoryOwn) { this("btClock", cPtr, cMemoryOwn); construct(); } @Override protected void reset(long cPtr, boolean cMemoryOwn) { if (!destroyed) destroy(); super.reset(swigCPtr = cPtr, cMemoryOwn); } public static long getCPtr(btClock obj) { return (obj == null) ? 0 : obj.swigCPtr; } @Override protected void finalize() throws Throwable { if (!destroyed) destroy(); super.finalize(); } @Override protected synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; LinearMathJNI.delete_btClock(swigCPtr); } swigCPtr = 0; } super.delete(); } public btClock() { this(LinearMathJNI.new_btClock__SWIG_0(), true); } public btClock(btClock other) { this(LinearMathJNI.new_btClock__SWIG_1(btClock.getCPtr(other), other), true); } public void reset() { LinearMathJNI.btClock_reset(swigCPtr, this); } public long getTimeMilliseconds() { return LinearMathJNI.btClock_getTimeMilliseconds(swigCPtr, this); } public long getTimeMicroseconds() { return LinearMathJNI.btClock_getTimeMicroseconds(swigCPtr, this); } public float getTimeSeconds() { return LinearMathJNI.btClock_getTimeSeconds(swigCPtr, this); } }
apache-2.0
papicella/snappy-store
lgpl/gemfire-jgroups/src/main/java/com/gemstone/org/jgroups/blocks/MethodLookup.java
368
/** Notice of modification as required by the LGPL * This file was modified by Gemstone Systems Inc. on * $Date$ **/ package com.gemstone.org.jgroups.blocks; import java.lang.reflect.Method; /** * @author Bela Ban * @version $Id: MethodLookup.java,v 1.3 2005/07/22 08:59:20 belaban Exp $ */ public interface MethodLookup { Method findMethod(short id); }
apache-2.0
zxwing/zstack-1
header/src/main/java/org/zstack/header/network/service/SnatStruct.java
1769
package org.zstack.header.network.service; import org.zstack.header.network.l3.L3NetworkInventory; /** * Created with IntelliJ IDEA. * User: frank * Time: 10:34 PM * To change this template use File | Settings | File Templates. */ public class SnatStruct { private String guestIp; private String guestGateway; private String guestNetmask; private String guestMac; private L3NetworkInventory l3Network; @Override public String toString() { StringBuilder sb = new StringBuilder("["); sb.append(String.format("guest ip: %s,", guestIp)); sb.append(String.format("guest mac: %s,", guestMac)); sb.append(String.format("guest netmask: %s,", guestNetmask)); sb.append(String.format("guest gateway: %s,", guestGateway)); sb.append(String.format("l3NetworkUuid: %s,", l3Network.getUuid())); sb.append("]"); return sb.toString(); } public String getGuestIp() { return guestIp; } public void setGuestIp(String guestIp) { this.guestIp = guestIp; } public String getGuestGateway() { return guestGateway; } public void setGuestGateway(String guestGateway) { this.guestGateway = guestGateway; } public String getGuestNetmask() { return guestNetmask; } public void setGuestNetmask(String guestNetmask) { this.guestNetmask = guestNetmask; } public String getGuestMac() { return guestMac; } public void setGuestMac(String guestMac) { this.guestMac = guestMac; } public L3NetworkInventory getL3Network() { return l3Network; } public void setL3Network(L3NetworkInventory l3Network) { this.l3Network = l3Network; } }
apache-2.0
zstackorg/zstack
core/src/main/java/org/zstack/core/progressbar/InProgressEvent.java
490
package org.zstack.core.progressbar; import org.zstack.header.message.APIEvent; public class InProgressEvent extends APIEvent { private String description; protected InProgressEvent(String apiId, String description) { super(apiId); this.description = description; } public InProgressEvent() { super(null); } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
apache-2.0
strahanjen/strahanjen.github.io
elasticsearch-master/core/src/main/java/org/elasticsearch/action/termvectors/MultiTermVectorsRequest.java
7542
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.termvectors; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.CompositeIndicesRequest; import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.RealtimeRequest; import org.elasticsearch.action.ValidateActions; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; public class MultiTermVectorsRequest extends ActionRequest<MultiTermVectorsRequest> implements Iterable<TermVectorsRequest>, CompositeIndicesRequest, RealtimeRequest { String preference; List<TermVectorsRequest> requests = new ArrayList<>(); final Set<String> ids = new HashSet<>(); public MultiTermVectorsRequest add(TermVectorsRequest termVectorsRequest) { requests.add(termVectorsRequest); return this; } public MultiTermVectorsRequest add(String index, @Nullable String type, String id) { requests.add(new TermVectorsRequest(index, type, id)); return this; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (requests.isEmpty()) { validationException = ValidateActions.addValidationError("multi term vectors: no documents requested", validationException); } else { for (int i = 0; i < requests.size(); i++) { TermVectorsRequest termVectorsRequest = requests.get(i); ActionRequestValidationException validationExceptionForDoc = termVectorsRequest.validate(); if (validationExceptionForDoc != null) { validationException = ValidateActions.addValidationError("at multi term vectors for doc " + i, validationExceptionForDoc); } } } return validationException; } @Override public List<? extends IndicesRequest> subRequests() { return requests; } @Override public Iterator<TermVectorsRequest> iterator() { return Collections.unmodifiableCollection(requests).iterator(); } public boolean isEmpty() { return requests.isEmpty() && ids.isEmpty(); } public List<TermVectorsRequest> getRequests() { return requests; } public void add(TermVectorsRequest template, BytesReference data) throws Exception { XContentParser.Token token; String currentFieldName = null; if (data.length() > 0) { try (XContentParser parser = XContentFactory.xContent(data).createParser(data)) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { if ("docs".equals(currentFieldName)) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { if (token != XContentParser.Token.START_OBJECT) { throw new IllegalArgumentException("docs array element should include an object"); } TermVectorsRequest termVectorsRequest = new TermVectorsRequest(template); TermVectorsRequest.parseRequest(termVectorsRequest, parser); add(termVectorsRequest); } } else if ("ids".equals(currentFieldName)) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { if (!token.isValue()) { throw new IllegalArgumentException("ids array element should only contain ids"); } ids.add(parser.text()); } } else { throw new ElasticsearchParseException("no parameter named [{}] and type ARRAY", currentFieldName); } } else if (token == XContentParser.Token.START_OBJECT && currentFieldName != null) { if ("parameters".equals(currentFieldName)) { TermVectorsRequest.parseRequest(template, parser); } else { throw new ElasticsearchParseException("no parameter named [{}] and type OBJECT", currentFieldName); } } else if (currentFieldName != null) { throw new ElasticsearchParseException("_mtermvectors: Parameter [{}] not supported", currentFieldName); } } } } for (String id : ids) { TermVectorsRequest curRequest = new TermVectorsRequest(template); curRequest.id(id); requests.add(curRequest); } } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); preference = in.readOptionalString(); int size = in.readVInt(); requests = new ArrayList<>(size); for (int i = 0; i < size; i++) { requests.add(TermVectorsRequest.readTermVectorsRequest(in)); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeOptionalString(preference); out.writeVInt(requests.size()); for (TermVectorsRequest termVectorsRequest : requests) { termVectorsRequest.writeTo(out); } } public void ids(String[] ids) { for (String id : ids) { this.ids.add(id.replaceAll("\\s", "")); } } public int size() { return requests.size(); } @Override public MultiTermVectorsRequest realtime(boolean realtime) { for (TermVectorsRequest request : requests) { request.realtime(realtime); } return this; } }
bsd-3-clause
rokn/Count_Words_2015
testing/openjdk/jdk/src/share/classes/javax/swing/JDialog.java
49133
/* * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing; import java.awt.*; import java.awt.event.*; import javax.accessibility.*; /** * The main class for creating a dialog window. You can use this class * to create a custom dialog, or invoke the many class methods * in {@link JOptionPane} to create a variety of standard dialogs. * For information about creating dialogs, see * <em>The Java Tutorial</em> section * <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/dialog.html">How * to Make Dialogs</a>. * * <p> * * The {@code JDialog} component contains a {@code JRootPane} * as its only child. * The {@code contentPane} should be the parent of any children of the * {@code JDialog}. * As a convenience {@code add} and its variants, {@code remove} and * {@code setLayout} have been overridden to forward to the * {@code contentPane} as necessary. This means you can write: * <pre> * dialog.add(child); * </pre> * And the child will be added to the contentPane. * The {@code contentPane} is always non-{@code null}. * Attempting to set it to {@code null} generates an exception. * The default {@code contentPane} has a {@code BorderLayout} * manager set on it. * Refer to {@link javax.swing.RootPaneContainer} * for details on adding, removing and setting the {@code LayoutManager} * of a {@code JDialog}. * <p> * Please see the {@code JRootPane} documentation for a complete * description of the {@code contentPane}, {@code glassPane}, * and {@code layeredPane} components. * <p> * In a multi-screen environment, you can create a {@code JDialog} * on a different screen device than its owner. See {@link java.awt.Frame} for * more information. * <p> * <strong>Warning:</strong> Swing is not thread safe. For more * information see <a * href="package-summary.html#threading">Swing's Threading * Policy</a>. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the {@code java.beans} package. * Please see {@link java.beans.XMLEncoder}. * * @see JOptionPane * @see JRootPane * @see javax.swing.RootPaneContainer * * @beaninfo * attribute: isContainer true * attribute: containerDelegate getContentPane * description: A toplevel window for creating dialog boxes. * * @author David Kloba * @author James Gosling * @author Scott Violet */ public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneContainer, TransferHandler.HasGetTransferHandler { /** * Key into the AppContext, used to check if should provide decorations * by default. */ private static final Object defaultLookAndFeelDecoratedKey = new StringBuffer("JDialog.defaultLookAndFeelDecorated"); private int defaultCloseOperation = HIDE_ON_CLOSE; /** * @see #getRootPane * @see #setRootPane */ protected JRootPane rootPane; /** * If true then calls to {@code add} and {@code setLayout} * will be forwarded to the {@code contentPane}. This is initially * false, but is set to true when the {@code JDialog} is constructed. * * @see #isRootPaneCheckingEnabled * @see #setRootPaneCheckingEnabled * @see javax.swing.RootPaneContainer */ protected boolean rootPaneCheckingEnabled = false; /** * The {@code TransferHandler} for this dialog. */ private TransferHandler transferHandler; /** * Creates a modeless dialog without a title and without a specified * {@code Frame} owner. A shared, hidden frame will be * set as the owner of the dialog. * <p> * This constructor sets the component's locale property to the value * returned by {@code JComponent.getDefaultLocale}. * <p> * NOTE: This constructor does not allow you to create an unowned * {@code JDialog}. To create an unowned {@code JDialog} * you must use either the {@code JDialog(Window)} or * {@code JDialog(Dialog)} constructor with an argument of * {@code null}. * * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()} * returns {@code true}. * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale */ public JDialog() { this((Frame)null, false); } /** * Creates a modeless dialog with the specified {@code Frame} * as its owner and an empty title. If {@code owner} * is {@code null}, a shared, hidden frame will be set as the * owner of the dialog. * <p> * This constructor sets the component's locale property to the value * returned by {@code JComponent.getDefaultLocale}. * <p> * NOTE: This constructor does not allow you to create an unowned * {@code JDialog}. To create an unowned {@code JDialog} * you must use either the {@code JDialog(Window)} or * {@code JDialog(Dialog)} constructor with an argument of * {@code null}. * * @param owner the {@code Frame} from which the dialog is displayed * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()} * returns {@code true}. * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale */ public JDialog(Frame owner) { this(owner, false); } /** * Creates a dialog with an empty title and the specified modality and * {@code Frame} as its owner. If {@code owner} is {@code null}, * a shared, hidden frame will be set as the owner of the dialog. * <p> * This constructor sets the component's locale property to the value * returned by {@code JComponent.getDefaultLocale}. * <p> * NOTE: This constructor does not allow you to create an unowned * {@code JDialog}. To create an unowned {@code JDialog} * you must use either the {@code JDialog(Window)} or * {@code JDialog(Dialog)} constructor with an argument of * {@code null}. * * @param owner the {@code Frame} from which the dialog is displayed * @param modal specifies whether dialog blocks user input to other top-level * windows when shown. If {@code true}, the modality type property is set to * {@code DEFAULT_MODALITY_TYPE}, otherwise the dialog is modeless. * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()} * returns {@code true}. * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale */ public JDialog(Frame owner, boolean modal) { this(owner, "", modal); } /** * Creates a modeless dialog with the specified title and * with the specified owner frame. If {@code owner} * is {@code null}, a shared, hidden frame will be set as the * owner of the dialog. * <p> * This constructor sets the component's locale property to the value * returned by {@code JComponent.getDefaultLocale}. * <p> * NOTE: This constructor does not allow you to create an unowned * {@code JDialog}. To create an unowned {@code JDialog} * you must use either the {@code JDialog(Window)} or * {@code JDialog(Dialog)} constructor with an argument of * {@code null}. * * @param owner the {@code Frame} from which the dialog is displayed * @param title the {@code String} to display in the dialog's * title bar * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()} * returns {@code true}. * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale */ public JDialog(Frame owner, String title) { this(owner, title, false); } /** * Creates a dialog with the specified title, owner {@code Frame} * and modality. If {@code owner} is {@code null}, * a shared, hidden frame will be set as the owner of this dialog. * <p> * This constructor sets the component's locale property to the value * returned by {@code JComponent.getDefaultLocale}. * <p> * NOTE: Any popup components ({@code JComboBox}, * {@code JPopupMenu}, {@code JMenuBar}) * created within a modal dialog will be forced to be lightweight. * <p> * NOTE: This constructor does not allow you to create an unowned * {@code JDialog}. To create an unowned {@code JDialog} * you must use either the {@code JDialog(Window)} or * {@code JDialog(Dialog)} constructor with an argument of * {@code null}. * * @param owner the {@code Frame} from which the dialog is displayed * @param title the {@code String} to display in the dialog's * title bar * @param modal specifies whether dialog blocks user input to other top-level * windows when shown. If {@code true}, the modality type property is set to * {@code DEFAULT_MODALITY_TYPE} otherwise the dialog is modeless * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()} * returns {@code true}. * * @see java.awt.Dialog.ModalityType * @see java.awt.Dialog.ModalityType#MODELESS * @see java.awt.Dialog#DEFAULT_MODALITY_TYPE * @see java.awt.Dialog#setModal * @see java.awt.Dialog#setModalityType * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale */ public JDialog(Frame owner, String title, boolean modal) { super(owner == null? SwingUtilities.getSharedOwnerFrame() : owner, title, modal); if (owner == null) { WindowListener ownerShutdownListener = SwingUtilities.getSharedOwnerFrameShutdownListener(); addWindowListener(ownerShutdownListener); } dialogInit(); } /** * Creates a dialog with the specified title, * owner {@code Frame}, modality and {@code GraphicsConfiguration}. * If {@code owner} is {@code null}, * a shared, hidden frame will be set as the owner of this dialog. * <p> * This constructor sets the component's locale property to the value * returned by {@code JComponent.getDefaultLocale}. * <p> * NOTE: Any popup components ({@code JComboBox}, * {@code JPopupMenu}, {@code JMenuBar}) * created within a modal dialog will be forced to be lightweight. * <p> * NOTE: This constructor does not allow you to create an unowned * {@code JDialog}. To create an unowned {@code JDialog} * you must use either the {@code JDialog(Window)} or * {@code JDialog(Dialog)} constructor with an argument of * {@code null}. * * @param owner the {@code Frame} from which the dialog is displayed * @param title the {@code String} to display in the dialog's * title bar * @param modal specifies whether dialog blocks user input to other top-level * windows when shown. If {@code true}, the modality type property is set to * {@code DEFAULT_MODALITY_TYPE}, otherwise the dialog is modeless. * @param gc the {@code GraphicsConfiguration} of the target screen device; * if {@code null}, the default system {@code GraphicsConfiguration} * is assumed * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()} * returns {@code true}. * @see java.awt.Dialog.ModalityType * @see java.awt.Dialog.ModalityType#MODELESS * @see java.awt.Dialog#DEFAULT_MODALITY_TYPE * @see java.awt.Dialog#setModal * @see java.awt.Dialog#setModalityType * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale * @since 1.4 */ public JDialog(Frame owner, String title, boolean modal, GraphicsConfiguration gc) { super(owner == null? SwingUtilities.getSharedOwnerFrame() : owner, title, modal, gc); if (owner == null) { WindowListener ownerShutdownListener = SwingUtilities.getSharedOwnerFrameShutdownListener(); addWindowListener(ownerShutdownListener); } dialogInit(); } /** * Creates a modeless dialog with the specified {@code Dialog} * as its owner and an empty title. * <p> * This constructor sets the component's locale property to the value * returned by {@code JComponent.getDefaultLocale}. * * @param owner the owner {@code Dialog} from which the dialog is displayed * or {@code null} if this dialog has no owner * @throws HeadlessException {@code if GraphicsEnvironment.isHeadless()} * returns {@code true}. * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale */ public JDialog(Dialog owner) { this(owner, false); } /** * Creates a dialog with an empty title and the specified modality and * {@code Dialog} as its owner. * <p> * This constructor sets the component's locale property to the value * returned by {@code JComponent.getDefaultLocale}. * * @param owner the owner {@code Dialog} from which the dialog is displayed * or {@code null} if this dialog has no owner * @param modal specifies whether dialog blocks user input to other top-level * windows when shown. If {@code true}, the modality type property is set to * {@code DEFAULT_MODALITY_TYPE}, otherwise the dialog is modeless. * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()} * returns {@code true}. * @see java.awt.Dialog.ModalityType * @see java.awt.Dialog.ModalityType#MODELESS * @see java.awt.Dialog#DEFAULT_MODALITY_TYPE * @see java.awt.Dialog#setModal * @see java.awt.Dialog#setModalityType * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale */ public JDialog(Dialog owner, boolean modal) { this(owner, "", modal); } /** * Creates a modeless dialog with the specified title and * with the specified owner dialog. * <p> * This constructor sets the component's locale property to the value * returned by {@code JComponent.getDefaultLocale}. * * @param owner the owner {@code Dialog} from which the dialog is displayed * or {@code null} if this dialog has no owner * @param title the {@code String} to display in the dialog's * title bar * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()} * returns {@code true}. * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale */ public JDialog(Dialog owner, String title) { this(owner, title, false); } /** * Creates a dialog with the specified title, modality * and the specified owner {@code Dialog}. * <p> * This constructor sets the component's locale property to the value * returned by {@code JComponent.getDefaultLocale}. * * @param owner the owner {@code Dialog} from which the dialog is displayed * or {@code null} if this dialog has no owner * @param title the {@code String} to display in the dialog's * title bar * @param modal specifies whether dialog blocks user input to other top-level * windows when shown. If {@code true}, the modality type property is set to * {@code DEFAULT_MODALITY_TYPE}, otherwise the dialog is modeless * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()} * returns {@code true}. * @see java.awt.Dialog.ModalityType * @see java.awt.Dialog.ModalityType#MODELESS * @see java.awt.Dialog#DEFAULT_MODALITY_TYPE * @see java.awt.Dialog#setModal * @see java.awt.Dialog#setModalityType * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale */ public JDialog(Dialog owner, String title, boolean modal) { super(owner, title, modal); dialogInit(); } /** * Creates a dialog with the specified title, owner {@code Dialog}, * modality and {@code GraphicsConfiguration}. * * <p> * NOTE: Any popup components ({@code JComboBox}, * {@code JPopupMenu}, {@code JMenuBar}) * created within a modal dialog will be forced to be lightweight. * <p> * This constructor sets the component's locale property to the value * returned by {@code JComponent.getDefaultLocale}. * * @param owner the owner {@code Dialog} from which the dialog is displayed * or {@code null} if this dialog has no owner * @param title the {@code String} to display in the dialog's * title bar * @param modal specifies whether dialog blocks user input to other top-level * windows when shown. If {@code true}, the modality type property is set to * {@code DEFAULT_MODALITY_TYPE}, otherwise the dialog is modeless * @param gc the {@code GraphicsConfiguration} of the target screen device; * if {@code null}, the default system {@code GraphicsConfiguration} * is assumed * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()} * returns {@code true}. * @see java.awt.Dialog.ModalityType * @see java.awt.Dialog.ModalityType#MODELESS * @see java.awt.Dialog#DEFAULT_MODALITY_TYPE * @see java.awt.Dialog#setModal * @see java.awt.Dialog#setModalityType * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale * @since 1.4 */ public JDialog(Dialog owner, String title, boolean modal, GraphicsConfiguration gc) { super(owner, title, modal, gc); dialogInit(); } /** * Creates a modeless dialog with the specified {@code Window} * as its owner and an empty title. * <p> * This constructor sets the component's locale property to the value * returned by {@code JComponent.getDefaultLocale}. * * @param owner the {@code Window} from which the dialog is displayed or * {@code null} if this dialog has no owner * * @throws IllegalArgumentException * if the {@code owner} is not an instance of {@link java.awt.Dialog Dialog} * or {@link java.awt.Frame Frame} * @throws IllegalArgumentException * if the {@code owner}'s {@code GraphicsConfiguration} is not from a screen device * @throws HeadlessException * when {@code GraphicsEnvironment.isHeadless()} returns {@code true} * * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale * * @since 1.6 */ public JDialog(Window owner) { this(owner, Dialog.ModalityType.MODELESS); } /** * Creates a dialog with an empty title and the specified modality and * {@code Window} as its owner. * <p> * This constructor sets the component's locale property to the value * returned by {@code JComponent.getDefaultLocale}. * * @param owner the {@code Window} from which the dialog is displayed or * {@code null} if this dialog has no owner * @param modalityType specifies whether dialog blocks input to other * windows when shown. {@code null} value and unsupported modality * types are equivalent to {@code MODELESS} * * @throws IllegalArgumentException * if the {@code owner} is not an instance of {@link java.awt.Dialog Dialog} * or {@link java.awt.Frame Frame} * @throws IllegalArgumentException * if the {@code owner}'s {@code GraphicsConfiguration} is not from a screen device * @throws HeadlessException * when {@code GraphicsEnvironment.isHeadless()} returns {@code true} * @throws SecurityException * if the calling thread does not have permission to create modal dialogs * with the given {@code modalityType} * * @see java.awt.Dialog.ModalityType * @see java.awt.Dialog#setModal * @see java.awt.Dialog#setModalityType * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale * * @since 1.6 */ public JDialog(Window owner, ModalityType modalityType) { this(owner, "", modalityType); } /** * Creates a modeless dialog with the specified title and owner * {@code Window}. * <p> * This constructor sets the component's locale property to the value * returned by {@code JComponent.getDefaultLocale}. * * @param owner the {@code Window} from which the dialog is displayed or * {@code null} if this dialog has no owner * @param title the {@code String} to display in the dialog's * title bar or {@code null} if the dialog has no title * * @throws IllegalArgumentException * if the {@code owner} is not an instance of {@link java.awt.Dialog Dialog} * or {@link java.awt.Frame Frame} * @throws IllegalArgumentException * if the {@code owner}'s {@code GraphicsConfiguration} is not from a screen device * @throws HeadlessException * when {@code GraphicsEnvironment.isHeadless()} returns {@code true} * * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale * * @since 1.6 */ public JDialog(Window owner, String title) { this(owner, title, Dialog.ModalityType.MODELESS); } /** * Creates a dialog with the specified title, owner {@code Window} and * modality. * <p> * This constructor sets the component's locale property to the value * returned by {@code JComponent.getDefaultLocale}. * * @param owner the {@code Window} from which the dialog is displayed or * {@code null} if this dialog has no owner * @param title the {@code String} to display in the dialog's * title bar or {@code null} if the dialog has no title * @param modalityType specifies whether dialog blocks input to other * windows when shown. {@code null} value and unsupported modality * types are equivalent to {@code MODELESS} * * @throws IllegalArgumentException * if the {@code owner} is not an instance of {@link java.awt.Dialog Dialog} * or {@link java.awt.Frame Frame} * @throws IllegalArgumentException * if the {@code owner}'s {@code GraphicsConfiguration} is not from a screen device * @throws HeadlessException * when {@code GraphicsEnvironment.isHeadless()} returns {@code true} * @throws SecurityException * if the calling thread does not have permission to create modal dialogs * with the given {@code modalityType} * * @see java.awt.Dialog.ModalityType * @see java.awt.Dialog#setModal * @see java.awt.Dialog#setModalityType * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale * * @since 1.6 */ public JDialog(Window owner, String title, Dialog.ModalityType modalityType) { super(owner, title, modalityType); dialogInit(); } /** * Creates a dialog with the specified title, owner {@code Window}, * modality and {@code GraphicsConfiguration}. * <p> * NOTE: Any popup components ({@code JComboBox}, * {@code JPopupMenu}, {@code JMenuBar}) * created within a modal dialog will be forced to be lightweight. * <p> * This constructor sets the component's locale property to the value * returned by {@code JComponent.getDefaultLocale}. * * @param owner the {@code Window} from which the dialog is displayed or * {@code null} if this dialog has no owner * @param title the {@code String} to display in the dialog's * title bar or {@code null} if the dialog has no title * @param modalityType specifies whether dialog blocks input to other * windows when shown. {@code null} value and unsupported modality * types are equivalent to {@code MODELESS} * @param gc the {@code GraphicsConfiguration} of the target screen device; * if {@code null}, the default system {@code GraphicsConfiguration} * is assumed * @throws IllegalArgumentException * if the {@code owner} is not an instance of {@link java.awt.Dialog Dialog} * or {@link java.awt.Frame Frame} * @throws IllegalArgumentException * if the {@code owner}'s {@code GraphicsConfiguration} is not from a screen device * @throws HeadlessException * when {@code GraphicsEnvironment.isHeadless()} returns {@code true} * @throws SecurityException * if the calling thread does not have permission to create modal dialogs * with the given {@code modalityType} * * @see java.awt.Dialog.ModalityType * @see java.awt.Dialog#setModal * @see java.awt.Dialog#setModalityType * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale * * @since 1.6 */ public JDialog(Window owner, String title, Dialog.ModalityType modalityType, GraphicsConfiguration gc) { super(owner, title, modalityType, gc); dialogInit(); } /** * Called by the constructors to init the {@code JDialog} properly. */ protected void dialogInit() { enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK); setLocale( JComponent.getDefaultLocale() ); setRootPane(createRootPane()); setRootPaneCheckingEnabled(true); if (JDialog.isDefaultLookAndFeelDecorated()) { boolean supportsWindowDecorations = UIManager.getLookAndFeel().getSupportsWindowDecorations(); if (supportsWindowDecorations) { setUndecorated(true); getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG); } } sun.awt.SunToolkit.checkAndSetPolicy(this, true); } /** * Called by the constructor methods to create the default * {@code rootPane}. */ protected JRootPane createRootPane() { JRootPane rp = new JRootPane(); // NOTE: this uses setOpaque vs LookAndFeel.installProperty as there // is NO reason for the RootPane not to be opaque. For painting to // work the contentPane must be opaque, therefor the RootPane can // also be opaque. rp.setOpaque(true); return rp; } /** * Handles window events depending on the state of the * {@code defaultCloseOperation} property. * * @see #setDefaultCloseOperation */ protected void processWindowEvent(WindowEvent e) { super.processWindowEvent(e); if (e.getID() == WindowEvent.WINDOW_CLOSING) { switch(defaultCloseOperation) { case HIDE_ON_CLOSE: setVisible(false); break; case DISPOSE_ON_CLOSE: dispose(); break; case DO_NOTHING_ON_CLOSE: default: break; } } } /** * Sets the operation that will happen by default when * the user initiates a "close" on this dialog. * You must specify one of the following choices: * <p> * <ul> * <li>{@code DO_NOTHING_ON_CLOSE} * (defined in {@code WindowConstants}): * Don't do anything; require the * program to handle the operation in the {@code windowClosing} * method of a registered {@code WindowListener} object. * * <li>{@code HIDE_ON_CLOSE} * (defined in {@code WindowConstants}): * Automatically hide the dialog after * invoking any registered {@code WindowListener} * objects. * * <li>{@code DISPOSE_ON_CLOSE} * (defined in {@code WindowConstants}): * Automatically hide and dispose the * dialog after invoking any registered {@code WindowListener} * objects. * </ul> * <p> * The value is set to {@code HIDE_ON_CLOSE} by default. Changes * to the value of this property cause the firing of a property * change event, with property name "defaultCloseOperation". * <p> * <b>Note</b>: When the last displayable window within the * Java virtual machine (VM) is disposed of, the VM may * terminate. See <a href="../../java/awt/doc-files/AWTThreadIssues.html"> * AWT Threading Issues</a> for more information. * * @param operation the operation which should be performed when the * user closes the dialog * @throws IllegalArgumentException if defaultCloseOperation value * isn't one of the above valid values * @see #addWindowListener * @see #getDefaultCloseOperation * @see WindowConstants * * @beaninfo * preferred: true * bound: true * enum: DO_NOTHING_ON_CLOSE WindowConstants.DO_NOTHING_ON_CLOSE * HIDE_ON_CLOSE WindowConstants.HIDE_ON_CLOSE * DISPOSE_ON_CLOSE WindowConstants.DISPOSE_ON_CLOSE * description: The dialog's default close operation. */ public void setDefaultCloseOperation(int operation) { if (operation != DO_NOTHING_ON_CLOSE && operation != HIDE_ON_CLOSE && operation != DISPOSE_ON_CLOSE) { throw new IllegalArgumentException("defaultCloseOperation must be one of: DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, or DISPOSE_ON_CLOSE"); } int oldValue = this.defaultCloseOperation; this.defaultCloseOperation = operation; firePropertyChange("defaultCloseOperation", oldValue, operation); } /** * Returns the operation which occurs when the user * initiates a "close" on this dialog. * * @return an integer indicating the window-close operation * @see #setDefaultCloseOperation */ public int getDefaultCloseOperation() { return defaultCloseOperation; } /** * Sets the {@code transferHandler} property, which is a mechanism to * support transfer of data into this component. Use {@code null} * if the component does not support data transfer operations. * <p> * If the system property {@code suppressSwingDropSupport} is {@code false} * (the default) and the current drop target on this component is either * {@code null} or not a user-set drop target, this method will change the * drop target as follows: If {@code newHandler} is {@code null} it will * clear the drop target. If not {@code null} it will install a new * {@code DropTarget}. * <p> * Note: When used with {@code JDialog}, {@code TransferHandler} only * provides data import capability, as the data export related methods * are currently typed to {@code JComponent}. * <p> * Please see * <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html"> * How to Use Drag and Drop and Data Transfer</a>, a section in * <em>The Java Tutorial</em>, for more information. * * @param newHandler the new {@code TransferHandler} * * @see TransferHandler * @see #getTransferHandler * @see java.awt.Component#setDropTarget * @since 1.6 * * @beaninfo * bound: true * hidden: true * description: Mechanism for transfer of data into the component */ public void setTransferHandler(TransferHandler newHandler) { TransferHandler oldHandler = transferHandler; transferHandler = newHandler; SwingUtilities.installSwingDropTargetAsNecessary(this, transferHandler); firePropertyChange("transferHandler", oldHandler, newHandler); } /** * Gets the {@code transferHandler} property. * * @return the value of the {@code transferHandler} property * * @see TransferHandler * @see #setTransferHandler * @since 1.6 */ public TransferHandler getTransferHandler() { return transferHandler; } /** * Calls {@code paint(g)}. This method was overridden to * prevent an unnecessary call to clear the background. * * @param g the {@code Graphics} context in which to paint */ public void update(Graphics g) { paint(g); } /** * Sets the menubar for this dialog. * * @param menu the menubar being placed in the dialog * * @see #getJMenuBar * * @beaninfo * hidden: true * description: The menubar for accessing pulldown menus from this dialog. */ public void setJMenuBar(JMenuBar menu) { getRootPane().setMenuBar(menu); } /** * Returns the menubar set on this dialog. * * @see #setJMenuBar */ public JMenuBar getJMenuBar() { return getRootPane().getMenuBar(); } /** * Returns whether calls to {@code add} and * {@code setLayout} are forwarded to the {@code contentPane}. * * @return true if {@code add} and {@code setLayout} * are fowarded; false otherwise * * @see #addImpl * @see #setLayout * @see #setRootPaneCheckingEnabled * @see javax.swing.RootPaneContainer */ protected boolean isRootPaneCheckingEnabled() { return rootPaneCheckingEnabled; } /** * Sets whether calls to {@code add} and * {@code setLayout} are forwarded to the {@code contentPane}. * * @param enabled true if {@code add} and {@code setLayout} * are forwarded, false if they should operate directly on the * {@code JDialog}. * * @see #addImpl * @see #setLayout * @see #isRootPaneCheckingEnabled * @see javax.swing.RootPaneContainer * @beaninfo * hidden: true * description: Whether the add and setLayout methods are forwarded */ protected void setRootPaneCheckingEnabled(boolean enabled) { rootPaneCheckingEnabled = enabled; } /** * Adds the specified child {@code Component}. * This method is overridden to conditionally forward calls to the * {@code contentPane}. * By default, children are added to the {@code contentPane} instead * of the frame, refer to {@link javax.swing.RootPaneContainer} for * details. * * @param comp the component to be enhanced * @param constraints the constraints to be respected * @param index the index * @throws IllegalArgumentException if {@code index} is invalid * @throws IllegalArgumentException if adding the container's parent * to itself * @throws IllegalArgumentException if adding a window to a container * * @see #setRootPaneCheckingEnabled * @see javax.swing.RootPaneContainer */ protected void addImpl(Component comp, Object constraints, int index) { if(isRootPaneCheckingEnabled()) { getContentPane().add(comp, constraints, index); } else { super.addImpl(comp, constraints, index); } } /** * Removes the specified component from the container. If * {@code comp} is not the {@code rootPane}, this will forward * the call to the {@code contentPane}. This will do nothing if * {@code comp} is not a child of the {@code JDialog} or * {@code contentPane}. * * @param comp the component to be removed * @throws NullPointerException if {@code comp} is null * @see #add * @see javax.swing.RootPaneContainer */ public void remove(Component comp) { if (comp == rootPane) { super.remove(comp); } else { getContentPane().remove(comp); } } /** * Sets the {@code LayoutManager}. * Overridden to conditionally forward the call to the * {@code contentPane}. * Refer to {@link javax.swing.RootPaneContainer} for * more information. * * @param manager the {@code LayoutManager} * @see #setRootPaneCheckingEnabled * @see javax.swing.RootPaneContainer */ public void setLayout(LayoutManager manager) { if(isRootPaneCheckingEnabled()) { getContentPane().setLayout(manager); } else { super.setLayout(manager); } } /** * Returns the {@code rootPane} object for this dialog. * * @see #setRootPane * @see RootPaneContainer#getRootPane */ public JRootPane getRootPane() { return rootPane; } /** * Sets the {@code rootPane} property. * This method is called by the constructor. * * @param root the {@code rootPane} object for this dialog * * @see #getRootPane * * @beaninfo * hidden: true * description: the RootPane object for this dialog. */ protected void setRootPane(JRootPane root) { if(rootPane != null) { remove(rootPane); } rootPane = root; if(rootPane != null) { boolean checkingEnabled = isRootPaneCheckingEnabled(); try { setRootPaneCheckingEnabled(false); add(rootPane, BorderLayout.CENTER); } finally { setRootPaneCheckingEnabled(checkingEnabled); } } } /** * Returns the {@code contentPane} object for this dialog. * * @return the {@code contentPane} property * * @see #setContentPane * @see RootPaneContainer#getContentPane */ public Container getContentPane() { return getRootPane().getContentPane(); } /** * Sets the {@code contentPane} property. * This method is called by the constructor. * <p> * Swing's painting architecture requires an opaque {@code JComponent} * in the containment hiearchy. This is typically provided by the * content pane. If you replace the content pane it is recommended you * replace it with an opaque {@code JComponent}. * @see JRootPane * * @param contentPane the {@code contentPane} object for this dialog * * @throws java.awt.IllegalComponentStateException (a runtime * exception) if the content pane parameter is {@code null} * @see #getContentPane * @see RootPaneContainer#setContentPane * * @beaninfo * hidden: true * description: The client area of the dialog where child * components are normally inserted. */ public void setContentPane(Container contentPane) { getRootPane().setContentPane(contentPane); } /** * Returns the {@code layeredPane} object for this dialog. * * @return the {@code layeredPane} property * * @see #setLayeredPane * @see RootPaneContainer#getLayeredPane */ public JLayeredPane getLayeredPane() { return getRootPane().getLayeredPane(); } /** * Sets the {@code layeredPane} property. * This method is called by the constructor. * * @param layeredPane the new {@code layeredPane} property * * @throws java.awt.IllegalComponentStateException (a runtime * exception) if the layered pane parameter is null * @see #getLayeredPane * @see RootPaneContainer#setLayeredPane * * @beaninfo * hidden: true * description: The pane which holds the various dialog layers. */ public void setLayeredPane(JLayeredPane layeredPane) { getRootPane().setLayeredPane(layeredPane); } /** * Returns the {@code glassPane} object for this dialog. * * @return the {@code glassPane} property * * @see #setGlassPane * @see RootPaneContainer#getGlassPane */ public Component getGlassPane() { return getRootPane().getGlassPane(); } /** * Sets the {@code glassPane} property. * This method is called by the constructor. * * @param glassPane the {@code glassPane} object for this dialog * @see #getGlassPane * @see RootPaneContainer#setGlassPane * * @beaninfo * hidden: true * description: A transparent pane used for menu rendering. */ public void setGlassPane(Component glassPane) { getRootPane().setGlassPane(glassPane); } /** * {@inheritDoc} * * @since 1.6 */ public Graphics getGraphics() { JComponent.getGraphicsInvoked(this); return super.getGraphics(); } /** * Repaints the specified rectangle of this component within * {@code time} milliseconds. Refer to {@code RepaintManager} * for details on how the repaint is handled. * * @param time maximum time in milliseconds before update * @param x the <i>x</i> coordinate * @param y the <i>y</i> coordinate * @param width the width * @param height the height * @see RepaintManager * @since 1.6 */ public void repaint(long time, int x, int y, int width, int height) { if (RepaintManager.HANDLE_TOP_LEVEL_PAINT) { RepaintManager.currentManager(this).addDirtyRegion( this, x, y, width, height); } else { super.repaint(time, x, y, width, height); } } /** * Provides a hint as to whether or not newly created {@code JDialog}s * should have their Window decorations (such as borders, widgets to * close the window, title...) provided by the current look * and feel. If {@code defaultLookAndFeelDecorated} is true, * the current {@code LookAndFeel} supports providing window * decorations, and the current window manager supports undecorated * windows, then newly created {@code JDialog}s will have their * Window decorations provided by the current {@code LookAndFeel}. * Otherwise, newly created {@code JDialog}s will have their * Window decorations provided by the current window manager. * <p> * You can get the same effect on a single JDialog by doing the following: * <pre> * JDialog dialog = new JDialog(); * dialog.setUndecorated(true); * dialog.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG); * </pre> * * @param defaultLookAndFeelDecorated A hint as to whether or not current * look and feel should provide window decorations * @see javax.swing.LookAndFeel#getSupportsWindowDecorations * @since 1.4 */ public static void setDefaultLookAndFeelDecorated(boolean defaultLookAndFeelDecorated) { if (defaultLookAndFeelDecorated) { SwingUtilities.appContextPut(defaultLookAndFeelDecoratedKey, Boolean.TRUE); } else { SwingUtilities.appContextPut(defaultLookAndFeelDecoratedKey, Boolean.FALSE); } } /** * Returns true if newly created {@code JDialog}s should have their * Window decorations provided by the current look and feel. This is only * a hint, as certain look and feels may not support this feature. * * @return true if look and feel should provide Window decorations. * @since 1.4 */ public static boolean isDefaultLookAndFeelDecorated() { Boolean defaultLookAndFeelDecorated = (Boolean) SwingUtilities.appContextGet(defaultLookAndFeelDecoratedKey); if (defaultLookAndFeelDecorated == null) { defaultLookAndFeelDecorated = Boolean.FALSE; } return defaultLookAndFeelDecorated.booleanValue(); } /** * Returns a string representation of this {@code JDialog}. * This method * is intended to be used only for debugging purposes, and the * content and format of the returned string may vary between * implementations. The returned string may be empty but may not * be {@code null}. * * @return a string representation of this {@code JDialog}. */ protected String paramString() { String defaultCloseOperationString; if (defaultCloseOperation == HIDE_ON_CLOSE) { defaultCloseOperationString = "HIDE_ON_CLOSE"; } else if (defaultCloseOperation == DISPOSE_ON_CLOSE) { defaultCloseOperationString = "DISPOSE_ON_CLOSE"; } else if (defaultCloseOperation == DO_NOTHING_ON_CLOSE) { defaultCloseOperationString = "DO_NOTHING_ON_CLOSE"; } else defaultCloseOperationString = ""; String rootPaneString = (rootPane != null ? rootPane.toString() : ""); String rootPaneCheckingEnabledString = (rootPaneCheckingEnabled ? "true" : "false"); return super.paramString() + ",defaultCloseOperation=" + defaultCloseOperationString + ",rootPane=" + rootPaneString + ",rootPaneCheckingEnabled=" + rootPaneCheckingEnabledString; } ///////////////// // Accessibility support //////////////// protected AccessibleContext accessibleContext = null; /** * Gets the AccessibleContext associated with this JDialog. * For JDialogs, the AccessibleContext takes the form of an * AccessibleJDialog. * A new AccessibleJDialog instance is created if necessary. * * @return an AccessibleJDialog that serves as the * AccessibleContext of this JDialog */ public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new AccessibleJDialog(); } return accessibleContext; } /** * This class implements accessibility support for the * {@code JDialog} class. It provides an implementation of the * Java Accessibility API appropriate to dialog user-interface * elements. */ protected class AccessibleJDialog extends AccessibleAWTDialog { // AccessibleContext methods // /** * Get the accessible name of this object. * * @return the localized name of the object -- can be null if this * object does not have a name */ public String getAccessibleName() { if (accessibleName != null) { return accessibleName; } else { if (getTitle() == null) { return super.getAccessibleName(); } else { return getTitle(); } } } /** * Get the state of this object. * * @return an instance of AccessibleStateSet containing the current * state set of the object * @see AccessibleState */ public AccessibleStateSet getAccessibleStateSet() { AccessibleStateSet states = super.getAccessibleStateSet(); if (isResizable()) { states.add(AccessibleState.RESIZABLE); } if (getFocusOwner() != null) { states.add(AccessibleState.ACTIVE); } if (isModal()) { states.add(AccessibleState.MODAL); } return states; } } // inner class AccessibleJDialog }
mit
mvolaart/openhab
bundles/binding/org.openhab.binding.tinkerforge/src/main/java/org/openhab/binding/tinkerforge/internal/model/impl/MBrickDCImpl.java
93360
/** * Copyright (c) 2010-2016 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.tinkerforge.internal.model.impl; import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EcoreUtil; import org.openhab.binding.tinkerforge.internal.LoggerConstants; import org.openhab.binding.tinkerforge.internal.TinkerforgeErrorHandler; import org.openhab.binding.tinkerforge.internal.config.DeviceOptions; import org.openhab.binding.tinkerforge.internal.model.CallbackListener; import org.openhab.binding.tinkerforge.internal.model.ConfigOptsDimmable; import org.openhab.binding.tinkerforge.internal.model.ConfigOptsMove; import org.openhab.binding.tinkerforge.internal.model.ConfigOptsSwitchSpeed; import org.openhab.binding.tinkerforge.internal.model.DCDriveMode; import org.openhab.binding.tinkerforge.internal.model.DimmableActor; import org.openhab.binding.tinkerforge.internal.model.MBaseDevice; import org.openhab.binding.tinkerforge.internal.model.MBrickDC; import org.openhab.binding.tinkerforge.internal.model.MBrickd; import org.openhab.binding.tinkerforge.internal.model.MDevice; import org.openhab.binding.tinkerforge.internal.model.MTFConfigConsumer; import org.openhab.binding.tinkerforge.internal.model.ModelPackage; import org.openhab.binding.tinkerforge.internal.model.MoveActor; import org.openhab.binding.tinkerforge.internal.model.PercentTypeActor; import org.openhab.binding.tinkerforge.internal.model.ProgrammableSwitchActor; import org.openhab.binding.tinkerforge.internal.model.SetPointActor; import org.openhab.binding.tinkerforge.internal.model.SwitchSensor; import org.openhab.binding.tinkerforge.internal.model.TFBrickDCConfiguration; import org.openhab.binding.tinkerforge.internal.tools.Tools; import org.openhab.binding.tinkerforge.internal.types.DecimalValue; import org.openhab.binding.tinkerforge.internal.types.DirectionValue; import org.openhab.binding.tinkerforge.internal.types.OnOffValue; import org.openhab.binding.tinkerforge.internal.types.PercentValue; import org.openhab.core.library.types.IncreaseDecreaseType; import org.openhab.core.library.types.PercentType; import org.openhab.core.library.types.UpDownType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.tinkerforge.BrickDC; import com.tinkerforge.IPConnection; import com.tinkerforge.NotConnectedException; import com.tinkerforge.TimeoutException; /** * <!-- begin-user-doc --> An implementation of the model object '<em><b>MBrick DC</b></em>'. * * @author Theo Weiss * @since 1.3.0 <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getSensorValue * <em>Sensor Value</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getSwitchState * <em>Switch State</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getLogger <em>Logger</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getUid <em>Uid</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#isPoll <em>Poll</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getEnabledA <em>Enabled A</em>} * </li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getTinkerforgeDevice * <em>Tinkerforge Device</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getIpConnection * <em>Ip Connection</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getConnectedUid * <em>Connected Uid</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getPosition <em>Position</em>} * </li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getDeviceIdentifier * <em>Device Identifier</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getName <em>Name</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getBrickd <em>Brickd</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getDirection <em>Direction</em>} * </li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getTfConfig <em>Tf Config</em>} * </li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getMinValue <em>Min Value</em>} * </li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getMaxValue <em>Max Value</em>} * </li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getPercentValue * <em>Percent Value</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getCallbackPeriod * <em>Callback Period</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getDeviceType <em>Device Type</em> * }</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getThreshold <em>Threshold</em>} * </li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getMaxVelocity * <em>Max Velocity</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getMinVelocity * <em>Min Velocity</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getVelocity <em>Velocity</em>} * </li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getTargetvelocity * <em>Targetvelocity</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getCurrentVelocity * <em>Current Velocity</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getAcceleration * <em>Acceleration</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getPwmFrequency * <em>Pwm Frequency</em>}</li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MBrickDCImpl#getDriveMode <em>Drive Mode</em>} * </li> * </ul> * </p> * * @generated */ public class MBrickDCImpl extends MinimalEObjectImpl.Container implements MBrickDC { /** * The cached value of the '{@link #getSensorValue() <em>Sensor Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getSensorValue() * @generated * @ordered */ protected DecimalValue sensorValue; /** * The default value of the '{@link #getSwitchState() <em>Switch State</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getSwitchState() * @generated * @ordered */ protected static final OnOffValue SWITCH_STATE_EDEFAULT = null; /** * The cached value of the '{@link #getSwitchState() <em>Switch State</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getSwitchState() * @generated * @ordered */ protected OnOffValue switchState = SWITCH_STATE_EDEFAULT; /** * The default value of the '{@link #getLogger() <em>Logger</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getLogger() * @generated * @ordered */ protected static final Logger LOGGER_EDEFAULT = null; /** * The cached value of the '{@link #getLogger() <em>Logger</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getLogger() * @generated * @ordered */ protected Logger logger = LOGGER_EDEFAULT; /** * The default value of the '{@link #getUid() <em>Uid</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getUid() * @generated * @ordered */ protected static final String UID_EDEFAULT = null; /** * The cached value of the '{@link #getUid() <em>Uid</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getUid() * @generated * @ordered */ protected String uid = UID_EDEFAULT; /** * The default value of the '{@link #isPoll() <em>Poll</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #isPoll() * @generated * @ordered */ protected static final boolean POLL_EDEFAULT = true; /** * The cached value of the '{@link #isPoll() <em>Poll</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #isPoll() * @generated * @ordered */ protected boolean poll = POLL_EDEFAULT; /** * The default value of the '{@link #getEnabledA() <em>Enabled A</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getEnabledA() * @generated * @ordered */ protected static final AtomicBoolean ENABLED_A_EDEFAULT = null; /** * The cached value of the '{@link #getEnabledA() <em>Enabled A</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getEnabledA() * @generated * @ordered */ protected AtomicBoolean enabledA = ENABLED_A_EDEFAULT; /** * The cached value of the '{@link #getTinkerforgeDevice() <em>Tinkerforge Device</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getTinkerforgeDevice() * @generated * @ordered */ protected BrickDC tinkerforgeDevice; /** * The default value of the '{@link #getIpConnection() <em>Ip Connection</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getIpConnection() * @generated * @ordered */ protected static final IPConnection IP_CONNECTION_EDEFAULT = null; /** * The cached value of the '{@link #getIpConnection() <em>Ip Connection</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getIpConnection() * @generated * @ordered */ protected IPConnection ipConnection = IP_CONNECTION_EDEFAULT; /** * The default value of the '{@link #getConnectedUid() <em>Connected Uid</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getConnectedUid() * @generated * @ordered */ protected static final String CONNECTED_UID_EDEFAULT = null; /** * The cached value of the '{@link #getConnectedUid() <em>Connected Uid</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getConnectedUid() * @generated * @ordered */ protected String connectedUid = CONNECTED_UID_EDEFAULT; /** * The default value of the '{@link #getPosition() <em>Position</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getPosition() * @generated * @ordered */ protected static final char POSITION_EDEFAULT = '\u0000'; /** * The cached value of the '{@link #getPosition() <em>Position</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getPosition() * @generated * @ordered */ protected char position = POSITION_EDEFAULT; /** * The default value of the '{@link #getDeviceIdentifier() <em>Device Identifier</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getDeviceIdentifier() * @generated * @ordered */ protected static final int DEVICE_IDENTIFIER_EDEFAULT = 0; /** * The cached value of the '{@link #getDeviceIdentifier() <em>Device Identifier</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getDeviceIdentifier() * @generated * @ordered */ protected int deviceIdentifier = DEVICE_IDENTIFIER_EDEFAULT; /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The default value of the '{@link #getDirection() <em>Direction</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getDirection() * @generated * @ordered */ protected static final DirectionValue DIRECTION_EDEFAULT = null; /** * The cached value of the '{@link #getDirection() <em>Direction</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getDirection() * @generated * @ordered */ protected DirectionValue direction = DIRECTION_EDEFAULT; /** * The cached value of the '{@link #getTfConfig() <em>Tf Config</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getTfConfig() * @generated * @ordered */ protected TFBrickDCConfiguration tfConfig; /** * The default value of the '{@link #getMinValue() <em>Min Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getMinValue() * @generated * @ordered */ protected static final BigDecimal MIN_VALUE_EDEFAULT = null; /** * The cached value of the '{@link #getMinValue() <em>Min Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getMinValue() * @generated * @ordered */ protected BigDecimal minValue = MIN_VALUE_EDEFAULT; /** * The default value of the '{@link #getMaxValue() <em>Max Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getMaxValue() * @generated * @ordered */ protected static final BigDecimal MAX_VALUE_EDEFAULT = null; /** * The cached value of the '{@link #getMaxValue() <em>Max Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getMaxValue() * @generated * @ordered */ protected BigDecimal maxValue = MAX_VALUE_EDEFAULT; /** * The default value of the '{@link #getPercentValue() <em>Percent Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getPercentValue() * @generated * @ordered */ protected static final PercentValue PERCENT_VALUE_EDEFAULT = null; /** * The cached value of the '{@link #getPercentValue() <em>Percent Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getPercentValue() * @generated * @ordered */ protected PercentValue percentValue = PERCENT_VALUE_EDEFAULT; /** * The default value of the '{@link #getCallbackPeriod() <em>Callback Period</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getCallbackPeriod() * @generated * @ordered */ protected static final long CALLBACK_PERIOD_EDEFAULT = 1000L; /** * The cached value of the '{@link #getCallbackPeriod() <em>Callback Period</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getCallbackPeriod() * @generated * @ordered */ protected long callbackPeriod = CALLBACK_PERIOD_EDEFAULT; /** * The default value of the '{@link #getDeviceType() <em>Device Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getDeviceType() * @generated * @ordered */ protected static final String DEVICE_TYPE_EDEFAULT = "brick_dc"; /** * The cached value of the '{@link #getDeviceType() <em>Device Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getDeviceType() * @generated * @ordered */ protected String deviceType = DEVICE_TYPE_EDEFAULT; /** * The default value of the '{@link #getThreshold() <em>Threshold</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getThreshold() * @generated * @ordered */ protected static final BigDecimal THRESHOLD_EDEFAULT = new BigDecimal("10"); /** * The cached value of the '{@link #getThreshold() <em>Threshold</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getThreshold() * @generated * @ordered */ protected BigDecimal threshold = THRESHOLD_EDEFAULT; /** * The default value of the '{@link #getMaxVelocity() <em>Max Velocity</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getMaxVelocity() * @generated * @ordered */ protected static final Short MAX_VELOCITY_EDEFAULT = new Short((short) 32767); /** * The cached value of the '{@link #getMaxVelocity() <em>Max Velocity</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getMaxVelocity() * @generated * @ordered */ protected Short maxVelocity = MAX_VELOCITY_EDEFAULT; /** * The default value of the '{@link #getMinVelocity() <em>Min Velocity</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getMinVelocity() * @generated * @ordered */ protected static final Short MIN_VELOCITY_EDEFAULT = new Short((short) -32767); /** * The cached value of the '{@link #getMinVelocity() <em>Min Velocity</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getMinVelocity() * @generated * @ordered */ protected Short minVelocity = MIN_VELOCITY_EDEFAULT; /** * The default value of the '{@link #getVelocity() <em>Velocity</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getVelocity() * @generated * @ordered */ protected static final short VELOCITY_EDEFAULT = 0; /** * The cached value of the '{@link #getVelocity() <em>Velocity</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getVelocity() * @generated * @ordered */ protected short velocity = VELOCITY_EDEFAULT; /** * The default value of the '{@link #getTargetvelocity() <em>Targetvelocity</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getTargetvelocity() * @generated * @ordered */ protected static final short TARGETVELOCITY_EDEFAULT = 0; /** * The cached value of the '{@link #getTargetvelocity() <em>Targetvelocity</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getTargetvelocity() * @generated * @ordered */ protected short targetvelocity = TARGETVELOCITY_EDEFAULT; /** * The default value of the '{@link #getCurrentVelocity() <em>Current Velocity</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getCurrentVelocity() * @generated * @ordered */ protected static final short CURRENT_VELOCITY_EDEFAULT = 0; /** * The cached value of the '{@link #getCurrentVelocity() <em>Current Velocity</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getCurrentVelocity() * @generated * @ordered */ protected short currentVelocity = CURRENT_VELOCITY_EDEFAULT; /** * The default value of the '{@link #getAcceleration() <em>Acceleration</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getAcceleration() * @generated * @ordered */ protected static final int ACCELERATION_EDEFAULT = 10000; /** * The cached value of the '{@link #getAcceleration() <em>Acceleration</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getAcceleration() * @generated * @ordered */ protected int acceleration = ACCELERATION_EDEFAULT; /** * The default value of the '{@link #getPwmFrequency() <em>Pwm Frequency</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getPwmFrequency() * @generated * @ordered */ protected static final int PWM_FREQUENCY_EDEFAULT = 15000; /** * The cached value of the '{@link #getPwmFrequency() <em>Pwm Frequency</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getPwmFrequency() * @generated * @ordered */ protected int pwmFrequency = PWM_FREQUENCY_EDEFAULT; /** * The default value of the '{@link #getDriveMode() <em>Drive Mode</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getDriveMode() * @generated * @ordered */ protected static final DCDriveMode DRIVE_MODE_EDEFAULT = DCDriveMode.BRAKE; /** * The cached value of the '{@link #getDriveMode() <em>Drive Mode</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getDriveMode() * @generated * @ordered */ protected DCDriveMode driveMode = DRIVE_MODE_EDEFAULT; private VelocityListener listener; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ protected MBrickDCImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override protected EClass eStaticClass() { return ModelPackage.Literals.MBRICK_DC; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public DecimalValue getSensorValue() { return sensorValue; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setSensorValue(DecimalValue newSensorValue) { DecimalValue oldSensorValue = sensorValue; sensorValue = newSensorValue; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__SENSOR_VALUE, oldSensorValue, sensorValue)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public OnOffValue getSwitchState() { return switchState; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setSwitchState(OnOffValue newSwitchState) { OnOffValue oldSwitchState = switchState; switchState = newSwitchState; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__SWITCH_STATE, oldSwitchState, switchState)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public Logger getLogger() { return logger; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setLogger(Logger newLogger) { Logger oldLogger = logger; logger = newLogger; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__LOGGER, oldLogger, logger)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public String getUid() { return uid; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setUid(String newUid) { String oldUid = uid; uid = newUid; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__UID, oldUid, uid)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public boolean isPoll() { return poll; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setPoll(boolean newPoll) { boolean oldPoll = poll; poll = newPoll; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__POLL, oldPoll, poll)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public AtomicBoolean getEnabledA() { return enabledA; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setEnabledA(AtomicBoolean newEnabledA) { AtomicBoolean oldEnabledA = enabledA; enabledA = newEnabledA; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__ENABLED_A, oldEnabledA, enabledA)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public BrickDC getTinkerforgeDevice() { return tinkerforgeDevice; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setTinkerforgeDevice(BrickDC newTinkerforgeDevice) { BrickDC oldTinkerforgeDevice = tinkerforgeDevice; tinkerforgeDevice = newTinkerforgeDevice; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__TINKERFORGE_DEVICE, oldTinkerforgeDevice, tinkerforgeDevice)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public IPConnection getIpConnection() { return ipConnection; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setIpConnection(IPConnection newIpConnection) { IPConnection oldIpConnection = ipConnection; ipConnection = newIpConnection; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__IP_CONNECTION, oldIpConnection, ipConnection)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public String getConnectedUid() { return connectedUid; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setConnectedUid(String newConnectedUid) { String oldConnectedUid = connectedUid; connectedUid = newConnectedUid; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__CONNECTED_UID, oldConnectedUid, connectedUid)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public char getPosition() { return position; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setPosition(char newPosition) { char oldPosition = position; position = newPosition; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__POSITION, oldPosition, position)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public int getDeviceIdentifier() { return deviceIdentifier; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setDeviceIdentifier(int newDeviceIdentifier) { int oldDeviceIdentifier = deviceIdentifier; deviceIdentifier = newDeviceIdentifier; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__DEVICE_IDENTIFIER, oldDeviceIdentifier, deviceIdentifier)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__NAME, oldName, name)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public MBrickd getBrickd() { if (eContainerFeatureID() != ModelPackage.MBRICK_DC__BRICKD) { return null; } return (MBrickd) eContainer(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public NotificationChain basicSetBrickd(MBrickd newBrickd, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject) newBrickd, ModelPackage.MBRICK_DC__BRICKD, msgs); return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setBrickd(MBrickd newBrickd) { if (newBrickd != eInternalContainer() || (eContainerFeatureID() != ModelPackage.MBRICK_DC__BRICKD && newBrickd != null)) { if (EcoreUtil.isAncestor(this, newBrickd)) { throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); } NotificationChain msgs = null; if (eInternalContainer() != null) { msgs = eBasicRemoveFromContainer(msgs); } if (newBrickd != null) { msgs = ((InternalEObject) newBrickd).eInverseAdd(this, ModelPackage.MBRICKD__MDEVICES, MBrickd.class, msgs); } msgs = basicSetBrickd(newBrickd, msgs); if (msgs != null) { msgs.dispatch(); } } else if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__BRICKD, newBrickd, newBrickd)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public TFBrickDCConfiguration getTfConfig() { return tfConfig; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public NotificationChain basicSetTfConfig(TFBrickDCConfiguration newTfConfig, NotificationChain msgs) { TFBrickDCConfiguration oldTfConfig = tfConfig; tfConfig = newTfConfig; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__TF_CONFIG, oldTfConfig, newTfConfig); if (msgs == null) { msgs = notification; } else { msgs.add(notification); } } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setTfConfig(TFBrickDCConfiguration newTfConfig) { if (newTfConfig != tfConfig) { NotificationChain msgs = null; if (tfConfig != null) { msgs = ((InternalEObject) tfConfig).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - ModelPackage.MBRICK_DC__TF_CONFIG, null, msgs); } if (newTfConfig != null) { msgs = ((InternalEObject) newTfConfig).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - ModelPackage.MBRICK_DC__TF_CONFIG, null, msgs); } msgs = basicSetTfConfig(newTfConfig, msgs); if (msgs != null) { msgs.dispatch(); } } else if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__TF_CONFIG, newTfConfig, newTfConfig)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public BigDecimal getMinValue() { return minValue; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setMinValue(BigDecimal newMinValue) { BigDecimal oldMinValue = minValue; minValue = newMinValue; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__MIN_VALUE, oldMinValue, minValue)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public BigDecimal getMaxValue() { return maxValue; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setMaxValue(BigDecimal newMaxValue) { BigDecimal oldMaxValue = maxValue; maxValue = newMaxValue; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__MAX_VALUE, oldMaxValue, maxValue)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public PercentValue getPercentValue() { return percentValue; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setPercentValue(PercentValue newPercentValue) { PercentValue oldPercentValue = percentValue; percentValue = newPercentValue; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__PERCENT_VALUE, oldPercentValue, percentValue)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public DirectionValue getDirection() { return direction; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setDirection(DirectionValue newDirection) { DirectionValue oldDirection = direction; direction = newDirection; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__DIRECTION, oldDirection, direction)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public long getCallbackPeriod() { return callbackPeriod; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setCallbackPeriod(long newCallbackPeriod) { long oldCallbackPeriod = callbackPeriod; callbackPeriod = newCallbackPeriod; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__CALLBACK_PERIOD, oldCallbackPeriod, callbackPeriod)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public BigDecimal getThreshold() { return threshold; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setThreshold(BigDecimal newThreshold) { BigDecimal oldThreshold = threshold; threshold = newThreshold; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__THRESHOLD, oldThreshold, threshold)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public Short getMaxVelocity() { return maxVelocity; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setMaxVelocity(Short newMaxVelocity) { Short oldMaxVelocity = maxVelocity; maxVelocity = newMaxVelocity; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__MAX_VELOCITY, oldMaxVelocity, maxVelocity)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public Short getMinVelocity() { return minVelocity; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setMinVelocity(Short newMinVelocity) { Short oldMinVelocity = minVelocity; minVelocity = newMinVelocity; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__MIN_VELOCITY, oldMinVelocity, minVelocity)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public String getDeviceType() { return deviceType; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public short getVelocity() { return velocity; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setVelocity(short newVelocity) { short oldVelocity = velocity; velocity = newVelocity; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__VELOCITY, oldVelocity, velocity)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public short getTargetvelocity() { return targetvelocity; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setTargetvelocity(short newTargetvelocity) { short oldTargetvelocity = targetvelocity; targetvelocity = newTargetvelocity; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__TARGETVELOCITY, oldTargetvelocity, targetvelocity)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public short getCurrentVelocity() { return currentVelocity; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setCurrentVelocity(short newCurrentVelocity) { short oldCurrentVelocity = currentVelocity; currentVelocity = newCurrentVelocity; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__CURRENT_VELOCITY, oldCurrentVelocity, currentVelocity)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public int getAcceleration() { return acceleration; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setAcceleration(int newAcceleration) { int oldAcceleration = acceleration; acceleration = newAcceleration; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__ACCELERATION, oldAcceleration, acceleration)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public int getPwmFrequency() { return pwmFrequency; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setPwmFrequency(int newPwmFrequency) { int oldPwmFrequency = pwmFrequency; pwmFrequency = newPwmFrequency; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__PWM_FREQUENCY, oldPwmFrequency, pwmFrequency)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public DCDriveMode getDriveMode() { return driveMode; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void setDriveMode(DCDriveMode newDriveMode) { DCDriveMode oldDriveMode = driveMode; driveMode = newDriveMode == null ? DRIVE_MODE_EDEFAULT : newDriveMode; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MBRICK_DC__DRIVE_MODE, oldDriveMode, driveMode)); } } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ @Override public void init() { logger = LoggerFactory.getLogger(MBrickDCImpl.class); poll = true; // don't use the setter to prevent notification setEnabledA(new AtomicBoolean()); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ @Override public void setValue(BigDecimal newValue, DeviceOptions opts) { setPoint(newValue.shortValue(), opts); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ @Override public void setValue(PercentType percentValue, DeviceOptions opts) { BigDecimal max = Tools.getBigDecimalOpt(ConfigOptsDimmable.MAX.toString(), opts); if (max == null) { logger.error("BrickDC dimmer option max is missing, items configuration has to be fixed!"); return; } else { logger.debug("Brick DC max {}", max); } BigDecimal min = Tools.getBigDecimalOpt(ConfigOptsDimmable.MIN.toString(), opts); logger.debug("Brick DC min {}", min); if (min == null) { logger.error("BrickDC dimmer option min is missing, items configuration has to be fixed!"); return; } setPercentValue(new PercentValue(percentValue.toBigDecimal())); BigDecimal abs = max.add(min.abs()); Short newVelocity = abs.divide(new BigDecimal(100)).multiply(percentValue.toBigDecimal()).subtract(min.abs()) .shortValue(); setPoint(newVelocity, opts); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ @Override public void dimm(IncreaseDecreaseType increaseDecrease, DeviceOptions opts) { logger.trace("dimmer increase increaseDecrease {} opts {}", increaseDecrease, opts); if (opts == null) { logger.error("Brick DC options are missing"); return; } if (increaseDecrease == null) { logger.error("Brick DC increaseDecrease may not be null!"); return; } Short step = Tools.getShortOpt(ConfigOptsDimmable.STEP.toString(), opts); if (step == null) { logger.error("BrickDC dimmer option step is missing, items configuration has to be fixed!"); return; } Short newVelocity = null; if (increaseDecrease.equals(IncreaseDecreaseType.INCREASE)) { newVelocity = (short) (this.targetvelocity + step); } else if (increaseDecrease.equals(IncreaseDecreaseType.DECREASE)) { newVelocity = (short) (this.targetvelocity - step); } logger.debug("Brick DC newVelocity {}", newVelocity); setPoint(newVelocity, opts); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ private void setPoint(Short targetspeed, DeviceOptions opts) { Integer xacceleration = Tools.getIntOpt(ConfigOptsMove.ACCELERATION.toString(), opts); String drivemodestr = Tools.getStringOpt(ConfigOptsMove.DRIVEMODE.toString(), opts); Short speed = null; logger.trace("setPiont speed {} opts {}", targetspeed, opts); if (opts == null) { logger.error("Brick DC options are missing"); return; } if (targetspeed == null) { logger.error("Brick DC setPoint targetspeed may not be null!"); return; } Short max = Tools.getShortOpt(ConfigOptsDimmable.MAX.toString(), opts); if (max == null) { logger.error("BrickDC dimmer option max is missing, items configuration has to be fixed!"); return; } else { logger.debug("Brick DC max {}", max); } Short min = Tools.getShortOpt(ConfigOptsDimmable.MIN.toString(), opts); logger.debug("Brick DC min {}", min); if (min == null) { logger.error("BrickDC dimmer option min is missing, items configuration has to be fixed!"); return; } if (targetspeed > max) { if (this.velocity < targetspeed) { logger.debug("setting velocity to max speed {}, which is lower then target speed {}", max, targetspeed); speed = max; } else { logger.debug("max velocity already reached {}", max); return; } } else if (targetspeed < min) { if (this.velocity > targetspeed) { logger.debug("setting velocity to min speed {}, which is higher then target speed {}", min, targetspeed); speed = min; } else { logger.debug("min velocity already reached {}", min); return; } } else { speed = targetspeed; } setSpeed(speed, xacceleration, drivemodestr, this.pwmFrequency); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ @Override public void turnSwitch(OnOffValue state, DeviceOptions opts) { logger.trace("turnSwitch called"); if (state == OnOffValue.OFF) { setSpeed((short) 0, null, null, null); } else if (state == OnOffValue.ON) { setSpeed(Tools.getShortOpt(ConfigOptsSwitchSpeed.SPEED.toString(), opts), null, null, null); } else { logger.error("{} unknown switchstate {}", LoggerConstants.TFMODELUPDATE, state); } } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ @Override public void fetchSwitchState() { fetchSensorValue(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated NOT */ @Override public void fetchSensorValue() { try { handleVelocity(tinkerforgeDevice.getVelocity(), false); } catch (TimeoutException e) { TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_TIMEOUT_EXCEPTION, e); } catch (NotConnectedException e) { TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_NOT_CONNECTION_EXCEPTION, e); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated NOT */ @Override public void moveon(DeviceOptions opts) { if (direction != null && direction != DirectionValue.UNDEF) { UpDownType directiontmp = this.direction == DirectionValue.LEFT ? UpDownType.UP : UpDownType.DOWN; move(directiontmp, opts); } else { logger.warn("cannot moveon because direction is undefined"); } } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ @Override public void move(UpDownType direction, DeviceOptions opts) { if (opts == null) { logger.error("Brick DC options are missing"); return; } if (direction == null) { logger.error("Brick DC direction may not be null, items configuration has to be fixed!"); return; } Integer itemacceleration = Tools.getIntOpt(ConfigOptsMove.ACCELERATION.toString(), opts); String drivemodestr = Tools.getStringOpt(ConfigOptsMove.DRIVEMODE.toString(), opts); Short speed = null; if (direction.equals(UpDownType.DOWN)) { speed = Tools.getShortOpt(ConfigOptsMove.RIGHTSPEED.toString(), opts); if (speed == null) { logger.error("\"rightspeed\" option missing or empty, items configuration has to be fixed!"); return; } else { setDirection(DirectionValue.RIGHT); } } else if (direction.equals(UpDownType.UP)) { speed = Tools.getShortOpt(ConfigOptsMove.LEFTSPEED.toString(), opts); if (speed == null) { logger.error("\"leftspeed\" option missing or empty, items configuration has to be fixed!"); return; } else { setDirection(DirectionValue.LEFT); } } setSpeed(speed, itemacceleration, drivemodestr, this.pwmFrequency); } /** * * @generated NOT */ private Short driveModeFromString(String drivemodestr) { logger.debug("drivemodestr short is: {}", drivemodestr); Short drivemode = null; if (drivemodestr != null) { if (drivemodestr.equals(DCDriveMode.BRAKE.toString().toLowerCase())) { drivemode = BrickDC.DRIVE_MODE_DRIVE_BRAKE; } else if (drivemodestr.equals(DCDriveMode.COAST.toString().toLowerCase())) { drivemode = BrickDC.DRIVE_MODE_DRIVE_COAST; } else { logger.error("invalid drivemode {}", drivemodestr); } } else { // use defaults if (driveMode == DCDriveMode.BRAKE) { drivemode = BrickDC.DRIVE_MODE_DRIVE_BRAKE; } else if (driveMode == DCDriveMode.COAST) { drivemode = BrickDC.DRIVE_MODE_DRIVE_COAST; } } logger.debug("drivemode short is: {}", drivemode); return drivemode; } /** * * @generated NOT */ private boolean setSpeed(Short speed, Integer acceleration, String drivemode, Integer pwm) { // use defaults if acceleration, drivemode or pwm are null Short xdrivemode = driveModeFromString(drivemode); Integer xacceleration = acceleration != null ? acceleration : this.acceleration; Integer xpwm = pwm != null ? pwm : this.pwmFrequency; short xspeed = 0; if (speed == null) { logger.warn("Brick DC got speed null, setting speed to 0"); } else { xspeed = speed; } try { if (xdrivemode != null) { // let Brick DC choose the drive mode tinkerforgeDevice.setDriveMode(xdrivemode); } if (xacceleration != null) { tinkerforgeDevice.setAcceleration(xacceleration); } if (xpwm != null) { tinkerforgeDevice.setPWMFrequency(xpwm); } setTargetvelocity(xspeed); tinkerforgeDevice.setVelocity(xspeed); return true; } catch (TimeoutException e) { TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_TIMEOUT_EXCEPTION, e); } catch (NotConnectedException e) { TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_NOT_CONNECTION_EXCEPTION, e); } return false; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ @Override public boolean setSpeed(Short velocity, int acceleration, String drivemode) { return setSpeed(velocity, acceleration, drivemode, null); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ @Override public void stop() { try { tinkerforgeDevice.setVelocity((short) 0); } catch (TimeoutException e) { TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_TIMEOUT_EXCEPTION, e); } catch (NotConnectedException e) { TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_NOT_CONNECTION_EXCEPTION, e); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated NOT */ @Override public void enable() { tinkerforgeDevice = new BrickDC(uid, ipConnection); if (tfConfig != null) { logger.debug("found tfConfig"); if (tfConfig.eIsSet(tfConfig.eClass().getEStructuralFeature("acceleration"))) { setAcceleration(tfConfig.getAcceleration()); } if (tfConfig.eIsSet(tfConfig.eClass().getEStructuralFeature("pwmFrequency"))) { setPwmFrequency(tfConfig.getPwmFrequency()); } if (tfConfig.eIsSet(tfConfig.eClass().getEStructuralFeature("driveMode"))) { setDriveMode(DCDriveMode.get(tfConfig.getDriveMode())); } if (tfConfig.eIsSet(tfConfig.eClass().getEStructuralFeature("threshold"))) { setThreshold(tfConfig.getThreshold()); } if (tfConfig.eIsSet(tfConfig.eClass().getEStructuralFeature("callbackPeriod"))) { setCallbackPeriod(tfConfig.getCallbackPeriod()); } } try { tinkerforgeDevice.setPWMFrequency(pwmFrequency); if (driveMode == DCDriveMode.BRAKE) { tinkerforgeDevice.setDriveMode(BrickDC.DRIVE_MODE_DRIVE_BRAKE); } else if (driveMode == DCDriveMode.COAST) { tinkerforgeDevice.setDriveMode(BrickDC.DRIVE_MODE_DRIVE_COAST); } tinkerforgeDevice.setCurrentVelocityPeriod((int) callbackPeriod); listener = new VelocityListener(); tinkerforgeDevice.addCurrentVelocityListener(listener); tinkerforgeDevice.enable(); handleVelocity(tinkerforgeDevice.getVelocity(), false); } catch (TimeoutException e) { TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_TIMEOUT_EXCEPTION, e); } catch (NotConnectedException e) { TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_NOT_CONNECTION_EXCEPTION, e); } } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ private class VelocityListener implements BrickDC.CurrentVelocityListener { @Override public void currentVelocity(short velocity) { handleVelocity(velocity); } } /** * * @generated NOT */ private void handleVelocity(short velocity, boolean usethreshold) { DecimalValue newValue = Tools.calculate(velocity); logger.trace("{} got new value {}", LoggerConstants.TFMODELUPDATE, newValue); if (usethreshold) { if (newValue.compareTo(getSensorValue(), getThreshold()) != 0) { logger.trace("{} setting new value {}", LoggerConstants.TFMODELUPDATE, newValue); setSensorValue(newValue); } else { logger.trace("{} omitting new value {}", LoggerConstants.TFMODELUPDATE, newValue); } } else { logger.trace("{} setting new value {}", LoggerConstants.TFMODELUPDATE, newValue); setSensorValue(newValue); } OnOffValue newSwitchState = newValue.onOffValue(0); logger.trace("new switchstate {} new value {}", newSwitchState, newValue); if (newSwitchState != switchState) { setSwitchState(newSwitchState); } } /** * * @generated NOT */ private void handleVelocity(short velocity) { handleVelocity(velocity, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated NOT */ @Override public void disable() { if (listener != null) { tinkerforgeDevice.removeCurrentVelocityListener(listener); } tinkerforgeDevice = null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ModelPackage.MBRICK_DC__BRICKD: if (eInternalContainer() != null) { msgs = eBasicRemoveFromContainer(msgs); } return basicSetBrickd((MBrickd) otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ModelPackage.MBRICK_DC__BRICKD: return basicSetBrickd(null, msgs); case ModelPackage.MBRICK_DC__TF_CONFIG: return basicSetTfConfig(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) { switch (eContainerFeatureID()) { case ModelPackage.MBRICK_DC__BRICKD: return eInternalContainer().eInverseRemove(this, ModelPackage.MBRICKD__MDEVICES, MBrickd.class, msgs); } return super.eBasicRemoveFromContainerFeature(msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ModelPackage.MBRICK_DC__SENSOR_VALUE: return getSensorValue(); case ModelPackage.MBRICK_DC__SWITCH_STATE: return getSwitchState(); case ModelPackage.MBRICK_DC__LOGGER: return getLogger(); case ModelPackage.MBRICK_DC__UID: return getUid(); case ModelPackage.MBRICK_DC__POLL: return isPoll(); case ModelPackage.MBRICK_DC__ENABLED_A: return getEnabledA(); case ModelPackage.MBRICK_DC__TINKERFORGE_DEVICE: return getTinkerforgeDevice(); case ModelPackage.MBRICK_DC__IP_CONNECTION: return getIpConnection(); case ModelPackage.MBRICK_DC__CONNECTED_UID: return getConnectedUid(); case ModelPackage.MBRICK_DC__POSITION: return getPosition(); case ModelPackage.MBRICK_DC__DEVICE_IDENTIFIER: return getDeviceIdentifier(); case ModelPackage.MBRICK_DC__NAME: return getName(); case ModelPackage.MBRICK_DC__BRICKD: return getBrickd(); case ModelPackage.MBRICK_DC__DIRECTION: return getDirection(); case ModelPackage.MBRICK_DC__TF_CONFIG: return getTfConfig(); case ModelPackage.MBRICK_DC__MIN_VALUE: return getMinValue(); case ModelPackage.MBRICK_DC__MAX_VALUE: return getMaxValue(); case ModelPackage.MBRICK_DC__PERCENT_VALUE: return getPercentValue(); case ModelPackage.MBRICK_DC__CALLBACK_PERIOD: return getCallbackPeriod(); case ModelPackage.MBRICK_DC__DEVICE_TYPE: return getDeviceType(); case ModelPackage.MBRICK_DC__THRESHOLD: return getThreshold(); case ModelPackage.MBRICK_DC__MAX_VELOCITY: return getMaxVelocity(); case ModelPackage.MBRICK_DC__MIN_VELOCITY: return getMinVelocity(); case ModelPackage.MBRICK_DC__VELOCITY: return getVelocity(); case ModelPackage.MBRICK_DC__TARGETVELOCITY: return getTargetvelocity(); case ModelPackage.MBRICK_DC__CURRENT_VELOCITY: return getCurrentVelocity(); case ModelPackage.MBRICK_DC__ACCELERATION: return getAcceleration(); case ModelPackage.MBRICK_DC__PWM_FREQUENCY: return getPwmFrequency(); case ModelPackage.MBRICK_DC__DRIVE_MODE: return getDriveMode(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ModelPackage.MBRICK_DC__SENSOR_VALUE: setSensorValue((DecimalValue) newValue); return; case ModelPackage.MBRICK_DC__SWITCH_STATE: setSwitchState((OnOffValue) newValue); return; case ModelPackage.MBRICK_DC__LOGGER: setLogger((Logger) newValue); return; case ModelPackage.MBRICK_DC__UID: setUid((String) newValue); return; case ModelPackage.MBRICK_DC__POLL: setPoll((Boolean) newValue); return; case ModelPackage.MBRICK_DC__ENABLED_A: setEnabledA((AtomicBoolean) newValue); return; case ModelPackage.MBRICK_DC__TINKERFORGE_DEVICE: setTinkerforgeDevice((BrickDC) newValue); return; case ModelPackage.MBRICK_DC__IP_CONNECTION: setIpConnection((IPConnection) newValue); return; case ModelPackage.MBRICK_DC__CONNECTED_UID: setConnectedUid((String) newValue); return; case ModelPackage.MBRICK_DC__POSITION: setPosition((Character) newValue); return; case ModelPackage.MBRICK_DC__DEVICE_IDENTIFIER: setDeviceIdentifier((Integer) newValue); return; case ModelPackage.MBRICK_DC__NAME: setName((String) newValue); return; case ModelPackage.MBRICK_DC__BRICKD: setBrickd((MBrickd) newValue); return; case ModelPackage.MBRICK_DC__DIRECTION: setDirection((DirectionValue) newValue); return; case ModelPackage.MBRICK_DC__TF_CONFIG: setTfConfig((TFBrickDCConfiguration) newValue); return; case ModelPackage.MBRICK_DC__MIN_VALUE: setMinValue((BigDecimal) newValue); return; case ModelPackage.MBRICK_DC__MAX_VALUE: setMaxValue((BigDecimal) newValue); return; case ModelPackage.MBRICK_DC__PERCENT_VALUE: setPercentValue((PercentValue) newValue); return; case ModelPackage.MBRICK_DC__CALLBACK_PERIOD: setCallbackPeriod((Long) newValue); return; case ModelPackage.MBRICK_DC__THRESHOLD: setThreshold((BigDecimal) newValue); return; case ModelPackage.MBRICK_DC__MAX_VELOCITY: setMaxVelocity((Short) newValue); return; case ModelPackage.MBRICK_DC__MIN_VELOCITY: setMinVelocity((Short) newValue); return; case ModelPackage.MBRICK_DC__VELOCITY: setVelocity((Short) newValue); return; case ModelPackage.MBRICK_DC__TARGETVELOCITY: setTargetvelocity((Short) newValue); return; case ModelPackage.MBRICK_DC__CURRENT_VELOCITY: setCurrentVelocity((Short) newValue); return; case ModelPackage.MBRICK_DC__ACCELERATION: setAcceleration((Integer) newValue); return; case ModelPackage.MBRICK_DC__PWM_FREQUENCY: setPwmFrequency((Integer) newValue); return; case ModelPackage.MBRICK_DC__DRIVE_MODE: setDriveMode((DCDriveMode) newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ModelPackage.MBRICK_DC__SENSOR_VALUE: setSensorValue((DecimalValue) null); return; case ModelPackage.MBRICK_DC__SWITCH_STATE: setSwitchState(SWITCH_STATE_EDEFAULT); return; case ModelPackage.MBRICK_DC__LOGGER: setLogger(LOGGER_EDEFAULT); return; case ModelPackage.MBRICK_DC__UID: setUid(UID_EDEFAULT); return; case ModelPackage.MBRICK_DC__POLL: setPoll(POLL_EDEFAULT); return; case ModelPackage.MBRICK_DC__ENABLED_A: setEnabledA(ENABLED_A_EDEFAULT); return; case ModelPackage.MBRICK_DC__TINKERFORGE_DEVICE: setTinkerforgeDevice((BrickDC) null); return; case ModelPackage.MBRICK_DC__IP_CONNECTION: setIpConnection(IP_CONNECTION_EDEFAULT); return; case ModelPackage.MBRICK_DC__CONNECTED_UID: setConnectedUid(CONNECTED_UID_EDEFAULT); return; case ModelPackage.MBRICK_DC__POSITION: setPosition(POSITION_EDEFAULT); return; case ModelPackage.MBRICK_DC__DEVICE_IDENTIFIER: setDeviceIdentifier(DEVICE_IDENTIFIER_EDEFAULT); return; case ModelPackage.MBRICK_DC__NAME: setName(NAME_EDEFAULT); return; case ModelPackage.MBRICK_DC__BRICKD: setBrickd((MBrickd) null); return; case ModelPackage.MBRICK_DC__DIRECTION: setDirection(DIRECTION_EDEFAULT); return; case ModelPackage.MBRICK_DC__TF_CONFIG: setTfConfig((TFBrickDCConfiguration) null); return; case ModelPackage.MBRICK_DC__MIN_VALUE: setMinValue(MIN_VALUE_EDEFAULT); return; case ModelPackage.MBRICK_DC__MAX_VALUE: setMaxValue(MAX_VALUE_EDEFAULT); return; case ModelPackage.MBRICK_DC__PERCENT_VALUE: setPercentValue(PERCENT_VALUE_EDEFAULT); return; case ModelPackage.MBRICK_DC__CALLBACK_PERIOD: setCallbackPeriod(CALLBACK_PERIOD_EDEFAULT); return; case ModelPackage.MBRICK_DC__THRESHOLD: setThreshold(THRESHOLD_EDEFAULT); return; case ModelPackage.MBRICK_DC__MAX_VELOCITY: setMaxVelocity(MAX_VELOCITY_EDEFAULT); return; case ModelPackage.MBRICK_DC__MIN_VELOCITY: setMinVelocity(MIN_VELOCITY_EDEFAULT); return; case ModelPackage.MBRICK_DC__VELOCITY: setVelocity(VELOCITY_EDEFAULT); return; case ModelPackage.MBRICK_DC__TARGETVELOCITY: setTargetvelocity(TARGETVELOCITY_EDEFAULT); return; case ModelPackage.MBRICK_DC__CURRENT_VELOCITY: setCurrentVelocity(CURRENT_VELOCITY_EDEFAULT); return; case ModelPackage.MBRICK_DC__ACCELERATION: setAcceleration(ACCELERATION_EDEFAULT); return; case ModelPackage.MBRICK_DC__PWM_FREQUENCY: setPwmFrequency(PWM_FREQUENCY_EDEFAULT); return; case ModelPackage.MBRICK_DC__DRIVE_MODE: setDriveMode(DRIVE_MODE_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ModelPackage.MBRICK_DC__SENSOR_VALUE: return sensorValue != null; case ModelPackage.MBRICK_DC__SWITCH_STATE: return SWITCH_STATE_EDEFAULT == null ? switchState != null : !SWITCH_STATE_EDEFAULT.equals(switchState); case ModelPackage.MBRICK_DC__LOGGER: return LOGGER_EDEFAULT == null ? logger != null : !LOGGER_EDEFAULT.equals(logger); case ModelPackage.MBRICK_DC__UID: return UID_EDEFAULT == null ? uid != null : !UID_EDEFAULT.equals(uid); case ModelPackage.MBRICK_DC__POLL: return poll != POLL_EDEFAULT; case ModelPackage.MBRICK_DC__ENABLED_A: return ENABLED_A_EDEFAULT == null ? enabledA != null : !ENABLED_A_EDEFAULT.equals(enabledA); case ModelPackage.MBRICK_DC__TINKERFORGE_DEVICE: return tinkerforgeDevice != null; case ModelPackage.MBRICK_DC__IP_CONNECTION: return IP_CONNECTION_EDEFAULT == null ? ipConnection != null : !IP_CONNECTION_EDEFAULT.equals(ipConnection); case ModelPackage.MBRICK_DC__CONNECTED_UID: return CONNECTED_UID_EDEFAULT == null ? connectedUid != null : !CONNECTED_UID_EDEFAULT.equals(connectedUid); case ModelPackage.MBRICK_DC__POSITION: return position != POSITION_EDEFAULT; case ModelPackage.MBRICK_DC__DEVICE_IDENTIFIER: return deviceIdentifier != DEVICE_IDENTIFIER_EDEFAULT; case ModelPackage.MBRICK_DC__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case ModelPackage.MBRICK_DC__BRICKD: return getBrickd() != null; case ModelPackage.MBRICK_DC__DIRECTION: return DIRECTION_EDEFAULT == null ? direction != null : !DIRECTION_EDEFAULT.equals(direction); case ModelPackage.MBRICK_DC__TF_CONFIG: return tfConfig != null; case ModelPackage.MBRICK_DC__MIN_VALUE: return MIN_VALUE_EDEFAULT == null ? minValue != null : !MIN_VALUE_EDEFAULT.equals(minValue); case ModelPackage.MBRICK_DC__MAX_VALUE: return MAX_VALUE_EDEFAULT == null ? maxValue != null : !MAX_VALUE_EDEFAULT.equals(maxValue); case ModelPackage.MBRICK_DC__PERCENT_VALUE: return PERCENT_VALUE_EDEFAULT == null ? percentValue != null : !PERCENT_VALUE_EDEFAULT.equals(percentValue); case ModelPackage.MBRICK_DC__CALLBACK_PERIOD: return callbackPeriod != CALLBACK_PERIOD_EDEFAULT; case ModelPackage.MBRICK_DC__DEVICE_TYPE: return DEVICE_TYPE_EDEFAULT == null ? deviceType != null : !DEVICE_TYPE_EDEFAULT.equals(deviceType); case ModelPackage.MBRICK_DC__THRESHOLD: return THRESHOLD_EDEFAULT == null ? threshold != null : !THRESHOLD_EDEFAULT.equals(threshold); case ModelPackage.MBRICK_DC__MAX_VELOCITY: return MAX_VELOCITY_EDEFAULT == null ? maxVelocity != null : !MAX_VELOCITY_EDEFAULT.equals(maxVelocity); case ModelPackage.MBRICK_DC__MIN_VELOCITY: return MIN_VELOCITY_EDEFAULT == null ? minVelocity != null : !MIN_VELOCITY_EDEFAULT.equals(minVelocity); case ModelPackage.MBRICK_DC__VELOCITY: return velocity != VELOCITY_EDEFAULT; case ModelPackage.MBRICK_DC__TARGETVELOCITY: return targetvelocity != TARGETVELOCITY_EDEFAULT; case ModelPackage.MBRICK_DC__CURRENT_VELOCITY: return currentVelocity != CURRENT_VELOCITY_EDEFAULT; case ModelPackage.MBRICK_DC__ACCELERATION: return acceleration != ACCELERATION_EDEFAULT; case ModelPackage.MBRICK_DC__PWM_FREQUENCY: return pwmFrequency != PWM_FREQUENCY_EDEFAULT; case ModelPackage.MBRICK_DC__DRIVE_MODE: return driveMode != DRIVE_MODE_EDEFAULT; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public int eBaseStructuralFeatureID(int derivedFeatureID, Class<?> baseClass) { if (baseClass == SwitchSensor.class) { switch (derivedFeatureID) { case ModelPackage.MBRICK_DC__SWITCH_STATE: return ModelPackage.SWITCH_SENSOR__SWITCH_STATE; default: return -1; } } if (baseClass == ProgrammableSwitchActor.class) { switch (derivedFeatureID) { default: return -1; } } if (baseClass == MBaseDevice.class) { switch (derivedFeatureID) { case ModelPackage.MBRICK_DC__LOGGER: return ModelPackage.MBASE_DEVICE__LOGGER; case ModelPackage.MBRICK_DC__UID: return ModelPackage.MBASE_DEVICE__UID; case ModelPackage.MBRICK_DC__POLL: return ModelPackage.MBASE_DEVICE__POLL; case ModelPackage.MBRICK_DC__ENABLED_A: return ModelPackage.MBASE_DEVICE__ENABLED_A; default: return -1; } } if (baseClass == MDevice.class) { switch (derivedFeatureID) { case ModelPackage.MBRICK_DC__TINKERFORGE_DEVICE: return ModelPackage.MDEVICE__TINKERFORGE_DEVICE; case ModelPackage.MBRICK_DC__IP_CONNECTION: return ModelPackage.MDEVICE__IP_CONNECTION; case ModelPackage.MBRICK_DC__CONNECTED_UID: return ModelPackage.MDEVICE__CONNECTED_UID; case ModelPackage.MBRICK_DC__POSITION: return ModelPackage.MDEVICE__POSITION; case ModelPackage.MBRICK_DC__DEVICE_IDENTIFIER: return ModelPackage.MDEVICE__DEVICE_IDENTIFIER; case ModelPackage.MBRICK_DC__NAME: return ModelPackage.MDEVICE__NAME; case ModelPackage.MBRICK_DC__BRICKD: return ModelPackage.MDEVICE__BRICKD; default: return -1; } } if (baseClass == MoveActor.class) { switch (derivedFeatureID) { case ModelPackage.MBRICK_DC__DIRECTION: return ModelPackage.MOVE_ACTOR__DIRECTION; default: return -1; } } if (baseClass == MTFConfigConsumer.class) { switch (derivedFeatureID) { case ModelPackage.MBRICK_DC__TF_CONFIG: return ModelPackage.MTF_CONFIG_CONSUMER__TF_CONFIG; default: return -1; } } if (baseClass == DimmableActor.class) { switch (derivedFeatureID) { case ModelPackage.MBRICK_DC__MIN_VALUE: return ModelPackage.DIMMABLE_ACTOR__MIN_VALUE; case ModelPackage.MBRICK_DC__MAX_VALUE: return ModelPackage.DIMMABLE_ACTOR__MAX_VALUE; default: return -1; } } if (baseClass == PercentTypeActor.class) { switch (derivedFeatureID) { case ModelPackage.MBRICK_DC__PERCENT_VALUE: return ModelPackage.PERCENT_TYPE_ACTOR__PERCENT_VALUE; default: return -1; } } if (baseClass == SetPointActor.class) { switch (derivedFeatureID) { default: return -1; } } if (baseClass == CallbackListener.class) { switch (derivedFeatureID) { case ModelPackage.MBRICK_DC__CALLBACK_PERIOD: return ModelPackage.CALLBACK_LISTENER__CALLBACK_PERIOD; default: return -1; } } return super.eBaseStructuralFeatureID(derivedFeatureID, baseClass); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public int eDerivedStructuralFeatureID(int baseFeatureID, Class<?> baseClass) { if (baseClass == SwitchSensor.class) { switch (baseFeatureID) { case ModelPackage.SWITCH_SENSOR__SWITCH_STATE: return ModelPackage.MBRICK_DC__SWITCH_STATE; default: return -1; } } if (baseClass == ProgrammableSwitchActor.class) { switch (baseFeatureID) { default: return -1; } } if (baseClass == MBaseDevice.class) { switch (baseFeatureID) { case ModelPackage.MBASE_DEVICE__LOGGER: return ModelPackage.MBRICK_DC__LOGGER; case ModelPackage.MBASE_DEVICE__UID: return ModelPackage.MBRICK_DC__UID; case ModelPackage.MBASE_DEVICE__POLL: return ModelPackage.MBRICK_DC__POLL; case ModelPackage.MBASE_DEVICE__ENABLED_A: return ModelPackage.MBRICK_DC__ENABLED_A; default: return -1; } } if (baseClass == MDevice.class) { switch (baseFeatureID) { case ModelPackage.MDEVICE__TINKERFORGE_DEVICE: return ModelPackage.MBRICK_DC__TINKERFORGE_DEVICE; case ModelPackage.MDEVICE__IP_CONNECTION: return ModelPackage.MBRICK_DC__IP_CONNECTION; case ModelPackage.MDEVICE__CONNECTED_UID: return ModelPackage.MBRICK_DC__CONNECTED_UID; case ModelPackage.MDEVICE__POSITION: return ModelPackage.MBRICK_DC__POSITION; case ModelPackage.MDEVICE__DEVICE_IDENTIFIER: return ModelPackage.MBRICK_DC__DEVICE_IDENTIFIER; case ModelPackage.MDEVICE__NAME: return ModelPackage.MBRICK_DC__NAME; case ModelPackage.MDEVICE__BRICKD: return ModelPackage.MBRICK_DC__BRICKD; default: return -1; } } if (baseClass == MoveActor.class) { switch (baseFeatureID) { case ModelPackage.MOVE_ACTOR__DIRECTION: return ModelPackage.MBRICK_DC__DIRECTION; default: return -1; } } if (baseClass == MTFConfigConsumer.class) { switch (baseFeatureID) { case ModelPackage.MTF_CONFIG_CONSUMER__TF_CONFIG: return ModelPackage.MBRICK_DC__TF_CONFIG; default: return -1; } } if (baseClass == DimmableActor.class) { switch (baseFeatureID) { case ModelPackage.DIMMABLE_ACTOR__MIN_VALUE: return ModelPackage.MBRICK_DC__MIN_VALUE; case ModelPackage.DIMMABLE_ACTOR__MAX_VALUE: return ModelPackage.MBRICK_DC__MAX_VALUE; default: return -1; } } if (baseClass == PercentTypeActor.class) { switch (baseFeatureID) { case ModelPackage.PERCENT_TYPE_ACTOR__PERCENT_VALUE: return ModelPackage.MBRICK_DC__PERCENT_VALUE; default: return -1; } } if (baseClass == SetPointActor.class) { switch (baseFeatureID) { default: return -1; } } if (baseClass == CallbackListener.class) { switch (baseFeatureID) { case ModelPackage.CALLBACK_LISTENER__CALLBACK_PERIOD: return ModelPackage.MBRICK_DC__CALLBACK_PERIOD; default: return -1; } } return super.eDerivedStructuralFeatureID(baseFeatureID, baseClass); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public int eDerivedOperationID(int baseOperationID, Class<?> baseClass) { if (baseClass == SwitchSensor.class) { switch (baseOperationID) { case ModelPackage.SWITCH_SENSOR___FETCH_SWITCH_STATE: return ModelPackage.MBRICK_DC___FETCH_SWITCH_STATE; default: return -1; } } if (baseClass == ProgrammableSwitchActor.class) { switch (baseOperationID) { case ModelPackage.PROGRAMMABLE_SWITCH_ACTOR___TURN_SWITCH__ONOFFVALUE_DEVICEOPTIONS: return ModelPackage.MBRICK_DC___TURN_SWITCH__ONOFFVALUE_DEVICEOPTIONS; default: return -1; } } if (baseClass == MBaseDevice.class) { switch (baseOperationID) { case ModelPackage.MBASE_DEVICE___INIT: return ModelPackage.MBRICK_DC___INIT; case ModelPackage.MBASE_DEVICE___ENABLE: return ModelPackage.MBRICK_DC___ENABLE; case ModelPackage.MBASE_DEVICE___DISABLE: return ModelPackage.MBRICK_DC___DISABLE; default: return -1; } } if (baseClass == MDevice.class) { switch (baseOperationID) { default: return -1; } } if (baseClass == MoveActor.class) { switch (baseOperationID) { case ModelPackage.MOVE_ACTOR___MOVE__UPDOWNTYPE_DEVICEOPTIONS: return ModelPackage.MBRICK_DC___MOVE__UPDOWNTYPE_DEVICEOPTIONS; case ModelPackage.MOVE_ACTOR___STOP: return ModelPackage.MBRICK_DC___STOP; case ModelPackage.MOVE_ACTOR___MOVEON__DEVICEOPTIONS: return ModelPackage.MBRICK_DC___MOVEON__DEVICEOPTIONS; default: return -1; } } if (baseClass == MTFConfigConsumer.class) { switch (baseOperationID) { default: return -1; } } if (baseClass == DimmableActor.class) { switch (baseOperationID) { case ModelPackage.DIMMABLE_ACTOR___DIMM__INCREASEDECREASETYPE_DEVICEOPTIONS: return ModelPackage.MBRICK_DC___DIMM__INCREASEDECREASETYPE_DEVICEOPTIONS; default: return -1; } } if (baseClass == PercentTypeActor.class) { switch (baseOperationID) { case ModelPackage.PERCENT_TYPE_ACTOR___SET_VALUE__PERCENTTYPE_DEVICEOPTIONS: return ModelPackage.MBRICK_DC___SET_VALUE__PERCENTTYPE_DEVICEOPTIONS; default: return -1; } } if (baseClass == SetPointActor.class) { switch (baseOperationID) { case ModelPackage.SET_POINT_ACTOR___SET_VALUE__BIGDECIMAL_DEVICEOPTIONS: return ModelPackage.MBRICK_DC___SET_VALUE__BIGDECIMAL_DEVICEOPTIONS; default: return -1; } } if (baseClass == CallbackListener.class) { switch (baseOperationID) { default: return -1; } } return super.eDerivedOperationID(baseOperationID, baseClass); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public Object eInvoke(int operationID, EList<?> arguments) throws InvocationTargetException { switch (operationID) { case ModelPackage.MBRICK_DC___INIT: init(); return null; case ModelPackage.MBRICK_DC___SET_SPEED__SHORT_INT_STRING: return setSpeed((Short) arguments.get(0), (Integer) arguments.get(1), (String) arguments.get(2)); case ModelPackage.MBRICK_DC___SET_VALUE__BIGDECIMAL_DEVICEOPTIONS: setValue((BigDecimal) arguments.get(0), (DeviceOptions) arguments.get(1)); return null; case ModelPackage.MBRICK_DC___SET_VALUE__PERCENTTYPE_DEVICEOPTIONS: setValue((PercentType) arguments.get(0), (DeviceOptions) arguments.get(1)); return null; case ModelPackage.MBRICK_DC___DIMM__INCREASEDECREASETYPE_DEVICEOPTIONS: dimm((IncreaseDecreaseType) arguments.get(0), (DeviceOptions) arguments.get(1)); return null; case ModelPackage.MBRICK_DC___MOVE__UPDOWNTYPE_DEVICEOPTIONS: move((UpDownType) arguments.get(0), (DeviceOptions) arguments.get(1)); return null; case ModelPackage.MBRICK_DC___STOP: stop(); return null; case ModelPackage.MBRICK_DC___MOVEON__DEVICEOPTIONS: moveon((DeviceOptions) arguments.get(0)); return null; case ModelPackage.MBRICK_DC___ENABLE: enable(); return null; case ModelPackage.MBRICK_DC___DISABLE: disable(); return null; case ModelPackage.MBRICK_DC___TURN_SWITCH__ONOFFVALUE_DEVICEOPTIONS: turnSwitch((OnOffValue) arguments.get(0), (DeviceOptions) arguments.get(1)); return null; case ModelPackage.MBRICK_DC___FETCH_SWITCH_STATE: fetchSwitchState(); return null; case ModelPackage.MBRICK_DC___FETCH_SENSOR_VALUE: fetchSensorValue(); return null; } return super.eInvoke(operationID, arguments); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public String toString() { if (eIsProxy()) { return super.toString(); } StringBuffer result = new StringBuffer(super.toString()); result.append(" (sensorValue: "); result.append(sensorValue); result.append(", switchState: "); result.append(switchState); result.append(", logger: "); result.append(logger); result.append(", uid: "); result.append(uid); result.append(", poll: "); result.append(poll); result.append(", enabledA: "); result.append(enabledA); result.append(", tinkerforgeDevice: "); result.append(tinkerforgeDevice); result.append(", ipConnection: "); result.append(ipConnection); result.append(", connectedUid: "); result.append(connectedUid); result.append(", position: "); result.append(position); result.append(", deviceIdentifier: "); result.append(deviceIdentifier); result.append(", name: "); result.append(name); result.append(", direction: "); result.append(direction); result.append(", minValue: "); result.append(minValue); result.append(", maxValue: "); result.append(maxValue); result.append(", percentValue: "); result.append(percentValue); result.append(", callbackPeriod: "); result.append(callbackPeriod); result.append(", deviceType: "); result.append(deviceType); result.append(", threshold: "); result.append(threshold); result.append(", maxVelocity: "); result.append(maxVelocity); result.append(", minVelocity: "); result.append(minVelocity); result.append(", velocity: "); result.append(velocity); result.append(", targetvelocity: "); result.append(targetvelocity); result.append(", currentVelocity: "); result.append(currentVelocity); result.append(", acceleration: "); result.append(acceleration); result.append(", pwmFrequency: "); result.append(pwmFrequency); result.append(", driveMode: "); result.append(driveMode); result.append(')'); return result.toString(); } } // MBrickDCImpl
epl-1.0
armenrz/adempiere
base/src/org/adempiere/exceptions/BPartnerNoAddressException.java
1621
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 2009 SC ARHIPAC SERVICE SRL. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * *****************************************************************************/ package org.adempiere.exceptions; import org.compiere.model.I_C_BPartner; /** * Thrown when an location/address is required for a BPartner but not found. * @author Teo Sarca, www.arhipac.ro */ public class BPartnerNoAddressException extends BPartnerException { /** * */ private static final long serialVersionUID = -1892858395845764918L; public static final String AD_Message = "BPartnerNoAddress"; /** * @param message * @param bp */ public BPartnerNoAddressException(I_C_BPartner bp) { super(AD_Message, bp); } }
gpl-2.0
ibmsoe/pig
test/org/apache/pig/test/TestConversions.java
18733
/* * 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.pig.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.Random; import org.apache.pig.ResourceSchema; import org.apache.pig.ResourceSchema.ResourceFieldSchema; import org.apache.pig.builtin.PigStorage; import org.apache.pig.builtin.Utf8StorageConverter; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.pig.impl.util.Utils; import org.apache.pig.parser.ParserException; import org.apache.pig.test.utils.GenRandomData; import org.apache.pig.test.utils.TestHelper; import org.joda.time.DateTime; import org.junit.Test; /** * Test class to test conversions from bytes to types * and vice versa * */ public class TestConversions { PigStorage ps = new PigStorage(); Random r = new Random(42L); final int MAX = 10; @Test public void testBytesToBoolean() throws IOException { // valid booleans String[] a = { "true", "True", "TRUE", "false", "False", "FALSE" }; Boolean[] b = { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE }; for (int i = 0; i < b.length; ++i) { byte[] bytes = a[i].getBytes(); assertEquals(b[i], ps.getLoadCaster().bytesToBoolean(bytes)); } // invalid booleans // the string that is neither "true" nor "false" cannot be converted to a boolean value a = new String[] { "neither true nor false" }; for (String s : a) { byte[] bytes = s.getBytes(); Boolean bool = ps.getLoadCaster().bytesToBoolean(bytes); assertNull(bool); } } @Test public void testBytesToInteger() throws IOException { // valid ints String[] a = {"1234 ", " 4321", " 12345 ", "1", "-2345", "1234567", "1.1", "-23.45", ""}; Integer[] ia = {1234, 4321, 12345, 1, -2345, 1234567, 1, -23}; for (int i = 0; i < ia.length; i++) { byte[] b = a[i].getBytes(); assertEquals(ia[i], ps.getLoadCaster().bytesToInteger(b)); } // invalid ints a = new String[]{"1234567890123456", "This is an int", "", " "}; for (String s : a) { byte[] b = s.getBytes(); Integer i = ps.getLoadCaster().bytesToInteger(b); assertNull(i); } } @Test public void testBytesToFloat() throws IOException { // valid floats String[] a = {"1", "-2.345", "12.12334567", "1.02e-2",".23344", "23.1234567897", "12312.33", "002312.33", "1.02e-2", ""}; Float[] f = {1f, -2.345f, 12.12334567f, 1.02e-2f,.23344f, 23.1234567f, // 23.1234567f is a truncation case 12312.33f, 2312.33f, 1.02e-2f }; for (int j = 0; j < f.length; j++) { byte[] b = a[j].getBytes(); assertEquals(f[j], ps.getLoadCaster().bytesToFloat(b)); } // invalid floats a = new String[]{"1a.1", "23.1234567a890123456", "This is a float", "", " "}; for (String s : a) { byte[] b = s.getBytes(); Float fl = ps.getLoadCaster().bytesToFloat(b); assertNull(fl); } } @Test public void testBytesToDouble() throws IOException { // valid doubles String[] a = {"1", "-2.345", "12.12334567890123456", "1.02e12","-.23344", ""}; Double[] d = {1.0, -2.345, 12.12334567890123456, 1.02e12, -.23344}; for (int j = 0; j < d.length; j++) { byte[] b = a[j].getBytes(); assertEquals(d[j], ps.getLoadCaster().bytesToDouble(b)); } // invalid doubles a = new String[]{"-0x1.1", "-23a.45", "This is a double", "", " "}; for (String s : a) { byte[] b = s.getBytes(); Double dl = ps.getLoadCaster().bytesToDouble(b); assertNull(dl); } } @Test public void testBytesToLong() throws IOException { // valid Longs String[] a = {"1703598819951657279 ", " 999888123L ", " 1234 ", " 1234", "1234 ", "1", "-2345", "123456789012345678", "1.1", "-23.45", "21345345", "3422342", ""}; Long[] la = {1703598819951657279L, 999888123L, 1234L, 1234L, 1234L, 1L, -2345L, 123456789012345678L, 1L, -23L, 21345345L, 3422342L}; for (int i = 0; i < la.length; i++) { byte[] b = a[i].getBytes(); assertEquals(la[i], ps.getLoadCaster().bytesToLong(b)); } // invalid longs a = new String[]{"This is a long", "1.0e1000", "", " "}; for (String s : a) { byte[] b = s.getBytes(); Long l = ps.getLoadCaster().bytesToLong(b); assertNull(l); } } @Test public void testBytesToChar() throws IOException { // valid Strings String[] a = {"1", "-2345", "text", "hello\nworld", ""}; for (String s : a) { byte[] b = s.getBytes(); assertEquals(s, ps.getLoadCaster().bytesToCharArray(b)); } } @Test public void testBytesToTuple() throws IOException { for (int i = 0; i < MAX; i++) { Tuple t = GenRandomData.genRandSmallBagTextTuple(r, 1, 100); ResourceFieldSchema fs = GenRandomData.getSmallBagTextTupleFieldSchema(); Tuple convertedTuple = ps.getLoadCaster().bytesToTuple(t.toString().getBytes(), fs); assertEquals(t, convertedTuple); } } @Test public void testBytesToBag() throws IOException { ResourceFieldSchema fs = GenRandomData.getFullTupTextDataBagFieldSchema(); for (int i = 0; i < MAX; i++) { DataBag b = GenRandomData.genRandFullTupTextDataBag(r,5,100); DataBag convertedBag = ps.getLoadCaster().bytesToBag(b.toString().getBytes(), fs); assertTrue(b.equals(convertedBag)); } } @Test public void testBytesToMap() throws IOException { ResourceFieldSchema fs = GenRandomData.getRandMapFieldSchema(); for (int i = 0; i < MAX; i++) { Map<String, Object> m = GenRandomData.genRandMap(r,5); String expectedMapString = DataType.mapToString(m); Map<String, Object> convertedMap = ps.getLoadCaster().bytesToMap(expectedMapString.getBytes(), fs); assertTrue(TestHelper.mapEquals(m, convertedMap)); } } @Test public void testBooleanToBytes() throws IOException { assertTrue(DataType.equalByteArrays(Boolean.TRUE.toString().getBytes(), ((Utf8StorageConverter)ps.getLoadCaster()).toBytes(Boolean.TRUE))); assertTrue(DataType.equalByteArrays(Boolean.FALSE.toString().getBytes(), ((Utf8StorageConverter)ps.getLoadCaster()).toBytes(Boolean.FALSE))); } @Test public void testIntegerToBytes() throws IOException { Integer i = r.nextInt(); assertTrue(DataType.equalByteArrays(i.toString().getBytes(), ((Utf8StorageConverter)ps.getLoadCaster()).toBytes(i))); } @Test public void testLongToBytes() throws IOException { Long l = r.nextLong(); assertTrue(DataType.equalByteArrays(l.toString().getBytes(), ((Utf8StorageConverter)ps.getLoadCaster()).toBytes(l))); } @Test public void testFloatToBytes() throws IOException { Float f = r.nextFloat(); assertTrue(DataType.equalByteArrays(f.toString().getBytes(), ((Utf8StorageConverter)ps.getLoadCaster()).toBytes(f))); } @Test public void testDoubleToBytes() throws IOException { Double d = r.nextDouble(); assertTrue(DataType.equalByteArrays(d.toString().getBytes(), ((Utf8StorageConverter)ps.getLoadCaster()).toBytes(d))); } @Test public void testDateTimeToBytes() throws IOException { DateTime dt = new DateTime(r.nextLong()); assertTrue(DataType.equalByteArrays(dt.toString().getBytes(), ((Utf8StorageConverter)ps.getLoadCaster()).toBytes(dt))); } @Test public void testCharArrayToBytes() throws IOException { String s = GenRandomData.genRandString(r); assertTrue(s.equals(new String(((Utf8StorageConverter)ps.getLoadCaster()).toBytes(s)))); } @Test public void testTupleToBytes() throws IOException { Tuple t = GenRandomData.genRandSmallBagTextTuple(r, 1, 100); assertTrue(DataType.equalByteArrays(t.toString().getBytes(), ((Utf8StorageConverter)ps.getLoadCaster()).toBytes(t))); } @Test public void testBagToBytes() throws IOException { DataBag b = GenRandomData.genRandFullTupTextDataBag(r,5,100); assertTrue(DataType.equalByteArrays(b.toString().getBytes(), ((Utf8StorageConverter)ps.getLoadCaster()).toBytes(b))); } @Test public void testMapToBytes() throws IOException { Map<String, Object> m = GenRandomData.genRandMap(r,5); assertTrue(DataType.equalByteArrays(DataType.mapToString(m).getBytes(), ((Utf8StorageConverter)ps.getLoadCaster()).toBytes(m))); } @Test public void testBytesToBagWithConversion() throws IOException { DataBag b = GenRandomData.genFloatDataBag(r,5,100); ResourceFieldSchema fs = GenRandomData.getFloatDataBagFieldSchema(5); DataBag convertedBag = ps.getLoadCaster().bytesToBag(b.toString().getBytes(), fs); Iterator<Tuple> iter1 = b.iterator(); Iterator<Tuple> iter2 = convertedBag.iterator(); for (int i=0;i<100;i++) { Tuple t1 = (Tuple)iter1.next(); assertTrue(iter2.hasNext()); Tuple t2 = (Tuple)iter2.next(); for (int j=0;j<5;j++) { assertTrue(t2.get(j) instanceof Integer); Integer expectedValue = ((Float)t1.get(j)).intValue(); assertEquals(expectedValue, t2.get(j)); } } } @Test public void testBytesToTupleWithConversion() throws IOException { for (int i=0;i<100;i++) { Tuple t = GenRandomData.genMixedTupleToConvert(r); ResourceFieldSchema fs = GenRandomData.getMixedTupleToConvertFieldSchema(); Tuple convertedTuple = ps.getLoadCaster().bytesToTuple(t.toString().getBytes(), fs); assertTrue(convertedTuple.get(0) instanceof String); assertEquals(convertedTuple.get(0), ((Integer)t.get(0)).toString()); assertTrue(convertedTuple.get(1) instanceof Long); Integer origValue1 = (Integer)t.get(1); assertEquals(convertedTuple.get(1), Long.valueOf(origValue1.longValue())); assertNull(convertedTuple.get(2)); assertTrue(convertedTuple.get(3) instanceof Double); Float origValue3 = (Float)t.get(3); assertEquals(((Double)convertedTuple.get(3)).doubleValue(), origValue3.doubleValue(), 0.01); assertTrue(convertedTuple.get(4) instanceof Float); Double origValue4 = (Double)t.get(4); assertEquals((Float)convertedTuple.get(4), origValue4.floatValue(), 0.01); assertTrue(convertedTuple.get(5) instanceof String); assertEquals(convertedTuple.get(5), t.get(5)); assertNull(convertedTuple.get(6)); assertNull(convertedTuple.get(7)); assertNull(convertedTuple.get(8)); assertTrue(convertedTuple.get(9) instanceof Boolean); String origValue9 = (String)t.get(9); assertEquals(Boolean.valueOf(origValue9), convertedTuple.get(9)); } } @Test public void testBytesToComplexTypeMisc() throws IOException, ParserException { String s = "(a,b"; Schema schema = Utils.getSchemaFromString("t:tuple(a:chararray, b:chararray)"); ResourceFieldSchema rfs = new ResourceSchema(schema).getFields()[0]; Tuple t = ps.getLoadCaster().bytesToTuple(s.getBytes(), rfs); assertNull(t); s = "{(a,b}"; schema = Utils.getSchemaFromString("b:bag{t:tuple(a:chararray, b:chararray)}"); rfs = new ResourceSchema(schema).getFields()[0]; DataBag b = ps.getLoadCaster().bytesToBag(s.getBytes(), rfs); assertNull(b); s = "{(a,b)"; schema = Utils.getSchemaFromString("b:bag{t:tuple(a:chararray, b:chararray)}"); rfs = new ResourceSchema(schema).getFields()[0]; b = ps.getLoadCaster().bytesToBag(s.getBytes(), rfs); assertNull(b); s = "[ab]"; schema = Utils.getSchemaFromString("m:map[chararray]"); rfs = new ResourceSchema(schema).getFields()[0]; Map<String, Object> m = ps.getLoadCaster().bytesToMap(s.getBytes(), rfs); assertNull(m); s = "[a#b"; m = ps.getLoadCaster().bytesToMap(s.getBytes(), rfs); assertNull(m); s = "[a#]"; m = ps.getLoadCaster().bytesToMap(s.getBytes(), rfs); Map.Entry<String, Object> entry = m.entrySet().iterator().next(); assertEquals("a", entry.getKey()); assertNull(entry.getValue()); s = "[#]"; m = ps.getLoadCaster().bytesToMap(s.getBytes(), rfs); assertNull(m); s = "[a#}"; m = ps.getLoadCaster().bytesToMap(s.getBytes(), rfs); assertNull(m); s = "[a#)"; m = ps.getLoadCaster().bytesToMap(s.getBytes(), rfs); assertNull(m); s = "[]"; m = ps.getLoadCaster().bytesToMap(s.getBytes(), rfs); assertTrue(m.isEmpty()); s = "(a,b)"; schema = Utils.getSchemaFromString("t:tuple()"); rfs = new ResourceSchema(schema).getFields()[0]; t = ps.getLoadCaster().bytesToTuple(s.getBytes(), rfs); assertEquals(2, t.size()); assertTrue(t.get(0) instanceof DataByteArray); assertEquals("a", t.get(0).toString()); assertTrue(t.get(1) instanceof DataByteArray); assertEquals("b", t.get(1).toString()); s = "[a#(1,2,3)]"; schema = Utils.getSchemaFromString("m:map[]"); rfs = new ResourceSchema(schema).getFields()[0]; m = ps.getLoadCaster().bytesToMap(s.getBytes(), rfs); entry = m.entrySet().iterator().next(); assertEquals("a", entry.getKey()); assertTrue(entry.getValue() instanceof DataByteArray); assertEquals("(1,2,3)", entry.getValue().toString()); s = "(a,b,(123,456,{(1,2,3)}))"; schema = Utils.getSchemaFromString("t:tuple()"); rfs = new ResourceSchema(schema).getFields()[0]; t = ps.getLoadCaster().bytesToTuple(s.getBytes(), rfs); assertTrue(t.size()==3); assertTrue(t.get(0) instanceof DataByteArray); assertEquals("a", t.get(0).toString()); assertTrue(t.get(1) instanceof DataByteArray); assertEquals("b", t.get(1).toString()); assertTrue(t.get(2) instanceof DataByteArray); assertEquals("(123,456,{(1,2,3)})", t.get(2).toString()); s = "(a,b,(123,456,{(1,2,3}))"; schema = Utils.getSchemaFromString("t:tuple()"); rfs = new ResourceSchema(schema).getFields()[0]; t = ps.getLoadCaster().bytesToTuple(s.getBytes(), rfs); assertNull(t); } @Test public void testOverflow() throws IOException, ParserException { Schema schema; ResourceFieldSchema rfs; Tuple tuple, convertedTuple; tuple = TupleFactory.getInstance().newTuple(1); schema = Utils.getSchemaFromString("t:tuple(a:int)"); rfs = new ResourceSchema(schema).getFields()[0]; // long bigger than Integer.MAX_VALUE tuple.set(0, Integer.valueOf(Integer.MAX_VALUE).longValue() + 1); convertedTuple = ps.getLoadCaster().bytesToTuple(tuple.toString().getBytes(), rfs); assertNull("Invalid cast to int: " + tuple.get(0) + " -> " + convertedTuple.get(0), convertedTuple.get(0)); // long smaller than Integer.MIN_VALUE tuple.set(0, Integer.valueOf(Integer.MIN_VALUE).longValue() - 1); convertedTuple = ps.getLoadCaster().bytesToTuple(tuple.toString().getBytes(), rfs); assertNull("Invalid cast to int: " + tuple.get(0) + " -> " + convertedTuple.get(0), convertedTuple.get(0)); // double bigger than Integer.MAX_VALUE tuple.set(0, Integer.valueOf(Integer.MAX_VALUE).doubleValue() + 1); convertedTuple = ps.getLoadCaster().bytesToTuple(tuple.toString().getBytes(), rfs); assertNull("Invalid cast to int: " + tuple.get(0) + " -> " + convertedTuple.get(0), convertedTuple.get(0)); // double smaller than Integer.MIN_VALUE tuple.set(0, Integer.valueOf(Integer.MIN_VALUE).doubleValue() - 1); convertedTuple = ps.getLoadCaster().bytesToTuple(tuple.toString().getBytes(), rfs); assertNull("Invalid cast to int: " + tuple.get(0) + " -> " + convertedTuple.get(0), convertedTuple.get(0)); schema = Utils.getSchemaFromString("t:tuple(a:long)"); rfs = new ResourceSchema(schema).getFields()[0]; // double bigger than Long.MAX_VALUE tuple.set(0, Long.valueOf(Long.MAX_VALUE).doubleValue() + 10000); convertedTuple = ps.getLoadCaster().bytesToTuple(tuple.toString().getBytes(), rfs); assertNull("Invalid cast to long: " + tuple.get(0) + " -> " + convertedTuple.get(0), convertedTuple.get(0)); // double smaller than Long.MIN_VALUE tuple.set(0, Long.valueOf(Long.MIN_VALUE).doubleValue() - 10000); convertedTuple = ps.getLoadCaster().bytesToTuple(tuple.toString().getBytes(), rfs); assertNull("Invalid cast to long: " + tuple.get(0) + " -> " + convertedTuple.get(0), convertedTuple.get(0)); } }
apache-2.0
rcpoison/guava
guava-tests/test/com/google/common/collect/HashBiMapTest.java
7823
/* * 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.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; import com.google.common.collect.testing.google.BiMapTestSuiteBuilder; import com.google.common.collect.testing.google.TestStringBiMapGenerator; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Tests for {@link HashBiMap}. * * @author Mike Bostock */ @GwtCompatible(emulated = true) public class HashBiMapTest extends TestCase { public static final class HashBiMapGenerator extends TestStringBiMapGenerator { @Override protected BiMap<String, String> create(Entry<String, String>[] entries) { BiMap<String, String> result = HashBiMap.create(); for (Entry<String, String> entry : entries) { result.put(entry.getKey(), entry.getValue()); } return result; } } @GwtIncompatible("suite") @SuppressUnderAndroid public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(BiMapTestSuiteBuilder.using(new HashBiMapGenerator()) .named("HashBiMap") .withFeatures(CollectionSize.ANY, CollectionFeature.SERIALIZABLE, CollectionFeature.SUPPORTS_ITERATOR_REMOVE, CollectionFeature.KNOWN_ORDER, MapFeature.ALLOWS_NULL_KEYS, MapFeature.ALLOWS_NULL_VALUES, MapFeature.ALLOWS_ANY_NULL_QUERIES, MapFeature.GENERAL_PURPOSE) .createTestSuite()); suite.addTestSuite(HashBiMapTest.class); return suite; } public void testMapConstructor() { /* Test with non-empty Map. */ Map<String, String> map = ImmutableMap.of( "canada", "dollar", "chile", "peso", "switzerland", "franc"); HashBiMap<String, String> bimap = HashBiMap.create(map); assertEquals("dollar", bimap.get("canada")); assertEquals("canada", bimap.inverse().get("dollar")); } private static final int N = 1000; public void testBashIt() throws Exception { BiMap<Integer, Integer> bimap = HashBiMap.create(N); BiMap<Integer, Integer> inverse = bimap.inverse(); for (int i = 0; i < N; i++) { assertNull(bimap.put(2 * i, 2 * i + 1)); } for (int i = 0; i < N; i++) { assertEquals(2 * i + 1, (int) bimap.get(2 * i)); } for (int i = 0; i < N; i++) { assertEquals(2 * i, (int) inverse.get(2 * i + 1)); } for (int i = 0; i < N; i++) { int oldValue = bimap.get(2 * i); assertEquals(2 * i + 1, (int) bimap.put(2 * i, oldValue - 2)); } for (int i = 0; i < N; i++) { assertEquals(2 * i - 1, (int) bimap.get(2 * i)); } for (int i = 0; i < N; i++) { assertEquals(2 * i, (int) inverse.get(2 * i - 1)); } Set<Entry<Integer, Integer>> entries = bimap.entrySet(); for (Entry<Integer, Integer> entry : entries) { entry.setValue(entry.getValue() + 2 * N); } for (int i = 0; i < N; i++) { assertEquals(2 * N + 2 * i - 1, (int) bimap.get(2 * i)); } } public void testBiMapEntrySetIteratorRemove() { BiMap<Integer, String> map = HashBiMap.create(); map.put(1, "one"); Set<Map.Entry<Integer, String>> entries = map.entrySet(); Iterator<Map.Entry<Integer, String>> iterator = entries.iterator(); Map.Entry<Integer, String> entry = iterator.next(); entry.setValue("two"); // changes the iterator's current entry value assertEquals("two", map.get(1)); assertEquals(Integer.valueOf(1), map.inverse().get("two")); iterator.remove(); // removes the updated entry assertTrue(map.isEmpty()); } @GwtIncompatible("insertion order currently not preserved in GWT") public void testInsertionOrder() { BiMap<String, Integer> map = HashBiMap.create(); map.put("foo", 1); map.put("bar", 2); map.put("quux", 3); assertThat(map.entrySet()).containsExactly( Maps.immutableEntry("foo", 1), Maps.immutableEntry("bar", 2), Maps.immutableEntry("quux", 3)).inOrder(); } @GwtIncompatible("insertion order currently not preserved in GWT") public void testInsertionOrderAfterRemoveFirst() { BiMap<String, Integer> map = HashBiMap.create(); map.put("foo", 1); map.put("bar", 2); map.put("quux", 3); map.remove("foo"); assertThat(map.entrySet()).containsExactly( Maps.immutableEntry("bar", 2), Maps.immutableEntry("quux", 3)).inOrder(); } @GwtIncompatible("insertion order currently not preserved in GWT") public void testInsertionOrderAfterRemoveMiddle() { BiMap<String, Integer> map = HashBiMap.create(); map.put("foo", 1); map.put("bar", 2); map.put("quux", 3); map.remove("bar"); assertThat(map.entrySet()).containsExactly( Maps.immutableEntry("foo", 1), Maps.immutableEntry("quux", 3)).inOrder(); } @GwtIncompatible("insertion order currently not preserved in GWT") public void testInsertionOrderAfterRemoveLast() { BiMap<String, Integer> map = HashBiMap.create(); map.put("foo", 1); map.put("bar", 2); map.put("quux", 3); map.remove("quux"); assertThat(map.entrySet()).containsExactly( Maps.immutableEntry("foo", 1), Maps.immutableEntry("bar", 2)).inOrder(); } @GwtIncompatible("insertion order currently not preserved in GWT") public void testInsertionOrderAfterForcePut() { BiMap<String, Integer> map = HashBiMap.create(); map.put("foo", 1); map.put("bar", 2); map.put("quux", 3); map.forcePut("quux", 1); assertThat(map.entrySet()).containsExactly( Maps.immutableEntry("bar", 2), Maps.immutableEntry("quux", 1)).inOrder(); } @GwtIncompatible("insertion order currently not preserved in GWT") public void testInsertionOrderAfterInverseForcePut() { BiMap<String, Integer> map = HashBiMap.create(); map.put("foo", 1); map.put("bar", 2); map.put("quux", 3); map.inverse().forcePut(1, "quux"); assertThat(map.entrySet()).containsExactly( Maps.immutableEntry("bar", 2), Maps.immutableEntry("quux", 1)).inOrder(); } @GwtIncompatible("insertion order currently not preserved in GWT") public void testInverseInsertionOrderAfterInverseForcePut() { BiMap<String, Integer> map = HashBiMap.create(); map.put("foo", 1); map.put("bar", 2); map.put("quux", 3); map.inverse().forcePut(1, "quux"); assertThat(map.inverse().entrySet()).containsExactly( Maps.immutableEntry(2, "bar"), Maps.immutableEntry(1, "quux")).inOrder(); } public void testInverseEntrySetValue() { BiMap<Integer, String> map = HashBiMap.create(); map.put(1, "one"); Entry<String, Integer> inverseEntry = Iterables.getOnlyElement(map.inverse().entrySet()); inverseEntry.setValue(2); assertEquals(Integer.valueOf(2), inverseEntry.getValue()); } }
apache-2.0
prazanna/kite
kite-morphlines/kite-morphlines-solr-core/src/main/java/org/kitesdk/morphline/solr/SanitizeUnknownSolrFieldsBuilder.java
4102
/* * Copyright 2013 Cloudera 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.kitesdk.morphline.solr; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.TreeMap; import org.apache.solr.schema.IndexSchema; import org.kitesdk.morphline.api.Command; import org.kitesdk.morphline.api.CommandBuilder; import org.kitesdk.morphline.api.MorphlineContext; import org.kitesdk.morphline.api.Record; import org.kitesdk.morphline.base.AbstractCommand; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.typesafe.config.Config; /** * Command that sanitizes record fields that are unknown to Solr schema.xml by either deleting them * (renameToPrefix is absent or a zero length string), or by moving them to a field prefixed with * the given renameToPrefix (e.g. renameToPrefix = "ignored_" to use typical dynamic Solr fields). * <p> * Recall that Solr throws an exception on any attempt to load a document that contains a field that * isn't specified in schema.xml. */ public final class SanitizeUnknownSolrFieldsBuilder implements CommandBuilder { @Override public Collection<String> getNames() { return Collections.singletonList("sanitizeUnknownSolrFields"); } @Override public Command build(Config config, Command parent, Command child, MorphlineContext context) { return new SanitizeUnknownSolrFields(this, config, parent, child, context); } /////////////////////////////////////////////////////////////////////////////// // Nested classes: /////////////////////////////////////////////////////////////////////////////// private static final class SanitizeUnknownSolrFields extends AbstractCommand { private final IndexSchema schema; private final String renameToPrefix; public SanitizeUnknownSolrFields(CommandBuilder builder, Config config, Command parent, Command child, MorphlineContext context) { super(builder, config, parent, child, context); Config solrLocatorConfig = getConfigs().getConfig(config, "solrLocator"); SolrLocator locator = new SolrLocator(solrLocatorConfig, context); LOG.debug("solrLocator: {}", locator); this.schema = locator.getIndexSchema(); Preconditions.checkNotNull(schema); LOG.trace("Solr schema: \n{}", Joiner.on("\n").join(new TreeMap(schema.getFields()).values())); String str = getConfigs().getString(config, "renameToPrefix", "").trim(); this.renameToPrefix = str.length() > 0 ? str : null; validateArguments(); } @Override protected boolean doProcess(Record record) { Collection<Map.Entry> entries = new ArrayList<Map.Entry>(record.getFields().asMap().entrySet()); for (Map.Entry<String, Collection<Object>> entry : entries) { String key = entry.getKey(); if (schema.getFieldOrNull(key) == null && !LoadSolrBuilder.LOAD_SOLR_DELETE_BY_ID.equals(key) && !LoadSolrBuilder.LOAD_SOLR_DELETE_BY_QUERY.equals(key) && !LoadSolrBuilder.LOAD_SOLR_CHILD_DOCUMENTS.equals(key)) { LOG.debug("Sanitizing unknown Solr field: {}", key); Collection values = entry.getValue(); if (renameToPrefix != null) { record.getFields().putAll(renameToPrefix + key, values); } values.clear(); // implicitly removes key from record } } // pass record to next command in chain: return super.doProcess(record); } } }
apache-2.0
syl20bnr/jenkins
core/src/main/java/hudson/slaves/CommandLauncher.java
7086
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly * * 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 hudson.slaves; import hudson.EnvVars; import hudson.Util; import hudson.Extension; import hudson.model.Descriptor; import jenkins.model.Jenkins; import hudson.model.TaskListener; import hudson.remoting.Channel; import hudson.util.StreamCopyThread; import hudson.util.FormValidation; import hudson.util.ProcessTree; import java.io.IOException; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; /** * {@link ComputerLauncher} through a remote login mechanism like ssh/rsh. * * @author Stephen Connolly * @author Kohsuke Kawaguchi */ public class CommandLauncher extends ComputerLauncher { /** * Command line to launch the agent, like * "ssh myslave java -jar /path/to/hudson-remoting.jar" */ private final String agentCommand; /** * Optional environment variables to add to the current environment. Can be null. */ private final EnvVars env; @DataBoundConstructor public CommandLauncher(String command) { this(command, null); } public CommandLauncher(String command, EnvVars env) { this.agentCommand = command; this.env = env; } public String getCommand() { return agentCommand; } /** * Gets the formatted current time stamp. */ private static String getTimestamp() { return String.format("[%1$tD %1$tT]", new Date()); } @Override public void launch(SlaveComputer computer, final TaskListener listener) { EnvVars _cookie = null; Process _proc = null; try { listener.getLogger().println(hudson.model.Messages.Slave_Launching(getTimestamp())); if(getCommand().trim().length()==0) { listener.getLogger().println(Messages.CommandLauncher_NoLaunchCommand()); return; } listener.getLogger().println("$ " + getCommand()); ProcessBuilder pb = new ProcessBuilder(Util.tokenize(getCommand())); final EnvVars cookie = _cookie = EnvVars.createCookie(); pb.environment().putAll(cookie); pb.environment().put("WORKSPACE", computer.getNode().getRemoteFS()); //path for local slave log {// system defined variables String rootUrl = Jenkins.getInstance().getRootUrl(); if (rootUrl!=null) { pb.environment().put("HUDSON_URL", rootUrl); // for backward compatibility pb.environment().put("JENKINS_URL", rootUrl); pb.environment().put("SLAVEJAR_URL", rootUrl+"/jnlpJars/slave.jar"); } } if (env != null) { pb.environment().putAll(env); } final Process proc = _proc = pb.start(); // capture error information from stderr. this will terminate itself // when the process is killed. new StreamCopyThread("stderr copier for remote agent on " + computer.getDisplayName(), proc.getErrorStream(), listener.getLogger()).start(); computer.setChannel(proc.getInputStream(), proc.getOutputStream(), listener.getLogger(), new Channel.Listener() { @Override public void onClosed(Channel channel, IOException cause) { try { int exitCode = proc.exitValue(); if (exitCode!=0) { listener.error("Process terminated with exit code "+exitCode); } } catch (IllegalThreadStateException e) { // hasn't terminated yet } try { ProcessTree.get().killAll(proc, cookie); } catch (InterruptedException e) { LOGGER.log(Level.INFO, "interrupted", e); } } }); LOGGER.info("slave agent launched for " + computer.getDisplayName()); } catch (InterruptedException e) { e.printStackTrace(listener.error(Messages.ComputerLauncher_abortedLaunch())); } catch (RuntimeException e) { e.printStackTrace(listener.error(Messages.ComputerLauncher_unexpectedError())); } catch (Error e) { e.printStackTrace(listener.error(Messages.ComputerLauncher_unexpectedError())); } catch (IOException e) { Util.displayIOException(e, listener); String msg = Util.getWin32ErrorMessage(e); if (msg == null) { msg = ""; } else { msg = " : " + msg; } msg = hudson.model.Messages.Slave_UnableToLaunch(computer.getDisplayName(), msg); LOGGER.log(Level.SEVERE, msg, e); e.printStackTrace(listener.error(msg)); if(_proc!=null) try { ProcessTree.get().killAll(_proc, _cookie); } catch (InterruptedException x) { x.printStackTrace(listener.error(Messages.ComputerLauncher_abortedLaunch())); } } } private static final Logger LOGGER = Logger.getLogger(CommandLauncher.class.getName()); @Extension public static class DescriptorImpl extends Descriptor<ComputerLauncher> { public String getDisplayName() { return Messages.CommandLauncher_displayName(); } public FormValidation doCheckCommand(@QueryParameter String value) { if(Util.fixEmptyAndTrim(value)==null) return FormValidation.error(Messages.CommandLauncher_NoLaunchCommand()); else return FormValidation.ok(); } } }
mit
PramodSSImmaneni/apex-malhar
library/src/test/java/com/datatorrent/lib/logs/ApacheLogParseMapOutputOperatorTest.java
4593
/** * 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.datatorrent.lib.logs; import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.datatorrent.lib.testbench.CollectorTestSink; /** * Functional tests for {@link com.datatorrent.lib.logs.ApacheLogParseMapOutputOperator}. */ public class ApacheLogParseMapOutputOperatorTest { private static Logger log = LoggerFactory.getLogger(ApacheLogParseMapOutputOperatorTest.class); /** * Test oper logic emits correct results */ @SuppressWarnings({"rawtypes", "unchecked"}) @Test public void testNodeProcessing() { ApacheLogParseMapOutputOperator oper = new ApacheLogParseMapOutputOperator(); CollectorTestSink sink = new CollectorTestSink(); oper.output.setSink(sink); oper.setRegexGroups(new String[] {null, "ipAddr", null, "userId", "date", "url", "httpCode", "bytes", null, "agent"}); String token = "127.0.0.1 - - [04/Apr/2013:17:17:21 -0700] \"GET /favicon.ico HTTP/1.1\" 404 498 \"-\" \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31\""; oper.setup(null); oper.beginWindow(0); oper.data.process(token); oper.endWindow(); Assert.assertEquals("number emitted tuples", 1, sink.collectedTuples.size()); Map<String, Object> map = (Map<String, Object>)sink.collectedTuples.get(0); log.debug("map {}", map); Assert.assertEquals("Size of map is 7", 7, map.size()); Assert.assertEquals("checking ip", "127.0.0.1", map.get("ipAddr")); Assert.assertEquals("checking userid", "-", map.get("userId")); Assert.assertEquals("checking date", "04/Apr/2013:17:17:21 -0700", map.get("date")); Assert.assertEquals("checking url", "/favicon.ico", map.get("url")); Assert.assertEquals("checking http code", "404", map.get("httpCode")); Assert.assertEquals("checking bytes", "498", map.get("bytes")); Assert.assertEquals("checking agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31", map.get("agent")); } /** * Test oper logic emits correct results */ @SuppressWarnings({"rawtypes", "unchecked"}) @Test public void testUserDefinedPattern() { ApacheLogParseMapOutputOperator oper = new ApacheLogParseMapOutputOperator(); CollectorTestSink sink = new CollectorTestSink(); oper.output.setSink(sink); oper.setRegexGroups(new String[] {null, "ipAddr", null, "userId", "date", "url", "httpCode", "rest"}); String token = "127.0.0.1 - - [04/Apr/2013:17:17:21 -0700] \"GET /favicon.ico HTTP/1.1\" 404 498 \"-\" \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31\""; oper.setLogRegex("^([\\d\\.]+) (\\S+) (\\S+) \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"[A-Z]+ (.+?) HTTP/\\S+\" (\\d{3})(.*)"); oper.setup(null); oper.beginWindow(0); oper.data.process(token); oper.endWindow(); Assert.assertEquals("number emitted tuples", 1, sink.collectedTuples.size()); Map<String, Object> map = (Map<String, Object>)sink.collectedTuples.get(0); log.debug("map {}", map); Assert.assertEquals("Size of map is 6", 6, map.size()); Assert.assertEquals("checking ip", "127.0.0.1", map.get("ipAddr")); Assert.assertEquals("checking userid", "-", map.get("userId")); Assert.assertEquals("checking date", "04/Apr/2013:17:17:21 -0700", map.get("date")); Assert.assertEquals("checking url", "/favicon.ico", map.get("url")); Assert.assertEquals("checking http code", "404", map.get("httpCode")); Assert.assertEquals("checking bytes", "498 \"-\" \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31\"", map.get("rest")); } }
apache-2.0
abhijitiitr/es
src/main/java/org/elasticsearch/action/mlt/MoreLikeThisRequestBuilder.java
8425
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.mlt; import org.elasticsearch.ElasticsearchIllegalArgumentException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.search.Scroll; import org.elasticsearch.search.builder.SearchSourceBuilder; import java.util.Map; /** */ public class MoreLikeThisRequestBuilder extends ActionRequestBuilder<MoreLikeThisRequest, SearchResponse, MoreLikeThisRequestBuilder, Client> { public MoreLikeThisRequestBuilder(Client client) { super(client, new MoreLikeThisRequest()); } public MoreLikeThisRequestBuilder(Client client, String index, String type, String id) { super(client, new MoreLikeThisRequest(index).type(type).id(id)); } /** * The fields of the document to use in order to find documents "like" this one. Defaults to run * against all the document fields. */ public MoreLikeThisRequestBuilder setField(String... fields) { request.fields(fields); return this; } /** * Sets the routing. Required if routing isn't id based. */ public MoreLikeThisRequestBuilder setRouting(String routing) { request.routing(routing); return this; } /** * The percent of the terms to match for each field. Defaults to <tt>0.3f</tt>. */ public MoreLikeThisRequestBuilder setPercentTermsToMatch(float percentTermsToMatch) { request.percentTermsToMatch(percentTermsToMatch); return this; } /** * The frequency below which terms will be ignored in the source doc. Defaults to <tt>2</tt>. */ public MoreLikeThisRequestBuilder setMinTermFreq(int minTermFreq) { request.minTermFreq(minTermFreq); return this; } /** * The maximum number of query terms that will be included in any generated query. Defaults to <tt>25</tt>. */ public MoreLikeThisRequestBuilder maxQueryTerms(int maxQueryTerms) { request.maxQueryTerms(maxQueryTerms); return this; } /** * Any word in this set is considered "uninteresting" and ignored. * <p/> * <p>Even if your Analyzer allows stopwords, you might want to tell the MoreLikeThis code to ignore them, as * for the purposes of document similarity it seems reasonable to assume that "a stop word is never interesting". * <p/> * <p>Defaults to no stop words. */ public MoreLikeThisRequestBuilder setStopWords(String... stopWords) { request.stopWords(stopWords); return this; } /** * The frequency at which words will be ignored which do not occur in at least this * many docs. Defaults to <tt>5</tt>. */ public MoreLikeThisRequestBuilder setMinDocFreq(int minDocFreq) { request.minDocFreq(minDocFreq); return this; } /** * The maximum frequency in which words may still appear. Words that appear * in more than this many docs will be ignored. Defaults to unbounded. */ public MoreLikeThisRequestBuilder setMaxDocFreq(int maxDocFreq) { request.maxDocFreq(maxDocFreq); return this; } /** * The minimum word length below which words will be ignored. Defaults to <tt>0</tt>. */ public MoreLikeThisRequestBuilder setMinWordLen(int minWordLen) { request.minWordLength(minWordLen); return this; } /** * The maximum word length above which words will be ignored. Defaults to unbounded. */ public MoreLikeThisRequestBuilder setMaxWordLen(int maxWordLen) { request().maxWordLength(maxWordLen); return this; } /** * The boost factor to use when boosting terms. Defaults to <tt>1</tt>. */ public MoreLikeThisRequestBuilder setBoostTerms(float boostTerms) { request.boostTerms(boostTerms); return this; } /** * Whether to include the queried document. Defaults to <tt>false</tt>. */ public MoreLikeThisRequestBuilder setInclude(boolean include) { request.include(include); return this; } /** * An optional search source request allowing to control the search request for the * more like this documents. */ public MoreLikeThisRequestBuilder setSearchSource(SearchSourceBuilder sourceBuilder) { request.searchSource(sourceBuilder); return this; } /** * An optional search source request allowing to control the search request for the * more like this documents. */ public MoreLikeThisRequestBuilder setSearchSource(String searchSource) { request.searchSource(searchSource); return this; } /** * An optional search source request allowing to control the search request for the * more like this documents. */ public MoreLikeThisRequestBuilder setSearchSource(Map searchSource) { request.searchSource(searchSource); return this; } /** * An optional search source request allowing to control the search request for the * more like this documents. */ public MoreLikeThisRequestBuilder setSearchSource(XContentBuilder builder) { request.searchSource(builder); return this; } /** * An optional search source request allowing to control the search request for the * more like this documents. */ public MoreLikeThisRequestBuilder setSearchSource(byte[] searchSource) { request.searchSource(searchSource); return this; } /** * The search type of the mlt search query. */ public MoreLikeThisRequestBuilder setSearchType(SearchType searchType) { request.searchType(searchType); return this; } /** * The search type of the mlt search query. */ public MoreLikeThisRequestBuilder setSearchType(String searchType) throws ElasticsearchIllegalArgumentException { request.searchType(searchType); return this; } /** * The indices the resulting mlt query will run against. If not set, will run * against the index the document was fetched from. */ public MoreLikeThisRequestBuilder setSearchIndices(String... searchIndices) { request.searchIndices(searchIndices); return this; } /** * The types the resulting mlt query will run against. If not set, will run * against the type of the document fetched. */ public MoreLikeThisRequestBuilder setSearchTypes(String... searchTypes) { request.searchTypes(searchTypes); return this; } /** * An optional search scroll request to be able to continue and scroll the search * operation. */ public MoreLikeThisRequestBuilder setSearchScroll(Scroll searchScroll) { request.searchScroll(searchScroll); return this; } /** * The number of documents to return, defaults to 10. */ public MoreLikeThisRequestBuilder setSearchSize(int size) { request.searchSize(size); return this; } /** * From which search result set to return. */ public MoreLikeThisRequestBuilder setSearchFrom(int from) { request.searchFrom(from); return this; } @Override protected void doExecute(ActionListener<SearchResponse> listener) { client.moreLikeThis(request, listener); } }
apache-2.0
sriksun/falcon
addons/hivedr/src/main/java/org/apache/falcon/hive/DefaultPartitioner.java
14693
/** * 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.falcon.hive; import com.google.common.collect.Lists; import org.apache.commons.lang3.StringUtils; import org.apache.falcon.hive.util.DRStatusStore; import org.apache.falcon.hive.util.EventSourcerUtils; import org.apache.falcon.hive.util.HiveDRUtils; import org.apache.falcon.hive.util.ReplicationStatus; import org.apache.hive.hcatalog.api.repl.Command; import org.apache.hive.hcatalog.api.repl.ReplicationTask; import org.apache.hive.hcatalog.api.repl.StagingDirectoryProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.OutputStream; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import static org.apache.hive.hcatalog.api.HCatNotificationEvent.Scope; /** * Partitioner for partitioning events for a given DB. */ public class DefaultPartitioner implements Partitioner { private static final Logger LOG = LoggerFactory.getLogger(DefaultPartitioner.class); private EventFilter eventFilter; private final DRStatusStore drStore; private final EventSourcerUtils eventSourcerUtils; private enum CMDTYPE { SRC_CMD_TYPE, TGT_CMD_TYPE } public DefaultPartitioner(DRStatusStore drStore, EventSourcerUtils eventSourcerUtils) { this.drStore = drStore; this.eventSourcerUtils = eventSourcerUtils; } private class EventFilter { private final Map<String, Long> eventFilterMap; public EventFilter(String sourceMetastoreUri, String targetMetastoreUri, String jobName, String database) throws Exception { eventFilterMap = new HashMap<>(); Iterator<ReplicationStatus> replStatusIter = drStore.getTableReplicationStatusesInDb(sourceMetastoreUri, targetMetastoreUri, jobName, database); while (replStatusIter.hasNext()) { ReplicationStatus replStatus = replStatusIter.next(); eventFilterMap.put(replStatus.getTable(), replStatus.getEventId()); } } } public ReplicationEventMetadata partition(final HiveDROptions drOptions, final String databaseName, final Iterator<ReplicationTask> taskIter) throws Exception { long lastCounter = 0; String dbName = databaseName.toLowerCase(); // init filtering before partitioning this.eventFilter = new EventFilter(drOptions.getSourceMetastoreUri(), drOptions.getTargetMetastoreUri(), drOptions.getJobName(), dbName); String srcStagingDirProvider = drOptions.getSourceStagingPath(); String dstStagingDirProvider = drOptions.getTargetStagingPath(); List<Command> dbSrcEventList = Lists.newArrayList(); List<Command> dbTgtEventList = Lists.newArrayList(); Map<String, List<String>> eventMetaFileMap = new HashMap<>(); Map<String, List<OutputStream>> outputStreamMap = new HashMap<>(); String srcFilename = null; String tgtFilename = null; OutputStream srcOutputStream = null; OutputStream tgtOutputStream = null; while (taskIter.hasNext()) { ReplicationTask task = taskIter.next(); if (task.needsStagingDirs()) { task.withSrcStagingDirProvider(new StagingDirectoryProvider.TrivialImpl(srcStagingDirProvider, HiveDRUtils.SEPARATOR)); task.withDstStagingDirProvider(new StagingDirectoryProvider.TrivialImpl(dstStagingDirProvider, HiveDRUtils.SEPARATOR)); } if (task.isActionable()) { Scope eventScope = task.getEvent().getEventScope(); String tableName = task.getEvent().getTableName(); if (StringUtils.isNotEmpty(tableName)) { tableName = tableName.toLowerCase(); } boolean firstEventForTable = (eventScope == Scope.TABLE) && isFirstEventForTable(eventMetaFileMap, tableName); if (firstEventForTable && (task.getSrcWhCommands() != null || task.getDstWhCommands() != null)) { ++lastCounter; } Iterable<? extends org.apache.hive.hcatalog.api.repl.Command> srcCmds = task.getSrcWhCommands(); if (srcCmds != null) { if (eventScope == Scope.DB) { processDBScopeCommands(dbSrcEventList, srcCmds, outputStreamMap, CMDTYPE.SRC_CMD_TYPE); } else if (eventScope == Scope.TABLE) { OutputStream srcOut; if (firstEventForTable) { srcFilename = eventSourcerUtils.getSrcFileName(String.valueOf(lastCounter)).toString(); srcOutputStream = eventSourcerUtils.getFileOutputStream(srcFilename); srcOut = srcOutputStream; } else { srcOut = outputStreamMap.get(tableName).get(0); } processTableScopeCommands(srcCmds, eventMetaFileMap, tableName, dbSrcEventList, srcOut); } else { throw new Exception("Event scope is not DB or Table"); } } Iterable<? extends org.apache.hive.hcatalog.api.repl.Command> dstCmds = task.getDstWhCommands(); if (dstCmds != null) { if (eventScope == Scope.DB) { processDBScopeCommands(dbTgtEventList, dstCmds, outputStreamMap, CMDTYPE.TGT_CMD_TYPE); } else if (eventScope == Scope.TABLE) { OutputStream tgtOut; if (firstEventForTable) { tgtFilename = eventSourcerUtils.getTargetFileName(String.valueOf(lastCounter)).toString(); tgtOutputStream = eventSourcerUtils.getFileOutputStream(tgtFilename); tgtOut = tgtOutputStream; } else { tgtOut = outputStreamMap.get(tableName).get(1); } processTableScopeCommands(dstCmds, eventMetaFileMap, tableName, dbTgtEventList, tgtOut); } else { throw new Exception("Event scope is not DB or Table"); } } // If first table event, update the state data at the end if (firstEventForTable) { updateStateDataIfFirstTableEvent(tableName, srcFilename, tgtFilename, srcOutputStream, tgtOutputStream, eventMetaFileMap, outputStreamMap); } } else { LOG.error("Task is not actionable with event Id : {}", task.getEvent().getEventId()); } } ReplicationEventMetadata eventMetadata = new ReplicationEventMetadata(); // If there were only DB events for this run if (eventMetaFileMap.isEmpty()) { ++lastCounter; if (!dbSrcEventList.isEmpty()) { srcFilename = eventSourcerUtils.getSrcFileName(String.valueOf(lastCounter)).toString(); srcOutputStream = eventSourcerUtils.getFileOutputStream(srcFilename); eventSourcerUtils.persistReplicationEvents(srcOutputStream, dbSrcEventList); } if (!dbTgtEventList.isEmpty()) { tgtFilename = eventSourcerUtils.getTargetFileName(String.valueOf(lastCounter)).toString(); tgtOutputStream = eventSourcerUtils.getFileOutputStream(tgtFilename); eventSourcerUtils.persistReplicationEvents(tgtOutputStream, dbTgtEventList); } // Close the stream eventSourcerUtils.closeOutputStream(srcOutputStream); eventSourcerUtils.closeOutputStream(tgtOutputStream); EventSourcerUtils.updateEventMetadata(eventMetadata, dbName, null, srcFilename, tgtFilename); } else { closeAllStreams(outputStreamMap); for (Map.Entry<String, List<String>> entry : eventMetaFileMap.entrySet()) { String srcFile = null; String tgtFile = null; if (entry.getValue() != null) { srcFile = entry.getValue().get(0); tgtFile = entry.getValue().get(1); } EventSourcerUtils.updateEventMetadata(eventMetadata, dbName, entry.getKey(), srcFile, tgtFile); } } return eventMetadata; } private void updateStateDataIfFirstTableEvent(final String tableName, final String srcFilename, final String tgtFilename, final OutputStream srcOutputStream, final OutputStream tgtOutputStream, Map<String, List<String>> eventMetaFileMap, Map<String, List<OutputStream>> outputStreamMap) { List<String> files = Arrays.asList(srcFilename, tgtFilename); eventMetaFileMap.put(tableName, files); List<OutputStream> streams = Arrays.asList(srcOutputStream, tgtOutputStream); outputStreamMap.put(tableName, streams); } private void closeAllStreams(final Map<String, List<OutputStream>> outputStreamMap) throws Exception { if (outputStreamMap == null || outputStreamMap.isEmpty()) { return; } for (Map.Entry<String, List<OutputStream>> entry : outputStreamMap.entrySet()) { List<OutputStream> streams = entry.getValue(); for (OutputStream out : streams) { if (out != null) { eventSourcerUtils.closeOutputStream(out); } } } } private void processDBScopeCommands(final List<Command> dbEventList, final Iterable<? extends org.apache.hive .hcatalog.api.repl.Command> cmds, final Map<String, List<OutputStream>> outputStreamMap, CMDTYPE cmdType ) throws Exception { addCmdsToDBEventList(dbEventList, cmds); /* add DB event to all tables */ if (!outputStreamMap.isEmpty()) { addDbEventToAllTablesEventFile(cmds, outputStreamMap, cmdType); } } private void processTableScopeCommands(final Iterable<? extends org.apache.hive.hcatalog.api.repl.Command> cmds, final Map<String, List<String>> eventMetaFileMap, String tableName, final List<Command> dbEventList, final OutputStream out) throws Exception { // First event for this table // Before adding this event, add all the DB events if (isFirstEventForTable(eventMetaFileMap, tableName)) { addDbEventsToTableEventFile(out, dbEventList, tableName); } addTableEventToFile(out, cmds, tableName); } private boolean isFirstEventForTable(final Map<String, List<String>> eventMetaFileMap, final String tableName) { List<String> files = eventMetaFileMap.get(tableName); return (files == null || files.isEmpty()); } private void addCmdsToDBEventList(List<Command> dbEventList, final java.lang.Iterable <? extends org.apache.hive.hcatalog.api.repl.Command> cmds) { for (Command cmd : cmds) { dbEventList.add(cmd); } } private void addDbEventToAllTablesEventFile( final java.lang.Iterable<? extends org.apache.hive.hcatalog.api.repl.Command> cmds, final Map<String, List<OutputStream>> outputStreamMap, final CMDTYPE cmdType) throws Exception { for (Map.Entry<String, List<OutputStream>> entry : outputStreamMap.entrySet()) { String tableName = entry.getKey(); List<OutputStream> streams = entry.getValue(); OutputStream out; if (CMDTYPE.SRC_CMD_TYPE == cmdType) { out = streams.get(0); } else { out = streams.get(1); } addTableEventToFile(out, cmds, tableName); } } private void addDbEventsToTableEventFile(final OutputStream out, final List<Command> dbEventList, final String tableName) throws Exception { /* First event for the table, add db events before adding this event */ addTableEventToFile(out, dbEventList, tableName); } private void addTableEventToFile(final OutputStream out, final java.lang.Iterable<? extends org.apache.hive.hcatalog.api.repl.Command> cmds, final String tableName) throws Exception { Long eventId = eventFilter.eventFilterMap.get(tableName); /* If not already processed, add it */ for (Command cmd : cmds) { persistEvent(out, eventId, cmd); } } private void persistEvent(final OutputStream out, final Long eventId, final Command cmd) throws Exception { if (out == null) { LOG.debug("persistEvent : out is null"); return; } if (eventId == null || cmd.getEventId() > eventId) { eventSourcerUtils.persistReplicationEvents(out, cmd); } } public boolean isPartitioningRequired(final HiveDROptions options) { return (HiveDRUtils.getReplicationType(options.getSourceTables()) == HiveDRUtils.ReplicationType.DB); } }
apache-2.0
autermann/checkstyle
src/test/resources/com/puppycrawl/tools/checkstyle/InputEmptyCatchBlockCheck.java
5932
//////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2015 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import java.io.IOException; public class InputEmptyCatchBlockCheck { private void foo() { try { throw new RuntimeException(); } catch (Exception expected) { //Expected } } private void foo1() { try { throw new RuntimeException(); } catch (Exception e) {} } private void foo2() { try { throw new IOException(); } catch (IOException | NullPointerException | ArithmeticException ignore) { } } private void foo3() { // comment try { throw new IOException(); } catch (IOException | NullPointerException | ArithmeticException e) { //This is expected } } private void foo4() { try { throw new IOException(); } catch (IOException | NullPointerException | ArithmeticException e) { /* This is expected*/ } } private void foo5() { try { throw new IOException(); } catch (IOException | NullPointerException | ArithmeticException e) { // Some singleline comment } } private void foo6() { try { throw new IOException(); } catch (IOException expected) { // This is expected int k = 0; } } public void testTryCatch() { try { int y=0; int u=8; int e=u-y; return; } catch (Exception e) { System.out.println(e); return; } finally { return; } } public void testTryCatch2() { try { } catch (Exception e) { //OK //This is expected /* This is expected */ /**This is expected */ } finally { } } public void testTryCatch3() { try { int y=0; int u=8; int e=u-y; } catch (IllegalArgumentException e) { System.out.println(e); //some comment return; } catch (IllegalStateException ex) { System.out.println(ex); return; } } public void testTryCatch4() { int y=0; int u=8; try { int e=u-y; } catch (IllegalArgumentException e) { System.out.println(e); return; } } public void setFormats() { try { int k = 4; } catch (Exception e) { Object k = null; if (k != null) k = "ss"; else { return; } } } public void setFormats1() { try { int k = 4; } catch (Exception e) { Object k = null; if (k != null) { k = "ss"; } else { return; } } } public void setFormats2() { try { int k = 4; } catch (Exception e) { Object k = null; if (k != null) { k = "ss"; return; } } } public void setFormats3() { try { int k = 4; } catch (Exception e) { Object k = null; if (k != null) { k = "ss"; } } } private void some() { try { throw new IOException(); } catch (IOException e) { /* ololo * blalba */ } } private void some1() { try { throw new IOException(); } catch (IOException e) { /* lalala * This is expected */ } } private void some2() { try { throw new IOException(); } catch (IOException e) { /* * This is expected * lalala */ } } private void some3() { try { throw new IOException(); } catch (IOException e) { // some comment //This is expected } } private void some4() { try { throw new IOException(); } catch (IOException e) { //This is expected // some comment } } private void some5() { try { throw new IOException(); } catch (IOException e) { /* some comment */ //This is expected } } private void emptyMultilineComent() { try { throw new IOException(); } catch (IOException e) { /* */ } } }
lgpl-2.1
psadusumilli/ignite
modules/core/src/main/java/org/apache/ignite/marshaller/Marshaller.java
4385
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.marshaller; import java.io.InputStream; import java.io.OutputStream; import org.apache.ignite.IgniteBinary; import org.apache.ignite.IgniteCheckedException; import org.jetbrains.annotations.Nullable; /** * {@code Marshaller} allows to marshal or unmarshal objects in grid. It provides * serialization/deserialization mechanism for all instances that are sent across networks * or are otherwise serialized. * <p> * Ignite provides the following {@code Marshaller} implementations: * <ul> * <li>Default binary marshaller. Will be used when no other marshaller is explicitly set to the * configuration. For more information, see {@link IgniteBinary}.</li> * <li>{@link org.apache.ignite.marshaller.jdk.JdkMarshaller}</li> * </ul> * <p> * Below are examples of marshaller configuration, usage, and injection into tasks, jobs, * and SPI's. * <h2 class="header">Java Example</h2> * {@code Marshaller} can be explicitly configured in code. * <pre name="code" class="java"> * JdkMarshaller marshaller = new JdkMarshaller(); * * IgniteConfiguration cfg = new IgniteConfiguration(); * * // Override marshaller. * cfg.setMarshaller(marshaller); * * // Starts grid. * G.start(cfg); * </pre> * <h2 class="header">Spring Example</h2> * Marshaller can be configured from Spring XML configuration file: * <pre name="code" class="xml"> * &lt;bean id="grid.custom.cfg" class="org.apache.ignite.configuration.IgniteConfiguration" singleton="true"&gt; * ... * &lt;property name="marshaller"&gt; * &lt;bean class="org.apache.ignite.marshaller.jdk.JdkMarshaller"/&gt; * &lt;/property&gt; * ... * &lt;/bean&gt; * </pre> * <p> * <img src="http://ignite.apache.org/images/spring-small.png"> * <br> * For information about Spring framework visit <a href="http://www.springframework.org/">www.springframework.org</a> */ public interface Marshaller { /** * Sets marshaller context. * * @param ctx Marshaller context. */ public void setContext(MarshallerContext ctx); /** * Marshals object to the output stream. This method should not close * given output stream. * * @param obj Object to marshal. * @param out Output stream to marshal into. * @throws IgniteCheckedException If marshalling failed. */ public void marshal(@Nullable Object obj, OutputStream out) throws IgniteCheckedException; /** * Marshals object to byte array. * * @param obj Object to marshal. * @return Byte array. * @throws IgniteCheckedException If marshalling failed. */ public byte[] marshal(@Nullable Object obj) throws IgniteCheckedException; /** * Unmarshals object from the input stream using given class loader. * This method should not close given input stream. * * @param <T> Type of unmarshalled object. * @param in Input stream. * @param clsLdr Class loader to use. * @return Unmarshalled object. * @throws IgniteCheckedException If unmarshalling failed. */ public <T> T unmarshal(InputStream in, @Nullable ClassLoader clsLdr) throws IgniteCheckedException; /** * Unmarshals object from byte array using given class loader. * * @param <T> Type of unmarshalled object. * @param arr Byte array. * @param clsLdr Class loader to use. * @return Unmarshalled object. * @throws IgniteCheckedException If unmarshalling failed. */ public <T> T unmarshal(byte[] arr, @Nullable ClassLoader clsLdr) throws IgniteCheckedException; }
apache-2.0
mduerig/jackrabbit-oak
oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/rdb/RDBBlobStoreFriend.java
2992
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.plugins.document.rdb; import static org.apache.jackrabbit.oak.plugins.document.rdb.RDBJDBCTools.closeResultSet; import static org.apache.jackrabbit.oak.plugins.document.rdb.RDBJDBCTools.closeStatement; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.List; import org.apache.jackrabbit.oak.commons.StringUtils; public class RDBBlobStoreFriend { public static void storeBlock(RDBBlobStore ds, byte[] digest, int level, byte[] data) throws IOException { ds.storeBlock(digest, level, data); } public static byte[] readBlockFromBackend(RDBBlobStore ds, byte[] digest) throws Exception { return ds.readBlockFromBackend(digest); } public static void killMetaEntry(RDBBlobStore ds, byte[] digest) throws Exception { String id = StringUtils.convertBytesToHex(digest); Connection con = ds.ch.getRWConnection(); PreparedStatement prepDelMeta = null; try { prepDelMeta = con.prepareStatement("delete from " + ds.tnMeta + " where ID = ?"); prepDelMeta.setString(1, id); prepDelMeta.execute(); } finally { closeStatement(prepDelMeta); con.commit(); ds.ch.closeConnection(con); } } public static boolean isDataEntryPresent(RDBBlobStore ds, byte[] digest) throws Exception { String id = StringUtils.convertBytesToHex(digest); Connection con = ds.ch.getROConnection(); PreparedStatement prep = null; ResultSet rs = null; try { prep = con.prepareStatement("select ID from " + ds.tnData + " where ID = ?"); prep.setString(1, id); rs = prep.executeQuery(); return rs.next(); } finally { closeResultSet(rs); closeStatement(prep); con.commit(); ds.ch.closeConnection(con); } } public static void deleteChunks(RDBBlobStore ds, List<String> chunkIds, long maxLastModifiedTime) throws Exception { ds.deleteChunks(chunkIds, maxLastModifiedTime); } }
apache-2.0
bruthe/hadoop-2.6.0r
src/yarn/registry/org/apache/hadoop/registry/server/services/package-info.java
1637
/* * 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. */ /** * Basic services for the YARN registry * <ul> * <li>The {@link org.apache.hadoop.registry.server.services.RegistryAdminService}</ol> * extends the shared Yarn Registry client with registry setup and * (potentially asynchronous) administrative actions. * </li> * <li> * The {@link org.apache.hadoop.registry.server.services.MicroZookeeperService} * is a transient Zookeeper instance bound to the YARN service lifecycle. * It is suitable for testing. * </li> * <li> * The {@link org.apache.hadoop.registry.server.services.AddingCompositeService} * extends the standard YARN composite service by making its add and remove * methods public. It is a utility service used in parts of the codebase * </li> * * </ul> * */ package org.apache.hadoop.registry.server.services;
apache-2.0
irina-mitrea-luxoft/gateway
mina.netty/src/main/java/org/kaazing/mina/netty/bootstrap/ConnectionlessClientBootstrap.java
2672
/** * Copyright 2007-2016, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.mina.netty.bootstrap; class ConnectionlessClientBootstrap extends ConnectionlessBootstrap implements ClientBootstrap { // private volatile ChannelPipeline pipeline = pipeline(); // private volatile ChannelPipelineFactory pipelineFactory = pipelineFactory(pipeline); ConnectionlessClientBootstrap() { // super.setPipeline(pipeline(new ConnectionlessChannelHandler())); } // @Override // public ChannelPipeline getPipeline() { // ChannelPipeline pipeline = this.pipeline; // if (pipeline == null) { // throw new IllegalStateException( // "getPipeline() cannot be called " + // "if setPipelineFactory() was called."); // } // return pipeline; // } // // @Override // public void setPipeline(ChannelPipeline pipeline) { // if (pipeline == null) { // throw new NullPointerException("pipeline"); // } // this.pipeline = pipeline; // pipelineFactory = pipelineFactory(pipeline); // } // // @Override // public Map<String, ChannelHandler> getPipelineAsMap() { // ChannelPipeline pipeline = this.pipeline; // if (pipeline == null) { // throw new IllegalStateException("pipelineFactory in use"); // } // return pipeline.toMap(); // } // // @Override // public void setPipelineAsMap(Map<String, ChannelHandler> pipelineMap) { // throw new UnsupportedOperationException(); // } // // @Override // public ChannelPipelineFactory getPipelineFactory() { // return pipelineFactory; // } // // @Override // public void setPipelineFactory(ChannelPipelineFactory pipelineFactory) { // if (pipelineFactory == null) { // throw new NullPointerException("pipelineFactory"); // } // pipeline = null; // this.pipelineFactory = pipelineFactory; // } // // private static final class ConnectionlessChannelHandler extends SimpleChannelUpstreamHandler { // } }
apache-2.0
siosio/intellij-community
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/optionalIsPresent/beforeTernaryPrimitiveSimple.java
314
// "Replace Optional.isPresent() condition with functional style expression" "GENERIC_ERROR_OR_WARNING" import java.util.Arrays; import java.util.List; import java.util.Optional; public class Main { void test(Optional<String> foo) { double bar = foo.isPresent<caret>() ? foo.get().length() * 1.2 : 0; } }
apache-2.0
cooldoger/cassandra
src/java/org/apache/cassandra/service/reads/repair/RepairedDataVerifier.java
4139
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.service.reads.repair; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.ColumnFamilyStore; import org.apache.cassandra.db.PartitionRangeReadCommand; import org.apache.cassandra.db.ReadCommand; import org.apache.cassandra.db.SinglePartitionReadCommand; import org.apache.cassandra.metrics.TableMetrics; import org.apache.cassandra.tracing.Tracing; import org.apache.cassandra.utils.NoSpamLogger; public interface RepairedDataVerifier { public void verify(RepairedDataTracker tracker); static RepairedDataVerifier simple(ReadCommand command) { return new SimpleVerifier(command); } static class SimpleVerifier implements RepairedDataVerifier { private static final Logger logger = LoggerFactory.getLogger(SimpleVerifier.class); private final ReadCommand command; private static final String INCONSISTENCY_WARNING = "Detected mismatch between repaired datasets for table {}.{} during read of {}. {}"; SimpleVerifier(ReadCommand command) { this.command = command; } @Override public void verify(RepairedDataTracker tracker) { Tracing.trace("Verifying repaired data tracker {}", tracker); // some mismatch occurred between the repaired datasets on the replicas if (tracker.digests.keySet().size() > 1) { // if any of the digests should be considered inconclusive, because there were // pending repair sessions which had not yet been committed or unrepaired partition // deletes which meant some sstables were skipped during reads, mark the inconsistency // as confirmed if (tracker.inconclusiveDigests.isEmpty()) { TableMetrics metrics = ColumnFamilyStore.metricsFor(command.metadata().id); metrics.confirmedRepairedInconsistencies.mark(); NoSpamLogger.log(logger, NoSpamLogger.Level.WARN, 1, TimeUnit.MINUTES, INCONSISTENCY_WARNING, command.metadata().keyspace, command.metadata().name, getCommandString(), tracker); } else if (DatabaseDescriptor.reportUnconfirmedRepairedDataMismatches()) { TableMetrics metrics = ColumnFamilyStore.metricsFor(command.metadata().id); metrics.unconfirmedRepairedInconsistencies.mark(); NoSpamLogger.log(logger, NoSpamLogger.Level.WARN, 1, TimeUnit.MINUTES, INCONSISTENCY_WARNING, command.metadata().keyspace, command.metadata().name, getCommandString(), tracker); } } } private String getCommandString() { return command instanceof SinglePartitionReadCommand ? ((SinglePartitionReadCommand)command).partitionKey().toString() : ((PartitionRangeReadCommand)command).dataRange().keyRange().getString(command.metadata().partitionKeyType); } } }
apache-2.0
zlamalp/perun
perun-base/src/main/java/cz/metacentrum/perun/core/api/exceptions/rt/EmptyPasswordRuntimeException.java
521
package cz.metacentrum.perun.core.api.exceptions.rt; /** * Checked version of EmptyPasswordRuntimeException. * * @author Michal Prochazka */ public class EmptyPasswordRuntimeException extends PerunRuntimeException { static final long serialVersionUID = 0; public EmptyPasswordRuntimeException(String message) { super(message); } public EmptyPasswordRuntimeException(String message, Throwable cause) { super(message, cause); } public EmptyPasswordRuntimeException(Throwable cause) { super(cause); } }
bsd-2-clause
uprasad/fred
src/freenet/client/events/StartedCompressionEvent.java
750
/* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package freenet.client.events; import freenet.support.compress.Compressor.COMPRESSOR_TYPE; /** * Event indicating that we are attempting to compress the file. */ public class StartedCompressionEvent implements ClientEvent { public final COMPRESSOR_TYPE codec; public StartedCompressionEvent(COMPRESSOR_TYPE codec) { this.codec = codec; } final static int code = 0x08; @Override public String getDescription() { return "Started compression attempt with "+codec.name; } @Override public int getCode() { return code; } }
gpl-2.0
amckee23/drools
drools-decisiontables/src/test/java/org/drools/decisiontable/parser/RulesheetUtil.java
1757
/* * Copyright 2005 JBoss 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.drools.decisiontable.parser; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.drools.decisiontable.parser.xls.ExcelParser; import org.drools.template.parser.DataListener; public class RulesheetUtil { /** * Utility method showing how to get a rule sheet listener from a stream. */ public static RuleSheetListener getRuleSheetListener(final InputStream stream) throws IOException { final Map<String, List<DataListener>> sheetListeners = new HashMap<String, List<DataListener>>(); final List<DataListener> listeners = new ArrayList<DataListener>(); final RuleSheetListener listener = new DefaultRuleSheetListener(); listeners.add(listener); sheetListeners.put( ExcelParser.DEFAULT_RULESHEET_NAME, listeners ); final ExcelParser parser = new ExcelParser( sheetListeners ); try { parser.parseFile( stream ); } finally { stream.close(); } stream.close(); return listener; } }
apache-2.0
GlenRSmith/elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/bucket/TermsDocCountErrorIT.java
47671
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.search.aggregations.bucket; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.search.aggregations.Aggregator.SubAggCollectionMode; import org.elasticsearch.search.aggregations.BucketOrder; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregatorFactory.ExecutionMode; import org.elasticsearch.test.ESIntegTestCase; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.elasticsearch.search.aggregations.AggregationBuilders.sum; import static org.elasticsearch.search.aggregations.AggregationBuilders.terms; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse; import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.hamcrest.core.IsNull.notNullValue; @ESIntegTestCase.SuiteScopeTestCase public class TermsDocCountErrorIT extends ESIntegTestCase { private static final String STRING_FIELD_NAME = "s_value"; private static final String LONG_FIELD_NAME = "l_value"; private static final String DOUBLE_FIELD_NAME = "d_value"; public static String randomExecutionHint() { return randomBoolean() ? null : randomFrom(ExecutionMode.values()).toString(); } private static int numRoutingValues; @Override public void setupSuiteScopeCluster() throws Exception { assertAcked(client().admin().indices().prepareCreate("idx").setMapping(STRING_FIELD_NAME, "type=keyword").get()); List<IndexRequestBuilder> builders = new ArrayList<>(); int numDocs = between(10, 200); int numUniqueTerms = between(2, numDocs / 2); for (int i = 0; i < numDocs; i++) { builders.add( client().prepareIndex("idx") .setId("" + i) .setSource( jsonBuilder().startObject() .field(STRING_FIELD_NAME, "val" + randomInt(numUniqueTerms)) .field(LONG_FIELD_NAME, randomInt(numUniqueTerms)) .field(DOUBLE_FIELD_NAME, 1.0 * randomInt(numUniqueTerms)) .endObject() ) ); } assertAcked( prepareCreate("idx_single_shard").setMapping(STRING_FIELD_NAME, "type=keyword") .setSettings(Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)) ); for (int i = 0; i < numDocs; i++) { builders.add( client().prepareIndex("idx_single_shard") .setId("" + i) .setSource( jsonBuilder().startObject() .field(STRING_FIELD_NAME, "val" + randomInt(numUniqueTerms)) .field(LONG_FIELD_NAME, randomInt(numUniqueTerms)) .field(DOUBLE_FIELD_NAME, 1.0 * randomInt(numUniqueTerms)) .endObject() ) ); } numRoutingValues = between(1, 40); assertAcked(prepareCreate("idx_with_routing").setMapping("{ \"_routing\" : { \"required\" : true } }")); for (int i = 0; i < numDocs; i++) { builders.add( client().prepareIndex("idx_single_shard") .setId("" + i) .setRouting(String.valueOf(randomInt(numRoutingValues))) .setSource( jsonBuilder().startObject() .field(STRING_FIELD_NAME, "val" + randomInt(numUniqueTerms)) .field(LONG_FIELD_NAME, randomInt(numUniqueTerms)) .field(DOUBLE_FIELD_NAME, 1.0 * randomInt(numUniqueTerms)) .endObject() ) ); } Map<String, Integer> shard0DocsPerTerm = new HashMap<>(); shard0DocsPerTerm.put("A", 25); shard0DocsPerTerm.put("B", 18); shard0DocsPerTerm.put("C", 6); shard0DocsPerTerm.put("D", 3); shard0DocsPerTerm.put("E", 2); shard0DocsPerTerm.put("F", 2); shard0DocsPerTerm.put("G", 2); shard0DocsPerTerm.put("H", 2); shard0DocsPerTerm.put("I", 1); shard0DocsPerTerm.put("J", 1); buildIndex(shard0DocsPerTerm, "idx_fixed_docs_0", 0, builders); Map<String, Integer> shard1DocsPerTerm = new HashMap<>(); shard1DocsPerTerm.put("A", 30); shard1DocsPerTerm.put("B", 25); shard1DocsPerTerm.put("F", 17); shard1DocsPerTerm.put("Z", 16); shard1DocsPerTerm.put("G", 15); shard1DocsPerTerm.put("H", 14); shard1DocsPerTerm.put("I", 10); shard1DocsPerTerm.put("Q", 6); shard1DocsPerTerm.put("J", 8); shard1DocsPerTerm.put("C", 4); buildIndex(shard1DocsPerTerm, "idx_fixed_docs_1", 1, builders); Map<String, Integer> shard2DocsPerTerm = new HashMap<>(); shard2DocsPerTerm.put("A", 45); shard2DocsPerTerm.put("C", 44); shard2DocsPerTerm.put("Z", 36); shard2DocsPerTerm.put("G", 30); shard2DocsPerTerm.put("E", 29); shard2DocsPerTerm.put("H", 28); shard2DocsPerTerm.put("Q", 2); shard2DocsPerTerm.put("D", 1); buildIndex(shard2DocsPerTerm, "idx_fixed_docs_2", 2, builders); Map<String, Integer> shard3DocsPerTerm = Map.of("A", 1, "B", 1, "C", 1); buildIndex(shard3DocsPerTerm, "idx_fixed_docs_3", 3, builders); Map<String, Integer> shard4DocsPerTerm = Map.of("K", 1, "L", 1, "M", 1); buildIndex(shard4DocsPerTerm, "idx_fixed_docs_4", 4, builders); Map<String, Integer> shard5DocsPerTerm = Map.of("X", 1, "Y", 1, "Z", 1); buildIndex(shard5DocsPerTerm, "idx_fixed_docs_5", 5, builders); indexRandom(true, builders); ensureSearchable(); } private void buildIndex(Map<String, Integer> docsPerTerm, String index, int shard, List<IndexRequestBuilder> builders) throws IOException { assertAcked( prepareCreate(index).setMapping(STRING_FIELD_NAME, "type=keyword") .setSettings(Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)) ); for (Map.Entry<String, Integer> entry : docsPerTerm.entrySet()) { for (int i = 0; i < entry.getValue(); i++) { String term = entry.getKey(); builders.add( client().prepareIndex(index) .setId(term + "-" + i) .setSource(jsonBuilder().startObject().field(STRING_FIELD_NAME, term).field("shard", shard).endObject()) ); } } } private void assertDocCountErrorWithinBounds(int size, SearchResponse accurateResponse, SearchResponse testResponse) { Terms accurateTerms = accurateResponse.getAggregations().get("terms"); assertThat(accurateTerms, notNullValue()); assertThat(accurateTerms.getName(), equalTo("terms")); assertThat(accurateTerms.getDocCountError(), equalTo(0L)); Terms testTerms = testResponse.getAggregations().get("terms"); assertThat(testTerms, notNullValue()); assertThat(testTerms.getName(), equalTo("terms")); assertThat(testTerms.getDocCountError(), greaterThanOrEqualTo(0L)); List<? extends Bucket> testBuckets = testTerms.getBuckets(); assertThat(testBuckets.size(), lessThanOrEqualTo(size)); assertThat(accurateTerms.getBuckets().size(), greaterThanOrEqualTo(testBuckets.size())); for (Terms.Bucket testBucket : testBuckets) { assertThat(testBucket, notNullValue()); Terms.Bucket accurateBucket = accurateTerms.getBucketByKey(testBucket.getKeyAsString()); assertThat(accurateBucket, notNullValue()); assertThat(accurateBucket.getDocCountError(), equalTo(0L)); assertThat(testBucket.getDocCountError(), lessThanOrEqualTo(testTerms.getDocCountError())); assertThat(testBucket.getDocCount() + testBucket.getDocCountError(), greaterThanOrEqualTo(accurateBucket.getDocCount())); assertThat(testBucket.getDocCount() - testBucket.getDocCountError(), lessThanOrEqualTo(accurateBucket.getDocCount())); } for (Terms.Bucket accurateBucket : accurateTerms.getBuckets()) { assertThat(accurateBucket, notNullValue()); Terms.Bucket testBucket = accurateTerms.getBucketByKey(accurateBucket.getKeyAsString()); if (testBucket == null) { assertThat(accurateBucket.getDocCount(), lessThanOrEqualTo(testTerms.getDocCountError())); } } } private void assertNoDocCountError(int size, SearchResponse accurateResponse, SearchResponse testResponse) { Terms accurateTerms = accurateResponse.getAggregations().get("terms"); assertThat(accurateTerms, notNullValue()); assertThat(accurateTerms.getName(), equalTo("terms")); assertThat(accurateTerms.getDocCountError(), equalTo(0L)); Terms testTerms = testResponse.getAggregations().get("terms"); assertThat(testTerms, notNullValue()); assertThat(testTerms.getName(), equalTo("terms")); assertThat(testTerms.getDocCountError(), equalTo(0L)); List<? extends Bucket> testBuckets = testTerms.getBuckets(); assertThat(testBuckets.size(), lessThanOrEqualTo(size)); assertThat(accurateTerms.getBuckets().size(), greaterThanOrEqualTo(testBuckets.size())); for (Terms.Bucket testBucket : testBuckets) { assertThat(testBucket, notNullValue()); Terms.Bucket accurateBucket = accurateTerms.getBucketByKey(testBucket.getKeyAsString()); assertThat(accurateBucket, notNullValue()); assertThat(accurateBucket.getDocCountError(), equalTo(0L)); assertThat(testBucket.getDocCountError(), equalTo(0L)); } } private void assertNoDocCountErrorSingleResponse(int size, SearchResponse testResponse) { Terms testTerms = testResponse.getAggregations().get("terms"); assertThat(testTerms, notNullValue()); assertThat(testTerms.getName(), equalTo("terms")); assertThat(testTerms.getDocCountError(), equalTo(0L)); List<? extends Bucket> testBuckets = testTerms.getBuckets(); assertThat(testBuckets.size(), lessThanOrEqualTo(size)); for (Terms.Bucket testBucket : testBuckets) { assertThat(testBucket, notNullValue()); assertThat(testBucket.getDocCountError(), equalTo(0L)); } } private void assertUnboundedDocCountError(int size, SearchResponse accurateResponse, SearchResponse testResponse) { Terms accurateTerms = accurateResponse.getAggregations().get("terms"); assertThat(accurateTerms, notNullValue()); assertThat(accurateTerms.getName(), equalTo("terms")); assertThat(accurateTerms.getDocCountError(), equalTo(0L)); Terms testTerms = testResponse.getAggregations().get("terms"); assertThat(testTerms, notNullValue()); assertThat(testTerms.getName(), equalTo("terms")); assertThat(testTerms.getDocCountError(), anyOf(equalTo(-1L), equalTo(0L))); List<? extends Bucket> testBuckets = testTerms.getBuckets(); assertThat(testBuckets.size(), lessThanOrEqualTo(size)); assertThat(accurateTerms.getBuckets().size(), greaterThanOrEqualTo(testBuckets.size())); for (Terms.Bucket testBucket : testBuckets) { assertThat(testBucket, notNullValue()); Terms.Bucket accurateBucket = accurateTerms.getBucketByKey(testBucket.getKeyAsString()); assertThat(accurateBucket, notNullValue()); assertThat(accurateBucket.getDocCountError(), equalTo(0L)); assertThat(testBucket.getDocCountError(), anyOf(equalTo(-1L), equalTo(0L))); } } public void testStringValueField() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(STRING_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(STRING_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertDocCountErrorWithinBounds(size, accurateResponse, testResponse); } public void testStringValueFieldSingleShard() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(STRING_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(STRING_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertNoDocCountError(size, accurateResponse, testResponse); } public void testStringValueFieldWithRouting() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse testResponse = client().prepareSearch("idx_with_routing") .setRouting(String.valueOf(between(1, numRoutingValues))) .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(STRING_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertNoDocCountErrorSingleResponse(size, testResponse); } public void testStringValueFieldDocCountAsc() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(STRING_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .order(BucketOrder.count(true)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(STRING_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .order(BucketOrder.count(true)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertUnboundedDocCountError(size, accurateResponse, testResponse); } public void testStringValueFieldTermSortAsc() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(STRING_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .order(BucketOrder.key(true)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(STRING_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .order(BucketOrder.key(true)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertNoDocCountError(size, accurateResponse, testResponse); } public void testStringValueFieldTermSortDesc() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(STRING_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .order(BucketOrder.key(false)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(STRING_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .order(BucketOrder.key(false)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertNoDocCountError(size, accurateResponse, testResponse); } public void testStringValueFieldSubAggAsc() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(STRING_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .order(BucketOrder.aggregation("sortAgg", true)) .collectMode(randomFrom(SubAggCollectionMode.values())) .subAggregation(sum("sortAgg").field(LONG_FIELD_NAME)) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(STRING_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .order(BucketOrder.aggregation("sortAgg", true)) .collectMode(randomFrom(SubAggCollectionMode.values())) .subAggregation(sum("sortAgg").field(LONG_FIELD_NAME)) ) .get(); assertSearchResponse(testResponse); assertUnboundedDocCountError(size, accurateResponse, testResponse); } public void testStringValueFieldSubAggDesc() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(STRING_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .order(BucketOrder.aggregation("sortAgg", false)) .collectMode(randomFrom(SubAggCollectionMode.values())) .subAggregation(sum("sortAgg").field(LONG_FIELD_NAME)) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(STRING_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .order(BucketOrder.aggregation("sortAgg", false)) .collectMode(randomFrom(SubAggCollectionMode.values())) .subAggregation(sum("sortAgg").field(LONG_FIELD_NAME)) ) .get(); assertSearchResponse(testResponse); assertUnboundedDocCountError(size, accurateResponse, testResponse); } public void testLongValueField() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(LONG_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(LONG_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertDocCountErrorWithinBounds(size, accurateResponse, testResponse); } public void testLongValueFieldSingleShard() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(LONG_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(LONG_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertNoDocCountError(size, accurateResponse, testResponse); } public void testLongValueFieldWithRouting() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse testResponse = client().prepareSearch("idx_with_routing") .setRouting(String.valueOf(between(1, numRoutingValues))) .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(LONG_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertNoDocCountErrorSingleResponse(size, testResponse); } public void testLongValueFieldDocCountAsc() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(LONG_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .order(BucketOrder.count(true)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(LONG_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .order(BucketOrder.count(true)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertUnboundedDocCountError(size, accurateResponse, testResponse); } public void testLongValueFieldTermSortAsc() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(LONG_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .order(BucketOrder.key(true)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(LONG_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .order(BucketOrder.key(true)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertNoDocCountError(size, accurateResponse, testResponse); } public void testLongValueFieldTermSortDesc() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(LONG_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .order(BucketOrder.key(false)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(LONG_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .order(BucketOrder.key(false)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertNoDocCountError(size, accurateResponse, testResponse); } public void testLongValueFieldSubAggAsc() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(LONG_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .order(BucketOrder.aggregation("sortAgg", true)) .collectMode(randomFrom(SubAggCollectionMode.values())) .subAggregation(sum("sortAgg").field(LONG_FIELD_NAME)) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(LONG_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .order(BucketOrder.aggregation("sortAgg", true)) .collectMode(randomFrom(SubAggCollectionMode.values())) .subAggregation(sum("sortAgg").field(LONG_FIELD_NAME)) ) .get(); assertSearchResponse(testResponse); assertUnboundedDocCountError(size, accurateResponse, testResponse); } public void testLongValueFieldSubAggDesc() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(LONG_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .order(BucketOrder.aggregation("sortAgg", false)) .collectMode(randomFrom(SubAggCollectionMode.values())) .subAggregation(sum("sortAgg").field(DOUBLE_FIELD_NAME)) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(LONG_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .order(BucketOrder.aggregation("sortAgg", false)) .collectMode(randomFrom(SubAggCollectionMode.values())) .subAggregation(sum("sortAgg").field(DOUBLE_FIELD_NAME)) ) .get(); assertSearchResponse(testResponse); assertUnboundedDocCountError(size, accurateResponse, testResponse); } public void testDoubleValueField() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(DOUBLE_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(DOUBLE_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertDocCountErrorWithinBounds(size, accurateResponse, testResponse); } public void testDoubleValueFieldSingleShard() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(DOUBLE_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(DOUBLE_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertNoDocCountError(size, accurateResponse, testResponse); } public void testDoubleValueFieldWithRouting() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse testResponse = client().prepareSearch("idx_with_routing") .setRouting(String.valueOf(between(1, numRoutingValues))) .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(DOUBLE_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertNoDocCountErrorSingleResponse(size, testResponse); } public void testDoubleValueFieldDocCountAsc() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(DOUBLE_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .order(BucketOrder.count(true)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(DOUBLE_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .order(BucketOrder.count(true)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertUnboundedDocCountError(size, accurateResponse, testResponse); } public void testDoubleValueFieldTermSortAsc() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(DOUBLE_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .order(BucketOrder.key(true)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(DOUBLE_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .order(BucketOrder.key(true)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertNoDocCountError(size, accurateResponse, testResponse); } public void testDoubleValueFieldTermSortDesc() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(DOUBLE_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .order(BucketOrder.key(false)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(DOUBLE_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .order(BucketOrder.key(false)) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(testResponse); assertNoDocCountError(size, accurateResponse, testResponse); } public void testDoubleValueFieldSubAggAsc() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(DOUBLE_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .order(BucketOrder.aggregation("sortAgg", true)) .collectMode(randomFrom(SubAggCollectionMode.values())) .subAggregation(sum("sortAgg").field(LONG_FIELD_NAME)) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(DOUBLE_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .order(BucketOrder.aggregation("sortAgg", true)) .collectMode(randomFrom(SubAggCollectionMode.values())) .subAggregation(sum("sortAgg").field(LONG_FIELD_NAME)) ) .get(); assertSearchResponse(testResponse); assertUnboundedDocCountError(size, accurateResponse, testResponse); } public void testDoubleValueFieldSubAggDesc() throws Exception { int size = randomIntBetween(1, 20); int shardSize = randomIntBetween(size, size * 2); SearchResponse accurateResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(DOUBLE_FIELD_NAME) .showTermDocCountError(true) .size(10000) .shardSize(10000) .order(BucketOrder.aggregation("sortAgg", false)) .collectMode(randomFrom(SubAggCollectionMode.values())) .subAggregation(sum("sortAgg").field(LONG_FIELD_NAME)) ) .get(); assertSearchResponse(accurateResponse); SearchResponse testResponse = client().prepareSearch("idx_single_shard") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(DOUBLE_FIELD_NAME) .showTermDocCountError(true) .size(size) .shardSize(shardSize) .order(BucketOrder.aggregation("sortAgg", false)) .collectMode(randomFrom(SubAggCollectionMode.values())) .subAggregation(sum("sortAgg").field(LONG_FIELD_NAME)) ) .get(); assertSearchResponse(testResponse); assertUnboundedDocCountError(size, accurateResponse, testResponse); } /** * Test a case where we know exactly how many of each term is on each shard * so we know the exact error value for each term. To do this we search over * 3 one-shard indices. */ public void testFixedDocs() throws Exception { SearchResponse response = client().prepareSearch("idx_fixed_docs_0", "idx_fixed_docs_1", "idx_fixed_docs_2") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(STRING_FIELD_NAME) .showTermDocCountError(true) .size(5) .shardSize(5) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(response); Terms terms = response.getAggregations().get("terms"); assertThat(terms, notNullValue()); assertThat(terms.getDocCountError(), equalTo(46L)); List<? extends Bucket> buckets = terms.getBuckets(); assertThat(buckets, notNullValue()); assertThat(buckets.size(), equalTo(5)); Bucket bucket = buckets.get(0); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo("A")); assertThat(bucket.getDocCount(), equalTo(100L)); assertThat(bucket.getDocCountError(), equalTo(0L)); bucket = buckets.get(1); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo("Z")); assertThat(bucket.getDocCount(), equalTo(52L)); assertThat(bucket.getDocCountError(), equalTo(2L)); bucket = buckets.get(2); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo("C")); assertThat(bucket.getDocCount(), equalTo(50L)); assertThat(bucket.getDocCountError(), equalTo(15L)); bucket = buckets.get(3); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo("G")); assertThat(bucket.getDocCount(), equalTo(45L)); assertThat(bucket.getDocCountError(), equalTo(2L)); bucket = buckets.get(4); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo("B")); assertThat(bucket.getDocCount(), equalTo(43L)); assertThat(bucket.getDocCountError(), equalTo(29L)); } /** * Tests the upper bounds are correct when performing incremental reductions * See https://github.com/elastic/elasticsearch/issues/40005 for more details */ public void testIncrementalReduction() { SearchResponse response = client().prepareSearch("idx_fixed_docs_3", "idx_fixed_docs_4", "idx_fixed_docs_5") .addAggregation( terms("terms").executionHint(randomExecutionHint()) .field(STRING_FIELD_NAME) .showTermDocCountError(true) .size(5) .shardSize(5) .collectMode(randomFrom(SubAggCollectionMode.values())) ) .get(); assertSearchResponse(response); Terms terms = response.getAggregations().get("terms"); assertThat(terms.getDocCountError(), equalTo(0L)); } }
apache-2.0
gpolitis/jitsi
src/net/java/sip/communicator/service/argdelegation/UriHandler.java
1519
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.java.sip.communicator.service.argdelegation; /** * This interface is meant to be implemented by all bundles that wish to handle * URIs passed as invocation arguments. * * @author Emil Ivov <emcho at sip-communicator.org> */ public interface UriHandler { /** * The name of the property that we use in the service registration * properties to store a protocol name when registering <tt>UriHandler</tt>s */ public static final String PROTOCOL_PROPERTY = "ProtocolName"; /** * Returns the protocols that this handler is responsible for. * * @return protocols that this handler is responsible for */ public String[] getProtocol(); /** * Handles/opens the URI. * * @param uri the URI that the handler has to open. */ public void handleUri(String uri); }
apache-2.0
GlenRSmith/elasticsearch
server/src/main/java/org/elasticsearch/common/logging/Loggers.java
6886
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.common.logging; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.Configurator; import org.apache.logging.log4j.core.config.LoggerConfig; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.index.Index; import org.elasticsearch.index.shard.ShardId; import java.util.Arrays; import java.util.Map; import java.util.stream.Stream; /** * A set of utilities around Logging. */ public class Loggers { public static final String SPACE = " "; public static final Setting<Level> LOG_DEFAULT_LEVEL_SETTING = new Setting<>( "logger.level", Level.INFO.name(), Level::valueOf, Setting.Property.NodeScope ); public static final Setting.AffixSetting<Level> LOG_LEVEL_SETTING = Setting.prefixKeySetting( "logger.", (key) -> new Setting<>(key, Level.INFO.name(), Level::valueOf, Setting.Property.Dynamic, Setting.Property.NodeScope) ); public static Logger getLogger(Class<?> clazz, ShardId shardId, String... prefixes) { return getLogger( clazz, shardId.getIndex(), Stream.concat(Stream.of(Integer.toString(shardId.id())), Arrays.stream(prefixes)).toArray(String[]::new) ); } /** * Just like {@link #getLogger(Class, ShardId, String...)} but String loggerName instead of * Class and no extra prefixes. */ public static Logger getLogger(String loggerName, ShardId shardId) { String prefix = formatPrefix(shardId.getIndexName(), Integer.toString(shardId.id())); return new PrefixLogger(LogManager.getLogger(loggerName), prefix); } public static Logger getLogger(Class<?> clazz, Index index, String... prefixes) { return getLogger(clazz, Stream.concat(Stream.of(Loggers.SPACE, index.getName()), Arrays.stream(prefixes)).toArray(String[]::new)); } public static Logger getLogger(Class<?> clazz, String... prefixes) { return new PrefixLogger(LogManager.getLogger(clazz), formatPrefix(prefixes)); } public static Logger getLogger(Logger parentLogger, String s) { Logger inner = LogManager.getLogger(parentLogger.getName() + s); if (parentLogger instanceof PrefixLogger) { return new PrefixLogger(inner, ((PrefixLogger) parentLogger).prefix()); } return inner; } private static String formatPrefix(String... prefixes) { String prefix = null; if (prefixes != null && prefixes.length > 0) { StringBuilder sb = new StringBuilder(); for (String prefixX : prefixes) { if (prefixX != null) { if (prefixX.equals(SPACE)) { sb.append(" "); } else { sb.append("[").append(prefixX).append("]"); } } } if (sb.length() > 0) { prefix = sb.toString(); } } return prefix; } /** * Set the level of the logger. If the new level is null, the logger will inherit it's level from its nearest ancestor with a non-null * level. */ public static void setLevel(Logger logger, String level) { final Level l; if (level == null) { l = null; } else { l = Level.valueOf(level); } setLevel(logger, l); } public static void setLevel(Logger logger, Level level) { if (LogManager.ROOT_LOGGER_NAME.equals(logger.getName()) == false) { Configurator.setLevel(logger.getName(), level); } else { final LoggerContext ctx = LoggerContext.getContext(false); final Configuration config = ctx.getConfiguration(); final LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName()); loggerConfig.setLevel(level); ctx.updateLoggers(); } // we have to descend the hierarchy final LoggerContext ctx = LoggerContext.getContext(false); for (final LoggerConfig loggerConfig : ctx.getConfiguration().getLoggers().values()) { if (LogManager.ROOT_LOGGER_NAME.equals(logger.getName()) || loggerConfig.getName().startsWith(logger.getName() + ".")) { Configurator.setLevel(loggerConfig.getName(), level); } } } public static void addAppender(final Logger logger, final Appender appender) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); config.addAppender(appender); LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName()); if (logger.getName().equals(loggerConfig.getName()) == false) { loggerConfig = new LoggerConfig(logger.getName(), logger.getLevel(), true); config.addLogger(logger.getName(), loggerConfig); } loggerConfig.addAppender(appender, null, null); ctx.updateLoggers(); } public static void removeAppender(final Logger logger, final Appender appender) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName()); if (logger.getName().equals(loggerConfig.getName()) == false) { loggerConfig = new LoggerConfig(logger.getName(), logger.getLevel(), true); config.addLogger(logger.getName(), loggerConfig); } loggerConfig.removeAppender(appender.getName()); ctx.updateLoggers(); } public static Appender findAppender(final Logger logger, final Class<? extends Appender> clazz) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); final LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName()); for (final Map.Entry<String, Appender> entry : loggerConfig.getAppenders().entrySet()) { if (entry.getValue().getClass().equals(clazz)) { return entry.getValue(); } } return null; } }
apache-2.0
GlenRSmith/elasticsearch
build-tools/src/testFixtures/java/org/elasticsearch/gradle/internal/test/GradleIntegrationTestCase.java
8639
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.gradle.internal.test; import org.apache.commons.io.FileUtils; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.BuildTask; import org.gradle.testkit.runner.GradleRunner; import org.gradle.testkit.runner.TaskOutcome; import org.junit.Rule; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.lang.management.ManagementFactory; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.hamcrest.CoreMatchers.containsString; public abstract class GradleIntegrationTestCase extends GradleUnitTestCase { @Rule public TemporaryFolder testkitTmpDir = new TemporaryFolder(); public File workingProjectDir = null; public abstract String projectName(); protected File getProjectDir() { if (workingProjectDir == null) { File root = new File("src/testKit/"); if (root.exists() == false) { throw new RuntimeException( "Could not find resources dir for integration tests. " + "Note that these tests can only be ran by Gradle and are not currently supported by the IDE" ); } try { workingProjectDir = new File(testkitTmpDir.getRoot(), projectName()); File sourcFolder = new File(root, projectName()); FileUtils.copyDirectory(sourcFolder, workingProjectDir); } catch (IOException e) { throw new UncheckedIOException(e); } } return workingProjectDir; } protected GradleRunner getGradleRunner() { File testkit; try { testkit = testkitTmpDir.newFolder(); } catch (IOException e) { throw new UncheckedIOException(e); } return new InternalAwareGradleRunner( GradleRunner.create() .withProjectDir(getProjectDir()) .withPluginClasspath() .withTestKitDir(testkit) .forwardOutput() .withDebug(ManagementFactory.getRuntimeMXBean().getInputArguments().toString().indexOf("-agentlib:jdwp") > 0) ); } protected File getBuildDir(String name) { return new File(getProjectDir(), "build"); } protected void assertOutputContains(String output, String... lines) { for (String line : lines) { assertOutputContains(output, line); } List<Integer> index = Stream.of(lines).map(line -> output.indexOf(line)).collect(Collectors.toList()); if (index.equals(index.stream().sorted().collect(Collectors.toList())) == false) { fail( "Expected the following lines to appear in this order:\n" + Stream.of(lines).map(line -> " - `" + line + "`").collect(Collectors.joining("\n")) + "\nTBut the order was different. Output is:\n\n```" + output + "\n```\n" ); } } protected void assertOutputContains(String output, Set<String> lines) { for (String line : lines) { assertOutputContains(output, line); } } protected void assertOutputContains(String output, String line) { assertThat("Expected the following line in output:\n\n" + line + "\n\nOutput is:\n" + output, output, containsString(line)); } protected void assertOutputMissing(String output, String line) { assertFalse("Expected the following line not to be in output:\n\n" + line + "\n\nOutput is:\n" + output, output.contains(line)); } protected void assertOutputMissing(String output, String... lines) { for (String line : lines) { assertOutputMissing(line); } } protected void assertTaskFailed(BuildResult result, String taskName) { assertTaskOutcome(result, taskName, TaskOutcome.FAILED); } protected void assertTaskSuccessful(BuildResult result, String... taskNames) { for (String taskName : taskNames) { assertTaskOutcome(result, taskName, TaskOutcome.SUCCESS); } } protected void assertTaskSkipped(BuildResult result, String... taskNames) { for (String taskName : taskNames) { assertTaskOutcome(result, taskName, TaskOutcome.SKIPPED); } } protected void assertTaskNoSource(BuildResult result, String... taskNames) { for (String taskName : taskNames) { assertTaskOutcome(result, taskName, TaskOutcome.NO_SOURCE); } } private void assertTaskOutcome(BuildResult result, String taskName, TaskOutcome taskOutcome) { BuildTask task = result.task(taskName); if (task == null) { fail( "Expected task `" + taskName + "` to be " + taskOutcome + ", but it did not run" + "\n\nOutput is:\n" + result.getOutput() ); } assertEquals( "Expected task `" + taskName + "` to be " + taskOutcome + " but it was: " + task.getOutcome() + "\n\nOutput is:\n" + result.getOutput(), taskOutcome, task.getOutcome() ); } protected void assertTaskUpToDate(BuildResult result, String... taskNames) { for (String taskName : taskNames) { BuildTask task = result.task(taskName); if (task == null) { fail("Expected task `" + taskName + "` to be up-to-date, but it did not run"); } assertEquals( "Expected task to be up to date but it was: " + task.getOutcome() + "\n\nOutput is:\n" + result.getOutput(), TaskOutcome.UP_TO_DATE, task.getOutcome() ); } } protected void assertNoDeprecationWarning(BuildResult result) { assertOutputMissing(result.getOutput(), "Deprecated Gradle features were used in this build"); } protected void assertBuildFileExists(BuildResult result, String projectName, String path) { Path absPath = getBuildDir(projectName).toPath().resolve(path); assertTrue( result.getOutput() + "\n\nExpected `" + absPath + "` to exists but it did not" + "\n\nOutput is:\n" + result.getOutput(), Files.exists(absPath) ); } protected void assertBuildFileDoesNotExists(BuildResult result, String projectName, String path) { Path absPath = getBuildDir(projectName).toPath().resolve(path); assertFalse( result.getOutput() + "\n\nExpected `" + absPath + "` bo to exists but it did" + "\n\nOutput is:\n" + result.getOutput(), Files.exists(absPath) ); } protected String getLocalTestDownloadsPath() { return getLocalTestPath("test.local-test-downloads-path"); } private String getLocalTestPath(String propertyName) { String property = System.getProperty(propertyName); Objects.requireNonNull(property, propertyName + " not passed to tests"); File file = new File(property); assertTrue("Expected " + property + " to exist, but it did not!", file.exists()); if (File.separator.equals("\\")) { // Use / on Windows too, the build script is not happy with \ return file.getAbsolutePath().replace(File.separator, "/"); } else { return file.getAbsolutePath(); } } public void assertOutputOnlyOnce(String output, String... text) { for (String each : text) { int i = output.indexOf(each); if (i == -1) { fail("Expected \n```" + each + "```\nto appear at most once, but it didn't at all.\n\nOutout is:\n" + output); } if (output.indexOf(each) != output.lastIndexOf(each)) { fail("Expected `" + each + "` to appear at most once, but it did multiple times.\n\nOutout is:\n" + output); } } } }
apache-2.0
WilliamNouet/nifi
nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/test/java/org/apache/nifi/web/security/jwt/JwtServiceTest.java
18241
/* * 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.nifi.web.security.jwt; import io.jsonwebtoken.JwtException; import org.apache.commons.codec.CharEncoding; import org.apache.commons.codec.binary.Base64; import org.apache.nifi.admin.service.AdministrationException; import org.apache.nifi.admin.service.KeyService; import org.apache.nifi.key.Key; import org.apache.nifi.web.security.token.LoginAuthenticationToken; import org.codehaus.jettison.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.LinkedHashMap; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; public class JwtServiceTest { private static final Logger logger = LoggerFactory.getLogger(JwtServiceTest.class); /** * These constant strings were generated using the tool at http://jwt.io */ private static final String VALID_SIGNED_TOKEN = "eyJhbGciOiJIUzI1NiJ9" + ".eyJzdWIiOiJhbG9wcmVzdG8iLCJpc3MiOiJNb2NrSWRlbnRpdHlQcm92aWRl" + "ciIsImF1ZCI6Ik1vY2tJZGVudGl0eVByb3ZpZGVyIiwicHJlZmVycmVkX3VzZ" + "XJuYW1lIjoiYWxvcHJlc3RvIiwia2lkIjoxLCJleHAiOjI0NDc4MDg3NjEsIm" + "lhdCI6MTQ0NzgwODcwMX0.r6aGZ6FNNYMOpcXW8BK2VYaQeX1uO0Aw1KJfjB3Q1DU"; // This token has an empty subject field private static final String INVALID_SIGNED_TOKEN = "eyJhbGciOiJIUzI1NiJ9" + ".eyJzdWIiOiIiLCJpc3MiOiJNb2NrSWRlbnRpdHlQcm92aWRlciIsImF1ZCI6Ik1vY2tJZG" + "VudGl0eVByb3ZpZGVyIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiYWxvcHJlc3RvI" + "iwia2lkIjoxLCJleHAiOjI0NDc4MDg3NjEsImlhdCI6MTQ0NzgwODcwMX0" + ".x_1p2M6E0vwWHWMujIUnSL3GkFoDqqICllRxo2SMNaw"; private static final String VALID_UNSIGNED_TOKEN = "eyJhbGciOiJIUzI1NiJ9" + ".eyJzdWIiOiJhbG9wcmVzdG8iLCJpc3MiOiJNb2NrSWRlbnRpdHlQcm92aWRlciIsImF1ZC" + "I6Ik1vY2tJZGVudGl0eVByb3ZpZGVyIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiYWxvcHJl" + "c3RvIiwia2lkIjoiYWxvcHJlc3RvIiwiZXhwIjoyNDQ3ODA4NzYxLCJpYXQiOjE0NDc4MDg3MDF9"; // This token has an empty subject field private static final String INVALID_UNSIGNED_TOKEN = "eyJhbGciOiJIUzI1NiJ9" + ".eyJzdWIiOiIiLCJpc3MiOiJNb2NrSWRlbnRpdHlQcm92aWRlciIsImF1ZCI6Ik1vY2tJZGVu" + "dGl0eVByb3ZpZGVyIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiYWxvcHJlc3RvIiwia2lkIjoi" + "YWxvcHJlc3RvIiwiZXhwIjoyNDQ3ODA4NzYxLCJpYXQiOjE0NDc4MDg3MDF9"; // Algorithm field is "none" private static final String VALID_MALSIGNED_TOKEN = "eyJhbGciOiJub25lIn0" + ".eyJzdWIiOiJhbG9wcmVzdG8iLCJpc3MiOiJNb2NrSWRlbnRpdHlQcm92aWRlciIsImF1ZC" + "I6Ik1vY2tJZGVudGl0eVByb3ZpZGVyIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiYWxvcHJl" + "c3RvIiwia2lkIjoiYWxvcHJlc3RvIiwiZXhwIjoxNDQ3ODA4NzYxLCJpYXQiOjE0NDc4MDg3MDF9" + ".mPO_wMNMl_zjMNevhNvUoXbSJ9Kx6jAe5OxDIAzKQbI"; // Algorithm field is "none" and no signature is present private static final String VALID_MALSIGNED_NO_SIG_TOKEN = "eyJhbGciOiJub25lIn0" + ".eyJzdWIiOiJhbG9wcmVzdG8iLCJpc3MiOiJNb2NrSWRlbnRpdHlQcm92aWRlciIsImF1ZCI6Ik1vY" + "2tJZGVudGl0eVByb3ZpZGVyIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiYWxvcHJlc3RvIiwia2lkIj" + "oiYWxvcHJlc3RvIiwiZXhwIjoyNDQ3ODA4NzYxLCJpYXQiOjE0NDc4MDg3MDF9."; // This token has an empty subject field private static final String INVALID_MALSIGNED_TOKEN = "eyJhbGciOiJIUzI1NiJ9" + ".eyJzdWIiOiIiLCJpc3MiOiJNb2NrSWRlbnRpdHlQcm92aWRlciIsImF1ZCI6Ik1vY2tJZGVud" + "Gl0eVByb3ZpZGVyIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiYWxvcHJlc3RvIiwia2lkIjoiYW" + "xvcHJlc3RvIiwiZXhwIjoxNDQ3ODA4NzYxLCJpYXQiOjE0NDc4MDg3MDF9.WAwmUY4KHKV2oARNodkqDkbZsfRXGZfD2Ccy64GX9QF"; // This token is signed but expired private static final String EXPIRED_SIGNED_TOKEN = "eyJhbGciOiJIUzI1NiJ9" + ".eyJzdWIiOiIiLCJpc3MiOiJNb2NrSWRlbnRpdHlQcm92aWRlciIsImF1ZCI6Ik" + "1vY2tJZGVudGl0eVByb3ZpZGVyIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiYWxvc" + "HJlc3RvIiwia2lkIjoxLCJleHAiOjE0NDc4MDg3NjEsImlhdCI6MTQ0NzgwODcw" + "MX0.ZPDIhNKuL89vTGXcuztOYaGifwcrQy_gid4j8Sspmto"; // Subject is "mgilman" but signed with "alopresto" key private static final String IMPOSTER_SIGNED_TOKEN = "eyJhbGciOiJIUzI1NiJ9" + ".eyJzdWIiOiJtZ2lsbWFuIiwiaXNzIjoiTW9ja0lkZW50aXR5UHJvdmlkZXIiLCJ" + "hdWQiOiJNb2NrSWRlbnRpdHlQcm92aWRlciIsInByZWZlcnJlZF91c2VybmFtZSI" + "6ImFsb3ByZXN0byIsImtpZCI6MSwiZXhwIjoyNDQ3ODA4NzYxLCJpYXQiOjE0NDc" + "4MDg3MDF9.aw5OAvLTnb_sHmSQOQzW-A7NImiZgXJ2ngbbNL2Ymkc"; // Issuer field is set to unknown provider private static final String UNKNOWN_ISSUER_TOKEN = "eyJhbGciOiJIUzI1NiJ9" + ".eyJzdWIiOiJhbG9wcmVzdG8iLCJpc3MiOiJVbmtub3duSWRlbnRpdHlQcm92aWRlciIsIm" + "F1ZCI6Ik1vY2tJZGVudGl0eVByb3ZpZGVyIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiYWxv" + "cHJlc3RvIiwia2lkIjoiYWxvcHJlc3RvIiwiZXhwIjoyNDQ3ODA4NzYxLCJpYXQiOjE0NDc4MDg3MDF9" + ".SAd9tyNwSaijWet9wvAWSNmpxmPSK4XQuLx7h3ARqBo"; // Issuer field is absent private static final String NO_ISSUER_TOKEN = "eyJhbGciOiJIUzI1NiJ9" + ".eyJzdWIiOiJhbG9wcmVzdG8iLCJhdWQiOiJNb2NrSWRlbnRpdHlQcm92a" + "WRlciIsInByZWZlcnJlZF91c2VybmFtZSI6ImFsb3ByZXN0byIsImtpZCI" + "6MSwiZXhwIjoyNDQ3ODA4NzYxLCJpYXQiOjE0NDc4MDg3MDF9.6kDjDanA" + "g0NQDb3C8FmgbBAYDoIfMAEkF4WMVALsbJA"; private static final String DEFAULT_HEADER = "{\"alg\":\"HS256\"}"; private static final String DEFAULT_IDENTITY = "alopresto"; private static final String TOKEN_DELIMITER = "."; private static final String HMAC_SECRET = "test_hmac_shared_secret"; private KeyService mockKeyService; // Class under test private JwtService jwtService; private String generateHS256Token(String rawHeader, String rawPayload, boolean isValid, boolean isSigned) { return generateHS256Token(rawHeader, rawPayload, HMAC_SECRET, isValid, isSigned); } private String generateHS256Token(String rawHeader, String rawPayload, String hmacSecret, boolean isValid, boolean isSigned) { try { logger.info("Generating token for " + rawHeader + " + " + rawPayload); String base64Header = Base64.encodeBase64URLSafeString(rawHeader.getBytes(CharEncoding.UTF_8)); String base64Payload = Base64.encodeBase64URLSafeString(rawPayload.getBytes(CharEncoding.UTF_8)); // TODO: Support valid/invalid manipulation final String body = base64Header + TOKEN_DELIMITER + base64Payload; String signature = generateHMAC(hmacSecret, body); return body + TOKEN_DELIMITER + signature; } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) { final String errorMessage = "Could not generate the token"; logger.error(errorMessage, e); fail(errorMessage); return null; } } private String generateHMAC(String hmacSecret, String body) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException { Mac hmacSHA256 = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(hmacSecret.getBytes("UTF-8"), "HmacSHA256"); hmacSHA256.init(secret_key); return Base64.encodeBase64URLSafeString(hmacSHA256.doFinal(body.getBytes("UTF-8"))); } @Before public void setUp() throws Exception { final Key key = new Key(); key.setId(1); key.setIdentity(DEFAULT_IDENTITY); key.setKey(HMAC_SECRET); mockKeyService = Mockito.mock(KeyService.class); when(mockKeyService.getKey(anyInt())).thenReturn(key); when(mockKeyService.getOrCreateKey(anyString())).thenReturn(key); jwtService = new JwtService(mockKeyService); } @After public void tearDown() throws Exception { } @Test public void testShouldGetAuthenticationForValidToken() throws Exception { // Arrange String token = VALID_SIGNED_TOKEN; // Act String identity = jwtService.getAuthenticationFromToken(token); logger.debug("Extracted identity: " + identity); // Assert assertEquals("Identity", DEFAULT_IDENTITY, identity); } @Test(expected = JwtException.class) public void testShouldNotGetAuthenticationForInvalidToken() throws Exception { // Arrange String token = INVALID_SIGNED_TOKEN; // Act String identity = jwtService.getAuthenticationFromToken(token); logger.debug("Extracted identity: " + identity); // Assert // Should fail } @Test(expected = JwtException.class) public void testShouldNotGetAuthenticationForEmptyToken() throws Exception { // Arrange String token = ""; // Act String identity = jwtService.getAuthenticationFromToken(token); logger.debug("Extracted identity: " + identity); // Assert // Should fail } @Test(expected = JwtException.class) public void testShouldNotGetAuthenticationForUnsignedToken() throws Exception { // Arrange String token = VALID_UNSIGNED_TOKEN; // Act String identity = jwtService.getAuthenticationFromToken(token); logger.debug("Extracted identity: " + identity); // Assert // Should fail } @Test(expected = JwtException.class) public void testShouldNotGetAuthenticationForMalsignedToken() throws Exception { // Arrange String token = VALID_MALSIGNED_TOKEN; // Act String identity = jwtService.getAuthenticationFromToken(token); logger.debug("Extracted identity: " + identity); // Assert // Should fail } @Test(expected = JwtException.class) public void testShouldNotGetAuthenticationForTokenWithWrongAlgorithm() throws Exception { // Arrange String token = VALID_MALSIGNED_TOKEN; // Act String identity = jwtService.getAuthenticationFromToken(token); logger.debug("Extracted identity: " + identity); // Assert // Should fail } @Test(expected = JwtException.class) public void testShouldNotGetAuthenticationForTokenWithWrongAlgorithmAndNoSignature() throws Exception { // Arrange String token = VALID_MALSIGNED_NO_SIG_TOKEN; // Act String identity = jwtService.getAuthenticationFromToken(token); logger.debug("Extracted identity: " + identity); // Assert // Should fail } @Ignore("Not yet implemented") @Test(expected = JwtException.class) public void testShouldNotGetAuthenticationForTokenFromUnknownIdentityProvider() throws Exception { // Arrange String token = UNKNOWN_ISSUER_TOKEN; // Act String identity = jwtService.getAuthenticationFromToken(token); logger.debug("Extracted identity: " + identity); // Assert // Should fail } @Test(expected = JwtException.class) public void testShouldNotGetAuthenticationForTokenFromEmptyIdentityProvider() throws Exception { // Arrange String token = NO_ISSUER_TOKEN; // Act String identity = jwtService.getAuthenticationFromToken(token); logger.debug("Extracted identity: " + identity); // Assert // Should fail } @Test(expected = JwtException.class) public void testShouldNotGetAuthenticationForExpiredToken() throws Exception { // Arrange String token = EXPIRED_SIGNED_TOKEN; // Act String identity = jwtService.getAuthenticationFromToken(token); logger.debug("Extracted identity: " + identity); // Assert // Should fail } @Test(expected = JwtException.class) public void testShouldNotGetAuthenticationForImposterToken() throws Exception { // Arrange String token = IMPOSTER_SIGNED_TOKEN; // Act String identity = jwtService.getAuthenticationFromToken(token); logger.debug("Extracted identity: " + identity); // Assert // Should fail } @Test public void testShouldGenerateSignedToken() throws Exception { // Arrange // Token expires in 60 seconds final int EXPIRATION_MILLIS = 60000; LoginAuthenticationToken loginAuthenticationToken = new LoginAuthenticationToken("alopresto", EXPIRATION_MILLIS, "MockIdentityProvider"); logger.debug("Generating token for " + loginAuthenticationToken); final String EXPECTED_HEADER = DEFAULT_HEADER; // Convert the expiration time from ms to s final long TOKEN_EXPIRATION_SEC = (long) (loginAuthenticationToken.getExpiration() / 1000.0); // Act String token = jwtService.generateSignedToken(loginAuthenticationToken); logger.debug("Generated JWT: " + token); // Run after the SUT generates the token to ensure the same issued at time // Split the token, decode the middle section, and form a new String final String DECODED_PAYLOAD = new String(Base64.decodeBase64(token.split("\\.")[1].getBytes())); final long ISSUED_AT_SEC = Long.valueOf(DECODED_PAYLOAD.substring(DECODED_PAYLOAD.lastIndexOf(":") + 1, DECODED_PAYLOAD.length() - 1)); logger.trace("Actual token was issued at " + ISSUED_AT_SEC); // Always use LinkedHashMap to enforce order of the keys because the signature depends on order Map<String, Object> claims = new LinkedHashMap<>(); claims.put("sub", "alopresto"); claims.put("iss", "MockIdentityProvider"); claims.put("aud", "MockIdentityProvider"); claims.put("preferred_username", "alopresto"); claims.put("kid", 1); claims.put("exp", TOKEN_EXPIRATION_SEC); claims.put("iat", ISSUED_AT_SEC); logger.trace("JSON Object to String: " + new JSONObject(claims).toString()); final String EXPECTED_PAYLOAD = new JSONObject(claims).toString(); final String EXPECTED_TOKEN_STRING = generateHS256Token(EXPECTED_HEADER, EXPECTED_PAYLOAD, true, true); logger.debug("Expected JWT: " + EXPECTED_TOKEN_STRING); // Assert assertEquals("JWT token", EXPECTED_TOKEN_STRING, token); } @Test(expected = IllegalArgumentException.class) public void testShouldNotGenerateTokenWithNullAuthenticationToken() throws Exception { // Arrange LoginAuthenticationToken nullLoginAuthenticationToken = null; logger.debug("Generating token for " + nullLoginAuthenticationToken); // Act jwtService.generateSignedToken(nullLoginAuthenticationToken); // Assert // Should throw exception } @Test(expected = JwtException.class) public void testShouldNotGenerateTokenWithEmptyIdentity() throws Exception { // Arrange final int EXPIRATION_MILLIS = 60000; LoginAuthenticationToken emptyIdentityLoginAuthenticationToken = new LoginAuthenticationToken("", EXPIRATION_MILLIS, "MockIdentityProvider"); logger.debug("Generating token for " + emptyIdentityLoginAuthenticationToken); // Act jwtService.generateSignedToken(emptyIdentityLoginAuthenticationToken); // Assert // Should throw exception } @Test(expected = JwtException.class) public void testShouldNotGenerateTokenWithNullIdentity() throws Exception { // Arrange final int EXPIRATION_MILLIS = 60000; LoginAuthenticationToken nullIdentityLoginAuthenticationToken = new LoginAuthenticationToken(null, EXPIRATION_MILLIS, "MockIdentityProvider"); logger.debug("Generating token for " + nullIdentityLoginAuthenticationToken); // Act jwtService.generateSignedToken(nullIdentityLoginAuthenticationToken); // Assert // Should throw exception } @Test(expected = JwtException.class) public void testShouldNotGenerateTokenWithMissingKey() throws Exception { // Arrange final int EXPIRATION_MILLIS = 60000; LoginAuthenticationToken loginAuthenticationToken = new LoginAuthenticationToken("alopresto", EXPIRATION_MILLIS, "MockIdentityProvider"); logger.debug("Generating token for " + loginAuthenticationToken); // Set up the bad key service KeyService missingKeyService = Mockito.mock(KeyService.class); when(missingKeyService.getOrCreateKey(anyString())).thenThrow(new AdministrationException("Could not find a " + "key for that user")); jwtService = new JwtService(missingKeyService); // Act jwtService.generateSignedToken(loginAuthenticationToken); // Assert // Should throw exception } }
apache-2.0
goodwinnk/intellij-community
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XValueWithInlinePresentation.java
907
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.xdebugger.impl.frame; import org.jetbrains.annotations.Nullable; public interface XValueWithInlinePresentation { /** * Value to be shown near variable in execution line (experimental feature). Should be calculated fast. */ @Nullable String computeInlinePresentation(); }
apache-2.0
PommeVerte/incubator-tinkerpop
gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/SackStepTest.java
1354
/* * 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.tinkerpop.gremlin.process.traversal.step.map; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; import org.apache.tinkerpop.gremlin.process.traversal.step.StepTest; import java.util.Collections; import java.util.List; /** * @author Daniel Kuppitz (http://gremlin.guru) */ public class SackStepTest extends StepTest { @Override protected List<Traversal> getTraversals() { return Collections.singletonList(__.sack()); } }
apache-2.0
rokn/Count_Words_2015
testing/openjdk/jdk/test/sun/security/pkcs11/ec/ReadCertificates.java
5575
/* * Copyright (c) 2006, 2007, 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 6405536 6414980 * @summary Make sure that we can parse certificates using various named curves * and verify their signatures * @author Andreas Sterbenz * @library .. */ import java.io.*; import java.util.*; import java.security.cert.*; import java.security.*; import java.security.interfaces.*; import javax.security.auth.x500.X500Principal; public class ReadCertificates extends PKCS11Test { private static CertificateFactory factory; private static SecureRandom random; private static Collection<X509Certificate> readCertificates(File file) throws Exception { System.out.println("Loading " + file.getName() + "..."); InputStream in = new FileInputStream(file); Collection<X509Certificate> certs = (Collection<X509Certificate>)factory.generateCertificates(in); in.close(); return certs; } public static void main(String[] args) throws Exception { main(new ReadCertificates()); } public void main(Provider p) throws Exception { if (p.getService("Signature", "SHA1withECDSA") == null) { System.out.println("Provider does not support ECDSA, skipping..."); return; } Security.insertProviderAt(p, 1); random = new SecureRandom(); factory = CertificateFactory.getInstance("X.509"); try { // clear certificate cache in from a previous run with a different // provider (undocumented hack for the Sun provider) factory.generateCertificate(null); } catch (CertificateException e) { // ignore } Map<X500Principal,X509Certificate> certs = new LinkedHashMap<X500Principal,X509Certificate>(); File dir = new File(BASE, "certs"); File closedDir = new File(CLOSED_BASE, "certs"); File[] files = concat(dir.listFiles(), closedDir.listFiles()); Arrays.sort(files); for (File file : files) { if (file.isFile() == false) { continue; } Collection<X509Certificate> certList = readCertificates(file); for (X509Certificate cert : certList) { X509Certificate old = certs.put(cert.getSubjectX500Principal(), cert); if (old != null) { System.out.println("Duplicate subject:"); System.out.println("Old Certificate: " + old); System.out.println("New Certificate: " + cert); throw new Exception(file.getPath()); } } } System.out.println("OK: " + certs.size() + " certificates."); for (X509Certificate cert : certs.values()) { X509Certificate issuer = certs.get(cert.getIssuerX500Principal()); System.out.println("Verifying " + cert.getSubjectX500Principal() + "..."); PublicKey key = issuer.getPublicKey(); // First try the provider under test (if it does not support the // necessary algorithm then try any registered provider). try { cert.verify(key, p.getName()); } catch (NoSuchAlgorithmException e) { System.out.println("Warning: " + e.getMessage() + ". Trying another provider..."); cert.verify(key); } } // try some random invalid signatures to make sure we get the correct // error System.out.println("Checking incorrect signatures..."); List<X509Certificate> certList = new ArrayList<X509Certificate>(certs.values()); for (int i = 0; i < 20; i++) { X509Certificate cert, signer; do { cert = getRandomCert(certList); signer = getRandomCert(certList); } while (cert.getIssuerX500Principal().equals(signer.getSubjectX500Principal())); try { cert.verify(signer.getPublicKey()); throw new Exception("Verified invalid signature"); } catch (SignatureException e) { System.out.println("OK: " + e); } catch (InvalidKeyException e) { System.out.println("OK: " + e); } } Security.removeProvider(p.getName()); System.out.println("OK"); } private static X509Certificate getRandomCert(List<X509Certificate> certs) { int n = random.nextInt(certs.size()); return certs.get(n); } }
mit
paolodenti/openhab
bundles/binding/org.openhab.binding.denon/src/main/java/org/openhab/binding/denon/internal/communication/entities/commands/AppCommandResponse.java
1177
/** * Copyright (c) 2010-2016, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.denon.internal.communication.entities.commands; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * Response to an {@link AppCommandRequest}, wraps a list of {@link CommandRx} * * @author Jeroen Idserda * @since 1.7.0 */ @XmlRootElement(name = "rx") @XmlAccessorType(XmlAccessType.FIELD) public class AppCommandResponse { @XmlElement(name = "cmd") private List<CommandRx> commands = new ArrayList<CommandRx>(); public AppCommandResponse() { } public List<CommandRx> getCommands() { return commands; } public void setCommands(List<CommandRx> commands) { this.commands = commands; } }
epl-1.0
davidsan/one
test/DistanceDelayReportTest.java
2292
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package test; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Vector; import junit.framework.TestCase; import report.DistanceDelayReport; import core.Coord; import core.DTNHost; import core.Message; import core.MessageListener; import core.SimClock; public class DistanceDelayReportTest extends TestCase { private SimClock clock; File outFile; private Vector<MessageListener> ml; private DistanceDelayReport r; private TestUtils utils; public void setUp() throws IOException { final String NS = "DistanceDelayReport."; TestSettings ts = new TestSettings(); outFile = File.createTempFile("ddrtest", ".tmp"); outFile.deleteOnExit(); ts.putSetting(NS + "output", outFile.getAbsolutePath()); ts.putSetting(NS + report.Report.PRECISION_SETTING, "1"); clock = SimClock.getInstance(); r = new DistanceDelayReport(); ml = new Vector<MessageListener>(); ml.add(r); this.utils = new TestUtils(null, ml, ts); } public void testMessageTransferred() throws IOException { DTNHost h1 = utils.createHost(new Coord(0,0)); DTNHost h2 = utils.createHost(new Coord(2,0)); DTNHost h3 = utils.createHost(new Coord(0,5)); BufferedReader reader; Message m1 = new Message(h1, h2, "tst1", 1); h1.createNewMessage(m1); clock.advance(1.5); h1.sendMessage("tst1", h2); h2.messageTransferred("tst1", h1); Message m2 = new Message(h2,h1, "tst2", 1); h2.createNewMessage(m2); clock.advance(0.5); h2.sendMessage("tst2", h1); h1.messageTransferred("tst2", h2); Message m3 = new Message(h1,h3, "tst3", 1); h1.createNewMessage(m3); clock.advance(1.0); h1.sendMessage("tst3", h2); h2.messageTransferred("tst3", h1); h2.sendMessage("tst3", h3); h3.messageTransferred("tst3", h2); r.done(); reader = new BufferedReader(new FileReader(outFile)); reader.readLine(); // skip headers reader.readLine(); // skip headers assertEquals("2.0 1.5 1 tst1",reader.readLine()); assertEquals("2.0 0.5 1 tst2",reader.readLine()); assertEquals("5.0 1.0 2 tst3",reader.readLine()); } }
gpl-3.0
JuudeDemos/android-sdk-20
src/android/os/SystemPropertiesTest.java
1639
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.os; import static junit.framework.Assert.assertEquals; import junit.framework.TestCase; import android.os.SystemProperties; import android.test.suitebuilder.annotation.SmallTest; public class SystemPropertiesTest extends TestCase { private static final String KEY = "com.android.frameworks.coretests"; @SmallTest public void testProperties() throws Exception { if (false) { String value; SystemProperties.set(KEY, ""); value = SystemProperties.get(KEY, "default"); assertEquals("default", value); SystemProperties.set(KEY, "AAA"); value = SystemProperties.get(KEY, "default"); assertEquals("AAA", value); value = SystemProperties.get(KEY); assertEquals("AAA", value); SystemProperties.set(KEY, ""); value = SystemProperties.get(KEY, "default"); assertEquals("default", value); value = SystemProperties.get(KEY); assertEquals("", value); } } }
apache-2.0
d/bazel
src/main/java/com/google/devtools/build/lib/actions/NotifyOnActionCacheHit.java
1040
// Copyright 2014 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.actions; /** * An action which must know when it is skipped due to an action cache hit. * * Use should be rare, as the action graph is a functional model. */ public interface NotifyOnActionCacheHit extends Action { /** * Called when action has "cache hit", and therefore need not be executed. * * @param executor the executor */ void actionCacheHit(Executor executor); }
apache-2.0
asedunov/intellij-community
plugins/InspectionGadgets/testsrc/com/siyeh/ig/threading/AtomicFieldUpdaterNotStaticFinalInspectionTest.java
1812
/* * Copyright 2000-2015 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.siyeh.ig.threading; import com.intellij.codeInspection.InspectionProfileEntry; import com.siyeh.ig.LightInspectionTestCase; import org.jetbrains.annotations.Nullable; /** * @author Bas Leijdekkers */ @SuppressWarnings("AtomicFieldUpdaterNotStaticFinal") public class AtomicFieldUpdaterNotStaticFinalInspectionTest extends LightInspectionTestCase { public void testSimple() { doTest("import java.util.concurrent.atomic.AtomicLongFieldUpdater;" + "class A {" + " private volatile long l = 0;" + " private AtomicLongFieldUpdater /*AtomicLongFieldUpdater field 'updater' is not declared 'static final'*/updater/**/ = AtomicLongFieldUpdater.newUpdater(A.class, \"l\");" + "}"); } public void testNoWarning() { doTest("import java.util.concurrent.atomic.AtomicLongFieldUpdater;" + "class A {" + " private volatile long l = 0;" + " private static final AtomicLongFieldUpdater updater = AtomicLongFieldUpdater.newUpdater(A.class, \"l\");" + "}"); } @Nullable @Override protected InspectionProfileEntry getInspection() { return new AtomicFieldUpdaterNotStaticFinalInspection(); } }
apache-2.0
mirego/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/ElemNumber.java
69751
/* * 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. */ /* * $Id: ElemNumber.java 468643 2006-10-28 06:56:03Z minchau $ */ package org.apache.xalan.templates; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.Locale; import java.util.NoSuchElementException; import javax.xml.transform.TransformerException; import org.apache.xalan.res.XSLTErrorResources; import org.apache.xalan.transformer.CountersTable; import org.apache.xalan.transformer.DecimalToRoman; import org.apache.xalan.transformer.TransformerImpl; import org.apache.xml.dtm.DTM; import org.apache.xml.utils.FastStringBuffer; import org.apache.xml.utils.NodeVector; import org.apache.xml.utils.PrefixResolver; import org.apache.xml.utils.StringBufferPool; import org.apache.xml.utils.res.XResourceBundle; import org.apache.xml.utils.res.CharArrayWrapper; import org.apache.xml.utils.res.IntArrayWrapper; import org.apache.xml.utils.res.LongArrayWrapper; import org.apache.xml.utils.res.StringArrayWrapper; import org.apache.xpath.NodeSetDTM; import org.apache.xpath.XPath; import org.apache.xpath.XPathContext; import org.apache.xpath.objects.XObject; import org.w3c.dom.Node; import org.xml.sax.SAXException; // import org.apache.xalan.dtm.*; /** * Implement xsl:number. * <pre> * <!ELEMENT xsl:number EMPTY> * <!ATTLIST xsl:number * level (single|multiple|any) "single" * count %pattern; #IMPLIED * from %pattern; #IMPLIED * value %expr; #IMPLIED * format %avt; '1' * lang %avt; #IMPLIED * letter-value %avt; #IMPLIED * grouping-separator %avt; #IMPLIED * grouping-size %avt; #IMPLIED * > * </pre> * @see <a href="http://www.w3.org/TR/xslt#number">number in XSLT Specification</a> * @xsl.usage advanced */ public class ElemNumber extends ElemTemplateElement { static final long serialVersionUID = 8118472298274407610L; /** * Chars for converting integers into alpha counts. * @see TransformerImpl#int2alphaCount */ private CharArrayWrapper m_alphaCountTable = null; private class MyPrefixResolver implements PrefixResolver { DTM dtm; int handle; boolean handleNullPrefix; /** * Constructor for MyPrefixResolver. * @param xpathExpressionContext */ public MyPrefixResolver(Node xpathExpressionContext, DTM dtm, int handle, boolean handleNullPrefix) { this.dtm = dtm; this.handle = handle; this.handleNullPrefix = handleNullPrefix; } /** * @see PrefixResolver#getNamespaceForPrefix(String, Node) */ public String getNamespaceForPrefix(String prefix) { return dtm.getNamespaceURI(handle); } /** * @see PrefixResolver#getNamespaceForPrefix(String, Node) * this shouldn't get called. */ public String getNamespaceForPrefix(String prefix, Node context) { return getNamespaceForPrefix(prefix); } /** * @see PrefixResolver#getBaseIdentifier() */ public String getBaseIdentifier() { return ElemNumber.this.getBaseIdentifier(); } /** * @see PrefixResolver#handlesNullPrefixes() */ public boolean handlesNullPrefixes() { return handleNullPrefix; } } /** * Only nodes are counted that match this pattern. * @serial */ private XPath m_countMatchPattern = null; /** * Set the "count" attribute. * The count attribute is a pattern that specifies what nodes * should be counted at those levels. If count attribute is not * specified, then it defaults to the pattern that matches any * node with the same node type as the current node and, if the * current node has an expanded-name, with the same expanded-name * as the current node. * * @param v Value to set for "count" attribute. */ public void setCount(XPath v) { m_countMatchPattern = v; } /** * Get the "count" attribute. * The count attribute is a pattern that specifies what nodes * should be counted at those levels. If count attribute is not * specified, then it defaults to the pattern that matches any * node with the same node type as the current node and, if the * current node has an expanded-name, with the same expanded-name * as the current node. * * @return Value of "count" attribute. */ public XPath getCount() { return m_countMatchPattern; } /** * Specifies where to count from. * For level="single" or level="multiple": * Only ancestors that are searched are * those that are descendants of the nearest ancestor that matches * the from pattern. * For level="any: * Only nodes after the first node before the * current node that match the from pattern are considered. * @serial */ private XPath m_fromMatchPattern = null; /** * Set the "from" attribute. Specifies where to count from. * For level="single" or level="multiple": * Only ancestors that are searched are * those that are descendants of the nearest ancestor that matches * the from pattern. * For level="any: * Only nodes after the first node before the * current node that match the from pattern are considered. * * @param v Value to set for "from" attribute. */ public void setFrom(XPath v) { m_fromMatchPattern = v; } /** * Get the "from" attribute. * For level="single" or level="multiple": * Only ancestors that are searched are * those that are descendants of the nearest ancestor that matches * the from pattern. * For level="any: * Only nodes after the first node before the * current node that match the from pattern are considered. * * @return Value of "from" attribute. */ public XPath getFrom() { return m_fromMatchPattern; } /** * When level="single", it goes up to the first node in the ancestor-or-self axis * that matches the count pattern, and constructs a list of length one containing * one plus the number of preceding siblings of that ancestor that match the count * pattern. If there is no such ancestor, it constructs an empty list. If the from * attribute is specified, then the only ancestors that are searched are those * that are descendants of the nearest ancestor that matches the from pattern. * Preceding siblings has the same meaning here as with the preceding-sibling axis. * * When level="multiple", it constructs a list of all ancestors of the current node * in document order followed by the element itself; it then selects from the list * those nodes that match the count pattern; it then maps each node in the list to * one plus the number of preceding siblings of that node that match the count pattern. * If the from attribute is specified, then the only ancestors that are searched are * those that are descendants of the nearest ancestor that matches the from pattern. * Preceding siblings has the same meaning here as with the preceding-sibling axis. * * When level="any", it constructs a list of length one containing the number of * nodes that match the count pattern and belong to the set containing the current * node and all nodes at any level of the document that are before the current node * in document order, excluding any namespace and attribute nodes (in other words * the union of the members of the preceding and ancestor-or-self axes). If the * from attribute is specified, then only nodes after the first node before the * current node that match the from pattern are considered. * @serial */ private int m_level = Constants.NUMBERLEVEL_SINGLE; /** * Set the "level" attribute. * The level attribute specifies what levels of the source tree should * be considered; it has the values single, multiple or any. The default * is single. * * @param v Value to set for "level" attribute. */ public void setLevel(int v) { m_level = v; } /** * Get the "level" attribute. * The level attribute specifies what levels of the source tree should * be considered; it has the values single, multiple or any. The default * is single. * * @return Value of "level" attribute. */ public int getLevel() { return m_level; } /** * The value attribute contains an expression. The expression is evaluated * and the resulting object is converted to a number as if by a call to the * number function. * @serial */ private XPath m_valueExpr = null; /** * Set the "value" attribute. * The value attribute contains an expression. The expression is evaluated * and the resulting object is converted to a number as if by a call to the * number function. * * @param v Value to set for "value" attribute. */ public void setValue(XPath v) { m_valueExpr = v; } /** * Get the "value" attribute. * The value attribute contains an expression. The expression is evaluated * and the resulting object is converted to a number as if by a call to the * number function. * * @return Value of "value" attribute. */ public XPath getValue() { return m_valueExpr; } /** * The "format" attribute is used to control conversion of a list of * numbers into a string. * @see <a href="http://www.w3.org/TR/xslt#convert">convert in XSLT Specification</a> * @serial */ private AVT m_format_avt = null; /** * Set the "format" attribute. * The "format" attribute is used to control conversion of a list of * numbers into a string. * @see <a href="http://www.w3.org/TR/xslt#convert">convert in XSLT Specification</a> * * @param v Value to set for "format" attribute. */ public void setFormat(AVT v) { m_format_avt = v; } /** * Get the "format" attribute. * The "format" attribute is used to control conversion of a list of * numbers into a string. * @see <a href="http://www.w3.org/TR/xslt#convert">convert in XSLT Specification</a> * * @return Value of "format" attribute. */ public AVT getFormat() { return m_format_avt; } /** * When numbering with an alphabetic sequence, the lang attribute * specifies which language's alphabet is to be used. * @serial */ private AVT m_lang_avt = null; /** * Set the "lang" attribute. * When numbering with an alphabetic sequence, the lang attribute * specifies which language's alphabet is to be used; it has the same * range of values as xml:lang [XML]; if no lang value is specified, * the language should be determined from the system environment. * Implementers should document for which languages they support numbering. * @see <a href="http://www.w3.org/TR/xslt#convert">convert in XSLT Specification</a> * * @param v Value to set for "lang" attribute. */ public void setLang(AVT v) { m_lang_avt = v; } /** * Get the "lang" attribute. * When numbering with an alphabetic sequence, the lang attribute * specifies which language's alphabet is to be used; it has the same * range of values as xml:lang [XML]; if no lang value is specified, * the language should be determined from the system environment. * Implementers should document for which languages they support numbering. * @see <a href="http://www.w3.org/TR/xslt#convert">convert in XSLT Specification</a> * * @return Value ofr "lang" attribute. */ public AVT getLang() { return m_lang_avt; } /** * The letter-value attribute disambiguates between numbering * sequences that use letters. * @serial */ private AVT m_lettervalue_avt = null; /** * Set the "letter-value" attribute. * The letter-value attribute disambiguates between numbering sequences * that use letters. * @see <a href="http://www.w3.org/TR/xslt#convert">convert in XSLT Specification</a> * * @param v Value to set for "letter-value" attribute. */ public void setLetterValue(AVT v) { m_lettervalue_avt = v; } /** * Get the "letter-value" attribute. * The letter-value attribute disambiguates between numbering sequences * that use letters. * @see <a href="http://www.w3.org/TR/xslt#convert">convert in XSLT Specification</a> * * @return Value to set for "letter-value" attribute. */ public AVT getLetterValue() { return m_lettervalue_avt; } /** * The grouping-separator attribute gives the separator * used as a grouping (e.g. thousands) separator in decimal * numbering sequences. * @serial */ private AVT m_groupingSeparator_avt = null; /** * Set the "grouping-separator" attribute. * The grouping-separator attribute gives the separator * used as a grouping (e.g. thousands) separator in decimal * numbering sequences. * @see <a href="http://www.w3.org/TR/xslt#convert">convert in XSLT Specification</a> * * @param v Value to set for "grouping-separator" attribute. */ public void setGroupingSeparator(AVT v) { m_groupingSeparator_avt = v; } /** * Get the "grouping-separator" attribute. * The grouping-separator attribute gives the separator * used as a grouping (e.g. thousands) separator in decimal * numbering sequences. * @see <a href="http://www.w3.org/TR/xslt#convert">convert in XSLT Specification</a> * * @return Value of "grouping-separator" attribute. */ public AVT getGroupingSeparator() { return m_groupingSeparator_avt; } /** * The optional grouping-size specifies the size (normally 3) of the grouping. * @serial */ private AVT m_groupingSize_avt = null; /** * Set the "grouping-size" attribute. * The optional grouping-size specifies the size (normally 3) of the grouping. * @see <a href="http://www.w3.org/TR/xslt#convert">convert in XSLT Specification</a> * * @param v Value to set for "grouping-size" attribute. */ public void setGroupingSize(AVT v) { m_groupingSize_avt = v; } /** * Get the "grouping-size" attribute. * The optional grouping-size specifies the size (normally 3) of the grouping. * @see <a href="http://www.w3.org/TR/xslt#convert">convert in XSLT Specification</a> * * @return Value of "grouping-size" attribute. */ public AVT getGroupingSize() { return m_groupingSize_avt; } /** * Shouldn't this be in the transformer? Big worries about threads... */ // private XResourceBundle thisBundle; /** * Table to help in converting decimals to roman numerals. * @see org.apache.xalan.transformer.DecimalToRoman */ private final static DecimalToRoman m_romanConvertTable[] = { new DecimalToRoman(1000, "M", 900, "CM"), new DecimalToRoman(500, "D", 400, "CD"), new DecimalToRoman(100L, "C", 90L, "XC"), new DecimalToRoman(50L, "L", 40L, "XL"), new DecimalToRoman(10L, "X", 9L, "IX"), new DecimalToRoman(5L, "V", 4L, "IV"), new DecimalToRoman(1L, "I", 1L, "I") }; /** * This function is called after everything else has been * recomposed, and allows the template to set remaining * values that may be based on some other property that * depends on recomposition. */ public void compose(StylesheetRoot sroot) throws TransformerException { super.compose(sroot); StylesheetRoot.ComposeState cstate = sroot.getComposeState(); java.util.Vector vnames = cstate.getVariableNames(); if(null != m_countMatchPattern) m_countMatchPattern.fixupVariables(vnames, cstate.getGlobalsSize()); if(null != m_format_avt) m_format_avt.fixupVariables(vnames, cstate.getGlobalsSize()); if(null != m_fromMatchPattern) m_fromMatchPattern.fixupVariables(vnames, cstate.getGlobalsSize()); if(null != m_groupingSeparator_avt) m_groupingSeparator_avt.fixupVariables(vnames, cstate.getGlobalsSize()); if(null != m_groupingSize_avt) m_groupingSize_avt.fixupVariables(vnames, cstate.getGlobalsSize()); if(null != m_lang_avt) m_lang_avt.fixupVariables(vnames, cstate.getGlobalsSize()); if(null != m_lettervalue_avt) m_lettervalue_avt.fixupVariables(vnames, cstate.getGlobalsSize()); if(null != m_valueExpr) m_valueExpr.fixupVariables(vnames, cstate.getGlobalsSize()); } /** * Get an int constant identifying the type of element. * @see org.apache.xalan.templates.Constants * * @return The token ID for this element */ public int getXSLToken() { return Constants.ELEMNAME_NUMBER; } /** * Return the node name. * * @return The element's name */ public String getNodeName() { return Constants.ELEMNAME_NUMBER_STRING; } /** * Execute an xsl:number instruction. The xsl:number element is * used to insert a formatted number into the result tree. * * @param transformer non-null reference to the the current transform-time state. * * @throws TransformerException */ public void execute( TransformerImpl transformer) throws TransformerException { int sourceNode = transformer.getXPathContext().getCurrentNode(); String countString = getCountString(transformer, sourceNode); try { transformer.getResultTreeHandler().characters(countString.toCharArray(), 0, countString.length()); } catch(SAXException se) { throw new TransformerException(se); } } /** * Add a child to the child list. * * @param newChild Child to add to child list * * @return Child just added to child list * * @throws DOMException */ public ElemTemplateElement appendChild(ElemTemplateElement newChild) { error(XSLTErrorResources.ER_CANNOT_ADD, new Object[]{ newChild.getNodeName(), this.getNodeName() }); //"Can not add " +((ElemTemplateElement)newChild).m_elemName + //" to " + this.m_elemName); return null; } /** * Given a 'from' pattern (ala xsl:number), a match pattern * and a context, find the first ancestor that matches the * pattern (including the context handed in). * * @param xctxt The XPath runtime state for this. * @param fromMatchPattern The ancestor must match this pattern. * @param countMatchPattern The ancestor must also match this pattern. * @param context The node that "." expresses. * @param namespaceContext The context in which namespaces in the * queries are supposed to be expanded. * * @return the first ancestor that matches the given pattern * * @throws javax.xml.transform.TransformerException */ int findAncestor( XPathContext xctxt, XPath fromMatchPattern, XPath countMatchPattern, int context, ElemNumber namespaceContext) throws javax.xml.transform.TransformerException { DTM dtm = xctxt.getDTM(context); while (DTM.NULL != context) { if (null != fromMatchPattern) { if (fromMatchPattern.getMatchScore(xctxt, context) != XPath.MATCH_SCORE_NONE) { //context = null; break; } } if (null != countMatchPattern) { if (countMatchPattern.getMatchScore(xctxt, context) != XPath.MATCH_SCORE_NONE) { break; } } context = dtm.getParent(context); } return context; } /** * Given a 'from' pattern (ala xsl:number), a match pattern * and a context, find the first ancestor that matches the * pattern (including the context handed in). * @param xctxt The XPath runtime state for this. * @param fromMatchPattern The ancestor must match this pattern. * @param countMatchPattern The ancestor must also match this pattern. * @param context The node that "." expresses. * @param namespaceContext The context in which namespaces in the * queries are supposed to be expanded. * * @return the first preceding, ancestor or self node that * matches the given pattern * * @throws javax.xml.transform.TransformerException */ private int findPrecedingOrAncestorOrSelf( XPathContext xctxt, XPath fromMatchPattern, XPath countMatchPattern, int context, ElemNumber namespaceContext) throws javax.xml.transform.TransformerException { DTM dtm = xctxt.getDTM(context); while (DTM.NULL != context) { if (null != fromMatchPattern) { if (fromMatchPattern.getMatchScore(xctxt, context) != XPath.MATCH_SCORE_NONE) { context = DTM.NULL; break; } } if (null != countMatchPattern) { if (countMatchPattern.getMatchScore(xctxt, context) != XPath.MATCH_SCORE_NONE) { break; } } int prevSibling = dtm.getPreviousSibling(context); if (DTM.NULL == prevSibling) { context = dtm.getParent(context); } else { // Now go down the chain of children of this sibling context = dtm.getLastChild(prevSibling); if (context == DTM.NULL) context = prevSibling; } } return context; } /** * Get the count match pattern, or a default value. * * @param support The XPath runtime state for this. * @param contextNode The node that "." expresses. * * @return the count match pattern, or a default value. * * @throws javax.xml.transform.TransformerException */ XPath getCountMatchPattern(XPathContext support, int contextNode) throws javax.xml.transform.TransformerException { XPath countMatchPattern = m_countMatchPattern; DTM dtm = support.getDTM(contextNode); if (null == countMatchPattern) { switch (dtm.getNodeType(contextNode)) { case DTM.ELEMENT_NODE : MyPrefixResolver resolver; if (dtm.getNamespaceURI(contextNode) == null) { resolver = new MyPrefixResolver(dtm.getNode(contextNode), dtm,contextNode, false); } else { resolver = new MyPrefixResolver(dtm.getNode(contextNode), dtm,contextNode, true); } countMatchPattern = new XPath(dtm.getNodeName(contextNode), this, resolver, XPath.MATCH, support.getErrorListener()); break; case DTM.ATTRIBUTE_NODE : // countMatchPattern = m_stylesheet.createMatchPattern("@"+contextNode.getNodeName(), this); countMatchPattern = new XPath("@" + dtm.getNodeName(contextNode), this, this, XPath.MATCH, support.getErrorListener()); break; case DTM.CDATA_SECTION_NODE : case DTM.TEXT_NODE : // countMatchPattern = m_stylesheet.createMatchPattern("text()", this); countMatchPattern = new XPath("text()", this, this, XPath.MATCH, support.getErrorListener()); break; case DTM.COMMENT_NODE : // countMatchPattern = m_stylesheet.createMatchPattern("comment()", this); countMatchPattern = new XPath("comment()", this, this, XPath.MATCH, support.getErrorListener()); break; case DTM.DOCUMENT_NODE : // countMatchPattern = m_stylesheet.createMatchPattern("/", this); countMatchPattern = new XPath("/", this, this, XPath.MATCH, support.getErrorListener()); break; case DTM.PROCESSING_INSTRUCTION_NODE : // countMatchPattern = m_stylesheet.createMatchPattern("pi("+contextNode.getNodeName()+")", this); countMatchPattern = new XPath("pi(" + dtm.getNodeName(contextNode) + ")", this, this, XPath.MATCH, support.getErrorListener()); break; default : countMatchPattern = null; } } return countMatchPattern; } /** * Given an XML source node, get the count according to the * parameters set up by the xsl:number attributes. * @param transformer non-null reference to the the current transform-time state. * @param sourceNode The source node being counted. * * @return The count of nodes * * @throws TransformerException */ String getCountString(TransformerImpl transformer, int sourceNode) throws TransformerException { long[] list = null; XPathContext xctxt = transformer.getXPathContext(); CountersTable ctable = transformer.getCountersTable(); if (null != m_valueExpr) { XObject countObj = m_valueExpr.execute(xctxt, sourceNode, this); //According to Errata E24 double d_count = java.lang.Math.floor(countObj.num()+ 0.5); if (Double.isNaN(d_count)) return "NaN"; else if (d_count < 0 && Double.isInfinite(d_count)) return "-Infinity"; else if (Double.isInfinite(d_count)) return "Infinity"; else if (d_count == 0) return "0"; else{ long count = (long)d_count; list = new long[1]; list[0] = count; } } else { if (Constants.NUMBERLEVEL_ANY == m_level) { list = new long[1]; list[0] = ctable.countNode(xctxt, this, sourceNode); } else { NodeVector ancestors = getMatchingAncestors(xctxt, sourceNode, Constants.NUMBERLEVEL_SINGLE == m_level); int lastIndex = ancestors.size() - 1; if (lastIndex >= 0) { list = new long[lastIndex + 1]; for (int i = lastIndex; i >= 0; i--) { int target = ancestors.elementAt(i); list[lastIndex - i] = ctable.countNode(xctxt, this, target); } } } } return (null != list) ? formatNumberList(transformer, list, sourceNode) : ""; } /** * Get the previous node to be counted. * * @param xctxt The XPath runtime state for this. * @param pos The current node * * @return the previous node to be counted. * * @throws TransformerException */ public int getPreviousNode(XPathContext xctxt, int pos) throws TransformerException { XPath countMatchPattern = getCountMatchPattern(xctxt, pos); DTM dtm = xctxt.getDTM(pos); if (Constants.NUMBERLEVEL_ANY == m_level) { XPath fromMatchPattern = m_fromMatchPattern; // Do a backwards document-order walk 'till a node is found that matches // the 'from' pattern, or a node is found that matches the 'count' pattern, // or the top of the tree is found. while (DTM.NULL != pos) { // Get the previous sibling, if there is no previous sibling, // then count the parent, but if there is a previous sibling, // dive down to the lowest right-hand (last) child of that sibling. int next = dtm.getPreviousSibling(pos); if (DTM.NULL == next) { next = dtm.getParent(pos); if ((DTM.NULL != next) && ((((null != fromMatchPattern) && (fromMatchPattern.getMatchScore( xctxt, next) != XPath.MATCH_SCORE_NONE))) || (dtm.getNodeType(next) == DTM.DOCUMENT_NODE))) { pos = DTM.NULL; // return null from function. break; // from while loop } } else { // dive down to the lowest right child. int child = next; while (DTM.NULL != child) { child = dtm.getLastChild(next); if (DTM.NULL != child) next = child; } } pos = next; if ((DTM.NULL != pos) && ((null == countMatchPattern) || (countMatchPattern.getMatchScore(xctxt, pos) != XPath.MATCH_SCORE_NONE))) { break; } } } else // NUMBERLEVEL_MULTI or NUMBERLEVEL_SINGLE { while (DTM.NULL != pos) { pos = dtm.getPreviousSibling(pos); if ((DTM.NULL != pos) && ((null == countMatchPattern) || (countMatchPattern.getMatchScore(xctxt, pos) != XPath.MATCH_SCORE_NONE))) { break; } } } return pos; } /** * Get the target node that will be counted.. * * @param xctxt The XPath runtime state for this. * @param sourceNode non-null reference to the <a href="http://www.w3.org/TR/xslt#dt-current-node">current source node</a>. * * @return the target node that will be counted * * @throws TransformerException */ public int getTargetNode(XPathContext xctxt, int sourceNode) throws TransformerException { int target = DTM.NULL; XPath countMatchPattern = getCountMatchPattern(xctxt, sourceNode); if (Constants.NUMBERLEVEL_ANY == m_level) { target = findPrecedingOrAncestorOrSelf(xctxt, m_fromMatchPattern, countMatchPattern, sourceNode, this); } else { target = findAncestor(xctxt, m_fromMatchPattern, countMatchPattern, sourceNode, this); } return target; } /** * Get the ancestors, up to the root, that match the * pattern. * * @param xctxt The XPath runtime state for this. * @param node Count this node and it's ancestors. * @param stopAtFirstFound Flag indicating to stop after the * first node is found (difference between level = single * or multiple) * @return The number of ancestors that match the pattern. * * @throws javax.xml.transform.TransformerException */ NodeVector getMatchingAncestors( XPathContext xctxt, int node, boolean stopAtFirstFound) throws javax.xml.transform.TransformerException { NodeSetDTM ancestors = new NodeSetDTM(xctxt.getDTMManager()); XPath countMatchPattern = getCountMatchPattern(xctxt, node); DTM dtm = xctxt.getDTM(node); while (DTM.NULL != node) { if ((null != m_fromMatchPattern) && (m_fromMatchPattern.getMatchScore(xctxt, node) != XPath.MATCH_SCORE_NONE)) { // The following if statement gives level="single" different // behavior from level="multiple", which seems incorrect according // to the XSLT spec. For now we are leaving this in to replicate // the same behavior in XT, but, for all intents and purposes we // think this is a bug, or there is something about level="single" // that we still don't understand. if (!stopAtFirstFound) break; } if (null == countMatchPattern) System.out.println( "Programmers error! countMatchPattern should never be null!"); if (countMatchPattern.getMatchScore(xctxt, node) != XPath.MATCH_SCORE_NONE) { ancestors.addElement(node); if (stopAtFirstFound) break; } node = dtm.getParent(node); } return ancestors; } // end getMatchingAncestors method /** * Get the locale we should be using. * * @param transformer non-null reference to the the current transform-time state. * @param contextNode The node that "." expresses. * * @return The locale to use. May be specified by "lang" attribute, * but if not, use default locale on the system. * * @throws TransformerException */ Locale getLocale(TransformerImpl transformer, int contextNode) throws TransformerException { Locale locale = null; if (null != m_lang_avt) { XPathContext xctxt = transformer.getXPathContext(); String langValue = m_lang_avt.evaluate(xctxt, contextNode, this); if (null != langValue) { // Not really sure what to do about the country code, so I use the // default from the system. // TODO: fix xml:lang handling. locale = new Locale(langValue.toUpperCase(), ""); //Locale.getDefault().getDisplayCountry()); if (null == locale) { transformer.getMsgMgr().warn(this, null, xctxt.getDTM(contextNode).getNode(contextNode), XSLTErrorResources.WG_LOCALE_NOT_FOUND, new Object[]{ langValue }); //"Warning: Could not find locale for xml:lang="+langValue); locale = Locale.getDefault(); } } } else { locale = Locale.getDefault(); } return locale; } /** * Get the number formatter to be used the format the numbers * * @param transformer non-null reference to the the current transform-time state. * @param contextNode The node that "." expresses. * * ($objectName$) @return The number formatter to be used * * @throws TransformerException */ private DecimalFormat getNumberFormatter( TransformerImpl transformer, int contextNode) throws TransformerException { // Patch from Steven Serocki // Maybe we really want to do the clone in getLocale() and return // a clone of the default Locale?? Locale locale = (Locale)getLocale(transformer, contextNode).clone(); // Helper to format local specific numbers to strings. DecimalFormat formatter = null; //synchronized (locale) //{ // formatter = (DecimalFormat) NumberFormat.getNumberInstance(locale); //} String digitGroupSepValue = (null != m_groupingSeparator_avt) ? m_groupingSeparator_avt.evaluate( transformer.getXPathContext(), contextNode, this) : null; // Validate grouping separator if an AVT was used; otherwise this was // validated statically in XSLTAttributeDef.java. if ((digitGroupSepValue != null) && (!m_groupingSeparator_avt.isSimple()) && (digitGroupSepValue.length() != 1)) { transformer.getMsgMgr().warn( this, XSLTErrorResources.WG_ILLEGAL_ATTRIBUTE_VALUE, new Object[]{ Constants.ATTRNAME_NAME, m_groupingSeparator_avt.getName()}); } String nDigitsPerGroupValue = (null != m_groupingSize_avt) ? m_groupingSize_avt.evaluate( transformer.getXPathContext(), contextNode, this) : null; // TODO: Handle digit-group attributes if ((null != digitGroupSepValue) && (null != nDigitsPerGroupValue) && // Ignore if separation value is empty string (digitGroupSepValue.length() > 0)) { try { formatter = (DecimalFormat) NumberFormat.getNumberInstance(locale); formatter.setGroupingSize( Integer.valueOf(nDigitsPerGroupValue).intValue()); DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols(); symbols.setGroupingSeparator(digitGroupSepValue.charAt(0)); formatter.setDecimalFormatSymbols(symbols); formatter.setGroupingUsed(true); } catch (NumberFormatException ex) { formatter.setGroupingUsed(false); } } return formatter; } /** * Format a vector of numbers into a formatted string. * * @param transformer non-null reference to the the current transform-time state. * @param list Array of one or more long integer numbers. * @param contextNode The node that "." expresses. * @return String that represents list according to * %conversion-atts; attributes. * TODO: Optimize formatNumberList so that it caches the last count and * reuses that info for the next count. * * @throws TransformerException */ String formatNumberList( TransformerImpl transformer, long[] list, int contextNode) throws TransformerException { String numStr; FastStringBuffer formattedNumber = StringBufferPool.get(); try { int nNumbers = list.length, numberWidth = 1; char numberType = '1'; String formatToken, lastSepString = null, formatTokenString = null; // If a seperator hasn't been specified, then use "." // as a default separator. // For instance: [2][1][5] with a format value of "1 " // should format to "2.1.5 " (I think). // Otherwise, use the seperator specified in the format string. // For instance: [2][1][5] with a format value of "01-001. " // should format to "02-001-005 ". String lastSep = "."; boolean isFirstToken = true; // true if first token String formatValue = (null != m_format_avt) ? m_format_avt.evaluate( transformer.getXPathContext(), contextNode, this) : null; if (null == formatValue) formatValue = "1"; NumberFormatStringTokenizer formatTokenizer = new NumberFormatStringTokenizer(formatValue); // int sepCount = 0; // keep track of seperators // Loop through all the numbers in the list. for (int i = 0; i < nNumbers; i++) { // Loop to the next digit, letter, or separator. if (formatTokenizer.hasMoreTokens()) { formatToken = formatTokenizer.nextToken(); // If the first character of this token is a character or digit, then // it is a number format directive. if (Character.isLetterOrDigit( formatToken.charAt(formatToken.length() - 1))) { numberWidth = formatToken.length(); numberType = formatToken.charAt(numberWidth - 1); } // If there is a number format directive ahead, // then append the formatToken. else if (formatTokenizer.isLetterOrDigitAhead()) { formatTokenString = formatToken; // Append the formatToken string... // For instance [2][1][5] with a format value of "1--1. " // should format to "2--1--5. " (I guess). while (formatTokenizer.nextIsSep()) { formatToken = formatTokenizer.nextToken(); formatTokenString += formatToken; } // Record this separator, so it can be used as the // next separator, if the next is the last. // For instance: [2][1][5] with a format value of "1-1 " // should format to "2-1-5 ". if (!isFirstToken) lastSep = formatTokenString; // Since we know the next is a number or digit, we get it now. formatToken = formatTokenizer.nextToken(); numberWidth = formatToken.length(); numberType = formatToken.charAt(numberWidth - 1); } else // only separators left { // Set up the string for the trailing characters after // the last number is formatted (i.e. after the loop). lastSepString = formatToken; // And append any remaining characters to the lastSepString. while (formatTokenizer.hasMoreTokens()) { formatToken = formatTokenizer.nextToken(); lastSepString += formatToken; } } // else } // end if(formatTokenizer.hasMoreTokens()) // if this is the first token and there was a prefix // append the prefix else, append the separator // For instance, [2][1][5] with a format value of "(1-1.) " // should format to "(2-1-5.) " (I guess). if (null != formatTokenString && isFirstToken) { formattedNumber.append(formatTokenString); } else if (null != lastSep &&!isFirstToken) formattedNumber.append(lastSep); getFormattedNumber(transformer, contextNode, numberType, numberWidth, list[i], formattedNumber); isFirstToken = false; // After the first pass, this should be false } // end for loop // Check to see if we finished up the format string... // Skip past all remaining letters or digits while (formatTokenizer.isLetterOrDigitAhead()) { formatTokenizer.nextToken(); } if (lastSepString != null) formattedNumber.append(lastSepString); while (formatTokenizer.hasMoreTokens()) { formatToken = formatTokenizer.nextToken(); formattedNumber.append(formatToken); } numStr = formattedNumber.toString(); } finally { StringBufferPool.free(formattedNumber); } return numStr; } // end formatNumberList method /* * Get Formatted number */ /** * Format the given number and store it in the given buffer * * * @param transformer non-null reference to the the current transform-time state. * @param contextNode The node that "." expresses. * @param numberType Type to format to * @param numberWidth Maximum length of formatted number * @param listElement Number to format * @param formattedNumber Buffer to store formatted number * * @throws javax.xml.transform.TransformerException */ private void getFormattedNumber( TransformerImpl transformer, int contextNode, char numberType, int numberWidth, long listElement, FastStringBuffer formattedNumber) throws javax.xml.transform.TransformerException { String letterVal = (m_lettervalue_avt != null) ? m_lettervalue_avt.evaluate( transformer.getXPathContext(), contextNode, this) : null; /** * Wrapper of Chars for converting integers into alpha counts. */ CharArrayWrapper alphaCountTable = null; XResourceBundle thisBundle = null; switch (numberType) { case 'A' : if (null == m_alphaCountTable){ thisBundle = (XResourceBundle) XResourceBundle.loadResourceBundle( org.apache.xml.utils.res.XResourceBundle.LANG_BUNDLE_NAME, getLocale(transformer, contextNode)); m_alphaCountTable = (CharArrayWrapper) thisBundle.getObject(org.apache.xml.utils.res.XResourceBundle.LANG_ALPHABET); } int2alphaCount(listElement, m_alphaCountTable, formattedNumber); break; case 'a' : if (null == m_alphaCountTable){ thisBundle = (XResourceBundle) XResourceBundle.loadResourceBundle( org.apache.xml.utils.res.XResourceBundle.LANG_BUNDLE_NAME, getLocale(transformer, contextNode)); m_alphaCountTable = (CharArrayWrapper) thisBundle.getObject(org.apache.xml.utils.res.XResourceBundle.LANG_ALPHABET); } FastStringBuffer stringBuf = StringBufferPool.get(); try { int2alphaCount(listElement, m_alphaCountTable, stringBuf); formattedNumber.append( stringBuf.toString().toLowerCase( getLocale(transformer, contextNode))); } finally { StringBufferPool.free(stringBuf); } break; case 'I' : formattedNumber.append(long2roman(listElement, true)); break; case 'i' : formattedNumber.append( long2roman(listElement, true).toLowerCase( getLocale(transformer, contextNode))); break; case 0x3042 : { thisBundle = (XResourceBundle) XResourceBundle.loadResourceBundle( org.apache.xml.utils.res.XResourceBundle.LANG_BUNDLE_NAME, new Locale("ja", "JP", "HA")); if (letterVal != null && letterVal.equals(Constants.ATTRVAL_TRADITIONAL)) formattedNumber.append(tradAlphaCount(listElement, thisBundle)); else //if (m_lettervalue_avt != null && m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC)) formattedNumber.append( int2singlealphaCount( listElement, (CharArrayWrapper) thisBundle.getObject(org.apache.xml.utils.res.XResourceBundle.LANG_ALPHABET))); break; } case 0x3044 : { thisBundle = (XResourceBundle) XResourceBundle.loadResourceBundle( org.apache.xml.utils.res.XResourceBundle.LANG_BUNDLE_NAME, new Locale("ja", "JP", "HI")); if ((letterVal != null) && letterVal.equals(Constants.ATTRVAL_TRADITIONAL)) formattedNumber.append(tradAlphaCount(listElement, thisBundle)); else //if (m_lettervalue_avt != null && m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC)) formattedNumber.append( int2singlealphaCount( listElement, (CharArrayWrapper) thisBundle.getObject(org.apache.xml.utils.res.XResourceBundle.LANG_ALPHABET))); break; } case 0x30A2 : { thisBundle = (XResourceBundle) XResourceBundle.loadResourceBundle( org.apache.xml.utils.res.XResourceBundle.LANG_BUNDLE_NAME, new Locale("ja", "JP", "A")); if (letterVal != null && letterVal.equals(Constants.ATTRVAL_TRADITIONAL)) formattedNumber.append(tradAlphaCount(listElement, thisBundle)); else //if (m_lettervalue_avt != null && m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC)) formattedNumber.append( int2singlealphaCount( listElement, (CharArrayWrapper) thisBundle.getObject(org.apache.xml.utils.res.XResourceBundle.LANG_ALPHABET))); break; } case 0x30A4 : { thisBundle = (XResourceBundle) XResourceBundle.loadResourceBundle( org.apache.xml.utils.res.XResourceBundle.LANG_BUNDLE_NAME, new Locale("ja", "JP", "I")); if (letterVal != null && letterVal.equals(Constants.ATTRVAL_TRADITIONAL)) formattedNumber.append(tradAlphaCount(listElement, thisBundle)); else //if (m_lettervalue_avt != null && m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC)) formattedNumber.append( int2singlealphaCount( listElement, (CharArrayWrapper) thisBundle.getObject(org.apache.xml.utils.res.XResourceBundle.LANG_ALPHABET))); break; } case 0x4E00 : { thisBundle = (XResourceBundle) XResourceBundle.loadResourceBundle( org.apache.xml.utils.res.XResourceBundle.LANG_BUNDLE_NAME, new Locale("zh", "CN")); if (letterVal != null && letterVal.equals(Constants.ATTRVAL_TRADITIONAL)) { formattedNumber.append(tradAlphaCount(listElement, thisBundle)); } else //if (m_lettervalue_avt != null && m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC)) int2alphaCount(listElement, (CharArrayWrapper) thisBundle.getObject(org.apache.xml.utils.res.XResourceBundle.LANG_ALPHABET), formattedNumber); break; } case 0x58F9 : { thisBundle = (XResourceBundle) XResourceBundle.loadResourceBundle( org.apache.xml.utils.res.XResourceBundle.LANG_BUNDLE_NAME, new Locale("zh", "TW")); if (letterVal != null && letterVal.equals(Constants.ATTRVAL_TRADITIONAL)) formattedNumber.append(tradAlphaCount(listElement, thisBundle)); else //if (m_lettervalue_avt != null && m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC)) int2alphaCount(listElement, (CharArrayWrapper) thisBundle.getObject(org.apache.xml.utils.res.XResourceBundle.LANG_ALPHABET), formattedNumber); break; } case 0x0E51 : { thisBundle = (XResourceBundle) XResourceBundle.loadResourceBundle( org.apache.xml.utils.res.XResourceBundle.LANG_BUNDLE_NAME, new Locale("th", "")); if (letterVal != null && letterVal.equals(Constants.ATTRVAL_TRADITIONAL)) formattedNumber.append(tradAlphaCount(listElement, thisBundle)); else //if (m_lettervalue_avt != null && m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC)) int2alphaCount(listElement, (CharArrayWrapper) thisBundle.getObject(org.apache.xml.utils.res.XResourceBundle.LANG_ALPHABET), formattedNumber); break; } case 0x05D0 : { thisBundle = (XResourceBundle) XResourceBundle.loadResourceBundle( org.apache.xml.utils.res.XResourceBundle.LANG_BUNDLE_NAME, new Locale("he", "")); if (letterVal != null && letterVal.equals(Constants.ATTRVAL_TRADITIONAL)) formattedNumber.append(tradAlphaCount(listElement, thisBundle)); else //if (m_lettervalue_avt != null && m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC)) int2alphaCount(listElement, (CharArrayWrapper) thisBundle.getObject(org.apache.xml.utils.res.XResourceBundle.LANG_ALPHABET), formattedNumber); break; } case 0x10D0 : { thisBundle = (XResourceBundle) XResourceBundle.loadResourceBundle( org.apache.xml.utils.res.XResourceBundle.LANG_BUNDLE_NAME, new Locale("ka", "")); if (letterVal != null && letterVal.equals(Constants.ATTRVAL_TRADITIONAL)) formattedNumber.append(tradAlphaCount(listElement, thisBundle)); else //if (m_lettervalue_avt != null && m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC)) int2alphaCount(listElement, (CharArrayWrapper) thisBundle.getObject(org.apache.xml.utils.res.XResourceBundle.LANG_ALPHABET), formattedNumber); break; } case 0x03B1 : { thisBundle = (XResourceBundle) XResourceBundle.loadResourceBundle( org.apache.xml.utils.res.XResourceBundle.LANG_BUNDLE_NAME, new Locale("el", "")); if (letterVal != null && letterVal.equals(Constants.ATTRVAL_TRADITIONAL)) formattedNumber.append(tradAlphaCount(listElement, thisBundle)); else //if (m_lettervalue_avt != null && m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC)) int2alphaCount(listElement, (CharArrayWrapper) thisBundle.getObject(org.apache.xml.utils.res.XResourceBundle.LANG_ALPHABET), formattedNumber); break; } case 0x0430 : { thisBundle = (XResourceBundle) XResourceBundle.loadResourceBundle( org.apache.xml.utils.res.XResourceBundle.LANG_BUNDLE_NAME, new Locale("cy", "")); if (letterVal != null && letterVal.equals(Constants.ATTRVAL_TRADITIONAL)) formattedNumber.append(tradAlphaCount(listElement, thisBundle)); else //if (m_lettervalue_avt != null && m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC)) int2alphaCount(listElement, (CharArrayWrapper) thisBundle.getObject(org.apache.xml.utils.res.XResourceBundle.LANG_ALPHABET), formattedNumber); break; } default : // "1" DecimalFormat formatter = getNumberFormatter(transformer, contextNode); String padString = formatter == null ? String.valueOf(0) : formatter.format(0); String numString = formatter == null ? String.valueOf(listElement) : formatter.format(listElement); int nPadding = numberWidth - numString.length(); for (int k = 0; k < nPadding; k++) { formattedNumber.append(padString); } formattedNumber.append(numString); } } /** * Get a string value for zero, which is not really defined by the 1.0 spec, * thought I think it might be cleared up by the erreta. */ String getZeroString() { return ""+0; } /** * Convert a long integer into alphabetic counting, in other words * count using the sequence A B C ... Z. * * @param val Value to convert -- must be greater than zero. * @param table a table containing one character for each digit in the radix * @return String representing alpha count of number. * @see TransformerImpl#DecimalToRoman * * Note that the radix of the conversion is inferred from the size * of the table. */ protected String int2singlealphaCount(long val, CharArrayWrapper table) { int radix = table.getLength(); // TODO: throw error on out of range input if (val > radix) { return getZeroString(); } else return (new Character(table.getChar((int)val - 1))).toString(); // index into table is off one, starts at 0 } /** * Convert a long integer into alphabetic counting, in other words * count using the sequence A B C ... Z AA AB AC.... etc. * * @param val Value to convert -- must be greater than zero. * @param table a table containing one character for each digit in the radix * @param aTable Array of alpha characters representing numbers * @param stringBuf Buffer where to save the string representing alpha count of number. * * @see TransformerImpl#DecimalToRoman * * Note that the radix of the conversion is inferred from the size * of the table. */ protected void int2alphaCount(long val, CharArrayWrapper aTable, FastStringBuffer stringBuf) { int radix = aTable.getLength(); char[] table = new char[radix]; // start table at 1, add last char at index 0. Reason explained above and below. int i; for (i = 0; i < radix - 1; i++) { table[i + 1] = aTable.getChar(i); } table[0] = aTable.getChar(i); // Create a buffer to hold the result // TODO: size of the table can be detereined by computing // logs of the radix. For now, we fake it. char buf[] = new char[100]; //some languages go left to right(ie. english), right to left (ie. Hebrew), //top to bottom (ie.Japanese), etc... Handle them differently //String orientation = thisBundle.getString(org.apache.xml.utils.res.XResourceBundle.LANG_ORIENTATION); // next character to set in the buffer int charPos; charPos = buf.length - 1; // work backward through buf[] // index in table of the last character that we stored int lookupIndex = 1; // start off with anything other than zero to make correction work // Correction number // // Correction can take on exactly two values: // // 0 if the next character is to be emitted is usual // // radix - 1 // if the next char to be emitted should be one less than // you would expect // // For example, consider radix 10, where 1="A" and 10="J" // // In this scheme, we count: A, B, C ... H, I, J (not A0 and certainly // not AJ), A1 // // So, how do we keep from emitting AJ for 10? After correctly emitting the // J, lookupIndex is zero. We now compute a correction number of 9 (radix-1). // In the following line, we'll compute (val+correction) % radix, which is, // (val+9)/10. By this time, val is 1, so we compute (1+9) % 10, which // is 10 % 10 or zero. So, we'll prepare to emit "JJ", but then we'll // later suppress the leading J as representing zero (in the mod system, // it can represent either 10 or zero). In summary, the correction value of // "radix-1" acts like "-1" when run through the mod operator, but with the // desireable characteristic that it never produces a negative number. long correction = 0; // TODO: throw error on out of range input do { // most of the correction calculation is explained above, the reason for the // term after the "|| " is that it correctly propagates carries across // multiple columns. correction = ((lookupIndex == 0) || (correction != 0 && lookupIndex == radix - 1)) ? (radix - 1) : 0; // index in "table" of the next char to emit lookupIndex = (int)(val + correction) % radix; // shift input by one "column" val = (val / radix); // if the next value we'd put out would be a leading zero, we're done. if (lookupIndex == 0 && val == 0) break; // put out the next character of output buf[charPos--] = table[lookupIndex]; // left to right or top to bottom } while (val > 0); stringBuf.append(buf, charPos + 1, (buf.length - charPos - 1)); } /** * Convert a long integer into traditional alphabetic counting, in other words * count using the traditional numbering. * * @param val Value to convert -- must be greater than zero. * @param thisBundle Resource bundle to use * * @return String representing alpha count of number. * @see XSLProcessor#DecimalToRoman * * Note that the radix of the conversion is inferred from the size * of the table. */ protected String tradAlphaCount(long val, XResourceBundle thisBundle) { // if this number is larger than the largest number we can represent, error! if (val > Long.MAX_VALUE) { this.error(XSLTErrorResources.ER_NUMBER_TOO_BIG); return XSLTErrorResources.ERROR_STRING; } char[] table = null; // index in table of the last character that we stored int lookupIndex = 1; // start off with anything other than zero to make correction work // Create a buffer to hold the result // TODO: size of the table can be detereined by computing // logs of the radix. For now, we fake it. char buf[] = new char[100]; //some languages go left to right(ie. english), right to left (ie. Hebrew), //top to bottom (ie.Japanese), etc... Handle them differently //String orientation = thisBundle.getString(org.apache.xml.utils.res.XResourceBundle.LANG_ORIENTATION); // next character to set in the buffer int charPos; charPos = 0; //start at 0 // array of number groups: ie.1000, 100, 10, 1 IntArrayWrapper groups = (IntArrayWrapper) thisBundle.getObject(org.apache.xml.utils.res.XResourceBundle.LANG_NUMBERGROUPS); // array of tables of hundreds, tens, digits... StringArrayWrapper tables = (StringArrayWrapper) (thisBundle.getObject(org.apache.xml.utils.res.XResourceBundle.LANG_NUM_TABLES)); //some languages have additive alphabetical notation, //some multiplicative-additive, etc... Handle them differently. String numbering = thisBundle.getString(org.apache.xml.utils.res.XResourceBundle.LANG_NUMBERING); // do multiplicative part first if (numbering.equals(org.apache.xml.utils.res.XResourceBundle.LANG_MULT_ADD)) { String mult_order = thisBundle.getString(org.apache.xml.utils.res.XResourceBundle.MULT_ORDER); LongArrayWrapper multiplier = (LongArrayWrapper) (thisBundle.getObject(org.apache.xml.utils.res.XResourceBundle.LANG_MULTIPLIER)); CharArrayWrapper zeroChar = (CharArrayWrapper) thisBundle.getObject("zero"); int i = 0; // skip to correct multiplier while (i < multiplier.getLength() && val < multiplier.getLong(i)) { i++; } do { if (i >= multiplier.getLength()) break; //number is smaller than multipliers // some languages (ie chinese) put a zero character (and only one) when // the multiplier is multiplied by zero. (ie, 1001 is 1X1000 + 0X100 + 0X10 + 1) // 0X100 is replaced by the zero character, we don't need one for 0X10 if (val < multiplier.getLong(i)) { if (zeroChar.getLength() == 0) { i++; } else { if (buf[charPos - 1] != zeroChar.getChar(0)) buf[charPos++] = zeroChar.getChar(0); i++; } } else if (val >= multiplier.getLong(i)) { long mult = val / multiplier.getLong(i); val = val % multiplier.getLong(i); // save this. int k = 0; while (k < groups.getLength()) { lookupIndex = 1; // initialize for each table if (mult / groups.getInt(k) <= 0) // look for right table k++; else { // get the table CharArrayWrapper THEletters = (CharArrayWrapper) thisBundle.getObject(tables.getString(k)); table = new char[THEletters.getLength() + 1]; int j; for (j = 0; j < THEletters.getLength(); j++) { table[j + 1] = THEletters.getChar(j); } table[0] = THEletters.getChar(j - 1); // don't need this // index in "table" of the next char to emit lookupIndex = (int)mult / groups.getInt(k); //this should not happen if (lookupIndex == 0 && mult == 0) break; char multiplierChar = ((CharArrayWrapper) (thisBundle.getObject( org.apache.xml.utils.res.XResourceBundle.LANG_MULTIPLIER_CHAR))).getChar(i); // put out the next character of output if (lookupIndex < table.length) { if (mult_order.equals(org.apache.xml.utils.res.XResourceBundle.MULT_PRECEDES)) { buf[charPos++] = multiplierChar; buf[charPos++] = table[lookupIndex]; } else { // don't put out 1 (ie 1X10 is just 10) if (lookupIndex == 1 && i == multiplier.getLength() - 1){} else buf[charPos++] = table[lookupIndex]; buf[charPos++] = multiplierChar; } break; // all done! } else return XSLTErrorResources.ERROR_STRING; } //end else } // end while i++; } // end else if } // end do while while (i < multiplier.getLength()); } // Now do additive part... int count = 0; String tableName; // do this for each table of hundreds, tens, digits... while (count < groups.getLength()) { if (val / groups.getInt(count) <= 0) // look for correct table count++; else { CharArrayWrapper theletters = (CharArrayWrapper) thisBundle.getObject(tables.getString(count)); table = new char[theletters.getLength() + 1]; int j; // need to start filling the table up at index 1 for (j = 0; j < theletters.getLength(); j++) { table[j + 1] = theletters.getChar(j); } table[0] = theletters.getChar(j - 1); // don't need this // index in "table" of the next char to emit lookupIndex = (int)val / groups.getInt(count); // shift input by one "column" val = val % groups.getInt(count); // this should not happen if (lookupIndex == 0 && val == 0) break; if (lookupIndex < table.length) { // put out the next character of output buf[charPos++] = table[lookupIndex]; // left to right or top to bottom } else return XSLTErrorResources.ERROR_STRING; count++; } } // end while // String s = new String(buf, 0, charPos); return new String(buf, 0, charPos); } /** * Convert a long integer into roman numerals. * @param val Value to convert. * @param prefixesAreOK true_ to enable prefix notation (e.g. 4 = "IV"), * false_ to disable prefix notation (e.g. 4 = "IIII"). * @return Roman numeral string. * @see DecimalToRoman * @see m_romanConvertTable */ protected String long2roman(long val, boolean prefixesAreOK) { if (val <= 0) { return getZeroString(); } String roman = ""; int place = 0; if (val <= 3999L) { do { while (val >= m_romanConvertTable[place].m_postValue) { roman += m_romanConvertTable[place].m_postLetter; val -= m_romanConvertTable[place].m_postValue; } if (prefixesAreOK) { if (val >= m_romanConvertTable[place].m_preValue) { roman += m_romanConvertTable[place].m_preLetter; val -= m_romanConvertTable[place].m_preValue; } } place++; } while (val > 0); } else { roman = XSLTErrorResources.ERROR_STRING; } return roman; } // end long2roman /** * Call the children visitors. * @param visitor The visitor whose appropriate method will be called. */ public void callChildVisitors(XSLTVisitor visitor, boolean callAttrs) { if(callAttrs) { if(null != m_countMatchPattern) m_countMatchPattern.getExpression().callVisitors(m_countMatchPattern, visitor); if(null != m_fromMatchPattern) m_fromMatchPattern.getExpression().callVisitors(m_fromMatchPattern, visitor); if(null != m_valueExpr) m_valueExpr.getExpression().callVisitors(m_valueExpr, visitor); if(null != m_format_avt) m_format_avt.callVisitors(visitor); if(null != m_groupingSeparator_avt) m_groupingSeparator_avt.callVisitors(visitor); if(null != m_groupingSize_avt) m_groupingSize_avt.callVisitors(visitor); if(null != m_lang_avt) m_lang_avt.callVisitors(visitor); if(null != m_lettervalue_avt) m_lettervalue_avt.callVisitors(visitor); } super.callChildVisitors(visitor, callAttrs); } /** * This class returns tokens using non-alphanumberic * characters as delimiters. */ class NumberFormatStringTokenizer { /** Current position in the format string */ private int currentPosition; /** Index of last character in the format string */ private int maxPosition; /** Format string to be tokenized */ private String str; /** * Construct a NumberFormatStringTokenizer. * * @param str Format string to be tokenized */ public NumberFormatStringTokenizer(String str) { this.str = str; maxPosition = str.length(); } /** * Reset tokenizer so that nextToken() starts from the beginning. */ public void reset() { currentPosition = 0; } /** * Returns the next token from this string tokenizer. * * @return the next token from this string tokenizer. * @throws NoSuchElementException if there are no more tokens in this * tokenizer's string. */ public String nextToken() { if (currentPosition >= maxPosition) { throw new NoSuchElementException(); } int start = currentPosition; while ((currentPosition < maxPosition) && Character.isLetterOrDigit(str.charAt(currentPosition))) { currentPosition++; } if ((start == currentPosition) && (!Character.isLetterOrDigit(str.charAt(currentPosition)))) { currentPosition++; } return str.substring(start, currentPosition); } /** * Tells if there is a digit or a letter character ahead. * * @return true if there is a number or character ahead. */ public boolean isLetterOrDigitAhead() { int pos = currentPosition; while (pos < maxPosition) { if (Character.isLetterOrDigit(str.charAt(pos))) return true; pos++; } return false; } /** * Tells if there is a digit or a letter character ahead. * * @return true if there is a number or character ahead. */ public boolean nextIsSep() { if (Character.isLetterOrDigit(str.charAt(currentPosition))) return false; else return true; } /** * Tells if <code>nextToken</code> will throw an exception * if it is called. * * @return true if <code>nextToken</code> can be called * without throwing an exception. */ public boolean hasMoreTokens() { return (currentPosition >= maxPosition) ? false : true; } /** * Calculates the number of times that this tokenizer's * <code>nextToken</code> method can be called before it generates an * exception. * * @return the number of tokens remaining in the string using the current * delimiter set. * @see java.util.StringTokenizer#nextToken() */ public int countTokens() { int count = 0; int currpos = currentPosition; while (currpos < maxPosition) { int start = currpos; while ((currpos < maxPosition) && Character.isLetterOrDigit(str.charAt(currpos))) { currpos++; } if ((start == currpos) && (Character.isLetterOrDigit(str.charAt(currpos)) == false)) { currpos++; } count++; } return count; } } // end NumberFormatStringTokenizer }
apache-2.0
dennishuo/hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/TaskStatus.java
17294
/** * 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.mapred; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.List; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; import org.apache.hadoop.util.StringInterner; import org.apache.hadoop.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /************************************************** * Describes the current status of a task. This is * not intended to be a comprehensive piece of data. * **************************************************/ @InterfaceAudience.Private @InterfaceStability.Unstable public abstract class TaskStatus implements Writable, Cloneable { static final Logger LOG = LoggerFactory.getLogger(TaskStatus.class.getName()); //enumeration for reporting current phase of a task. @InterfaceAudience.Private @InterfaceStability.Unstable public enum Phase{STARTING, MAP, SHUFFLE, SORT, REDUCE, CLEANUP} // what state is the task in? @InterfaceAudience.Private @InterfaceStability.Unstable public enum State {RUNNING, SUCCEEDED, FAILED, UNASSIGNED, KILLED, COMMIT_PENDING, FAILED_UNCLEAN, KILLED_UNCLEAN, PREEMPTED} private final TaskAttemptID taskid; private float progress; private volatile State runState; private String diagnosticInfo; private String stateString; private String taskTracker; private int numSlots; private long startTime; //in ms private long finishTime; private long outputSize = -1L; private volatile Phase phase = Phase.STARTING; private Counters counters; private boolean includeAllCounters; private SortedRanges.Range nextRecordRange = new SortedRanges.Range(); // max task-status string size static final int MAX_STRING_SIZE = 1024; /** * Testcases can override {@link #getMaxStringSize()} to control the max-size * of strings in {@link TaskStatus}. Note that the {@link TaskStatus} is never * exposed to clients or users (i.e Map or Reduce) and hence users cannot * override this api to pass large strings in {@link TaskStatus}. */ protected int getMaxStringSize() { return MAX_STRING_SIZE; } public TaskStatus() { taskid = new TaskAttemptID(); numSlots = 0; } public TaskStatus(TaskAttemptID taskid, float progress, int numSlots, State runState, String diagnosticInfo, String stateString, String taskTracker, Phase phase, Counters counters) { this.taskid = taskid; this.progress = progress; this.numSlots = numSlots; this.runState = runState; setDiagnosticInfo(diagnosticInfo); setStateString(stateString); this.taskTracker = taskTracker; this.phase = phase; this.counters = counters; this.includeAllCounters = true; } public TaskAttemptID getTaskID() { return taskid; } public abstract boolean getIsMap(); public int getNumSlots() { return numSlots; } public float getProgress() { return progress; } public void setProgress(float progress) { this.progress = progress; } public State getRunState() { return runState; } public String getTaskTracker() {return taskTracker;} public void setTaskTracker(String tracker) { this.taskTracker = tracker;} public void setRunState(State runState) { this.runState = runState; } public String getDiagnosticInfo() { return diagnosticInfo; } public void setDiagnosticInfo(String info) { // if the diag-info has already reached its max then log and return if (diagnosticInfo != null && diagnosticInfo.length() == getMaxStringSize()) { LOG.info("task-diagnostic-info for task " + taskid + " : " + info); return; } diagnosticInfo = ((diagnosticInfo == null) ? info : diagnosticInfo.concat(info)); // trim the string to MAX_STRING_SIZE if needed if (diagnosticInfo != null && diagnosticInfo.length() > getMaxStringSize()) { LOG.info("task-diagnostic-info for task " + taskid + " : " + diagnosticInfo); diagnosticInfo = diagnosticInfo.substring(0, getMaxStringSize()); } } public String getStateString() { return stateString; } /** * Set the state of the {@link TaskStatus}. */ public void setStateString(String stateString) { if (stateString != null) { if (stateString.length() <= getMaxStringSize()) { this.stateString = stateString; } else { // log it LOG.info("state-string for task " + taskid + " : " + stateString); // trim the state string this.stateString = stateString.substring(0, getMaxStringSize()); } } } /** * Get the next record range which is going to be processed by Task. * @return nextRecordRange */ public SortedRanges.Range getNextRecordRange() { return nextRecordRange; } /** * Set the next record range which is going to be processed by Task. * @param nextRecordRange */ public void setNextRecordRange(SortedRanges.Range nextRecordRange) { this.nextRecordRange = nextRecordRange; } /** * Get task finish time. if shuffleFinishTime and sortFinishTime * are not set before, these are set to finishTime. It takes care of * the case when shuffle, sort and finish are completed with in the * heartbeat interval and are not reported separately. if task state is * TaskStatus.FAILED then finish time represents when the task failed. * @return finish time of the task. */ public long getFinishTime() { return finishTime; } /** * Sets finishTime for the task status if and only if the * start time is set and passed finish time is greater than * zero. * * @param finishTime finish time of task. */ void setFinishTime(long finishTime) { if(this.getStartTime() > 0 && finishTime > 0) { this.finishTime = finishTime; } else { //Using String utils to get the stack trace. LOG.error("Trying to set finish time for task " + taskid + " when no start time is set, stackTrace is : " + StringUtils.stringifyException(new Exception())); } } /** * Get shuffle finish time for the task. If shuffle finish time was * not set due to shuffle/sort/finish phases ending within same * heartbeat interval, it is set to finish time of next phase i.e. sort * or task finish when these are set. * @return 0 if shuffleFinishTime, sortFinishTime and finish time are not set. else * it returns approximate shuffle finish time. */ public long getShuffleFinishTime() { return 0; } /** * Set shuffle finish time. * @param shuffleFinishTime */ void setShuffleFinishTime(long shuffleFinishTime) {} /** * Get map phase finish time for the task. If map finsh time was * not set due to sort phase ending within same heartbeat interval, * it is set to finish time of next phase i.e. sort phase * when it is set. * @return 0 if mapFinishTime, sortFinishTime are not set. else * it returns approximate map finish time. */ public long getMapFinishTime() { return 0; } /** * Set map phase finish time. * @param mapFinishTime */ void setMapFinishTime(long mapFinishTime) {} /** * Get sort finish time for the task,. If sort finish time was not set * due to sort and reduce phase finishing in same heartebat interval, it is * set to finish time, when finish time is set. * @return 0 if sort finish time and finish time are not set, else returns sort * finish time if that is set, else it returns finish time. */ public long getSortFinishTime() { return 0; } /** * Sets sortFinishTime, if shuffleFinishTime is not set before * then its set to sortFinishTime. * @param sortFinishTime */ void setSortFinishTime(long sortFinishTime) {} /** * Get start time of the task. * @return 0 is start time is not set, else returns start time. */ public long getStartTime() { return startTime; } /** * Set startTime of the task if start time is greater than zero. * @param startTime start time */ void setStartTime(long startTime) { //Making the assumption of passed startTime to be a positive //long value explicit. if (startTime > 0) { this.startTime = startTime; } else { //Using String utils to get the stack trace. LOG.error("Trying to set illegal startTime for task : " + taskid + ".Stack trace is : " + StringUtils.stringifyException(new Exception())); } } /** * Get current phase of this task. Phase.Map in case of map tasks, * for reduce one of Phase.SHUFFLE, Phase.SORT or Phase.REDUCE. * @return . */ public Phase getPhase(){ return this.phase; } /** * Set current phase of this task. * @param phase phase of this task */ public void setPhase(Phase phase){ TaskStatus.Phase oldPhase = getPhase(); if (oldPhase != phase){ // sort phase started if (phase == TaskStatus.Phase.SORT){ if (oldPhase == TaskStatus.Phase.MAP) { setMapFinishTime(System.currentTimeMillis()); } else { setShuffleFinishTime(System.currentTimeMillis()); } }else if (phase == TaskStatus.Phase.REDUCE){ setSortFinishTime(System.currentTimeMillis()); } this.phase = phase; } } boolean inTaskCleanupPhase() { return (this.phase == TaskStatus.Phase.CLEANUP && (this.runState == TaskStatus.State.FAILED_UNCLEAN || this.runState == TaskStatus.State.KILLED_UNCLEAN)); } public boolean getIncludeAllCounters() { return includeAllCounters; } public void setIncludeAllCounters(boolean send) { includeAllCounters = send; counters.setWriteAllCounters(send); } /** * Get task's counters. */ public Counters getCounters() { return counters; } /** * Set the task's counters. * @param counters */ public void setCounters(Counters counters) { this.counters = counters; } /** * Returns the number of bytes of output from this map. */ public long getOutputSize() { return outputSize; } /** * Set the size on disk of this task's output. * @param l the number of map output bytes */ void setOutputSize(long l) { outputSize = l; } /** * Get the list of maps from which output-fetches failed. * * @return the list of maps from which output-fetches failed. */ public List<TaskAttemptID> getFetchFailedMaps() { return null; } /** * Add to the list of maps from which output-fetches failed. * * @param mapTaskId map from which fetch failed */ public abstract void addFetchFailedMap(TaskAttemptID mapTaskId); /** * Update the status of the task. * * This update is done by ping thread before sending the status. * * @param progress * @param state * @param counters */ synchronized void statusUpdate(float progress, String state, Counters counters) { setProgress(progress); setStateString(state); setCounters(counters); } /** * Update the status of the task. * * @param status updated status */ synchronized void statusUpdate(TaskStatus status) { setProgress (status.getProgress()); this.runState = status.getRunState(); setStateString(status.getStateString()); this.nextRecordRange = status.getNextRecordRange(); setDiagnosticInfo(status.getDiagnosticInfo()); if (status.getStartTime() > 0) { this.setStartTime(status.getStartTime()); } if (status.getFinishTime() > 0) { this.setFinishTime(status.getFinishTime()); } this.phase = status.getPhase(); this.counters = status.getCounters(); this.outputSize = status.outputSize; } /** * Update specific fields of task status * * This update is done in JobTracker when a cleanup attempt of task * reports its status. Then update only specific fields, not all. * * @param runState * @param progress * @param state * @param phase * @param finishTime */ synchronized void statusUpdate(State runState, float progress, String state, Phase phase, long finishTime) { setRunState(runState); setProgress(progress); setStateString(state); setPhase(phase); if (finishTime > 0) { setFinishTime(finishTime); } } /** * Clear out transient information after sending out a status-update * from either the {@link Task} to the {@link TaskTracker} or from the * {@link TaskTracker} to the {@link JobTracker}. */ synchronized void clearStatus() { // Clear diagnosticInfo diagnosticInfo = ""; } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException cnse) { // Shouldn't happen since we do implement Clonable throw new InternalError(cnse.toString()); } } ////////////////////////////////////////////// // Writable ////////////////////////////////////////////// public void write(DataOutput out) throws IOException { taskid.write(out); out.writeFloat(progress); out.writeInt(numSlots); WritableUtils.writeEnum(out, runState); Text.writeString(out, diagnosticInfo); Text.writeString(out, stateString); WritableUtils.writeEnum(out, phase); out.writeLong(startTime); out.writeLong(finishTime); out.writeBoolean(includeAllCounters); out.writeLong(outputSize); counters.write(out); nextRecordRange.write(out); } public void readFields(DataInput in) throws IOException { this.taskid.readFields(in); setProgress(in.readFloat()); this.numSlots = in.readInt(); this.runState = WritableUtils.readEnum(in, State.class); setDiagnosticInfo(StringInterner.weakIntern(Text.readString(in))); setStateString(StringInterner.weakIntern(Text.readString(in))); this.phase = WritableUtils.readEnum(in, Phase.class); this.startTime = in.readLong(); this.finishTime = in.readLong(); counters = new Counters(); this.includeAllCounters = in.readBoolean(); this.outputSize = in.readLong(); counters.readFields(in); nextRecordRange.readFields(in); } ////////////////////////////////////////////////////////////////////////////// // Factory-like methods to create/read/write appropriate TaskStatus objects ////////////////////////////////////////////////////////////////////////////// static TaskStatus createTaskStatus(DataInput in, TaskAttemptID taskId, float progress, int numSlots, State runState, String diagnosticInfo, String stateString, String taskTracker, Phase phase, Counters counters) throws IOException { boolean isMap = in.readBoolean(); return createTaskStatus(isMap, taskId, progress, numSlots, runState, diagnosticInfo, stateString, taskTracker, phase, counters); } static TaskStatus createTaskStatus(boolean isMap, TaskAttemptID taskId, float progress, int numSlots, State runState, String diagnosticInfo, String stateString, String taskTracker, Phase phase, Counters counters) { return (isMap) ? new MapTaskStatus(taskId, progress, numSlots, runState, diagnosticInfo, stateString, taskTracker, phase, counters) : new ReduceTaskStatus(taskId, progress, numSlots, runState, diagnosticInfo, stateString, taskTracker, phase, counters); } static TaskStatus createTaskStatus(boolean isMap) { return (isMap) ? new MapTaskStatus() : new ReduceTaskStatus(); } }
apache-2.0
deki/spring-boot
spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/package-info.java
741
/* * Copyright 2012-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. */ /** * Custom JUnit runner to change the classpath. */ package org.springframework.boot.testsupport.runner.classpath;
apache-2.0
kentongray/ews-java-api
src/main/java/microsoft/exchange/webservices/data/property/definition/PropertyDefinition.java
6573
/* * The MIT License * Copyright (c) 2012 Microsoft Corporation * * 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 microsoft.exchange.webservices.data.property.definition; import microsoft.exchange.webservices.data.core.EwsServiceXmlReader; import microsoft.exchange.webservices.data.core.EwsServiceXmlWriter; import microsoft.exchange.webservices.data.core.PropertyBag; import microsoft.exchange.webservices.data.core.service.schema.ServiceObjectSchema; import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion; import microsoft.exchange.webservices.data.core.enumeration.property.PropertyDefinitionFlags; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; /** * Represents the definition of a folder or item property. */ public abstract class PropertyDefinition extends ServiceObjectPropertyDefinition { /** * The xml element name. */ private String xmlElementName; /** * The flags. */ private EnumSet<PropertyDefinitionFlags> flags; /** * The name. */ private String name; /** * The version. */ private ExchangeVersion version; /** * Initializes a new instance. * * @param xmlElementName Name of the XML element. * @param uri The URI. * @param version The version. */ protected PropertyDefinition(String xmlElementName, String uri, ExchangeVersion version) { super(uri); this.xmlElementName = xmlElementName; this.flags = EnumSet.of(PropertyDefinitionFlags.None); this.version = version; } /** * Initializes a new instance. * * @param xmlElementName Name of the XML element. * @param flags The flags. * @param version The version. */ protected PropertyDefinition(String xmlElementName, EnumSet<PropertyDefinitionFlags> flags, ExchangeVersion version) { super(); this.xmlElementName = xmlElementName; this.flags = flags; this.version = version; } /** * Initializes a new instance. * * @param xmlElementName Name of the XML element. * @param uri The URI. * @param flags The flags. * @param version The version. */ protected PropertyDefinition(String xmlElementName, String uri, EnumSet<PropertyDefinitionFlags> flags, ExchangeVersion version) { this(xmlElementName, uri, version); this.flags = flags; } /** * Determines whether the specified flag is set. * * @param flag The flag. * @return true if the specified flag is set; otherwise, false. */ public boolean hasFlag(PropertyDefinitionFlags flag) { return this.hasFlag(flag, null); } /** * Determines whether the specified flag is set. * * @param flag The flag. * @return true if the specified flag is set; otherwise, false. */ public boolean hasFlag(PropertyDefinitionFlags flag, ExchangeVersion version) { return this.flags.contains(flag); } /** * Registers associated internal property. * * @param properties The list in which to add the associated property. */ protected void registerAssociatedInternalProperties( List<PropertyDefinition> properties) { } /** * Gets a list of associated internal property. * * @return A list of PropertyDefinition objects. This is a hack. It is here * (currently) solely to help the API register the MeetingTimeZone * property definition that is internal. */ public List<PropertyDefinition> getAssociatedInternalProperties() { List<PropertyDefinition> properties = new ArrayList<PropertyDefinition>(); this.registerAssociatedInternalProperties(properties); return properties; } /** * Gets the minimum Exchange version that supports this property. * * @return The version. */ public ExchangeVersion getVersion() { return version; } /** * Gets a value indicating whether this property definition is for a * nullable type. * * @return always true */ public boolean isNullable() { return true; } /** * Loads from XML. * * @param reader The reader. * @param propertyBag The property bag. * @throws Exception the exception */ public abstract void loadPropertyValueFromXml(EwsServiceXmlReader reader, PropertyBag propertyBag) throws Exception; /** * Writes the property value to XML. * * @param writer the writer * @param propertyBag the property bag * @param isUpdateOperation indicates whether the context is an update operation * @throws Exception the exception */ public abstract void writePropertyValueToXml(EwsServiceXmlWriter writer, PropertyBag propertyBag, boolean isUpdateOperation) throws Exception; /** * Gets the name of the XML element. * * @return The name of the XML element. */ public String getXmlElement() { return this.xmlElementName; } /** * Gets the name of the property. * * @return Name of the property. */ public String getName() { if (null == this.name || this.name.isEmpty()) { ServiceObjectSchema.initializeSchemaPropertyNames(); } return name; } /** * Sets the name of the property. * * @param name name of the property */ public void setName(String name) { this.name = name; } /** * Gets the property definition's printable name. * * @return The property definition's printable name. */ @Override public String getPrintableName() { return this.getName(); } }
mit
geoffschoeman/mockito
src/org/mockito/internal/configuration/plugins/PluginLoader.java
2683
package org.mockito.internal.configuration.plugins; import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.misusing.MockitoConfigurationException; import org.mockito.internal.util.collections.Iterables; import org.mockito.plugins.PluginSwitch; import java.io.IOException; import java.net.URL; import java.util.Enumeration; class PluginLoader { private final PluginSwitch pluginSwitch; public PluginLoader(PluginSwitch pluginSwitch) { this.pluginSwitch = pluginSwitch; } /** * Scans the classpath for given pluginType. If not found, default class is used. */ <T> T loadPlugin(Class<T> pluginType, String defaultPluginClassName) { T plugin = loadImpl(pluginType); if (plugin != null) { return plugin; } try { // Default implementation. Use our own ClassLoader instead of the context // ClassLoader, as the default implementation is assumed to be part of // Mockito and may not be available via the context ClassLoader. return pluginType.cast(Class.forName(defaultPluginClassName).newInstance()); } catch (Exception e) { throw new MockitoException("Internal problem occurred, please report it. " + "Mockito is unable to load the default implementation of class that is a part of Mockito distribution. " + "Failed to load " + pluginType, e); } } /** * Equivalent to {@link java.util.ServiceLoader#load} but without requiring * Java 6 / Android 2.3 (Gingerbread). */ <T> T loadImpl(Class<T> service) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = ClassLoader.getSystemClassLoader(); } Enumeration<URL> resources; try { resources = loader.getResources("mockito-extensions/" + service.getName()); } catch (IOException e) { throw new MockitoException("Failed to load " + service, e); } try { String foundPluginClass = new PluginFinder(pluginSwitch).findPluginClass(Iterables.toIterable(resources)); if (foundPluginClass != null) { Class<?> pluginClass = loader.loadClass(foundPluginClass); Object plugin = pluginClass.newInstance(); return service.cast(plugin); } return null; } catch (Exception e) { throw new MockitoConfigurationException( "Failed to load " + service + " implementation declared in " + resources, e); } } }
mit
vongosling/cglib-ext
src/proxy/net/sf/cglib/proxy/FixedValue.java
1472
/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; /** * {@link Enhancer} callback that simply returns the value to return * from the proxied method. No information about what method * is being called is available to the callback, and the type of * the returned object must be compatible with the return type of * the proxied method. This makes this callback primarily useful * for forcing a particular method (through the use of a {@link CallbackFilter} * to return a fixed value with little overhead. */ public interface FixedValue extends Callback { /** * Return the object which the original method invocation should * return. This method is called for <b>every</b> method invocation. * @return an object matching the type of the return value for every * method this callback is mapped to */ Object loadObject() throws Exception; }
apache-2.0
tiarebalbi/spring-boot
spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/main/java/smoketest/actuator/customsecurity/ExampleRestControllerEndpoint.java
1233
/* * Copyright 2012-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 smoketest.actuator.customsecurity; import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; @Component @RestControllerEndpoint(id = "example") public class ExampleRestControllerEndpoint { @GetMapping("/echo") public ResponseEntity<String> echo(@RequestParam("text") String text) { return ResponseEntity.ok().header("echo", text).body(text); } }
apache-2.0