gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.util;
import io.netty.util.internal.StringUtil;
import org.junit.jupiter.api.Test;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import static io.netty.util.NetUtil.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class NetUtilTest {
private static final class TestMap extends HashMap<String, String> {
private static final long serialVersionUID = -298642816998608473L;
TestMap(String... values) {
for (int i = 0; i < values.length; i += 2) {
String key = values[i];
String value = values[i + 1];
put(key, value);
}
}
}
private static final Map<String, String> validIpV4Hosts = new TestMap(
"192.168.1.0", "c0a80100",
"10.255.255.254", "0afffffe",
"172.18.5.4", "ac120504",
"0.0.0.0", "00000000",
"127.0.0.1", "7f000001",
"255.255.255.255", "ffffffff",
"1.2.3.4", "01020304");
private static final Map<String, String> invalidIpV4Hosts = new TestMap(
"1.256.3.4", null,
"256.0.0.1", null,
"1.1.1.1.1", null,
"x.255.255.255", null,
"0.1:0.0", null,
"0.1.0.0:", null,
"127.0.0.", null,
"1.2..4", null,
"192.0.1", null,
"192.0.1.1.1", null,
"192.0.1.a", null,
"19a.0.1.1", null,
"a.0.1.1", null,
".0.1.1", null,
"127.0.0", null,
"192.0.1.256", null,
"0.0.200.259", null,
"1.1.-1.1", null,
"1.1. 1.1", null,
"1.1.1.1 ", null,
"1.1.+1.1", null,
"0.0x1.0.255", null,
"0.01x.0.255", null,
"0.x01.0.255", null,
"0.-.0.0", null,
"0..0.0", null,
"0.A.0.0", null,
"0.1111.0.0", null,
"...", null);
private static final Map<String, String> validIpV6Hosts = new TestMap(
"::ffff:5.6.7.8", "00000000000000000000ffff05060708",
"fdf8:f53b:82e4::53", "fdf8f53b82e400000000000000000053",
"fe80::200:5aee:feaa:20a2", "fe8000000000000002005aeefeaa20a2",
"2001::1", "20010000000000000000000000000001",
"2001:0000:4136:e378:8000:63bf:3fff:fdd2", "200100004136e378800063bf3ffffdd2",
"2001:0002:6c::430", "20010002006c00000000000000000430",
"2001:10:240:ab::a", "20010010024000ab000000000000000a",
"2002:cb0a:3cdd:1::1", "2002cb0a3cdd00010000000000000001",
"2001:db8:8:4::2", "20010db8000800040000000000000002",
"ff01:0:0:0:0:0:0:2", "ff010000000000000000000000000002",
"[fdf8:f53b:82e4::53]", "fdf8f53b82e400000000000000000053",
"[fe80::200:5aee:feaa:20a2]", "fe8000000000000002005aeefeaa20a2",
"[2001::1]", "20010000000000000000000000000001",
"[2001:0000:4136:e378:8000:63bf:3fff:fdd2]", "200100004136e378800063bf3ffffdd2",
"0:1:2:3:4:5:6:789a", "0000000100020003000400050006789a",
"0:1:2:3::f", "0000000100020003000000000000000f",
"0:0:0:0:0:0:10.0.0.1", "00000000000000000000ffff0a000001",
"0:0:0:0:0::10.0.0.1", "00000000000000000000ffff0a000001",
"0:0:0:0::10.0.0.1", "00000000000000000000ffff0a000001",
"::0:0:0:0:0:10.0.0.1", "00000000000000000000ffff0a000001",
"0::0:0:0:0:10.0.0.1", "00000000000000000000ffff0a000001",
"0:0::0:0:0:10.0.0.1", "00000000000000000000ffff0a000001",
"0:0:0::0:0:10.0.0.1", "00000000000000000000ffff0a000001",
"0:0:0:0::0:10.0.0.1", "00000000000000000000ffff0a000001",
"0:0:0:0:0:ffff:10.0.0.1", "00000000000000000000ffff0a000001",
"::ffff:192.168.0.1", "00000000000000000000ffffc0a80001",
// Test if various interface names after the percent sign are recognized.
"[::1%1]", "00000000000000000000000000000001",
"[::1%eth0]", "00000000000000000000000000000001",
"[::1%%]", "00000000000000000000000000000001",
"0:0:0:0:0:ffff:10.0.0.1%", "00000000000000000000ffff0a000001",
"0:0:0:0:0:ffff:10.0.0.1%1", "00000000000000000000ffff0a000001",
"[0:0:0:0:0:ffff:10.0.0.1%1]", "00000000000000000000ffff0a000001",
"[0:0:0:0:0::10.0.0.1%1]", "00000000000000000000ffff0a000001",
"[::0:0:0:0:ffff:10.0.0.1%1]", "00000000000000000000ffff0a000001",
"::0:0:0:0:ffff:10.0.0.1%1", "00000000000000000000ffff0a000001",
"::1%1", "00000000000000000000000000000001",
"::1%eth0", "00000000000000000000000000000001",
"::1%%", "00000000000000000000000000000001",
// Tests with leading or trailing compression
"0:0:0:0:0:0:0::", "00000000000000000000000000000000",
"0:0:0:0:0:0::", "00000000000000000000000000000000",
"0:0:0:0:0::", "00000000000000000000000000000000",
"0:0:0:0::", "00000000000000000000000000000000",
"0:0:0::", "00000000000000000000000000000000",
"0:0::", "00000000000000000000000000000000",
"0::", "00000000000000000000000000000000",
"::", "00000000000000000000000000000000",
"::0", "00000000000000000000000000000000",
"::0:0", "00000000000000000000000000000000",
"::0:0:0", "00000000000000000000000000000000",
"::0:0:0:0", "00000000000000000000000000000000",
"::0:0:0:0:0", "00000000000000000000000000000000",
"::0:0:0:0:0:0", "00000000000000000000000000000000",
"::0:0:0:0:0:0:0", "00000000000000000000000000000000");
private static final Map<String, String> invalidIpV6Hosts = new TestMap(
// Test method with garbage.
"Obvious Garbage", null,
// Test method with preferred style, too many :
"0:1:2:3:4:5:6:7:8", null,
// Test method with preferred style, not enough :
"0:1:2:3:4:5:6", null,
// Test method with preferred style, bad digits.
"0:1:2:3:4:5:6:x", null,
// Test method with preferred style, adjacent :
"0:1:2:3:4:5:6::7", null,
// Too many : separators trailing
"0:1:2:3:4:5:6:7::", null,
// Too many : separators leading
"::0:1:2:3:4:5:6:7", null,
// Too many : separators trailing
"1:2:3:4:5:6:7:", null,
// Too many : separators leading
":1:2:3:4:5:6:7", null,
// Compression with : separators trailing
"0:1:2:3:4:5::7:", null,
"0:1:2:3:4::7:", null,
"0:1:2:3::7:", null,
"0:1:2::7:", null,
"0:1::7:", null,
"0::7:", null,
// Compression at start with : separators trailing
"::0:1:2:3:4:5:7:", null,
"::0:1:2:3:4:7:", null,
"::0:1:2:3:7:", null,
"::0:1:2:7:", null,
"::0:1:7:", null,
"::7:", null,
// The : separators leading and trailing
":1:2:3:4:5:6:7:", null,
":1:2:3:4:5:6:", null,
":1:2:3:4:5:", null,
":1:2:3:4:", null,
":1:2:3:", null,
":1:2:", null,
":1:", null,
// Compression with : separators leading
":1::2:3:4:5:6:7", null,
":1::3:4:5:6:7", null,
":1::4:5:6:7", null,
":1::5:6:7", null,
":1::6:7", null,
":1::7", null,
":1:2:3:4:5:6::7", null,
":1:3:4:5:6::7", null,
":1:4:5:6::7", null,
":1:5:6::7", null,
":1:6::7", null,
":1::", null,
// Compression trailing with : separators leading
":1:2:3:4:5:6:7::", null,
":1:3:4:5:6:7::", null,
":1:4:5:6:7::", null,
":1:5:6:7::", null,
":1:6:7::", null,
":1:7::", null,
// Double compression
"1::2:3:4:5:6::", null,
"::1:2:3:4:5::6", null,
"::1:2:3:4:5:6::", null,
"::1:2:3:4:5::", null,
"::1:2:3:4::", null,
"::1:2:3::", null,
"::1:2::", null,
"::0::", null,
"12::0::12", null,
// Too many : separators leading 0
"0::1:2:3:4:5:6:7", null,
// Test method with preferred style, too many digits.
"0:1:2:3:4:5:6:789abcdef", null,
// Test method with compressed style, bad digits.
"0:1:2:3::x", null,
// Test method with compressed style, too many adjacent :
"0:1:2:::3", null,
// Test method with compressed style, too many digits.
"0:1:2:3::abcde", null,
// Test method with compressed style, not enough :
"0:1", null,
// Test method with ipv4 style, bad ipv6 digits.
"0:0:0:0:0:x:10.0.0.1", null,
// Test method with ipv4 style, bad ipv4 digits.
"0:0:0:0:0:0:10.0.0.x", null,
// Test method with ipv4 style, too many ipv6 digits.
"0:0:0:0:0:00000:10.0.0.1", null,
// Test method with ipv4 style, too many :
"0:0:0:0:0:0:0:10.0.0.1", null,
// Test method with ipv4 style, not enough :
"0:0:0:0:0:10.0.0.1", null,
// Test method with ipv4 style, too many .
"0:0:0:0:0:0:10.0.0.0.1", null,
// Test method with ipv4 style, not enough .
"0:0:0:0:0:0:10.0.1", null,
// Test method with ipv4 style, adjacent .
"0:0:0:0:0:0:10..0.0.1", null,
// Test method with ipv4 style, leading .
"0:0:0:0:0:0:.0.0.1", null,
// Test method with ipv4 style, leading .
"0:0:0:0:0:0:.10.0.0.1", null,
// Test method with ipv4 style, trailing .
"0:0:0:0:0:0:10.0.0.", null,
// Test method with ipv4 style, trailing .
"0:0:0:0:0:0:10.0.0.1.", null,
// Test method with compressed ipv4 style, bad ipv6 digits.
"::fffx:192.168.0.1", null,
// Test method with compressed ipv4 style, bad ipv4 digits.
"::ffff:192.168.0.x", null,
// Test method with compressed ipv4 style, too many adjacent :
":::ffff:192.168.0.1", null,
// Test method with compressed ipv4 style, too many ipv6 digits.
"::fffff:192.168.0.1", null,
// Test method with compressed ipv4 style, too many ipv4 digits.
"::ffff:1923.168.0.1", null,
// Test method with compressed ipv4 style, not enough :
":ffff:192.168.0.1", null,
// Test method with compressed ipv4 style, too many .
"::ffff:192.168.0.1.2", null,
// Test method with compressed ipv4 style, not enough .
"::ffff:192.168.0", null,
// Test method with compressed ipv4 style, adjacent .
"::ffff:192.168..0.1", null,
// Test method, bad ipv6 digits.
"x:0:0:0:0:0:10.0.0.1", null,
// Test method, bad ipv4 digits.
"0:0:0:0:0:0:x.0.0.1", null,
// Test method, too many ipv6 digits.
"00000:0:0:0:0:0:10.0.0.1", null,
// Test method, too many ipv4 digits.
"0:0:0:0:0:0:10.0.0.1000", null,
// Test method, too many :
"0:0:0:0:0:0:0:10.0.0.1", null,
// Test method, not enough :
"0:0:0:0:0:10.0.0.1", null,
// Test method, out of order trailing :
"0:0:0:0:0:10.0.0.1:", null,
// Test method, out of order leading :
":0:0:0:0:0:10.0.0.1", null,
// Test method, out of order leading :
"0:0:0:0::10.0.0.1:", null,
// Test method, out of order trailing :
":0:0:0:0::10.0.0.1", null,
// Test method, too many .
"0:0:0:0:0:0:10.0.0.0.1", null,
// Test method, not enough .
"0:0:0:0:0:0:10.0.1", null,
// Test method, adjacent .
"0:0:0:0:0:0:10.0.0..1", null,
// Empty contents
"", null,
// Invalid single compression
":", null,
":::", null,
// Trailing : (max number of : = 8)
"2001:0:4136:e378:8000:63bf:3fff:fdd2:", null,
// Leading : (max number of : = 8)
":aaaa:bbbb:cccc:dddd:eeee:ffff:1111:2222", null,
// Invalid character
"1234:2345:3456:4567:5678:6789::X890", null,
// Trailing . in IPv4
"::ffff:255.255.255.255.", null,
// To many characters in IPv4
"::ffff:0.0.1111.0", null,
// Test method, adjacent .
"::ffff:0.0..0", null,
// Not enough IPv4 entries trailing .
"::ffff:127.0.0.", null,
// Invalid trailing IPv4 character
"::ffff:127.0.0.a", null,
// Invalid leading IPv4 character
"::ffff:a.0.0.1", null,
// Invalid middle IPv4 character
"::ffff:127.a.0.1", null,
// Invalid middle IPv4 character
"::ffff:127.0.a.1", null,
// Not enough IPv4 entries no trailing .
"::ffff:1.2.4", null,
// Extra IPv4 entry
"::ffff:192.168.0.1.255", null,
// Not enough IPv6 content
":ffff:192.168.0.1.255", null,
// Intermixed IPv4 and IPv6 symbols
"::ffff:255.255:255.255.", null,
// Invalid IPv4 mapped address - invalid ipv4 separator
"0:0:0::0:0:00f.0.0.1", null,
// Invalid IPv4 mapped address - not enough f's
"0:0:0:0:0:fff:1.0.0.1", null,
// Invalid IPv4 mapped address - not IPv4 mapped, not IPv4 compatible
"0:0:0:0:0:ff00:1.0.0.1", null,
// Invalid IPv4 mapped address - not IPv4 mapped, not IPv4 compatible
"0:0:0:0:0:ff:1.0.0.1", null,
// Invalid IPv4 mapped address - too many f's
"0:0:0:0:0:fffff:1.0.0.1", null,
// Invalid IPv4 mapped address - too many bytes (too many 0's)
"0:0:0:0:0:0:ffff:1.0.0.1", null,
// Invalid IPv4 mapped address - too many bytes (too many 0's)
"::0:0:0:0:0:ffff:1.0.0.1", null,
// Invalid IPv4 mapped address - too many bytes (too many 0's)
"0:0:0:0:0:0::1.0.0.1", null,
// Invalid IPv4 mapped address - too many bytes (too many 0's)
"0:0:0:0:0:00000:1.0.0.1", null,
// Invalid IPv4 mapped address - too few bytes (not enough 0's)
"0:0:0:0:ffff:1.0.0.1", null,
// Invalid IPv4 mapped address - too few bytes (not enough 0's)
"ffff:192.168.0.1", null,
// Invalid IPv4 mapped address - 0's after the mapped ffff indicator
"0:0:0:0:0:ffff::10.0.0.1", null,
// Invalid IPv4 mapped address - 0's after the mapped ffff indicator
"0:0:0:0:ffff::10.0.0.1", null,
// Invalid IPv4 mapped address - 0's after the mapped ffff indicator
"0:0:0:ffff::10.0.0.1", null,
// Invalid IPv4 mapped address - 0's after the mapped ffff indicator
"0:0:ffff::10.0.0.1", null,
// Invalid IPv4 mapped address - 0's after the mapped ffff indicator
"0:ffff::10.0.0.1", null,
// Invalid IPv4 mapped address - 0's after the mapped ffff indicator
"ffff::10.0.0.1", null,
// Invalid IPv4 mapped address - not all 0's before the mapped separator
"1:0:0:0:0:ffff:10.0.0.1", null,
// Address that is similar to IPv4 mapped, but is invalid
"0:0:0:0:ffff:ffff:1.0.0.1", null,
// Valid number of separators, but invalid IPv4 format
"::1:2:3:4:5:6.7.8.9", null,
// Too many digits
"0:0:0:0:0:0:ffff:10.0.0.1", null,
// Invalid IPv4 format
":1.2.3.4", null,
// Invalid IPv4 format
"::.2.3.4", null,
// Invalid IPv4 format
"::ffff:0.1.2.", null);
private static final Map<byte[], String> ipv6ToAddressStrings = new HashMap<byte[], String>() {
private static final long serialVersionUID = 2999763170377573184L;
{
// From the RFC 5952 https://tools.ietf.org/html/rfc5952#section-4
put(new byte[] {
32, 1, 13, -72,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 1
},
"2001:db8::1");
put(new byte[] {
32, 1, 13, -72,
0, 0, 0, 0,
0, 0, 0, 0,
0, 2, 0, 1
},
"2001:db8::2:1");
put(new byte[] {
32, 1, 13, -72,
0, 0, 0, 1,
0, 1, 0, 1,
0, 1, 0, 1
},
"2001:db8:0:1:1:1:1:1");
// Other examples
put(new byte[] {
32, 1, 13, -72,
0, 0, 0, 0,
0, 0, 0, 0,
0, 2, 0, 1
},
"2001:db8::2:1");
put(new byte[] {
32, 1, 0, 0,
0, 0, 0, 1,
0, 0, 0, 0,
0, 0, 0, 1
},
"2001:0:0:1::1");
put(new byte[] {
32, 1, 13, -72,
0, 0, 0, 0,
0, 1, 0, 0,
0, 0, 0, 1
},
"2001:db8::1:0:0:1");
put(new byte[] {
32, 1, 13, -72,
0, 0, 0, 0,
0, 1, 0, 0,
0, 0, 0, 0
},
"2001:db8:0:0:1::");
put(new byte[] {
32, 1, 13, -72,
0, 0, 0, 0,
0, 0, 0, 0,
0, 2, 0, 0
},
"2001:db8::2:0");
put(new byte[] {
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 1
},
"::1");
put(new byte[] {
0, 0, 0, 0,
0, 0, 0, 1,
0, 0, 0, 0,
0, 0, 0, 1
},
"::1:0:0:0:1");
put(new byte[] {
0, 0, 0, 0,
1, 0, 0, 1,
0, 0, 0, 0,
1, 0, 0, 0
},
"::100:1:0:0:100:0");
put(new byte[] {
32, 1, 0, 0,
65, 54, -29, 120,
-128, 0, 99, -65,
63, -1, -3, -46
},
"2001:0:4136:e378:8000:63bf:3fff:fdd2");
put(new byte[] {
-86, -86, -69, -69,
-52, -52, -35, -35,
-18, -18, -1, -1,
17, 17, 34, 34
},
"aaaa:bbbb:cccc:dddd:eeee:ffff:1111:2222");
put(new byte[] {
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
},
"::");
}
};
private static final Map<String, String> ipv4MappedToIPv6AddressStrings = new TestMap(
// IPv4 addresses
"255.255.255.255", "::ffff:255.255.255.255",
"0.0.0.0", "::ffff:0.0.0.0",
"127.0.0.1", "::ffff:127.0.0.1",
"1.2.3.4", "::ffff:1.2.3.4",
"192.168.0.1", "::ffff:192.168.0.1",
// IPv4 compatible addresses are deprecated [1], so we don't support outputting them, but we do support
// parsing them into IPv4 mapped addresses. These values are treated the same as a plain IPv4 address above.
// [1] https://tools.ietf.org/html/rfc4291#section-2.5.5.1
"0:0:0:0:0:0:255.254.253.252", "::ffff:255.254.253.252",
"0:0:0:0:0::1.2.3.4", "::ffff:1.2.3.4",
"0:0:0:0::1.2.3.4", "::ffff:1.2.3.4",
"::0:0:0:0:0:1.2.3.4", "::ffff:1.2.3.4",
"0::0:0:0:0:1.2.3.4", "::ffff:1.2.3.4",
"0:0::0:0:0:1.2.3.4", "::ffff:1.2.3.4",
"0:0:0::0:0:1.2.3.4", "::ffff:1.2.3.4",
"0:0:0:0::0:1.2.3.4", "::ffff:1.2.3.4",
"0:0:0:0:0::1.2.3.4", "::ffff:1.2.3.4",
"::0:0:0:0:1.2.3.4", "::ffff:1.2.3.4",
"0::0:0:0:1.2.3.4", "::ffff:1.2.3.4",
"0:0::0:0:1.2.3.4", "::ffff:1.2.3.4",
"0:0:0::0:1.2.3.4", "::ffff:1.2.3.4",
"0:0:0:0::1.2.3.4", "::ffff:1.2.3.4",
"::0:0:0:0:1.2.3.4", "::ffff:1.2.3.4",
"0::0:0:0:1.2.3.4", "::ffff:1.2.3.4",
"0:0::0:0:1.2.3.4", "::ffff:1.2.3.4",
"0:0:0::0:1.2.3.4", "::ffff:1.2.3.4",
"0:0:0:0::1.2.3.4", "::ffff:1.2.3.4",
"::0:0:0:1.2.3.4", "::ffff:1.2.3.4",
"0::0:0:1.2.3.4", "::ffff:1.2.3.4",
"0:0::0:1.2.3.4", "::ffff:1.2.3.4",
"0:0:0::1.2.3.4", "::ffff:1.2.3.4",
"::0:0:1.2.3.4", "::ffff:1.2.3.4",
"0::0:1.2.3.4", "::ffff:1.2.3.4",
"0:0::1.2.3.4", "::ffff:1.2.3.4",
"::0:1.2.3.4", "::ffff:1.2.3.4",
"::1.2.3.4", "::ffff:1.2.3.4",
// IPv4 mapped (fully specified)
"0:0:0:0:0:ffff:1.2.3.4", "::ffff:1.2.3.4",
// IPv6 addresses
// Fully specified
"2001:0:4136:e378:8000:63bf:3fff:fdd2", "2001:0:4136:e378:8000:63bf:3fff:fdd2",
"aaaa:bbbb:cccc:dddd:eeee:ffff:1111:2222", "aaaa:bbbb:cccc:dddd:eeee:ffff:1111:2222",
"0:0:0:0:0:0:0:0", "::",
"0:0:0:0:0:0:0:1", "::1",
// Compressing at the beginning
"::1:0:0:0:1", "::1:0:0:0:1",
"::1:ffff:ffff", "::1:ffff:ffff",
"::", "::",
"::1", "::1",
"::ffff", "::ffff",
"::ffff:0", "::ffff:0",
"::ffff:ffff", "::ffff:ffff",
"::0987:9876:8765", "::987:9876:8765",
"::0987:9876:8765:7654", "::987:9876:8765:7654",
"::0987:9876:8765:7654:6543", "::987:9876:8765:7654:6543",
"::0987:9876:8765:7654:6543:5432", "::987:9876:8765:7654:6543:5432",
// Note the compression is removed (rfc 5952 section 4.2.2)
"::0987:9876:8765:7654:6543:5432:3210", "0:987:9876:8765:7654:6543:5432:3210",
// Compressing at the end
// Note the compression is removed (rfc 5952 section 4.2.2)
"2001:db8:abcd:bcde:cdef:def1:ef12::", "2001:db8:abcd:bcde:cdef:def1:ef12:0",
"2001:db8:abcd:bcde:cdef:def1::", "2001:db8:abcd:bcde:cdef:def1::",
"2001:db8:abcd:bcde:cdef::", "2001:db8:abcd:bcde:cdef::",
"2001:db8:abcd:bcde::", "2001:db8:abcd:bcde::",
"2001:db8:abcd::", "2001:db8:abcd::",
"2001:1234::", "2001:1234::",
"2001::", "2001::",
"0::", "::",
// Compressing in the middle
"1234:2345::7890", "1234:2345::7890",
"1234::2345:7890", "1234::2345:7890",
"1234:2345:3456::7890", "1234:2345:3456::7890",
"1234:2345::3456:7890", "1234:2345::3456:7890",
"1234::2345:3456:7890", "1234::2345:3456:7890",
"1234:2345:3456:4567::7890", "1234:2345:3456:4567::7890",
"1234:2345:3456::4567:7890", "1234:2345:3456::4567:7890",
"1234:2345::3456:4567:7890", "1234:2345::3456:4567:7890",
"1234::2345:3456:4567:7890", "1234::2345:3456:4567:7890",
"1234:2345:3456:4567:5678::7890", "1234:2345:3456:4567:5678::7890",
"1234:2345:3456:4567::5678:7890", "1234:2345:3456:4567::5678:7890",
"1234:2345:3456::4567:5678:7890", "1234:2345:3456::4567:5678:7890",
"1234:2345::3456:4567:5678:7890", "1234:2345::3456:4567:5678:7890",
"1234::2345:3456:4567:5678:7890", "1234::2345:3456:4567:5678:7890",
// Note the compression is removed (rfc 5952 section 4.2.2)
"1234:2345:3456:4567:5678:6789::7890", "1234:2345:3456:4567:5678:6789:0:7890",
// Note the compression is removed (rfc 5952 section 4.2.2)
"1234:2345:3456:4567:5678::6789:7890", "1234:2345:3456:4567:5678:0:6789:7890",
// Note the compression is removed (rfc 5952 section 4.2.2)
"1234:2345:3456:4567::5678:6789:7890", "1234:2345:3456:4567:0:5678:6789:7890",
// Note the compression is removed (rfc 5952 section 4.2.2)
"1234:2345:3456::4567:5678:6789:7890", "1234:2345:3456:0:4567:5678:6789:7890",
// Note the compression is removed (rfc 5952 section 4.2.2)
"1234:2345::3456:4567:5678:6789:7890", "1234:2345:0:3456:4567:5678:6789:7890",
// Note the compression is removed (rfc 5952 section 4.2.2)
"1234::2345:3456:4567:5678:6789:7890", "1234:0:2345:3456:4567:5678:6789:7890",
// IPv4 mapped addresses
"::ffff:255.255.255.255", "::ffff:255.255.255.255",
"::ffff:0.0.0.0", "::ffff:0.0.0.0",
"::ffff:127.0.0.1", "::ffff:127.0.0.1",
"::ffff:1.2.3.4", "::ffff:1.2.3.4",
"::ffff:192.168.0.1", "::ffff:192.168.0.1");
@Test
public void testLocalhost() {
assertNotNull(LOCALHOST);
}
@Test
public void testLoopback() {
assertNotNull(LOOPBACK_IF);
}
@Test
public void testIsValidIpV4Address() {
for (String host : validIpV4Hosts.keySet()) {
assertTrue(isValidIpV4Address(host), host);
}
for (String host : invalidIpV4Hosts.keySet()) {
assertFalse(isValidIpV4Address(host), host);
}
}
@Test
public void testIsValidIpV6Address() {
for (String host : validIpV6Hosts.keySet()) {
assertTrue(isValidIpV6Address(host), host);
if (host.charAt(0) != '[' && !host.contains("%")) {
assertNotNull(getByName(host, true), host);
String hostMod = '[' + host + ']';
assertTrue(isValidIpV6Address(hostMod), hostMod);
hostMod = host + '%';
assertTrue(isValidIpV6Address(hostMod), hostMod);
hostMod = host + "%eth1";
assertTrue(isValidIpV6Address(hostMod), hostMod);
hostMod = '[' + host + "%]";
assertTrue(isValidIpV6Address(hostMod), hostMod);
hostMod = '[' + host + "%1]";
assertTrue(isValidIpV6Address(hostMod), hostMod);
hostMod = '[' + host + "]%";
assertFalse(isValidIpV6Address(hostMod), hostMod);
hostMod = '[' + host + "]%1";
assertFalse(isValidIpV6Address(hostMod), hostMod);
}
}
for (String host : invalidIpV6Hosts.keySet()) {
assertFalse(isValidIpV6Address(host), host);
assertNull(getByName(host), host);
String hostMod = '[' + host + ']';
assertFalse(isValidIpV6Address(hostMod), hostMod);
hostMod = host + '%';
assertFalse(isValidIpV6Address(hostMod), hostMod);
hostMod = host + "%eth1";
assertFalse(isValidIpV6Address(hostMod), hostMod);
hostMod = '[' + host + "%]";
assertFalse(isValidIpV6Address(hostMod), hostMod);
hostMod = '[' + host + "%1]";
assertFalse(isValidIpV6Address(hostMod), hostMod);
hostMod = '[' + host + "]%";
assertFalse(isValidIpV6Address(hostMod), hostMod);
hostMod = '[' + host + "]%1";
assertFalse(isValidIpV6Address(hostMod), hostMod);
hostMod = host + ']';
assertFalse(isValidIpV6Address(hostMod), hostMod);
hostMod = '[' + host;
assertFalse(isValidIpV6Address(hostMod), hostMod);
}
}
@Test
public void testCreateByteArrayFromIpAddressString() {
for (Entry<String, String> e : validIpV4Hosts.entrySet()) {
String ip = e.getKey();
assertHexDumpEquals(e.getValue(), createByteArrayFromIpAddressString(ip), ip);
}
for (Entry<String, String> e : invalidIpV4Hosts.entrySet()) {
String ip = e.getKey();
assertHexDumpEquals(e.getValue(), createByteArrayFromIpAddressString(ip), ip);
}
for (Entry<String, String> e : validIpV6Hosts.entrySet()) {
String ip = e.getKey();
assertHexDumpEquals(e.getValue(), createByteArrayFromIpAddressString(ip), ip);
}
for (Entry<String, String> e : invalidIpV6Hosts.entrySet()) {
String ip = e.getKey();
assertHexDumpEquals(e.getValue(), createByteArrayFromIpAddressString(ip), ip);
}
}
@Test
public void testBytesToIpAddress() throws UnknownHostException {
for (Entry<String, String> e : validIpV4Hosts.entrySet()) {
assertEquals(e.getKey(), bytesToIpAddress(createByteArrayFromIpAddressString(e.getKey())));
assertEquals(e.getKey(), bytesToIpAddress(validIpV4ToBytes(e.getKey())));
}
for (Entry<byte[], String> testEntry : ipv6ToAddressStrings.entrySet()) {
assertEquals(testEntry.getValue(), bytesToIpAddress(testEntry.getKey()));
}
}
@Test
public void testIp6AddressToString() throws UnknownHostException {
for (Entry<byte[], String> testEntry : ipv6ToAddressStrings.entrySet()) {
assertEquals(testEntry.getValue(), toAddressString(InetAddress.getByAddress(testEntry.getKey())));
}
}
@Test
public void testIp4AddressToString() throws UnknownHostException {
for (Entry<String, String> e : validIpV4Hosts.entrySet()) {
assertEquals(e.getKey(), toAddressString(InetAddress.getByAddress(unhex(e.getValue()))));
}
}
@Test
public void testIPv4ToInt() throws UnknownHostException {
assertEquals(2130706433, ipv4AddressToInt((Inet4Address) InetAddress.getByName("127.0.0.1")));
assertEquals(-1062731519, ipv4AddressToInt((Inet4Address) InetAddress.getByName("192.168.1.1")));
}
@Test
public void testIpv4MappedIp6GetByName() {
for (Entry<String, String> testEntry : ipv4MappedToIPv6AddressStrings.entrySet()) {
String srcIp = testEntry.getKey();
String dstIp = testEntry.getValue();
Inet6Address inet6Address = getByName(srcIp, true);
assertNotNull(inet6Address, srcIp + ", " + dstIp);
assertEquals(dstIp, toAddressString(inet6Address, true), srcIp);
}
}
@Test
public void testInvalidIpv4MappedIp6GetByName() {
for (String host : invalidIpV4Hosts.keySet()) {
assertNull(getByName(host, true), host);
}
for (String host : invalidIpV6Hosts.keySet()) {
assertNull(getByName(host, true), host);
}
}
@Test
public void testIp6InetSocketAddressToString() throws UnknownHostException {
for (Entry<byte[], String> testEntry : ipv6ToAddressStrings.entrySet()) {
assertEquals('[' + testEntry.getValue() + "]:9999",
toSocketAddressString(new InetSocketAddress(InetAddress.getByAddress(testEntry.getKey()), 9999)));
}
}
@Test
public void testIp4SocketAddressToString() throws UnknownHostException {
for (Entry<String, String> e : validIpV4Hosts.entrySet()) {
assertEquals(e.getKey() + ":9999",
toSocketAddressString(new InetSocketAddress(InetAddress.getByAddress(unhex(e.getValue())), 9999)));
}
}
private static void assertHexDumpEquals(String expected, byte[] actual, String message) {
assertEquals(expected, hex(actual), message);
}
private static String hex(byte[] value) {
if (value == null) {
return null;
}
StringBuilder buf = new StringBuilder(value.length << 1);
for (byte b: value) {
String hex = StringUtil.byteToHexString(b);
if (hex.length() == 1) {
buf.append('0');
}
buf.append(hex);
}
return buf.toString();
}
private static byte[] unhex(String value) {
return value != null ? StringUtil.decodeHexDump(value) : null;
}
}
| |
/*
* Copyright 2015 Francois Steyn - Adept Internet (PTY) LTD (francois.s@adept.co.za).
*
* 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.adeptnet.auth.sso;
import org.adeptnet.auth.sso.common.SSOCredentials;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.AuthStatus;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.MessagePolicy;
import javax.security.auth.message.config.ServerAuthContext;
import javax.security.auth.message.module.ServerAuthModule;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequestWrapper;
import javax.servlet.ServletResponseWrapper;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import org.adeptnet.auth.kerberos.Krb5;
import org.adeptnet.auth.saml.SAMLClient;
import org.adeptnet.auth.saml.SAMLException;
import org.opensaml.ws.message.encoder.MessageEncodingException;
import org.adeptnet.auth.sso.common.Krb5Credentials;
import org.adeptnet.auth.sso.common.SAMLCredentials;
import org.adeptnet.auth.sso.common.SSOCallback;
/**
*
* @author Francois Steyn - Adept Internet (PTY) LTD (francois.s@adept.co.za)
*/
public class SSOAuthModule implements ServerAuthModule, ServerAuthContext, CallbackHandler {
private static final Logger LOG = Logger.getLogger(SSOAuthModule.class.getName());
private static final Class<?>[] SUPPORTED_MESSAGE_TYPES = new Class<?>[]{HttpServletRequest.class, HttpServletResponse.class};
private static final String IS_MANDATORY_INFO_KEY = "javax.security.auth.message.MessagePolicy.isMandatory";
private static final String SESSION_SAVED_SUBJECT_KEY = "ServerAuthModule.SAVED.SUBJECT";
private static final String PARAM_JAAS_CONTEXT_PARAM = "jaas-context";
private static final String PARAM_LOGIN_PAGE = "login-page";
private static final String PARAM_LOGIN_ERROR = "login-error-page";
//private static final String PARAM_DEFAULT_PAGE = "default-page";
private static final String J_SECURITY_CHECK = "/j_security_check";
private static final String J_SECURITY_LOGOUT = "/j_security_logout";
private CallbackHandler handler;
private String _jaasCtx;
private String _loginPage;
//private String _defaultPage;
private String _loginErrorPage;
private SSOCredentials credentials;
private Map<?, ?> options;
private String getStringOption(final java.util.Map<?, ?> options, final String name) throws AuthException {
final Object val = options.get(name);
if (val instanceof String) {
return (String) val;
} else {
throw new AuthException(String.format("'%s' must be supplied as a property in the provider-config in the domain.xml file!", name));
}
}
private String getLoginPage() throws AuthException {
if (_loginPage == null) {
_loginPage = getStringOption(options, PARAM_LOGIN_PAGE);
}
return _loginPage;
}
private String getLoginErrorPage() throws AuthException {
if (_loginErrorPage == null) {
_loginErrorPage = getStringOption(options, PARAM_LOGIN_ERROR);
}
return _loginErrorPage;
}
private String getJaasCtx() throws AuthException {
if (_jaasCtx == null) {
_jaasCtx = getStringOption(options, PARAM_JAAS_CONTEXT_PARAM);
}
return _jaasCtx;
}
@Override
public void initialize(final MessagePolicy requestPolicy, final MessagePolicy responsePolicy, final CallbackHandler handler, final Map options) throws AuthException {
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("initialize");
}
if (options == null) {
throw new AuthException("options is null");
}
if (handler == null) {
throw new AuthException("handler is null");
}
this.handler = handler;
this.options = options;
getLoginPage();
getJaasCtx();
}
@Override
public Class[] getSupportedMessageTypes() {
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("getSupportedMessageTypes");
}
return SUPPORTED_MESSAGE_TYPES;
}
private boolean isMandatory(final MessageInfo messageInfo) {
return Boolean.valueOf((String) messageInfo.getMap().get(IS_MANDATORY_INFO_KEY));
}
private AuthStatus redirectToErrorScreen(final HttpServletRequest request, final HttpServletResponse response, final String messageText, final String errorText) throws AuthException {
if (LOG.isLoggable(Level.FINER)) {
LOG.finer(String.format("redirectToErrorScreen messageText=%s errorText=%s", messageText, errorText));
}
request.setAttribute("messageText", messageText);
request.setAttribute("errorText", errorText);
final RequestDispatcher rDispatcher = request.getRequestDispatcher(getLoginErrorPage());
try {
rDispatcher.forward(request, response);
} catch (ServletException | IOException ex) {
LOG.log(Level.SEVERE, ex.getMessage(), ex);
}
return AuthStatus.SEND_FAILURE;
}
private AuthStatus redirectToErrorScreen(final HttpServletRequest request, final HttpServletResponse response, final Throwable throwable) throws AuthException {
LOG.log(Level.SEVERE, throwable.getMessage(), throwable);
return redirectToErrorScreen(request, response, throwable.getClass().getName(), throwable.getMessage());
}
private void doSSOHeader(final HttpServletRequest request, final HttpServletResponse response) {
if (request.getHeader(Krb5.AUTHORIZATION) == null) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader(Krb5.WWW_AUTHENTICATE, Krb5.NEGOTIATE);
}
request.setAttribute("doSSO", request.getRequestURI());
}
private AuthStatus redirectToLoginScreen(final HttpServletRequest request, final HttpServletResponse response) throws AuthException {
doSSOHeader(request, response);
final RequestDispatcher rDispatcher = request.getRequestDispatcher(getLoginPage());
try {
rDispatcher.forward(request, response);
} catch (ServletException | IOException ex) {
LOG.log(Level.SEVERE, ex.getMessage(), ex);
final AuthException ae = new AuthException(String.format("Redirect to loginPage: %s", getLoginPage()));
ae.initCause(ex);
throw ae;
}
return AuthStatus.SEND_CONTINUE;
}
private AuthStatus logoutSession(final HttpServletRequest request, final HttpServletResponse response, final Subject clientSubject) throws AuthException {
try {
request.logout();
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, String.format("validateRequest %s ==> logout redirect ", request.getRequestURI()));
}
try {
final HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
} catch (Throwable e) {
LOG.log(Level.WARNING, "Session was already invalid ", e);
}
return redirectToLoginScreen(request, response);
} catch (ServletException ex) {
return redirectToErrorScreen(request, response, ex);
}
}
private boolean restoreSavedCredentials(final Subject clientSubject, final HttpSession session, final HttpServletRequest request, final HttpServletResponse response) {
final Subject savedClientSubject = (session.getAttribute(SESSION_SAVED_SUBJECT_KEY) instanceof Subject ? (Subject) session.getAttribute(SESSION_SAVED_SUBJECT_KEY) : null); // NOPMD , long names
if (savedClientSubject != null) {
clientSubject.getPrincipals().addAll(savedClientSubject.getPrincipals());
clientSubject.getPublicCredentials().addAll(savedClientSubject.getPublicCredentials());
clientSubject.getPrivateCredentials().addAll(savedClientSubject.getPrivateCredentials());
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "CustomFormAuthModule validateRequest {0} ==> restored pricipals ==> SUCCESS {1}\n\n\n\n", new Object[]{request.getRequestURI(), response.getStatus()});
}
return true;
}
return false;
}
private String getOrigin(final HttpServletRequest request) {
final StringBuilder stringBuilder = new StringBuilder();
for (final java.util.Enumeration<String> vias = request.getHeaders("Via"); vias.hasMoreElements();) {
if (stringBuilder.length() > 0) {
stringBuilder.append(", ");
}
stringBuilder.append("Via:").append(vias.nextElement());
}
for (final java.util.Enumeration<String> vias = request.getHeaders("x-forwarded-for"); vias.hasMoreElements();) {
if (stringBuilder.length() > 0) {
stringBuilder.append(", ");
}
stringBuilder.append("x-forwarded-for:").append(vias.nextElement());
}
return String.format("%s:%s %s", request.getContextPath(), request.getRemoteAddr(), stringBuilder.toString());
}
private boolean isLoginPage(final String uri) throws AuthException {
return uri.endsWith(getLoginPage());
}
private boolean isRedirectUrl(final String uri) throws AuthException {
return (isLoginPage(uri)) || (uri.endsWith(J_SECURITY_CHECK)) || (uri.endsWith(J_SECURITY_LOGOUT));
}
private String getRedirectUrl(final String uri) throws AuthException {
if (isLoginPage(uri)) {
return uri.substring(0, uri.length() - getLoginPage().length());
}
if (uri.endsWith(J_SECURITY_CHECK)) {
return uri.substring(0, uri.length() - J_SECURITY_CHECK.length());
}
if (uri.endsWith(J_SECURITY_LOGOUT)) {
return uri.substring(0, uri.length() - J_SECURITY_LOGOUT.length());
}
return uri;
}
private AuthStatus doRedirect(final HttpServletRequest request, final HttpServletResponse response, final String url) throws AuthException {
try {
if (LOG.isLoggable(Level.FINER)) {
LOG.finer(String.format("sendRedirect: %s", url));
}
response.sendRedirect(url);
return AuthStatus.SEND_CONTINUE;
} catch (IOException ex) {
return redirectToErrorScreen(request, response, ex);
}
}
@Override
public AuthStatus validateRequest(final MessageInfo messageInfo, final Subject clientSubject, final Subject serviceSubject) throws AuthException {
try {
final HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
final HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine(String.format("validateRequest: %s - %s", handler, request.getRequestURI()));
}
final String auth = request.getHeader(Krb5.AUTHORIZATION);
if (request.getRequestURI().endsWith(J_SECURITY_LOGOUT) && (auth == null)) {
return logoutSession(request, response, clientSubject);
}
final HttpSession session = request.getSession(true);
if ((session != null) && (restoreSavedCredentials(clientSubject, session, request, response))) {
if (isRedirectUrl(request.getRequestURI())) {
return doRedirect(request, response, request.getContextPath());
} else {
return AuthStatus.SUCCESS;
}
}
if (!isMandatory(messageInfo) && !request.getRequestURI().endsWith(J_SECURITY_CHECK) && (auth == null)) {
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "CustomFormAuthModule validateRequest notMandatory {0} ==> SUCCESS {1}\n\n\n\n", new Object[]{request.getRequestURI(), response.getStatus()});
}
if (isLoginPage(request.getRequestURI())) {
doSSOHeader(request, response);
}
return AuthStatus.SUCCESS;
}
final String fragment = request.getParameter("j_fragment");
final String url = request.getParameter("j_url");
final String saml = request.getParameter(SAMLClient.SAML_RESPONSE);
final String redirectUrl;
if ((auth != null) && (auth.startsWith(String.format("%s ", Krb5.NEGOTIATE)))) {
credentials = new Krb5Credentials(request.getServerName(), auth.split(" ")[1], getOrigin(request));
if (isRedirectUrl(request.getRequestURI())) {
redirectUrl = request.getContextPath();
} else {
redirectUrl = null;
}
} else if (saml != null) {
credentials = new SAMLCredentials(request.getServerName(), "GET".equalsIgnoreCase(request.getMethod()), saml, request.getQueryString(), getOrigin(request));
final String relayState = request.getParameter(SAMLClient.SAML_RELAYSTATE);
redirectUrl = relayState == null ? null : new String(Base64.getDecoder().decode(relayState.getBytes()));
} else if (url != null) {
final String relayState = new String(Base64.getEncoder().encode(String.format("%s%s", getRedirectUrl(url), fragment).getBytes()));
try {
Common.getInstance(options).doSAMLRedirect(request, response, relayState);
} catch (SAMLException | MessageEncodingException ex) {
return redirectToErrorScreen(request, response, ex);
}
return AuthStatus.SEND_CONTINUE;
} else {
return redirectToLoginScreen(request, response);
}
try {
final LoginContext lc = new LoginContext(getJaasCtx(), clientSubject, this);
lc.login();
session.setAttribute(SESSION_SAVED_SUBJECT_KEY, clientSubject);// Save the Subject...
} catch (LoginException ex) {
return redirectToErrorScreen(request, response, ex);
}
if (redirectUrl == null) {
return AuthStatus.SUCCESS;
} else {
return doRedirect(request, response, redirectUrl);
}
} catch (Throwable ex) {
LOG.log(Level.SEVERE, ex.getMessage(), ex);
throw ex;
}
}
@Override
public AuthStatus secureResponse(final MessageInfo messageInfo, final Subject serviceSubject) throws AuthException {
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("secureResponse");
}
boolean wrapped = false;
HttpServletRequest r = (HttpServletRequest) messageInfo.getRequestMessage();
while (r != null && r instanceof HttpServletRequestWrapper) {
r = (HttpServletRequest) ((ServletRequestWrapper) r).getRequest();
wrapped = true;
}
if (wrapped) {
messageInfo.setRequestMessage(r);
}
wrapped = false;
HttpServletResponse s = (HttpServletResponse) messageInfo.getResponseMessage();
while (s != null && s instanceof HttpServletResponseWrapper) {
s = (HttpServletResponse) ((ServletResponseWrapper) s).getResponse();
wrapped = true;
}
if (wrapped) {
messageInfo.setResponseMessage(s);
}
return AuthStatus.SEND_SUCCESS;
}
@Override
public void cleanSubject(final MessageInfo messageInfo, final Subject subject) throws AuthException {
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("cleanSubject");
}
if (subject == null) {
return;
}
final Object o = messageInfo.getRequestMessage();
if ((o != null) && (o instanceof HttpServletRequest)) {
final HttpServletRequest request = (HttpServletRequest) o;
final HttpSession session = request.getSession(false);
if (session != null) {
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("session.removeAttribute");
}
session.removeAttribute(SESSION_SAVED_SUBJECT_KEY);
}
}
try {
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("lc.logout");
}
final LoginContext lc = new LoginContext(getJaasCtx(), subject, this);
lc.logout();
} catch (LoginException ex) {
LOG.log(Level.SEVERE, ex.getMessage(), ex);
}
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("clear subject");
}
subject.getPrincipals().clear();
subject.getPrivateCredentials().clear();
subject.getPublicCredentials().clear();
}
@Override
public void handle(final Callback[] callbacks) throws IOException, UnsupportedCallbackException {
if (LOG.isLoggable(Level.FINER)) {
LOG.finer(String.format("handle %d", callbacks.length));
}
final List<Callback> toHandle = new ArrayList<>();
for (final Callback cb : callbacks) {
if (LOG.isLoggable(Level.FINER)) {
LOG.finer(String.format("handle %s: %s", cb.getClass(), cb));
}
if (cb instanceof SSOCallback) {
final SSOCallback sso = (SSOCallback) cb;
sso.setCredentials(credentials);
continue;
}
toHandle.add(cb);
}
if ((handler != null) && (!toHandle.isEmpty())) {
try {
handler.handle(toHandle.toArray(new Callback[toHandle.size()]));
} catch (IOException | UnsupportedCallbackException ex) {
LOG.log(Level.SEVERE, ex.getMessage(), ex);
}
}
}
}
| |
/*
* 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.psi.util;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Condition;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.IncorrectOperationException;
import gnu.trove.THashMap;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class PsiTypesUtil {
@NonNls private static final Map<String, String> ourUnboxedTypes = new THashMap<>();
@NonNls private static final Map<String, String> ourBoxedTypes = new THashMap<>();
static {
ourUnboxedTypes.put(CommonClassNames.JAVA_LANG_BOOLEAN, "boolean");
ourUnboxedTypes.put(CommonClassNames.JAVA_LANG_BYTE, "byte");
ourUnboxedTypes.put(CommonClassNames.JAVA_LANG_SHORT, "short");
ourUnboxedTypes.put(CommonClassNames.JAVA_LANG_INTEGER, "int");
ourUnboxedTypes.put(CommonClassNames.JAVA_LANG_LONG, "long");
ourUnboxedTypes.put(CommonClassNames.JAVA_LANG_FLOAT, "float");
ourUnboxedTypes.put(CommonClassNames.JAVA_LANG_DOUBLE, "double");
ourUnboxedTypes.put(CommonClassNames.JAVA_LANG_CHARACTER, "char");
ourBoxedTypes.put("boolean", CommonClassNames.JAVA_LANG_BOOLEAN);
ourBoxedTypes.put("byte", CommonClassNames.JAVA_LANG_BYTE);
ourBoxedTypes.put("short", CommonClassNames.JAVA_LANG_SHORT);
ourBoxedTypes.put("int", CommonClassNames.JAVA_LANG_INTEGER);
ourBoxedTypes.put("long", CommonClassNames.JAVA_LANG_LONG);
ourBoxedTypes.put("float", CommonClassNames.JAVA_LANG_FLOAT);
ourBoxedTypes.put("double", CommonClassNames.JAVA_LANG_DOUBLE);
ourBoxedTypes.put("char", CommonClassNames.JAVA_LANG_CHARACTER);
}
@NonNls private static final String GET_CLASS_METHOD = "getClass";
private PsiTypesUtil() { }
public static Object getDefaultValue(PsiType type) {
if (!(type instanceof PsiPrimitiveType)) return null;
switch (type.getCanonicalText()) {
case "boolean":
return false;
case "byte":
return (byte)0;
case "char":
return '\0';
case "short":
return (short)0;
case "int":
return 0;
case "long":
return 0L;
case "float":
return 0F;
case "double":
return 0D;
default:
return null;
}
}
@NotNull
public static String getDefaultValueOfType(PsiType type) {
return getDefaultValueOfType(type, false);
}
@NotNull
public static String getDefaultValueOfType(PsiType type, boolean customDefaultValues) {
if (type instanceof PsiArrayType) {
int count = type.getArrayDimensions() - 1;
PsiType componentType = type.getDeepComponentType();
if (componentType instanceof PsiClassType) {
final PsiClassType classType = (PsiClassType)componentType;
if (classType.resolve() instanceof PsiTypeParameter) {
return PsiKeyword.NULL;
}
}
PsiType erasedComponentType = TypeConversionUtil.erasure(componentType);
StringBuilder buffer = new StringBuilder();
buffer.append(PsiKeyword.NEW);
buffer.append(" ");
buffer.append(erasedComponentType.getCanonicalText());
buffer.append("[0]");
for (int i = 0; i < count; i++) {
buffer.append("[]");
}
return buffer.toString();
}
if (type instanceof PsiPrimitiveType) {
return PsiType.BOOLEAN.equals(type) ? PsiKeyword.FALSE : "0";
}
if (customDefaultValues) {
PsiType rawType = type instanceof PsiClassType ? ((PsiClassType)type).rawType() : null;
if (rawType != null && rawType.equalsToText(CommonClassNames.JAVA_UTIL_OPTIONAL)) {
return CommonClassNames.JAVA_UTIL_OPTIONAL + ".empty()";
}
}
return PsiKeyword.NULL;
}
/**
* Returns the unboxed type name or parameter.
* @param type boxed java type name
* @return unboxed type name if available; same value otherwise
*/
@Contract("null -> null; !null -> !null")
@Nullable
public static String unboxIfPossible(@Nullable String type) {
if (type == null) return null;
final String s = ourUnboxedTypes.get(type);
return s == null? type : s;
}
/**
* Returns the boxed type name or parameter.
* @param type primitive java type name
* @return boxed type name if available; same value otherwise
*/
@Contract("null -> null; !null -> !null")
@Nullable
public static String boxIfPossible(@Nullable String type) {
if (type == null) return null;
final String s = ourBoxedTypes.get(type);
return s == null ? type : s;
}
@Nullable
public static PsiClass getPsiClass(@Nullable PsiType psiType) {
return psiType instanceof PsiClassType? ((PsiClassType)psiType).resolve() : null;
}
@NotNull
public static PsiClassType getClassType(@NotNull PsiClass psiClass) {
return JavaPsiFacade.getElementFactory(psiClass.getProject()).createType(psiClass);
}
@Nullable
public static PsiClassType getLowestUpperBoundClassType(@NotNull final PsiDisjunctionType type) {
final PsiType lub = type.getLeastUpperBound();
if (lub instanceof PsiClassType) {
return (PsiClassType)lub;
}
if (lub instanceof PsiIntersectionType) {
for (PsiType subType : ((PsiIntersectionType)lub).getConjuncts()) {
if (subType instanceof PsiClassType) {
final PsiClass aClass = ((PsiClassType)subType).resolve();
if (aClass != null && !aClass.isInterface()) {
return (PsiClassType)subType;
}
}
}
}
return null;
}
public static PsiType patchMethodGetClassReturnType(@NotNull PsiMethodReferenceExpression methodExpression,
@NotNull PsiMethod method) {
if (isGetClass(method)) {
final PsiType qualifierType = PsiMethodReferenceUtil.getQualifierType(methodExpression);
return qualifierType != null ? createJavaLangClassType(methodExpression, qualifierType, true) : null;
}
return null;
}
public static PsiType patchMethodGetClassReturnType(@NotNull PsiExpression call,
@NotNull PsiReferenceExpression methodExpression,
@NotNull PsiMethod method,
@NotNull Condition<? super IElementType> condition,
@NotNull LanguageLevel languageLevel) {
//JLS3 15.8.2
if (languageLevel.isAtLeast(LanguageLevel.JDK_1_5) && isGetClass(method)) {
PsiExpression qualifier = methodExpression.getQualifierExpression();
PsiType qualifierType = null;
final Project project = call.getProject();
if (qualifier != null) {
qualifierType = TypeConversionUtil.erasure(qualifier.getType());
}
else {
PsiElement parent = call.getContext();
while (parent != null && condition.value(parent instanceof StubBasedPsiElement ? ((StubBasedPsiElement)parent).getElementType()
: parent.getNode().getElementType())) {
parent = parent.getContext();
}
if (parent != null) {
qualifierType = JavaPsiFacade.getElementFactory(project).createType((PsiClass)parent);
}
}
return createJavaLangClassType(methodExpression, qualifierType, true);
}
return null;
}
public static boolean isGetClass(@NotNull PsiMethod method) {
if (GET_CLASS_METHOD.equals(method.getName())) {
PsiClass aClass = method.getContainingClass();
return aClass != null && CommonClassNames.JAVA_LANG_OBJECT.equals(aClass.getQualifiedName());
}
return false;
}
@Nullable
public static PsiType createJavaLangClassType(@NotNull PsiElement context, @Nullable PsiType qualifierType, boolean captureTopLevelWildcards) {
if (qualifierType != null) {
PsiUtil.ensureValidType(qualifierType);
JavaPsiFacade facade = JavaPsiFacade.getInstance(context.getProject());
PsiClass javaLangClass = facade.findClass(CommonClassNames.JAVA_LANG_CLASS, context.getResolveScope());
if (javaLangClass != null && javaLangClass.getTypeParameters().length == 1) {
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY.
put(javaLangClass.getTypeParameters()[0], PsiWildcardType.createExtends(context.getManager(), qualifierType));
final PsiClassType classType = facade.getElementFactory().createType(javaLangClass, substitutor, PsiUtil.getLanguageLevel(context));
return captureTopLevelWildcards ? PsiUtil.captureToplevelWildcards(classType, context) : classType;
}
}
return null;
}
/**
* Return type explicitly declared in parent
*/
@Nullable
public static PsiType getExpectedTypeByParent(@NotNull PsiElement element) {
final PsiElement parent = PsiUtil.skipParenthesizedExprUp(element.getParent());
if (parent instanceof PsiVariable) {
if (PsiUtil.checkSameExpression(element, ((PsiVariable)parent).getInitializer())) {
PsiTypeElement typeElement = ((PsiVariable)parent).getTypeElement();
if (typeElement != null && typeElement.isInferredType()) {
return null;
}
return ((PsiVariable)parent).getType();
}
}
else if (parent instanceof PsiAssignmentExpression) {
if (PsiUtil.checkSameExpression(element, ((PsiAssignmentExpression)parent).getRExpression())) {
PsiType type = ((PsiAssignmentExpression)parent).getLExpression().getType();
return !PsiType.NULL.equals(type) ? type : null;
}
}
else if (parent instanceof PsiReturnStatement) {
final PsiElement psiElement = PsiTreeUtil.getParentOfType(parent, PsiLambdaExpression.class, PsiMethod.class);
if (psiElement instanceof PsiLambdaExpression) {
return null;
}
else if (psiElement instanceof PsiMethod){
return ((PsiMethod)psiElement).getReturnType();
}
}
else if (PsiUtil.isCondition(element, parent)) {
return PsiType.BOOLEAN.getBoxedType(parent);
}
else if (parent instanceof PsiArrayInitializerExpression) {
final PsiElement gParent = parent.getParent();
if (gParent instanceof PsiNewExpression) {
final PsiType type = ((PsiNewExpression)gParent).getType();
if (type instanceof PsiArrayType) {
return ((PsiArrayType)type).getComponentType();
}
}
else if (gParent instanceof PsiVariable) {
final PsiType type = ((PsiVariable)gParent).getType();
if (type instanceof PsiArrayType) {
return ((PsiArrayType)type).getComponentType();
}
}
else if (gParent instanceof PsiArrayInitializerExpression) {
final PsiType expectedTypeByParent = getExpectedTypeByParent(parent);
return expectedTypeByParent instanceof PsiArrayType ? ((PsiArrayType)expectedTypeByParent).getComponentType() : null;
}
}
return null;
}
/**
* Returns the return type for enclosing method or lambda
*
* @param element element inside method or lambda to determine the return type of
* @return the return type or null if cannot be determined
*/
@Nullable
public static PsiType getMethodReturnType(@NotNull PsiElement element) {
final PsiElement methodOrLambda = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiLambdaExpression.class);
return methodOrLambda instanceof PsiMethod
? ((PsiMethod)methodOrLambda).getReturnType()
: methodOrLambda instanceof PsiLambdaExpression ? LambdaUtil.getFunctionalInterfaceReturnType((PsiLambdaExpression)methodOrLambda) : null;
}
public static boolean compareTypes(PsiType leftType, PsiType rightType, boolean ignoreEllipsis) {
if (ignoreEllipsis) {
if (leftType instanceof PsiEllipsisType) {
leftType = ((PsiEllipsisType)leftType).toArrayType();
}
if (rightType instanceof PsiEllipsisType) {
rightType = ((PsiEllipsisType)rightType).toArrayType();
}
}
return Comparing.equal(leftType, rightType);
}
/**
* Not compliant to specification, use {@link PsiTypesUtil#isDenotableType(PsiType, PsiElement)} instead
*/
@Deprecated
public static boolean isDenotableType(@Nullable PsiType type) {
return !(type instanceof PsiWildcardType || type instanceof PsiCapturedWildcardType);
}
/**
* @param context in which type should be checked
* @return false if type is null or has no explicit canonical type representation (e. g. intersection type)
*/
public static boolean isDenotableType(@Nullable PsiType type, @NotNull PsiElement context) {
if (type == null || type instanceof PsiWildcardType) return false;
PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(context.getProject());
try {
PsiType typeAfterReplacement = elementFactory.createTypeElementFromText(type.getCanonicalText(), context).getType();
return type.equals(typeAfterReplacement);
} catch (IncorrectOperationException e) {
return false;
}
}
public static boolean hasUnresolvedComponents(@NotNull PsiType type) {
return type.accept(new PsiTypeVisitor<Boolean>() {
@Nullable
@Override
public Boolean visitClassType(PsiClassType classType) {
PsiClassType.ClassResolveResult resolveResult = classType.resolveGenerics();
final PsiClass psiClass = resolveResult.getElement();
if (psiClass == null) {
return true;
}
PsiSubstitutor substitutor = resolveResult.getSubstitutor();
for (PsiTypeParameter param : PsiUtil.typeParametersIterable(psiClass)) {
PsiType psiType = substitutor.substitute(param);
if (psiType != null && psiType.accept(this)) {
return true;
}
}
return super.visitClassType(classType);
}
@Nullable
@Override
public Boolean visitArrayType(PsiArrayType arrayType) {
return arrayType.getComponentType().accept(this);
}
@NotNull
@Override
public Boolean visitWildcardType(PsiWildcardType wildcardType) {
final PsiType bound = wildcardType.getBound();
return bound != null && bound.accept(this);
}
@Override
public Boolean visitType(PsiType type) {
return false;
}
});
}
@NotNull
public static PsiType getParameterType(@NotNull PsiParameter[] parameters, int i, boolean varargs) {
final PsiParameter parameter = parameters[i < parameters.length ? i : parameters.length - 1];
PsiType parameterType = parameter.getType();
if (parameterType instanceof PsiEllipsisType && varargs) {
parameterType = ((PsiEllipsisType)parameterType).getComponentType();
}
if (!parameterType.isValid()) {
PsiUtil.ensureValidType(parameterType, "Invalid type of parameter " + parameter + " of " + parameter.getClass());
}
return parameterType;
}
@NotNull
public static PsiTypeParameter[] filterUnusedTypeParameters(@NotNull PsiTypeParameter[] typeParameters, @NotNull PsiType... types) {
if (typeParameters.length == 0) return PsiTypeParameter.EMPTY_ARRAY;
TypeParameterSearcher searcher = new TypeParameterSearcher();
for (PsiType type : types) {
type.accept(searcher);
}
return searcher.getTypeParameters().toArray(PsiTypeParameter.EMPTY_ARRAY);
}
@NotNull
public static PsiTypeParameter[] filterUnusedTypeParameters(@NotNull PsiType superReturnTypeInBaseClassType,
@NotNull PsiTypeParameter[] typeParameters) {
return filterUnusedTypeParameters(typeParameters, superReturnTypeInBaseClassType);
}
private static boolean isAccessibleAt(@NotNull PsiTypeParameter parameter, @NotNull PsiElement context) {
PsiTypeParameterListOwner owner = parameter.getOwner();
if(owner instanceof PsiMethod) {
return PsiTreeUtil.isAncestor(owner, context, false);
}
if(owner instanceof PsiClass) {
return PsiTreeUtil.isAncestor(owner, context, false) &&
InheritanceUtil.hasEnclosingInstanceInScope((PsiClass)owner, context, false, false);
}
return false;
}
public static boolean allTypeParametersResolved(@NotNull PsiElement context, @NotNull PsiType targetType) {
TypeParameterSearcher searcher = new TypeParameterSearcher();
targetType.accept(searcher);
Set<PsiTypeParameter> parameters = searcher.getTypeParameters();
return parameters.stream().allMatch(parameter -> isAccessibleAt(parameter, context));
}
@NotNull
public static PsiType createArrayType(@NotNull PsiType newType, int arrayDim) {
for(int i = 0; i < arrayDim; i++){
newType = newType.createArrayType();
}
return newType;
}
/**
* @return null if type can't be explicitly specified
*/
@Nullable
public static PsiTypeElement replaceWithExplicitType(PsiTypeElement typeElement) {
PsiType type = typeElement.getType();
if (!isDenotableType(type, typeElement)) {
return null;
}
Project project = typeElement.getProject();
PsiTypeElement typeElementByExplicitType = JavaPsiFacade.getElementFactory(project).createTypeElement(type);
PsiElement explicitTypeElement = typeElement.replace(typeElementByExplicitType);
explicitTypeElement = JavaCodeStyleManager.getInstance(project).shortenClassReferences(explicitTypeElement);
return (PsiTypeElement)CodeStyleManager.getInstance(project).reformat(explicitTypeElement);
}
public static class TypeParameterSearcher extends PsiTypeVisitor<Boolean> {
private final Set<PsiTypeParameter> myTypeParams = new HashSet<>();
@NotNull
public Set<PsiTypeParameter> getTypeParameters() {
return myTypeParams;
}
@Override
public Boolean visitType(final PsiType type) {
return false;
}
@Override
public Boolean visitArrayType(final PsiArrayType arrayType) {
return arrayType.getComponentType().accept(this);
}
@Override
public Boolean visitClassType(final PsiClassType classType) {
PsiClassType.ClassResolveResult resolveResult = classType.resolveGenerics();
final PsiClass aClass = resolveResult.getElement();
if (aClass instanceof PsiTypeParameter) {
myTypeParams.add((PsiTypeParameter)aClass);
}
if (aClass != null) {
PsiSubstitutor substitutor = resolveResult.getSubstitutor();
for (final PsiTypeParameter parameter : PsiUtil.typeParametersIterable(aClass)) {
PsiType psiType = substitutor.substitute(parameter);
if (psiType != null) {
psiType.accept(this);
}
}
}
return false;
}
@Override
public Boolean visitWildcardType(final PsiWildcardType wildcardType) {
final PsiType bound = wildcardType.getBound();
if (bound != null) {
bound.accept(this);
}
return false;
}
}
}
| |
package at.willhaben.willtest.misc.pages;
import at.willhaben.willtest.misc.utils.WhFluentWait;
import at.willhaben.willtest.misc.utils.XPathOrCssUtil;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.FluentWait;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* Base class for Pageobjects with some common functions.
*/
public abstract class PageObject {
public static final long DEFAULT_WAIT_TIMEOUT = 30L;
private final WebDriver driver;
protected PageObject(WebDriver driver) {
this.driver = driver;
initElements();
initPage();
}
/**
* @return current {@link WebDriver}
*/
public WebDriver getWebDriver() {
return driver;
}
/**
* This method calls the {@link PageFactory#initElements(WebDriver, Object)} method to init every annotated
* {@link WebElement} in the pageobject. It is automatically called on pageobject creation.
*/
protected void initElements() {
PageFactory.initElements(this.driver, this);
}
/**
* Called in the constructor {@link #PageObject(WebDriver)}. Can be
* overridden to wait for some conditions to become true to ensure the page is fully loaded.
*/
public void initPage() {}
/**
* Moves one page back.
*/
public void goBack() {
driver.navigate().back();
}
/**
* Refreshes the current page.
*/
public void refresh() {
driver.navigate().refresh();
}
/**
* Returns a random element of a given list.
* @param elements list of elements
* @param <T> type of elements
* @return a random element of the list
*/
public <T> T getRandomElement(List<T> elements) {
return getRandomElement(0, elements);
}
/**
* Returns a random element of a given list.
* @param lowerBound minimal index for the calculation of the random element
* @param elements list of elements
* @param <T> type of elements
* @return a random element of the list
*/
public <T> T getRandomElement(int lowerBound, List<T> elements) {
int randomIndex = ThreadLocalRandom.current().nextInt(elements.size() - lowerBound) + lowerBound;
return elements.get(randomIndex);
}
/**
* Clicks on a random {@link WebElement} in given list.
* @param elements list of {@link WebElement}
*/
public void clickRandomWebElement(List<WebElement> elements) {
getRandomElement(elements).click();
}
/**
* Clicks on a random {@link WebElement} in given list.
* @param lowerBound minimal index for the calculation of the random element
* @param elements list of {@link WebElement}
*/
public void clickRandomWebElement(int lowerBound, List<WebElement> elements) {
getRandomElement(lowerBound, elements).click();
}
/**
* Waiting on a specific {@link WebElement}.
* @param element to wait for
* @return Builder for waiting for a specific element.
*/
public WaitForBuilder waitFor(WebElement element) {
return new WaitForBuilder(this, element);
}
/**
* Waiting on a specific {@link WebElement} identified by an XPath expression or a CSS selector.
* @param xPathOrCss to wait for
* @return Builder for waiting for a specific element.
*/
public WaitForBuilder waitFor(String xPathOrCss) {
return new WaitForBuilder(this, XPathOrCssUtil.mapToBy(xPathOrCss));
}
/**
* Waiting on a specific {@link WebElement} identified by a {@link By}.
* @param by to wait for
* @return Builder for waiting for a specific element.
*/
public WaitForBuilder waitFor(By by) {
return new WaitForBuilder(this, by);
}
/**
* Waiting on a set of elements.
* @param elements to wait for
* @return Builder to create different waiting conditions.
*/
public RequireBuilder require(WebElement... elements) {
return new RequireBuilder(this, new RequireType(elements));
}
/**
* Waiting on a set of elements.
* @param xPathOrCss XPath or CSS locators to wait for
* @return Builder to create different waiting conditions.
*/
public RequireBuilder require(String... xPathOrCss) {
return new RequireBuilder(this, new RequireType(Arrays.stream(xPathOrCss)
.map(XPathOrCssUtil::mapToBy)
.toArray(By[]::new)));
}
/**
* Waiting on a set of elements.
* @param bys locators to wait for
* @return Builder to create different waiting conditions.
*/
public RequireBuilder require(By... bys) {
return new RequireBuilder(this, new RequireType(bys));
}
/**
* Used to check if an element is available or visible.
* @param webElement element to check
* @return Builder for checking appearance of element.
*/
public IsAvailableBuilder is(WebElement webElement) {
return new IsAvailableBuilder(this, webElement);
}
/**
* Used to check if an element is available or visible.
* @param xPathOrCss XPath or CSS locator of element
* @return Builder for checking appearance of element.
*/
public IsAvailableBuilder is(String xPathOrCss) {
return new IsAvailableBuilder(this, XPathOrCssUtil.mapToBy(xPathOrCss));
}
/**
* Used to check if an element is available or visible.
* @param by locator of the element to check
* @return Builder for checking appearance of element.
*/
public IsAvailableBuilder is(By by) {
return new IsAvailableBuilder(this, by);
}
/**
* Same as {@link #getWait(long)} with a default wait of {@value DEFAULT_WAIT_TIMEOUT} seconds.
* @return
*/
protected WhFluentWait<WebDriver> getWait() {
return getWait(DEFAULT_WAIT_TIMEOUT);
}
/**
* Generates a default {@link FluentWait} which ignores {@link NoSuchElementException} and
* {@link StaleElementReferenceException}. Polls every 250 milliseconds.
* @param timeout Timeout in seconds
* @return Waiter
*/
protected WhFluentWait<WebDriver> getWait(long timeout) {
return getWait(Duration.ofSeconds(timeout), Duration.ofMillis(250L));
}
protected WhFluentWait<WebDriver> getWait(Duration waitFor, Duration polling) {
return (WhFluentWait<WebDriver>) new WhFluentWait<>(driver)
.withTimeout(waitFor)
.ignoring(NoSuchElementException.class)
.ignoring(StaleElementReferenceException.class)
.pollingEvery(polling);
}
public <T> Optional<T> waitFor(Function<? super WebDriver, T> findFunction, long timeout) {
try {
return Optional.of(getWait(timeout).until(findFunction));
} catch (TimeoutException e) {
return Optional.empty();
}
}
protected Optional<WebElement> findWithFilter(By selector, Predicate<WebElement> predicate) {
return findWithFilter(driver, selector, predicate);
}
protected <T> Optional<T> findWithFilter(List<T> elements, Predicate<T> predicate) {
return elements.stream()
.filter(predicate)
.findFirst();
}
protected Optional<WebElement> findWithFilter(SearchContext searchContext, By selector, Predicate<WebElement> predicate) {
return searchContext.findElements(selector).stream()
.filter(predicate)
.findFirst();
}
}
| |
/*
* 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.kubernetes.highavailability;
import org.apache.flink.kubernetes.configuration.KubernetesLeaderElectionConfiguration;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.KubernetesConfigMapSharedWatcher;
import org.apache.flink.kubernetes.kubeclient.KubernetesSharedWatcher.Watch;
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesConfigMap;
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesException;
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesLeaderElector;
import org.apache.flink.kubernetes.utils.KubernetesUtils;
import org.apache.flink.runtime.leaderelection.LeaderElectionDriver;
import org.apache.flink.runtime.leaderelection.LeaderElectionEventHandler;
import org.apache.flink.runtime.leaderelection.LeaderElectionException;
import org.apache.flink.runtime.leaderelection.LeaderInformation;
import org.apache.flink.runtime.rpc.FatalErrorHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import static org.apache.flink.kubernetes.utils.Constants.LABEL_CONFIGMAP_TYPE_HIGH_AVAILABILITY;
import static org.apache.flink.kubernetes.utils.Constants.LEADER_ADDRESS_KEY;
import static org.apache.flink.kubernetes.utils.Constants.LEADER_SESSION_ID_KEY;
import static org.apache.flink.kubernetes.utils.KubernetesUtils.checkConfigMaps;
import static org.apache.flink.kubernetes.utils.KubernetesUtils.getLeaderInformationFromConfigMap;
import static org.apache.flink.util.Preconditions.checkNotNull;
/**
* {@link LeaderElectionDriver} implementation for Kubernetes. The active leader is elected using
* Kubernetes. The current leader's address as well as its leader session ID is published via
* Kubernetes ConfigMap. Note that the contending lock and leader storage are using the same
* ConfigMap. And every component(e.g. ResourceManager, Dispatcher, RestEndpoint, JobManager for
* each job) will have a separate ConfigMap.
*/
public class KubernetesLeaderElectionDriver implements LeaderElectionDriver {
private static final Logger LOG = LoggerFactory.getLogger(KubernetesLeaderElectionDriver.class);
private final FlinkKubeClient kubeClient;
private final String configMapName;
private final String lockIdentity;
private final KubernetesLeaderElector leaderElector;
// Labels will be used to clean up the ha related ConfigMaps.
private final Map<String, String> configMapLabels;
private final LeaderElectionEventHandler leaderElectionEventHandler;
private final FatalErrorHandler fatalErrorHandler;
private volatile boolean running;
private final Watch kubernetesWatch;
public KubernetesLeaderElectionDriver(
FlinkKubeClient kubeClient,
KubernetesConfigMapSharedWatcher configMapSharedWatcher,
ExecutorService watchExecutorService,
KubernetesLeaderElectionConfiguration leaderConfig,
LeaderElectionEventHandler leaderElectionEventHandler,
FatalErrorHandler fatalErrorHandler) {
this.kubeClient = checkNotNull(kubeClient, "Kubernetes client");
checkNotNull(leaderConfig, "Leader election configuration");
this.leaderElectionEventHandler =
checkNotNull(leaderElectionEventHandler, "LeaderElectionEventHandler");
this.fatalErrorHandler = checkNotNull(fatalErrorHandler);
this.configMapName = leaderConfig.getConfigMapName();
this.lockIdentity = leaderConfig.getLockIdentity();
this.leaderElector =
kubeClient.createLeaderElector(leaderConfig, new LeaderCallbackHandlerImpl());
this.configMapLabels =
KubernetesUtils.getConfigMapLabels(
leaderConfig.getClusterId(), LABEL_CONFIGMAP_TYPE_HIGH_AVAILABILITY);
running = true;
leaderElector.run();
kubernetesWatch =
checkNotNull(configMapSharedWatcher, "ConfigMap Shared Informer")
.watch(
configMapName,
new ConfigMapCallbackHandlerImpl(),
watchExecutorService);
}
@Override
public void close() {
if (!running) {
return;
}
running = false;
LOG.info("Closing {}.", this);
leaderElector.stop();
kubernetesWatch.close();
}
@Override
public void writeLeaderInformation(LeaderInformation leaderInformation) {
assert (running);
final UUID confirmedLeaderSessionID = leaderInformation.getLeaderSessionID();
final String confirmedLeaderAddress = leaderInformation.getLeaderAddress();
try {
kubeClient
.checkAndUpdateConfigMap(
configMapName,
configMap -> {
if (KubernetesLeaderElector.hasLeadership(
configMap, lockIdentity)) {
// Get the updated ConfigMap with new leader information
if (confirmedLeaderAddress == null) {
configMap.getData().remove(LEADER_ADDRESS_KEY);
} else {
configMap
.getData()
.put(LEADER_ADDRESS_KEY, confirmedLeaderAddress);
}
if (confirmedLeaderSessionID == null) {
configMap.getData().remove(LEADER_SESSION_ID_KEY);
} else {
configMap
.getData()
.put(
LEADER_SESSION_ID_KEY,
confirmedLeaderSessionID.toString());
}
configMap.getLabels().putAll(configMapLabels);
return Optional.of(configMap);
}
return Optional.empty();
})
.get();
if (LOG.isDebugEnabled()) {
LOG.debug(
"Successfully wrote leader information: Leader={}, session ID={}.",
confirmedLeaderAddress,
confirmedLeaderSessionID);
}
} catch (Exception e) {
fatalErrorHandler.onFatalError(
new KubernetesException(
"Could not write leader information since ConfigMap "
+ configMapName
+ " does not exist.",
e));
}
}
@Override
public boolean hasLeadership() {
assert (running);
final Optional<KubernetesConfigMap> configMapOpt = kubeClient.getConfigMap(configMapName);
if (configMapOpt.isPresent()) {
return KubernetesLeaderElector.hasLeadership(configMapOpt.get(), lockIdentity);
} else {
fatalErrorHandler.onFatalError(
new KubernetesException(
"ConfigMap " + configMapName + " does not exist.", null));
return false;
}
}
private class LeaderCallbackHandlerImpl extends KubernetesLeaderElector.LeaderCallbackHandler {
@Override
public void isLeader() {
leaderElectionEventHandler.onGrantLeadership();
}
@Override
public void notLeader() {
leaderElectionEventHandler.onRevokeLeadership();
// Continue to contend the leader
leaderElector.run();
}
}
private class ConfigMapCallbackHandlerImpl
implements FlinkKubeClient.WatchCallbackHandler<KubernetesConfigMap> {
@Override
public void onAdded(List<KubernetesConfigMap> configMaps) {
// noop
}
@Override
public void onModified(List<KubernetesConfigMap> configMaps) {
// We should only receive events for the watched ConfigMap
final KubernetesConfigMap configMap = checkConfigMaps(configMaps, configMapName);
if (KubernetesLeaderElector.hasLeadership(configMap, lockIdentity)) {
leaderElectionEventHandler.onLeaderInformationChange(
getLeaderInformationFromConfigMap(configMap));
}
}
@Override
public void onDeleted(List<KubernetesConfigMap> configMaps) {
final KubernetesConfigMap configMap = checkConfigMaps(configMaps, configMapName);
// The ConfigMap is deleted externally.
if (KubernetesLeaderElector.hasLeadership(configMap, lockIdentity)) {
fatalErrorHandler.onFatalError(
new LeaderElectionException(
"ConfigMap " + configMapName + " is deleted externally"));
}
}
@Override
public void onError(List<KubernetesConfigMap> configMaps) {
final KubernetesConfigMap configMap = checkConfigMaps(configMaps, configMapName);
if (KubernetesLeaderElector.hasLeadership(configMap, lockIdentity)) {
fatalErrorHandler.onFatalError(
new LeaderElectionException(
"Error while watching the ConfigMap " + configMapName));
}
}
@Override
public void handleError(Throwable throwable) {
fatalErrorHandler.onFatalError(
new LeaderElectionException(
"Error while watching the ConfigMap " + configMapName, throwable));
}
}
@Override
public String toString() {
return "KubernetesLeaderElectionDriver{configMapName='" + configMapName + "'}";
}
}
| |
// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// 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.
//
// 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 jodd.json;
import jodd.util.ArraysUtil;
import jodd.util.InExRules;
import jodd.util.UnsafeUtil;
import jodd.util.buffer.FastCharBuffer;
import java.util.HashMap;
import java.util.Map;
/**
* JSON serializer.
*/
public class JsonSerializer {
/**
* Static ctor.
*/
public static JsonSerializer create() {
return new JsonSerializer();
}
// ---------------------------------------------------------------- config
protected Map<Path, TypeJsonSerializer> pathSerializersMap;
protected TypeJsonSerializerMap typeSerializersMap;
protected InExRules<Path, PathQuery> rules = new InExRules<Path, PathQuery>() {
@Override
public boolean accept(Path value, PathQuery rule, boolean include) {
return rule.matches(value);
}
};
protected String classMetadataName = JoddJson.classMetadataName;
protected boolean deep = JoddJson.deepSerialization;
protected Class[] excludedTypes = null;
protected String[] excludedTypeNames = null;
protected boolean excludeNulls = false;
/**
* Defines custom {@link jodd.json.TypeJsonSerializer} for given path.
*/
public JsonSerializer withSerializer(String pathString, TypeJsonSerializer typeJsonSerializer) {
if (pathSerializersMap == null) {
pathSerializersMap = new HashMap<>();
}
pathSerializersMap.put(Path.parse(pathString), typeJsonSerializer);
return this;
}
/**
* Defines custom {@link jodd.json.TypeJsonSerializer} for given type.
*/
public JsonSerializer withSerializer(Class type, TypeJsonSerializer typeJsonSerializer) {
if (typeSerializersMap == null) {
typeSerializersMap = new TypeJsonSerializerMap(JoddJson.defaultSerializers);
}
typeSerializersMap.register(type, typeJsonSerializer);
return this;
}
/**
* Adds include path query.
*/
public JsonSerializer include(String include) {
rules.include(new PathQuery(include, true));
return this;
}
/**
* Adds a list of included path queries.
*/
public JsonSerializer include(String... includes) {
for (String include : includes) {
include(include);
}
return this;
}
/**
* Adds exclude path query.
*/
public JsonSerializer exclude(String exclude) {
rules.exclude(new PathQuery(exclude, false));
return this;
}
/**
* Adds a list of excluded path queries.
*/
public JsonSerializer exclude(String... excludes) {
for (String exclude : excludes) {
exclude(exclude);
}
return this;
}
/**
* Adds excludes with optional parent including. When parents are included,
* for each exclude query its parent will be included.
* For example, exclude of 'aaa.bb.ccc' would include it's parent: 'aaa.bb'.
*/
public JsonSerializer exclude(boolean includeParent, String... excludes) {
for (String exclude : excludes) {
if (includeParent) {
int dotIndex = exclude.lastIndexOf('.');
if (dotIndex != -1) {
PathQuery pathQuery = new PathQuery(exclude.substring(0, dotIndex), true);
rules.include(pathQuery);
}
}
PathQuery pathQuery = new PathQuery(exclude, false);
rules.exclude(pathQuery);
}
return this;
}
/**
* Sets local class meta-data name.
*/
public JsonSerializer setClassMetadataName(String name) {
classMetadataName = name;
return this;
}
/**
* Defines if collections should be followed, i.e. to perform
* deep serialization.
*/
public JsonSerializer deep(boolean includeCollections) {
this.deep = includeCollections;
return this;
}
/**
* Excludes type names. You can disable
* serialization of properties that are of some type.
* For example, you can disable properties of <code>InputStream</code>.
* You can use wildcards to describe type names.
*/
public JsonSerializer excludeTypes(String... typeNames) {
if (excludedTypeNames == null) {
excludedTypeNames = typeNames;
} else {
excludedTypeNames = ArraysUtil.join(excludedTypeNames, typeNames);
}
return this;
}
/**
* Excludes types. Supports interfaces and subclasses as well.
*/
public JsonSerializer excludeTypes(Class... types) {
if (excludedTypes == null) {
excludedTypes = types;
} else {
excludedTypes = ArraysUtil.join(excludedTypes, types);
}
return this;
}
/**
* Excludes <code>null</code> values while serializing.
*/
public JsonSerializer excludeNulls(boolean excludeNulls) {
this.excludeNulls = excludeNulls;
return this;
}
// ---------------------------------------------------------------- serialize
/**
* Serializes object into provided appendable.
*/
public void serialize(Object source, Appendable target) {
JsonContext jsonContext = new JsonContext(this, target, excludeNulls);
jsonContext.serialize(source);
}
/**
* Serializes object into source.
*/
public String serialize(Object source) {
FastCharBuffer fastCharBuffer = new FastCharBuffer();
serialize(source, fastCharBuffer);
return UnsafeUtil.createString(fastCharBuffer.toArray());
}
// ---------------------------------------------------------------- json context
/**
* Creates new JSON context.
*/
public JsonContext createJsonContext(Appendable appendable) {
return new JsonContext(this, appendable, excludeNulls);
}
}
| |
package ru.szhernovoy.jobvacancy.controller;/**
* Created by szhernovoy on 14.11.2016.
*/
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import ru.szhernovoy.jobvacancy.model.Vacancy;
import java.sql.*;
import java.util.Properties;
public class DBManager {
/**logger */
private static Logger log = LoggerFactory.getLogger(DBManager.class);
/**main connector to base */
private Connection conn;
public DBManager(final Properties fileProperties) {
this.connect(fileProperties);
}
/**
* Try connect to base date
* @param
* @return
*/
public boolean connect(Properties properties) {
boolean result = false;
try {
this.conn = DriverManager.getConnection(properties.getProperty("url"), properties);
result = true;
log.info("connect to a date base", conn);
} catch (SQLException e) {
log.error(e.getMessage(),e);
}
return result;
}
@Override
protected void finalize() throws Throwable {
this.close();
}
/**
* add vacancy into date base
* @param vacancy
* @return
*/
public boolean add(Vacancy vacancy){
PreparedStatement st = null;
ResultSet rs = null;
try {
int author_id = 0;
st = conn.prepareStatement("SELECT a.author_id FROM author as a WHERE a.linkAuthor = ?");
st.setString(1,vacancy.getUrlAuthor());
rs = st.executeQuery();
if(rs.next()) {
author_id = rs.getInt("author_id");
}
else{
st = conn.prepareStatement("INSERT INTO author(linkAuthor,nameAuthor) VALUES (?,?)",Statement.RETURN_GENERATED_KEYS);
st.setString(1,vacancy.getUrlAuthor());
st.setString(2,vacancy.getAuthor());
st.executeUpdate();
rs = st.getGeneratedKeys();
if(rs.next()){
author_id = rs.getInt("author_id");
}
log.info("update date in table author", st);
}
st = conn.prepareStatement("INSERT INTO vacancy(vacancy_name,vacancy_link,ask,answer,last_update,author_id) VALUES (?,?,?,?,?,?)");
st.setString(1,vacancy.getTitle());
st.setString(2,vacancy.getUrlVacancy());
st.setInt(3,vacancy.getView());
st.setInt(4,vacancy.getAnswer());
st.setTimestamp(5,new Timestamp(vacancy.getUpdateDate()));
st.setInt(6,author_id);
st.executeUpdate();
log.info("update date in table vacancy", st);
} catch (Exception e) {
log.error(e.getMessage(),e);
}
finally {
try{
rs.close();
st.close();
}
catch (Exception e){
log.error(e.getMessage(),e);
}
}
return true;
}
/**
* print all vacancies
* @return
*/
public boolean printVacancy(){
boolean result = true;
PreparedStatement st = null;
ResultSet rs = null;
try {
st = conn.prepareStatement("SELECT v.vacancy_name, v.ask, v.answer, v.last_update, a.nameAuthor FROM vacancy as v LEFT OUTER JOIN author as a ON v.author_id = a.author_id ORDER BY v.vacancy_id ");
rs = st.executeQuery();
while (rs.next()) {
log.info(String.format("vacancy - %s, view - %d, answer - %d, last update - %s, author - %s ",rs.getString("vacancy_name"),rs.getInt("ask"),rs.getInt("answer"),String.valueOf(rs.getTimestamp("last_update").getTime()),rs.getString("nameAuthor")));
}
} catch (Exception e) {
result = false;
log.error(e.getMessage(),e);
}
finally {
try{
rs.close();
st.close();
}
catch (Exception e){
result = false;
log.error(e.getMessage(),e);
}
}
return result;
}
/**
* close connect to base
* @return
*/
public boolean close(){
boolean result = false;
if(conn !=null ){
try{
conn.close();
result = true;
}
catch(SQLException e){
log.error(e.getMessage(),e);
}
}
return result;
}
/**
* get last download vacancies
* @return
*/
public long getLastLoad(){
PreparedStatement st = null;
ResultSet rs = null;
long result = 0;
try {
st = conn.prepareStatement("SELECT d.lastDate FROM work as d");
rs = st.executeQuery();
if(rs.next()) {
result = rs.getTimestamp("lastdate").getTime();
log.info("get time last load");
}
} catch (Exception e) {
log.error(e.getMessage(),e);
}
finally {
try{
st.close();
rs.close();
}
catch (Exception e){
log.error(e.getMessage(),e);
}
}
return result;
}
/**
* set last tome download vacancies
* @param time
* @return
*/
public long setTimeLoad(long time){
PreparedStatement st = null;
try {
st = conn.prepareStatement("INSERT INTO work(lastDate) VALUES (?)");
st.setTimestamp(1,new Timestamp(time));
st.executeUpdate();
log.info("update time last vacancies");
} catch (Exception e) {
log.error(e.getMessage(),e);
}
finally {
try{
st.close();
}
catch (Exception e){
log.error(e.getMessage(),e);
}
}
return time;
}
}
| |
package com.amazonaws.services.dynamodbv2.json.demo.mars;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Logger;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.json.demo.mars.util.ConfigParser;
import com.amazonaws.services.dynamodbv2.json.demo.mars.util.DynamoDBManager;
import com.amazonaws.services.dynamodbv2.json.demo.mars.util.MarsDynamoDBManager;
import com.amazonaws.services.dynamodbv2.json.demo.mars.worker.DynamoDBImageWorker;
import com.amazonaws.services.dynamodbv2.json.demo.mars.worker.DynamoDBJSONRootWorker;
import com.amazonaws.services.dynamodbv2.json.demo.mars.worker.DynamoDBMissionWorker;
import com.amazonaws.services.dynamodbv2.json.demo.mars.worker.DynamoDBSolWorker;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* <p>
* Downloads mars image JSON and ingests it into DynamoDB.
* </p>
* <p>
* Makes use of 2 DynamoDB Tables:
* <ul>
* <li>Resource table: stores ETags for manifests and image resources.</li>
* <li>Image table: stores the images from the Mars rover missions.</li>
* </ul>
* </p>
*/
public class ImageIngester implements Runnable {
/**
* Logger for the {@link ImageIngester}.
*/
public static final Logger LOGGER = Logger.getLogger(ImageIngester.class.getName());
// Configuration constants
/**
* Default number of threads for a thread pool.
*/
public static final int DEFAULT_THREADS = 1;
/**
* Properties key for number of threads in the pool for {@link DynamoDBJSONRootWorker}s and
* {@link DynamoDBMissionWorker}s.
*/
public static final String CONFIG_NUM_MANIFEST_THREADS = "ingester.manifest.threads";
/**
* Properties key for number of threads in the pool for {@link DynamoDBSolWorker}s.
*/
public static final String CONFIG_NUM_SOL_THREADS = "ingester.sol.threads";
/**
* Properties key for number of threads in the pool for {@link DynamoDBImageWorker}s.
*/
public static final String CONFIG_NUM_IMAGE_THREADS = "ingester.image.threads";
/**
* Flag for whether resources should be tracked by ETag in a DynamoDB table.
*/
public static final String CONFIG_TRACK_RESOURCES = "ingester.track-resources";
/**
* Default behavior is to not track resources.
*/
public static final boolean DEFAULT_TRACK_RESOURCES = false;
/**
* Flag for whether to store image thumbnails in the DynamoDB table.
*/
public static final String CONFIG_STORE_THUMBNAILS = "ingester.store-thumbnails";
/**
* Default is to not include thumbnails.
*/
public static final boolean DEFAULT_STORE_THUMBNAILS = false;
/**
* Properties key for the amount of time to wait between checking asynchronous tasks for completion.
*/
public static final String CONFIG_WAIT_TIME = "ingester.waitTime";
/**
* Default amount of time to wait between checking asynchronous tasks for completion.
*/
public static final long DEFAULT_WAIT_TIME = 20 * 1000; // 20 seconds
/**
* Properties key for the connect timeout when retrieving an HTTP resource.
*/
public static final String CONFIG_CONNECT_TIMEOUT = "ingester.timeout";
/**
* Default connect timeout when retrieving an HTTP resource.
*/
public static final int DEFAULT_CONNECT_TIMEOUT = 1000;
/**
* Properties key for image thumbnail width in pixels.
*/
public static final String CONFIG_THUMBNAIL_WIDTH = "ingester.image.thumbnail.width";
/**
* Properties key for image thumbnail height in pixels.
*/
public static final String CONFIG_THUMBNAIL_HEIGHT = "ingester.image.thumbnail.height";
/**
* Default value for image thumbnail width in pixels.
*/
public static final int DEFAULT_THUMBNAIL_WIDTH = 100;
/**
* Default value for image thumbnail height in pixels.
*/
public static final int DEFAULT_THUMBNAIL_HEIGHT = 100;
/**
* Properties key for DynamoDB endpoint.
*/
public static final String CONFIG_ENDPOINT = "dynamodb.endpoint";
/**
* Properties key for the JSON root URL.
*/
public static final String CONFIG_JSON_ROOT = "JSON.root";
/**
* Properties key for the DynamoDB resource table name.
*/
public static final String CONFIG_RESOURCE_TABLE = "dynamodb.resource";
/**
* Properties key for the DynamoDB image table name.
*/
public static final String CONFIG_IMAGE_TABLE = "dynamodb.image";
/**
* Properties key for the resource table create flag.
*/
public static final String CONFIG_RESOURCE_TABLE_CREATE = "dynamodb.resource.create";
/**
* Properties key for the resource table read capacity units.
*/
public static final String CONFIG_RESOURCE_TABLE_RCU = "dynamodb.resource.readCapacityUnits";
/**
* Properties key for the resource table write capacity units.
*/
public static final String CONFIG_RESOURCE_TABLE_WCU = "dynamodb.resource.writeCapacityUnits";
/**
* Properties key for the image table create flag.
*/
public static final String CONFIG_IMAGE_TABLE_CREATE = "dynamodb.image.create";
/**
* Properties key for the image table read capacity units.
*/
public static final String CONFIG_IMAGE_TABLE_RCU = "dynamodb.image.readCapacityUnits";
/**
* Properties key for the image table write capacity units.
*/
public static final String CONFIG_IMAGE_TABLE_WCU = "dynamodb.image.writeCapacityUnits";
/**
* Properties key for the read capacity units of the time global secondary index on the image table.
*/
public static final String CONFIG_IMAGE_TABLE_TIME_GSI_RCU = "dynamodb.image.globalSecondaryIndex.time.readCapacityUnits";
/**
* Properties key for the write capacity units of the time global secondary index on the image table.
*/
public static final String CONFIG_IMAGE_TABLE_TIME_GSI_WCU = "dynamodb.image.globalSecondaryIndex.time.writeCapacityUnits";
/**
* Properties key for the read capacity units of the vote global secondary index on the image table.
*/
public static final String CONFIG_IMAGE_TABLE_VOTE_GSI_RCU = "dynamodb.image.globalSecondaryIndex.vote.readCapacityUnits";
/**
* Properties key for the write capacity units of the vote global secondary index on the image table.
*/
public static final String CONFIG_IMAGE_TABLE_VOTE_GSI_WCU = "dynamodb.image.globalSecondaryIndex.vote.writeCapacityUnits";
/**
* Required String properties in configuration.
*/
private static final String[] REQUIRED_STRING_CONFIGURATIONS = {CONFIG_ENDPOINT, CONFIG_JSON_ROOT,
CONFIG_IMAGE_TABLE};
/**
* Required Boolean properties in configuration.
*/
private static final String[] REQUIRED_BOOLEAN_CONFIGURATIONS = {CONFIG_IMAGE_TABLE_CREATE};
/**
* Required Integer properties in configuration.
*/
private static final String[] REQUIRED_INTEGER_CONFIGURATIONS = {};
/**
* Required Long properties in configuration.
*/
private static final String[] REQUIRED_LONG_CONFIGURATIONS = {};
/**
* Creates an {@link ImageIngester} with a {@link DefaultAWSCredentialsProviderChain}.
*
* @param args
* The command line arguments for locating the application configuration.
*/
public static void main(final String[] args) {
try {
new Thread(new ImageIngester(args, new DefaultAWSCredentialsProviderChain())).start();
} catch (final ExitException e) {
LOGGER.warning("Exiting: " + e.getMessage());
} catch (final HelpException e) {
assert true; // Do nothing except quit
}
}
/**
* Checks for required DynamoDB tables. If the user specifies, this method will create the tables and block until
* they have an ACTIVE TableStatus. If after these actions the tables are not setup properly, the program will exit.
*
* @param dynamoDB
* {@link AmazonDynamoDB} to use to create DynamoDB tables
* @param config
* Configuration containing table creation parameters.
* @throws ExitException
* Error parsing the configuration
*/
private static void setupTables(final AmazonDynamoDB dynamoDB, final Properties config) throws ExitException {
boolean eTagTableExists = false;
boolean imageTableExists = false;
boolean eTagTableActive = false;
boolean imageTableActive = false;
final boolean trackResources = ConfigParser.parseBoolean(config, CONFIG_TRACK_RESOURCES,
DEFAULT_TRACK_RESOURCES);
if (trackResources) {
final String eTagTable = ConfigParser.parseString(config, CONFIG_RESOURCE_TABLE);
final boolean createETagTable = ConfigParser.parseBoolean(config, CONFIG_RESOURCE_TABLE_CREATE);
if (DynamoDBManager.doesTableExist(dynamoDB, eTagTable)) {
LOGGER.info("Resource table " + eTagTable + " exists");
eTagTableExists = true;
} else if (createETagTable) {
try {
final long eTagTableReadCapacityUnits = ConfigParser.parseLong(config, CONFIG_RESOURCE_TABLE_RCU);
final long eTagTableWriteCapacityUnits = ConfigParser.parseLong(config, CONFIG_RESOURCE_TABLE_WCU);
final ProvisionedThroughput eTagTablePT = new ProvisionedThroughput(eTagTableReadCapacityUnits,
eTagTableWriteCapacityUnits);
MarsDynamoDBManager.createResourceTable(dynamoDB, eTagTable, eTagTablePT);
eTagTableExists = true;
} catch (final Exception e) {
LOGGER.severe(e.getMessage());
}
} else {
LOGGER.warning("Resource table " + eTagTable + " does not exist");
}
}
final String imageTable = ConfigParser.parseString(config, CONFIG_IMAGE_TABLE);
final boolean createImageTable = ConfigParser.parseBoolean(config, CONFIG_IMAGE_TABLE_CREATE);
if (DynamoDBManager.doesTableExist(dynamoDB, imageTable)) {
LOGGER.info("Image table " + imageTable + " exists");
imageTableExists = true;
} else if (createImageTable) {
try {
final long imageTableReadCapacityUnits = ConfigParser.parseLong(config, CONFIG_IMAGE_TABLE_RCU);
final long imageTableWriteCapacityUnits = ConfigParser.parseLong(config, CONFIG_IMAGE_TABLE_WCU);
final ProvisionedThroughput imageTablePT = new ProvisionedThroughput(imageTableReadCapacityUnits,
imageTableWriteCapacityUnits);
final long imageTableTimeGSIReadCapacityUnits = ConfigParser.parseLong(config,
CONFIG_IMAGE_TABLE_TIME_GSI_RCU);
final long imageTableTimeGSIWriteCapacityUnits = ConfigParser.parseLong(config,
CONFIG_IMAGE_TABLE_TIME_GSI_WCU);
final ProvisionedThroughput imageTableTimeGSIPT = new ProvisionedThroughput(
imageTableTimeGSIReadCapacityUnits, imageTableTimeGSIWriteCapacityUnits);
final long imageTableVoteGSIReadCapacityUnits = ConfigParser.parseLong(config,
CONFIG_IMAGE_TABLE_VOTE_GSI_RCU);
final long imageTableVoteGSIWriteCapacityUnits = ConfigParser.parseLong(config,
CONFIG_IMAGE_TABLE_VOTE_GSI_WCU);
final ProvisionedThroughput imageTableVoteGSIPT = new ProvisionedThroughput(
imageTableVoteGSIReadCapacityUnits, imageTableVoteGSIWriteCapacityUnits);
MarsDynamoDBManager.createImageTable(dynamoDB, imageTable, imageTablePT, imageTableTimeGSIPT,
imageTableVoteGSIPT);
imageTableExists = true;
} catch (final Exception e) {
LOGGER.severe(e.getMessage());
}
} else {
LOGGER.warning("Image table " + imageTable + " does not exist");
}
if ((!trackResources || eTagTableExists) && imageTableExists) {
try {
if (trackResources) {
final String eTagTable = ConfigParser.parseString(config, CONFIG_RESOURCE_TABLE);
DynamoDBManager.waitForTableToBecomeActive(dynamoDB, eTagTable);
eTagTableActive = true;
}
DynamoDBManager.waitForTableToBecomeActive(dynamoDB, imageTable);
imageTableActive = true;
} catch (final IllegalStateException e) {
LOGGER.severe(e.getMessage());
}
}
if ((trackResources && !eTagTableActive) || !imageTableActive) {
throw new ExitException("Tables are not set up properly");
}
}
// State variables
/**
* Configuration for the {@link ImageIngester} application.
*/
private final Properties config;
/**
* DynamoDB table for reading and writing image ETags.
*/
private final String resourceTable;
/**
* DynamoDB table for persisting images.
*/
private final String imageTable;
/**
* {@link AmazonDynamoDB} for accessing Amazon Web Services resources.
*/
private final AmazonDynamoDB dynamoDB;
/**
* Wait time between checks for asynchronous tasks to complete.
*/
private final long waitTime;
/**
* Timeout for retrieving HTTP URL resources.
*/
private final int connectTimeout;
/**
* Thread pool for {@link DynamoDBJSONRootWorker} and {@link DynamoDBMissionWorker}.
*/
private final ExecutorService manifestPool;
/**
* Thread pool for {@link DynamoDBSolWorker}s.
*/
private ExecutorService solPool;
/**
* Thread pool for {@link DynamoDBImageWorker}s.
*/
private ExecutorService imagePool;
/**
* Constructs a {@link ImageIngester} with the specified command line arguments and Amazon Web Services credentials
* provider.
*
* @param args
* Command line arguments for retrieving the configuration
* @param credentialsProvider
* Amazon Web Services credentials provider
* @throws ExitException
* Error parsing configuration
*/
public ImageIngester(final String[] args, final AWSCredentialsProvider credentialsProvider) throws ExitException {
// Parse command line arguments to locate configuration file
final ImageIngesterCLI cli = new ImageIngesterCLI(args);
config = cli.getConfig();
// Validate the configuration file
ConfigParser.validateConfig(config, REQUIRED_STRING_CONFIGURATIONS, REQUIRED_BOOLEAN_CONFIGURATIONS,
REQUIRED_INTEGER_CONFIGURATIONS, REQUIRED_LONG_CONFIGURATIONS);
// Parse configuration settings
resourceTable = ConfigParser.parseString(config, CONFIG_RESOURCE_TABLE);
imageTable = ConfigParser.parseString(config, CONFIG_IMAGE_TABLE);
waitTime = ConfigParser.parseLong(config, CONFIG_WAIT_TIME, DEFAULT_WAIT_TIME);
connectTimeout = ConfigParser.parseInteger(config, CONFIG_CONNECT_TIMEOUT, DEFAULT_CONNECT_TIMEOUT);
final String endpoint = ConfigParser.parseString(config, CONFIG_ENDPOINT);
final int numManifestThreads = ConfigParser.parseInteger(config, CONFIG_NUM_MANIFEST_THREADS, DEFAULT_THREADS);
// Setup state
dynamoDB = new AmazonDynamoDBClient(credentialsProvider);
dynamoDB.setEndpoint(endpoint);
manifestPool = Executors.newFixedThreadPool(numManifestThreads);
}
/**
* Waits for all {@link DynamoDBImageWorker} tasks to complete.
*
* @param imageFutures
* Collection of futures corresponding to {@link DynamoDBImageWorker} tasks
*/
private void awaitTermination(final Collection<Future<?>> imageFutures) {
while (!imageFutures.isEmpty()) {
LOGGER.info(imageFutures.size() + " images left to process");
try {
Thread.sleep(waitTime);
} catch (final InterruptedException e) {
LOGGER.warning(e.getMessage());
}
final Iterator<Future<?>> it = imageFutures.iterator();
while (it.hasNext()) {
final Future<?> f = it.next();
if (f.isDone()) {
it.remove();
}
}
}
LOGGER.info("Ingestion completed.");
}
/**
* <p>
* Submits a {@link DynamoDBMissionWorker} for each mission. Gets results from mission futures as they become
* available and submits a new {@link DynamoDBSolWorker} to process each sol in the mission. Returns a future for
* each sol that contains an {@link ArrayNode} of all the images in the sol
* </p>
* <p>
* If there is an error parsing a mission, a warning is logged and the mission is skipped.
* </p>
*
* @param topLevelManifests
* Map of mission to its manifest URL
*
* @return futures for each sol that will provide an {@link ArrayNode} of images in the sol
* @throws ExitException
* Error parsing configuration
*/
private Collection<Future<ArrayNode>> processMissions(final Map<String, String> topLevelManifests)
throws ExitException {
final Collection<Future<Map<Integer, String>>> missions = new ArrayList<>();
final Collection<Future<ArrayNode>> solFutures = new ArrayList<>();
// Submit task for each mission
for (final Entry<String, String> manifest : topLevelManifests.entrySet()) {
final String resource = manifest.getValue();
final DynamoDBMissionWorker worker = new DynamoDBMissionWorker(resource, connectTimeout);
final Future<Map<Integer, String>> future = manifestPool.submit(worker);
// Add future to collection
missions.add(future);
}
manifestPool.shutdown();
final int numSolThreads = ConfigParser.parseInteger(config, CONFIG_NUM_SOL_THREADS, DEFAULT_THREADS);
solPool = Executors.newFixedThreadPool(numSolThreads);
// Process all mission futures
while (!missions.isEmpty()) {
final Iterator<Future<Map<Integer, String>>> it = missions.iterator();
while (it.hasNext()) {
final Future<Map<Integer, String>> missionFuture = it.next();
if (missionFuture.isDone()) {
// Process finished mission future
try {
final Map<Integer, String> mission = missionFuture.get();
// Submit task for each sol in the mission
for (final String solURL : mission.values()) {
final DynamoDBSolWorker worker = new DynamoDBSolWorker(
/* dynamoDB, resourceTable, */solURL, connectTimeout);
final Future<ArrayNode> future = solPool.submit(worker);
// Add sol future to collection
solFutures.add(future);
}
} catch (InterruptedException | ExecutionException e) {
// Skip mission if there was an error, but report
// warning
LOGGER.warning(e.getMessage());
} finally {
it.remove(); // future is processed (successful or
// error), remove from collection
}
}
}
// Wait a bit for the tasks to finish before checking again
try {
Thread.sleep(waitTime);
} catch (final InterruptedException e) {
LOGGER.warning(e.getMessage());
}
}
solPool.shutdown();
return solFutures;
}
/**
* Retrieves and parses the root JSON to get Mars mission manifests.
*
* @return Map of mission to manifest URL
* @throws ExitException
* if the parser cannot access or process the root manifest
*/
private Map<String, String> processRootJSON() throws ExitException {
// Parse parameters from configuration
final String rootURL = ConfigParser.parseString(config, CONFIG_JSON_ROOT);
// Get and parse top level manifest
final DynamoDBJSONRootWorker rootWorker = new DynamoDBJSONRootWorker(rootURL, connectTimeout);
final Future<Map<String, String>> rootFuture = manifestPool.submit(rootWorker);
Map<String, String> topLevelManifests;
try {
topLevelManifests = rootFuture.get();
} catch (InterruptedException | ExecutionException e) {
throw new ExitException("Could not process root JSON", e);
}
return topLevelManifests;
}
/**
* <p>
* Gets the results from each sol future as they become available and submits a new {@link DynamoDBImageWorker} to
* process each image contained in the sol.
* </p>
* <p>
* If there is an error processing a sol, a warning is logged and the sol is skipped.
* </p>
*
* @param solFutures
* Futures for each sol that provides an {@link ArrayNode} that contains the images from the sol
* @return Collection of {@link Future}s for monitoring {@link DynamoDBImageWorker} progress
* @throws ExitException
* Error parsing configuration
*/
private Collection<Future<?>> processSolFutures(final Collection<Future<ArrayNode>> solFutures)
throws ExitException {
final Collection<DynamoDBImageWorker> workers = new ArrayList<>();
final Collection<Future<?>> imageFutures = new ArrayList<>();
final int numImageThreads = ConfigParser.parseInteger(config, CONFIG_NUM_IMAGE_THREADS, DEFAULT_THREADS);
imagePool = Executors.newFixedThreadPool(numImageThreads);
// Process all sol futures
while (!solFutures.isEmpty()) {
LOGGER.info(solFutures.size() + " sols remaining");
// Wait a bit for the tasks to finish before checking again
try {
Thread.sleep(waitTime);
} catch (final InterruptedException e) {
LOGGER.warning(e.getMessage());
}
final Iterator<Future<ArrayNode>> it = solFutures.iterator();
while (it.hasNext()) {
final Future<ArrayNode> solFuture = it.next();
if (solFuture.isDone()) {
try {
final ArrayNode images = solFuture.get();
final int thumbnailWidth = ConfigParser.parseInteger(config, CONFIG_THUMBNAIL_WIDTH,
DEFAULT_THUMBNAIL_WIDTH);
final int thumbnailHeight = ConfigParser.parseInteger(config, CONFIG_THUMBNAIL_HEIGHT,
DEFAULT_THUMBNAIL_HEIGHT);
final boolean trackResources = ConfigParser.parseBoolean(config, CONFIG_TRACK_RESOURCES,
DEFAULT_TRACK_RESOURCES);
final boolean storeThumbnails = ConfigParser.parseBoolean(config, CONFIG_STORE_THUMBNAILS,
DEFAULT_STORE_THUMBNAILS);
// Submit task for each image in the sol
for (final JsonNode image : images) {
if (!image.isObject()) {
LOGGER.warning("Unexpected image: " + image);
continue;
}
final DynamoDBImageWorker worker = new DynamoDBImageWorker(dynamoDB, imageTable,
resourceTable, (ObjectNode) image, connectTimeout, thumbnailWidth, thumbnailHeight,
trackResources, storeThumbnails);
workers.add(worker);
}
} catch (InterruptedException | ExecutionException e) {
// Skip sol if there was an error, but report warning
LOGGER.warning(e.getMessage());
} finally {
it.remove(); // future is processed (successful or
// error), remove from collection
}
}
}
}
LOGGER.info("All sols processed.");
for (final DynamoDBImageWorker worker : workers) {
imageFutures.add(imagePool.submit(worker));
}
imagePool.shutdown();
return imageFutures;
}
/**
* {@inheritDoc}
*/
@Override
public void run() {
try {
setupTables(dynamoDB, config);
final Map<String, String> missions = processRootJSON();
final Collection<Future<ArrayNode>> imageArrayFutures = processMissions(missions);
final Collection<Future<?>> imageFutures = processSolFutures(imageArrayFutures);
awaitTermination(imageFutures);
} catch (final ExitException e) {
return;
}
}
}
| |
/*******************************************************************************
* SAT4J: a SATisfiability library for Java Copyright (C) 2004, 2012 Artois University and CNRS
*
* 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
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU Lesser General Public License Version 2.1 or later (the
* "LGPL"), in which case the provisions of the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of the LGPL, and not to allow others to use your version of
* this file under the terms of the EPL, indicate your decision by deleting
* the provisions above and replace them with the notice and other provisions
* required by the LGPL. If you do not delete the provisions above, a recipient
* may use your version of this file under the terms of the EPL or the LGPL.
*
* Based on the original MiniSat specification from:
*
* An extensible SAT solver. Niklas Een and Niklas Sorensson. Proceedings of the
* Sixth International Conference on Theory and Applications of Satisfiability
* Testing, LNCS 2919, pp 502-518, 2003.
*
* See www.minisat.se for the original solver in C++.
*
* Contributors:
* CRIL - initial API and implementation
*******************************************************************************/
package org.sat4j.minisat.constraints.cnf;
import static org.sat4j.core.LiteralsUtils.neg;
import java.io.Serializable;
import org.sat4j.minisat.core.Constr;
import org.sat4j.minisat.core.ILits;
import org.sat4j.minisat.core.Propagatable;
import org.sat4j.specs.IVecInt;
import org.sat4j.specs.UnitPropagationListener;
/**
* Lazy data structure for clause using the Head Tail data structure from SATO,
* The original scheme is improved by avoiding moving pointers to literals but
* moving the literals themselves.
*
* We suppose here that the clause contains at least 3 literals. Use the
* BinaryClause or UnaryClause clause data structures to deal with binary and
* unit clauses.
*
* @author leberre
* @see BinaryClause
* @see UnitClause
* @since 2.1
*/
public abstract class HTClause implements Propagatable, Constr, Serializable {
private static final long serialVersionUID = 1L;
protected double activity;
protected final int[] middleLits;
protected final ILits voc;
protected int head;
protected int tail;
/**
* Creates a new basic clause
*
* @param voc
* the vocabulary of the formula
* @param ps
* A VecInt that WILL BE EMPTY after calling that method.
*/
public HTClause(IVecInt ps, ILits voc) {
assert ps.size() > 1;
this.head = ps.get(0);
this.tail = ps.last();
final int size = ps.size() - 2;
assert size > 0;
this.middleLits = new int[size];
System.arraycopy(ps.toArray(), 1, this.middleLits, 0, size);
ps.clear();
assert ps.size() == 0;
this.voc = voc;
this.activity = 0;
}
/*
* (non-Javadoc)
*
* @see Constr#calcReason(Solver, Lit, Vec)
*/
public void calcReason(int p, IVecInt outReason) {
if (this.voc.isFalsified(this.head)) {
outReason.push(neg(this.head));
}
final int[] mylits = this.middleLits;
for (int mylit : mylits) {
if (this.voc.isFalsified(mylit)) {
outReason.push(neg(mylit));
}
}
if (this.voc.isFalsified(this.tail)) {
outReason.push(neg(this.tail));
}
}
/*
* (non-Javadoc)
*
* @see Constr#remove(Solver)
*/
public void remove(UnitPropagationListener upl) {
this.voc.watches(neg(this.head)).remove(this);
this.voc.watches(neg(this.tail)).remove(this);
}
/*
* (non-Javadoc)
*
* @see Constr#simplify(Solver)
*/
public boolean simplify() {
if (this.voc.isSatisfied(this.head) || this.voc.isSatisfied(this.tail)) {
return true;
}
for (int middleLit : this.middleLits) {
if (this.voc.isSatisfied(middleLit)) {
return true;
}
}
return false;
}
public boolean propagate(UnitPropagationListener s, int p) {
if (this.head == neg(p)) {
final int[] mylits = this.middleLits;
int temphead = 0;
// moving head on the right
while (temphead < mylits.length
&& this.voc.isFalsified(mylits[temphead])) {
temphead++;
}
assert temphead <= mylits.length;
if (temphead == mylits.length) {
this.voc.watch(p, this);
return s.enqueue(this.tail, this);
}
this.head = mylits[temphead];
mylits[temphead] = neg(p);
this.voc.watch(neg(this.head), this);
return true;
}
assert this.tail == neg(p);
final int[] mylits = this.middleLits;
int temptail = mylits.length - 1;
// moving tail on the left
while (temptail >= 0 && this.voc.isFalsified(mylits[temptail])) {
temptail--;
}
assert -1 <= temptail;
if (-1 == temptail) {
this.voc.watch(p, this);
return s.enqueue(this.head, this);
}
this.tail = mylits[temptail];
mylits[temptail] = neg(p);
this.voc.watch(neg(this.tail), this);
return true;
}
/*
* For learnt clauses only @author leberre
*/
public boolean locked() {
return this.voc.getReason(this.head) == this
|| this.voc.getReason(this.tail) == this;
}
/**
* @return the activity of the clause
*/
public double getActivity() {
return this.activity;
}
@Override
public String toString() {
StringBuffer stb = new StringBuffer();
stb.append(Lits.toString(this.head));
stb.append("["); //$NON-NLS-1$
stb.append(this.voc.valueToString(this.head));
stb.append("]"); //$NON-NLS-1$
stb.append(" "); //$NON-NLS-1$
for (int middleLit : this.middleLits) {
stb.append(Lits.toString(middleLit));
stb.append("["); //$NON-NLS-1$
stb.append(this.voc.valueToString(middleLit));
stb.append("]"); //$NON-NLS-1$
stb.append(" "); //$NON-NLS-1$
}
stb.append(Lits.toString(this.tail));
stb.append("["); //$NON-NLS-1$
stb.append(this.voc.valueToString(this.tail));
stb.append("]"); //$NON-NLS-1$
return stb.toString();
}
/**
* Return the ith literal of the clause. Note that the order of the literals
* does change during the search...
*
* @param i
* the index of the literal
* @return the literal
*/
public int get(int i) {
if (i == 0) {
return this.head;
}
if (i == this.middleLits.length + 1) {
return this.tail;
}
return this.middleLits[i - 1];
}
/**
* @param d
*/
public void rescaleBy(double d) {
this.activity *= d;
}
public int size() {
return this.middleLits.length + 2;
}
public void assertConstraint(UnitPropagationListener s) {
assert this.voc.isUnassigned(this.head);
boolean ret = s.enqueue(this.head, this);
assert ret;
}
public void assertConstraintIfNeeded(UnitPropagationListener s) {
if (voc.isFalsified(this.tail)) {
boolean ret = s.enqueue(this.head, this);
assert ret;
}
}
public ILits getVocabulary() {
return this.voc;
}
public int[] getLits() {
int[] tmp = new int[size()];
System.arraycopy(this.middleLits, 0, tmp, 1, this.middleLits.length);
tmp[0] = this.head;
tmp[tmp.length - 1] = this.tail;
return tmp;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
try {
HTClause wcl = (HTClause) obj;
if (wcl.head != this.head || wcl.tail != this.tail) {
return false;
}
if (this.middleLits.length != wcl.middleLits.length) {
return false;
}
boolean ok;
for (int lit : this.middleLits) {
ok = false;
for (int lit2 : wcl.middleLits) {
if (lit == lit2) {
ok = true;
break;
}
}
if (!ok) {
return false;
}
}
return true;
} catch (ClassCastException e) {
return false;
}
}
@Override
public int hashCode() {
long sum = this.head + this.tail;
for (int p : this.middleLits) {
sum += p;
}
return (int) sum / this.middleLits.length;
}
public boolean canBePropagatedMultipleTimes() {
return false;
}
public Constr toConstraint() {
return this;
}
public void calcReasonOnTheFly(int p, IVecInt trail, IVecInt outReason) {
calcReason(p, outReason);
}
}
| |
/**
*/
package CIM.IEC61970.Informative.MarketOperations.impl;
import CIM.IEC61970.Core.impl.PowerSystemResourceImpl;
import CIM.IEC61970.Informative.EnergyScheduling.EnergySchedulingPackage;
import CIM.IEC61970.Informative.EnergyScheduling.SubControlArea;
import CIM.IEC61970.Informative.Financial.FinancialPackage;
import CIM.IEC61970.Informative.Financial.TransmissionProvider;
import CIM.IEC61970.Informative.MarketOperations.CapacityBenefitMargin;
import CIM.IEC61970.Informative.MarketOperations.FTR;
import CIM.IEC61970.Informative.MarketOperations.Flowgate;
import CIM.IEC61970.Informative.MarketOperations.MarketOperationsPackage;
import CIM.IEC61970.Informative.MarketOperations.TransmissionReliabilityMargin;
import CIM.IEC61970.Informative.MarketOperations.ViolationLimit;
import CIM.IEC61970.Wires.Line;
import CIM.IEC61970.Wires.PowerTransformer;
import CIM.IEC61970.Wires.WiresPackage;
import java.util.Collection;
import java.util.Date;
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.util.EObjectWithInverseResolvingEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Flowgate</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getTransmissionReliabilityMargin <em>Transmission Reliability Margin</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getAfcUseCode <em>Afc Use Code</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getIdcOperationalName <em>Idc Operational Name</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getInServiceDate <em>In Service Date</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getViolationLimits <em>Violation Limits</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getOutOfServiceDate <em>Out Of Service Date</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getCapacityBenefitMargin <em>Capacity Benefit Margin</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#isCoordinatedFlag <em>Coordinated Flag</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#isAtcFlag <em>Atc Flag</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getDeletionDate <em>Deletion Date</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#isReciprocalFlag <em>Reciprocal Flag</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getIdcAssignedId <em>Idc Assigned Id</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getPowerTransormers <em>Power Transormers</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getPositiveImpactValue <em>Positive Impact Value</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getFTRs <em>FT Rs</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getLines <em>Lines</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getCounterFlowValue <em>Counter Flow Value</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getCoordinationStudyDate <em>Coordination Study Date</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getSubControlArea <em>Sub Control Area</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getIdcType <em>Idc Type</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#isManagingEntityFlag <em>Managing Entity Flag</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.impl.FlowgateImpl#getTransmissionProvider <em>Transmission Provider</em>}</li>
* </ul>
*
* @generated
*/
public class FlowgateImpl extends PowerSystemResourceImpl implements Flowgate {
/**
* The cached value of the '{@link #getTransmissionReliabilityMargin() <em>Transmission Reliability Margin</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTransmissionReliabilityMargin()
* @generated
* @ordered
*/
protected TransmissionReliabilityMargin transmissionReliabilityMargin;
/**
* The default value of the '{@link #getAfcUseCode() <em>Afc Use Code</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAfcUseCode()
* @generated
* @ordered
*/
protected static final Object AFC_USE_CODE_EDEFAULT = null;
/**
* The cached value of the '{@link #getAfcUseCode() <em>Afc Use Code</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAfcUseCode()
* @generated
* @ordered
*/
protected Object afcUseCode = AFC_USE_CODE_EDEFAULT;
/**
* The default value of the '{@link #getIdcOperationalName() <em>Idc Operational Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIdcOperationalName()
* @generated
* @ordered
*/
protected static final String IDC_OPERATIONAL_NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getIdcOperationalName() <em>Idc Operational Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIdcOperationalName()
* @generated
* @ordered
*/
protected String idcOperationalName = IDC_OPERATIONAL_NAME_EDEFAULT;
/**
* The default value of the '{@link #getInServiceDate() <em>In Service Date</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getInServiceDate()
* @generated
* @ordered
*/
protected static final Date IN_SERVICE_DATE_EDEFAULT = null;
/**
* The cached value of the '{@link #getInServiceDate() <em>In Service Date</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getInServiceDate()
* @generated
* @ordered
*/
protected Date inServiceDate = IN_SERVICE_DATE_EDEFAULT;
/**
* The cached value of the '{@link #getViolationLimits() <em>Violation Limits</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getViolationLimits()
* @generated
* @ordered
*/
protected EList<ViolationLimit> violationLimits;
/**
* The default value of the '{@link #getOutOfServiceDate() <em>Out Of Service Date</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOutOfServiceDate()
* @generated
* @ordered
*/
protected static final Date OUT_OF_SERVICE_DATE_EDEFAULT = null;
/**
* The cached value of the '{@link #getOutOfServiceDate() <em>Out Of Service Date</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOutOfServiceDate()
* @generated
* @ordered
*/
protected Date outOfServiceDate = OUT_OF_SERVICE_DATE_EDEFAULT;
/**
* The cached value of the '{@link #getCapacityBenefitMargin() <em>Capacity Benefit Margin</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCapacityBenefitMargin()
* @generated
* @ordered
*/
protected EList<CapacityBenefitMargin> capacityBenefitMargin;
/**
* The default value of the '{@link #isCoordinatedFlag() <em>Coordinated Flag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isCoordinatedFlag()
* @generated
* @ordered
*/
protected static final boolean COORDINATED_FLAG_EDEFAULT = false;
/**
* The cached value of the '{@link #isCoordinatedFlag() <em>Coordinated Flag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isCoordinatedFlag()
* @generated
* @ordered
*/
protected boolean coordinatedFlag = COORDINATED_FLAG_EDEFAULT;
/**
* The default value of the '{@link #isAtcFlag() <em>Atc Flag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isAtcFlag()
* @generated
* @ordered
*/
protected static final boolean ATC_FLAG_EDEFAULT = false;
/**
* The cached value of the '{@link #isAtcFlag() <em>Atc Flag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isAtcFlag()
* @generated
* @ordered
*/
protected boolean atcFlag = ATC_FLAG_EDEFAULT;
/**
* The default value of the '{@link #getDeletionDate() <em>Deletion Date</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDeletionDate()
* @generated
* @ordered
*/
protected static final Date DELETION_DATE_EDEFAULT = null;
/**
* The cached value of the '{@link #getDeletionDate() <em>Deletion Date</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDeletionDate()
* @generated
* @ordered
*/
protected Date deletionDate = DELETION_DATE_EDEFAULT;
/**
* The default value of the '{@link #isReciprocalFlag() <em>Reciprocal Flag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isReciprocalFlag()
* @generated
* @ordered
*/
protected static final boolean RECIPROCAL_FLAG_EDEFAULT = false;
/**
* The cached value of the '{@link #isReciprocalFlag() <em>Reciprocal Flag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isReciprocalFlag()
* @generated
* @ordered
*/
protected boolean reciprocalFlag = RECIPROCAL_FLAG_EDEFAULT;
/**
* The default value of the '{@link #getIdcAssignedId() <em>Idc Assigned Id</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIdcAssignedId()
* @generated
* @ordered
*/
protected static final int IDC_ASSIGNED_ID_EDEFAULT = 0;
/**
* The cached value of the '{@link #getIdcAssignedId() <em>Idc Assigned Id</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIdcAssignedId()
* @generated
* @ordered
*/
protected int idcAssignedId = IDC_ASSIGNED_ID_EDEFAULT;
/**
* The cached value of the '{@link #getPowerTransormers() <em>Power Transormers</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPowerTransormers()
* @generated
* @ordered
*/
protected EList<PowerTransformer> powerTransormers;
/**
* The default value of the '{@link #getPositiveImpactValue() <em>Positive Impact Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPositiveImpactValue()
* @generated
* @ordered
*/
protected static final int POSITIVE_IMPACT_VALUE_EDEFAULT = 0;
/**
* The cached value of the '{@link #getPositiveImpactValue() <em>Positive Impact Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPositiveImpactValue()
* @generated
* @ordered
*/
protected int positiveImpactValue = POSITIVE_IMPACT_VALUE_EDEFAULT;
/**
* The cached value of the '{@link #getFTRs() <em>FT Rs</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFTRs()
* @generated
* @ordered
*/
protected EList<FTR> ftRs;
/**
* The cached value of the '{@link #getLines() <em>Lines</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLines()
* @generated
* @ordered
*/
protected EList<Line> lines;
/**
* The default value of the '{@link #getCounterFlowValue() <em>Counter Flow Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCounterFlowValue()
* @generated
* @ordered
*/
protected static final int COUNTER_FLOW_VALUE_EDEFAULT = 0;
/**
* The cached value of the '{@link #getCounterFlowValue() <em>Counter Flow Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCounterFlowValue()
* @generated
* @ordered
*/
protected int counterFlowValue = COUNTER_FLOW_VALUE_EDEFAULT;
/**
* The default value of the '{@link #getCoordinationStudyDate() <em>Coordination Study Date</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCoordinationStudyDate()
* @generated
* @ordered
*/
protected static final Date COORDINATION_STUDY_DATE_EDEFAULT = null;
/**
* The cached value of the '{@link #getCoordinationStudyDate() <em>Coordination Study Date</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCoordinationStudyDate()
* @generated
* @ordered
*/
protected Date coordinationStudyDate = COORDINATION_STUDY_DATE_EDEFAULT;
/**
* The cached value of the '{@link #getSubControlArea() <em>Sub Control Area</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSubControlArea()
* @generated
* @ordered
*/
protected SubControlArea subControlArea;
/**
* The default value of the '{@link #getIdcType() <em>Idc Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIdcType()
* @generated
* @ordered
*/
protected static final Object IDC_TYPE_EDEFAULT = null;
/**
* The cached value of the '{@link #getIdcType() <em>Idc Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIdcType()
* @generated
* @ordered
*/
protected Object idcType = IDC_TYPE_EDEFAULT;
/**
* The default value of the '{@link #isManagingEntityFlag() <em>Managing Entity Flag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isManagingEntityFlag()
* @generated
* @ordered
*/
protected static final boolean MANAGING_ENTITY_FLAG_EDEFAULT = false;
/**
* The cached value of the '{@link #isManagingEntityFlag() <em>Managing Entity Flag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isManagingEntityFlag()
* @generated
* @ordered
*/
protected boolean managingEntityFlag = MANAGING_ENTITY_FLAG_EDEFAULT;
/**
* The cached value of the '{@link #getTransmissionProvider() <em>Transmission Provider</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTransmissionProvider()
* @generated
* @ordered
*/
protected EList<TransmissionProvider> transmissionProvider;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected FlowgateImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return MarketOperationsPackage.Literals.FLOWGATE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TransmissionReliabilityMargin getTransmissionReliabilityMargin() {
if (transmissionReliabilityMargin != null && transmissionReliabilityMargin.eIsProxy()) {
InternalEObject oldTransmissionReliabilityMargin = (InternalEObject)transmissionReliabilityMargin;
transmissionReliabilityMargin = (TransmissionReliabilityMargin)eResolveProxy(oldTransmissionReliabilityMargin);
if (transmissionReliabilityMargin != oldTransmissionReliabilityMargin) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, MarketOperationsPackage.FLOWGATE__TRANSMISSION_RELIABILITY_MARGIN, oldTransmissionReliabilityMargin, transmissionReliabilityMargin));
}
}
return transmissionReliabilityMargin;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TransmissionReliabilityMargin basicGetTransmissionReliabilityMargin() {
return transmissionReliabilityMargin;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetTransmissionReliabilityMargin(TransmissionReliabilityMargin newTransmissionReliabilityMargin, NotificationChain msgs) {
TransmissionReliabilityMargin oldTransmissionReliabilityMargin = transmissionReliabilityMargin;
transmissionReliabilityMargin = newTransmissionReliabilityMargin;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__TRANSMISSION_RELIABILITY_MARGIN, oldTransmissionReliabilityMargin, newTransmissionReliabilityMargin);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setTransmissionReliabilityMargin(TransmissionReliabilityMargin newTransmissionReliabilityMargin) {
if (newTransmissionReliabilityMargin != transmissionReliabilityMargin) {
NotificationChain msgs = null;
if (transmissionReliabilityMargin != null)
msgs = ((InternalEObject)transmissionReliabilityMargin).eInverseRemove(this, MarketOperationsPackage.TRANSMISSION_RELIABILITY_MARGIN__FLOWGATE, TransmissionReliabilityMargin.class, msgs);
if (newTransmissionReliabilityMargin != null)
msgs = ((InternalEObject)newTransmissionReliabilityMargin).eInverseAdd(this, MarketOperationsPackage.TRANSMISSION_RELIABILITY_MARGIN__FLOWGATE, TransmissionReliabilityMargin.class, msgs);
msgs = basicSetTransmissionReliabilityMargin(newTransmissionReliabilityMargin, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__TRANSMISSION_RELIABILITY_MARGIN, newTransmissionReliabilityMargin, newTransmissionReliabilityMargin));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object getAfcUseCode() {
return afcUseCode;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setAfcUseCode(Object newAfcUseCode) {
Object oldAfcUseCode = afcUseCode;
afcUseCode = newAfcUseCode;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__AFC_USE_CODE, oldAfcUseCode, afcUseCode));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getIdcOperationalName() {
return idcOperationalName;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setIdcOperationalName(String newIdcOperationalName) {
String oldIdcOperationalName = idcOperationalName;
idcOperationalName = newIdcOperationalName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__IDC_OPERATIONAL_NAME, oldIdcOperationalName, idcOperationalName));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Date getInServiceDate() {
return inServiceDate;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setInServiceDate(Date newInServiceDate) {
Date oldInServiceDate = inServiceDate;
inServiceDate = newInServiceDate;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__IN_SERVICE_DATE, oldInServiceDate, inServiceDate));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ViolationLimit> getViolationLimits() {
if (violationLimits == null) {
violationLimits = new EObjectWithInverseResolvingEList<ViolationLimit>(ViolationLimit.class, this, MarketOperationsPackage.FLOWGATE__VIOLATION_LIMITS, MarketOperationsPackage.VIOLATION_LIMIT__FLOWGATE);
}
return violationLimits;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Date getOutOfServiceDate() {
return outOfServiceDate;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setOutOfServiceDate(Date newOutOfServiceDate) {
Date oldOutOfServiceDate = outOfServiceDate;
outOfServiceDate = newOutOfServiceDate;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__OUT_OF_SERVICE_DATE, oldOutOfServiceDate, outOfServiceDate));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<CapacityBenefitMargin> getCapacityBenefitMargin() {
if (capacityBenefitMargin == null) {
capacityBenefitMargin = new EObjectWithInverseResolvingEList.ManyInverse<CapacityBenefitMargin>(CapacityBenefitMargin.class, this, MarketOperationsPackage.FLOWGATE__CAPACITY_BENEFIT_MARGIN, MarketOperationsPackage.CAPACITY_BENEFIT_MARGIN__FLOWGATE);
}
return capacityBenefitMargin;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isCoordinatedFlag() {
return coordinatedFlag;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCoordinatedFlag(boolean newCoordinatedFlag) {
boolean oldCoordinatedFlag = coordinatedFlag;
coordinatedFlag = newCoordinatedFlag;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__COORDINATED_FLAG, oldCoordinatedFlag, coordinatedFlag));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isAtcFlag() {
return atcFlag;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setAtcFlag(boolean newAtcFlag) {
boolean oldAtcFlag = atcFlag;
atcFlag = newAtcFlag;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__ATC_FLAG, oldAtcFlag, atcFlag));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Date getDeletionDate() {
return deletionDate;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDeletionDate(Date newDeletionDate) {
Date oldDeletionDate = deletionDate;
deletionDate = newDeletionDate;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__DELETION_DATE, oldDeletionDate, deletionDate));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isReciprocalFlag() {
return reciprocalFlag;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setReciprocalFlag(boolean newReciprocalFlag) {
boolean oldReciprocalFlag = reciprocalFlag;
reciprocalFlag = newReciprocalFlag;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__RECIPROCAL_FLAG, oldReciprocalFlag, reciprocalFlag));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getIdcAssignedId() {
return idcAssignedId;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setIdcAssignedId(int newIdcAssignedId) {
int oldIdcAssignedId = idcAssignedId;
idcAssignedId = newIdcAssignedId;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__IDC_ASSIGNED_ID, oldIdcAssignedId, idcAssignedId));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<PowerTransformer> getPowerTransormers() {
if (powerTransormers == null) {
powerTransormers = new EObjectWithInverseResolvingEList.ManyInverse<PowerTransformer>(PowerTransformer.class, this, MarketOperationsPackage.FLOWGATE__POWER_TRANSORMERS, WiresPackage.POWER_TRANSFORMER__FLOWGATES);
}
return powerTransormers;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getPositiveImpactValue() {
return positiveImpactValue;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setPositiveImpactValue(int newPositiveImpactValue) {
int oldPositiveImpactValue = positiveImpactValue;
positiveImpactValue = newPositiveImpactValue;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__POSITIVE_IMPACT_VALUE, oldPositiveImpactValue, positiveImpactValue));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<FTR> getFTRs() {
if (ftRs == null) {
ftRs = new EObjectWithInverseResolvingEList<FTR>(FTR.class, this, MarketOperationsPackage.FLOWGATE__FT_RS, MarketOperationsPackage.FTR__FLOWGATE);
}
return ftRs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Line> getLines() {
if (lines == null) {
lines = new EObjectWithInverseResolvingEList.ManyInverse<Line>(Line.class, this, MarketOperationsPackage.FLOWGATE__LINES, WiresPackage.LINE__FLOWGATES);
}
return lines;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getCounterFlowValue() {
return counterFlowValue;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCounterFlowValue(int newCounterFlowValue) {
int oldCounterFlowValue = counterFlowValue;
counterFlowValue = newCounterFlowValue;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__COUNTER_FLOW_VALUE, oldCounterFlowValue, counterFlowValue));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Date getCoordinationStudyDate() {
return coordinationStudyDate;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCoordinationStudyDate(Date newCoordinationStudyDate) {
Date oldCoordinationStudyDate = coordinationStudyDate;
coordinationStudyDate = newCoordinationStudyDate;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__COORDINATION_STUDY_DATE, oldCoordinationStudyDate, coordinationStudyDate));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SubControlArea getSubControlArea() {
if (subControlArea != null && subControlArea.eIsProxy()) {
InternalEObject oldSubControlArea = (InternalEObject)subControlArea;
subControlArea = (SubControlArea)eResolveProxy(oldSubControlArea);
if (subControlArea != oldSubControlArea) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, MarketOperationsPackage.FLOWGATE__SUB_CONTROL_AREA, oldSubControlArea, subControlArea));
}
}
return subControlArea;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SubControlArea basicGetSubControlArea() {
return subControlArea;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetSubControlArea(SubControlArea newSubControlArea, NotificationChain msgs) {
SubControlArea oldSubControlArea = subControlArea;
subControlArea = newSubControlArea;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__SUB_CONTROL_AREA, oldSubControlArea, newSubControlArea);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setSubControlArea(SubControlArea newSubControlArea) {
if (newSubControlArea != subControlArea) {
NotificationChain msgs = null;
if (subControlArea != null)
msgs = ((InternalEObject)subControlArea).eInverseRemove(this, EnergySchedulingPackage.SUB_CONTROL_AREA__FLOWGATE, SubControlArea.class, msgs);
if (newSubControlArea != null)
msgs = ((InternalEObject)newSubControlArea).eInverseAdd(this, EnergySchedulingPackage.SUB_CONTROL_AREA__FLOWGATE, SubControlArea.class, msgs);
msgs = basicSetSubControlArea(newSubControlArea, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__SUB_CONTROL_AREA, newSubControlArea, newSubControlArea));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object getIdcType() {
return idcType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setIdcType(Object newIdcType) {
Object oldIdcType = idcType;
idcType = newIdcType;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__IDC_TYPE, oldIdcType, idcType));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isManagingEntityFlag() {
return managingEntityFlag;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setManagingEntityFlag(boolean newManagingEntityFlag) {
boolean oldManagingEntityFlag = managingEntityFlag;
managingEntityFlag = newManagingEntityFlag;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.FLOWGATE__MANAGING_ENTITY_FLAG, oldManagingEntityFlag, managingEntityFlag));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<TransmissionProvider> getTransmissionProvider() {
if (transmissionProvider == null) {
transmissionProvider = new EObjectWithInverseResolvingEList.ManyInverse<TransmissionProvider>(TransmissionProvider.class, this, MarketOperationsPackage.FLOWGATE__TRANSMISSION_PROVIDER, FinancialPackage.TRANSMISSION_PROVIDER__FLOWGATE);
}
return transmissionProvider;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case MarketOperationsPackage.FLOWGATE__TRANSMISSION_RELIABILITY_MARGIN:
if (transmissionReliabilityMargin != null)
msgs = ((InternalEObject)transmissionReliabilityMargin).eInverseRemove(this, MarketOperationsPackage.TRANSMISSION_RELIABILITY_MARGIN__FLOWGATE, TransmissionReliabilityMargin.class, msgs);
return basicSetTransmissionReliabilityMargin((TransmissionReliabilityMargin)otherEnd, msgs);
case MarketOperationsPackage.FLOWGATE__VIOLATION_LIMITS:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getViolationLimits()).basicAdd(otherEnd, msgs);
case MarketOperationsPackage.FLOWGATE__CAPACITY_BENEFIT_MARGIN:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getCapacityBenefitMargin()).basicAdd(otherEnd, msgs);
case MarketOperationsPackage.FLOWGATE__POWER_TRANSORMERS:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getPowerTransormers()).basicAdd(otherEnd, msgs);
case MarketOperationsPackage.FLOWGATE__FT_RS:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getFTRs()).basicAdd(otherEnd, msgs);
case MarketOperationsPackage.FLOWGATE__LINES:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getLines()).basicAdd(otherEnd, msgs);
case MarketOperationsPackage.FLOWGATE__SUB_CONTROL_AREA:
if (subControlArea != null)
msgs = ((InternalEObject)subControlArea).eInverseRemove(this, EnergySchedulingPackage.SUB_CONTROL_AREA__FLOWGATE, SubControlArea.class, msgs);
return basicSetSubControlArea((SubControlArea)otherEnd, msgs);
case MarketOperationsPackage.FLOWGATE__TRANSMISSION_PROVIDER:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getTransmissionProvider()).basicAdd(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 MarketOperationsPackage.FLOWGATE__TRANSMISSION_RELIABILITY_MARGIN:
return basicSetTransmissionReliabilityMargin(null, msgs);
case MarketOperationsPackage.FLOWGATE__VIOLATION_LIMITS:
return ((InternalEList<?>)getViolationLimits()).basicRemove(otherEnd, msgs);
case MarketOperationsPackage.FLOWGATE__CAPACITY_BENEFIT_MARGIN:
return ((InternalEList<?>)getCapacityBenefitMargin()).basicRemove(otherEnd, msgs);
case MarketOperationsPackage.FLOWGATE__POWER_TRANSORMERS:
return ((InternalEList<?>)getPowerTransormers()).basicRemove(otherEnd, msgs);
case MarketOperationsPackage.FLOWGATE__FT_RS:
return ((InternalEList<?>)getFTRs()).basicRemove(otherEnd, msgs);
case MarketOperationsPackage.FLOWGATE__LINES:
return ((InternalEList<?>)getLines()).basicRemove(otherEnd, msgs);
case MarketOperationsPackage.FLOWGATE__SUB_CONTROL_AREA:
return basicSetSubControlArea(null, msgs);
case MarketOperationsPackage.FLOWGATE__TRANSMISSION_PROVIDER:
return ((InternalEList<?>)getTransmissionProvider()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case MarketOperationsPackage.FLOWGATE__TRANSMISSION_RELIABILITY_MARGIN:
if (resolve) return getTransmissionReliabilityMargin();
return basicGetTransmissionReliabilityMargin();
case MarketOperationsPackage.FLOWGATE__AFC_USE_CODE:
return getAfcUseCode();
case MarketOperationsPackage.FLOWGATE__IDC_OPERATIONAL_NAME:
return getIdcOperationalName();
case MarketOperationsPackage.FLOWGATE__IN_SERVICE_DATE:
return getInServiceDate();
case MarketOperationsPackage.FLOWGATE__VIOLATION_LIMITS:
return getViolationLimits();
case MarketOperationsPackage.FLOWGATE__OUT_OF_SERVICE_DATE:
return getOutOfServiceDate();
case MarketOperationsPackage.FLOWGATE__CAPACITY_BENEFIT_MARGIN:
return getCapacityBenefitMargin();
case MarketOperationsPackage.FLOWGATE__COORDINATED_FLAG:
return isCoordinatedFlag();
case MarketOperationsPackage.FLOWGATE__ATC_FLAG:
return isAtcFlag();
case MarketOperationsPackage.FLOWGATE__DELETION_DATE:
return getDeletionDate();
case MarketOperationsPackage.FLOWGATE__RECIPROCAL_FLAG:
return isReciprocalFlag();
case MarketOperationsPackage.FLOWGATE__IDC_ASSIGNED_ID:
return getIdcAssignedId();
case MarketOperationsPackage.FLOWGATE__POWER_TRANSORMERS:
return getPowerTransormers();
case MarketOperationsPackage.FLOWGATE__POSITIVE_IMPACT_VALUE:
return getPositiveImpactValue();
case MarketOperationsPackage.FLOWGATE__FT_RS:
return getFTRs();
case MarketOperationsPackage.FLOWGATE__LINES:
return getLines();
case MarketOperationsPackage.FLOWGATE__COUNTER_FLOW_VALUE:
return getCounterFlowValue();
case MarketOperationsPackage.FLOWGATE__COORDINATION_STUDY_DATE:
return getCoordinationStudyDate();
case MarketOperationsPackage.FLOWGATE__SUB_CONTROL_AREA:
if (resolve) return getSubControlArea();
return basicGetSubControlArea();
case MarketOperationsPackage.FLOWGATE__IDC_TYPE:
return getIdcType();
case MarketOperationsPackage.FLOWGATE__MANAGING_ENTITY_FLAG:
return isManagingEntityFlag();
case MarketOperationsPackage.FLOWGATE__TRANSMISSION_PROVIDER:
return getTransmissionProvider();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case MarketOperationsPackage.FLOWGATE__TRANSMISSION_RELIABILITY_MARGIN:
setTransmissionReliabilityMargin((TransmissionReliabilityMargin)newValue);
return;
case MarketOperationsPackage.FLOWGATE__AFC_USE_CODE:
setAfcUseCode(newValue);
return;
case MarketOperationsPackage.FLOWGATE__IDC_OPERATIONAL_NAME:
setIdcOperationalName((String)newValue);
return;
case MarketOperationsPackage.FLOWGATE__IN_SERVICE_DATE:
setInServiceDate((Date)newValue);
return;
case MarketOperationsPackage.FLOWGATE__VIOLATION_LIMITS:
getViolationLimits().clear();
getViolationLimits().addAll((Collection<? extends ViolationLimit>)newValue);
return;
case MarketOperationsPackage.FLOWGATE__OUT_OF_SERVICE_DATE:
setOutOfServiceDate((Date)newValue);
return;
case MarketOperationsPackage.FLOWGATE__CAPACITY_BENEFIT_MARGIN:
getCapacityBenefitMargin().clear();
getCapacityBenefitMargin().addAll((Collection<? extends CapacityBenefitMargin>)newValue);
return;
case MarketOperationsPackage.FLOWGATE__COORDINATED_FLAG:
setCoordinatedFlag((Boolean)newValue);
return;
case MarketOperationsPackage.FLOWGATE__ATC_FLAG:
setAtcFlag((Boolean)newValue);
return;
case MarketOperationsPackage.FLOWGATE__DELETION_DATE:
setDeletionDate((Date)newValue);
return;
case MarketOperationsPackage.FLOWGATE__RECIPROCAL_FLAG:
setReciprocalFlag((Boolean)newValue);
return;
case MarketOperationsPackage.FLOWGATE__IDC_ASSIGNED_ID:
setIdcAssignedId((Integer)newValue);
return;
case MarketOperationsPackage.FLOWGATE__POWER_TRANSORMERS:
getPowerTransormers().clear();
getPowerTransormers().addAll((Collection<? extends PowerTransformer>)newValue);
return;
case MarketOperationsPackage.FLOWGATE__POSITIVE_IMPACT_VALUE:
setPositiveImpactValue((Integer)newValue);
return;
case MarketOperationsPackage.FLOWGATE__FT_RS:
getFTRs().clear();
getFTRs().addAll((Collection<? extends FTR>)newValue);
return;
case MarketOperationsPackage.FLOWGATE__LINES:
getLines().clear();
getLines().addAll((Collection<? extends Line>)newValue);
return;
case MarketOperationsPackage.FLOWGATE__COUNTER_FLOW_VALUE:
setCounterFlowValue((Integer)newValue);
return;
case MarketOperationsPackage.FLOWGATE__COORDINATION_STUDY_DATE:
setCoordinationStudyDate((Date)newValue);
return;
case MarketOperationsPackage.FLOWGATE__SUB_CONTROL_AREA:
setSubControlArea((SubControlArea)newValue);
return;
case MarketOperationsPackage.FLOWGATE__IDC_TYPE:
setIdcType(newValue);
return;
case MarketOperationsPackage.FLOWGATE__MANAGING_ENTITY_FLAG:
setManagingEntityFlag((Boolean)newValue);
return;
case MarketOperationsPackage.FLOWGATE__TRANSMISSION_PROVIDER:
getTransmissionProvider().clear();
getTransmissionProvider().addAll((Collection<? extends TransmissionProvider>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case MarketOperationsPackage.FLOWGATE__TRANSMISSION_RELIABILITY_MARGIN:
setTransmissionReliabilityMargin((TransmissionReliabilityMargin)null);
return;
case MarketOperationsPackage.FLOWGATE__AFC_USE_CODE:
setAfcUseCode(AFC_USE_CODE_EDEFAULT);
return;
case MarketOperationsPackage.FLOWGATE__IDC_OPERATIONAL_NAME:
setIdcOperationalName(IDC_OPERATIONAL_NAME_EDEFAULT);
return;
case MarketOperationsPackage.FLOWGATE__IN_SERVICE_DATE:
setInServiceDate(IN_SERVICE_DATE_EDEFAULT);
return;
case MarketOperationsPackage.FLOWGATE__VIOLATION_LIMITS:
getViolationLimits().clear();
return;
case MarketOperationsPackage.FLOWGATE__OUT_OF_SERVICE_DATE:
setOutOfServiceDate(OUT_OF_SERVICE_DATE_EDEFAULT);
return;
case MarketOperationsPackage.FLOWGATE__CAPACITY_BENEFIT_MARGIN:
getCapacityBenefitMargin().clear();
return;
case MarketOperationsPackage.FLOWGATE__COORDINATED_FLAG:
setCoordinatedFlag(COORDINATED_FLAG_EDEFAULT);
return;
case MarketOperationsPackage.FLOWGATE__ATC_FLAG:
setAtcFlag(ATC_FLAG_EDEFAULT);
return;
case MarketOperationsPackage.FLOWGATE__DELETION_DATE:
setDeletionDate(DELETION_DATE_EDEFAULT);
return;
case MarketOperationsPackage.FLOWGATE__RECIPROCAL_FLAG:
setReciprocalFlag(RECIPROCAL_FLAG_EDEFAULT);
return;
case MarketOperationsPackage.FLOWGATE__IDC_ASSIGNED_ID:
setIdcAssignedId(IDC_ASSIGNED_ID_EDEFAULT);
return;
case MarketOperationsPackage.FLOWGATE__POWER_TRANSORMERS:
getPowerTransormers().clear();
return;
case MarketOperationsPackage.FLOWGATE__POSITIVE_IMPACT_VALUE:
setPositiveImpactValue(POSITIVE_IMPACT_VALUE_EDEFAULT);
return;
case MarketOperationsPackage.FLOWGATE__FT_RS:
getFTRs().clear();
return;
case MarketOperationsPackage.FLOWGATE__LINES:
getLines().clear();
return;
case MarketOperationsPackage.FLOWGATE__COUNTER_FLOW_VALUE:
setCounterFlowValue(COUNTER_FLOW_VALUE_EDEFAULT);
return;
case MarketOperationsPackage.FLOWGATE__COORDINATION_STUDY_DATE:
setCoordinationStudyDate(COORDINATION_STUDY_DATE_EDEFAULT);
return;
case MarketOperationsPackage.FLOWGATE__SUB_CONTROL_AREA:
setSubControlArea((SubControlArea)null);
return;
case MarketOperationsPackage.FLOWGATE__IDC_TYPE:
setIdcType(IDC_TYPE_EDEFAULT);
return;
case MarketOperationsPackage.FLOWGATE__MANAGING_ENTITY_FLAG:
setManagingEntityFlag(MANAGING_ENTITY_FLAG_EDEFAULT);
return;
case MarketOperationsPackage.FLOWGATE__TRANSMISSION_PROVIDER:
getTransmissionProvider().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case MarketOperationsPackage.FLOWGATE__TRANSMISSION_RELIABILITY_MARGIN:
return transmissionReliabilityMargin != null;
case MarketOperationsPackage.FLOWGATE__AFC_USE_CODE:
return AFC_USE_CODE_EDEFAULT == null ? afcUseCode != null : !AFC_USE_CODE_EDEFAULT.equals(afcUseCode);
case MarketOperationsPackage.FLOWGATE__IDC_OPERATIONAL_NAME:
return IDC_OPERATIONAL_NAME_EDEFAULT == null ? idcOperationalName != null : !IDC_OPERATIONAL_NAME_EDEFAULT.equals(idcOperationalName);
case MarketOperationsPackage.FLOWGATE__IN_SERVICE_DATE:
return IN_SERVICE_DATE_EDEFAULT == null ? inServiceDate != null : !IN_SERVICE_DATE_EDEFAULT.equals(inServiceDate);
case MarketOperationsPackage.FLOWGATE__VIOLATION_LIMITS:
return violationLimits != null && !violationLimits.isEmpty();
case MarketOperationsPackage.FLOWGATE__OUT_OF_SERVICE_DATE:
return OUT_OF_SERVICE_DATE_EDEFAULT == null ? outOfServiceDate != null : !OUT_OF_SERVICE_DATE_EDEFAULT.equals(outOfServiceDate);
case MarketOperationsPackage.FLOWGATE__CAPACITY_BENEFIT_MARGIN:
return capacityBenefitMargin != null && !capacityBenefitMargin.isEmpty();
case MarketOperationsPackage.FLOWGATE__COORDINATED_FLAG:
return coordinatedFlag != COORDINATED_FLAG_EDEFAULT;
case MarketOperationsPackage.FLOWGATE__ATC_FLAG:
return atcFlag != ATC_FLAG_EDEFAULT;
case MarketOperationsPackage.FLOWGATE__DELETION_DATE:
return DELETION_DATE_EDEFAULT == null ? deletionDate != null : !DELETION_DATE_EDEFAULT.equals(deletionDate);
case MarketOperationsPackage.FLOWGATE__RECIPROCAL_FLAG:
return reciprocalFlag != RECIPROCAL_FLAG_EDEFAULT;
case MarketOperationsPackage.FLOWGATE__IDC_ASSIGNED_ID:
return idcAssignedId != IDC_ASSIGNED_ID_EDEFAULT;
case MarketOperationsPackage.FLOWGATE__POWER_TRANSORMERS:
return powerTransormers != null && !powerTransormers.isEmpty();
case MarketOperationsPackage.FLOWGATE__POSITIVE_IMPACT_VALUE:
return positiveImpactValue != POSITIVE_IMPACT_VALUE_EDEFAULT;
case MarketOperationsPackage.FLOWGATE__FT_RS:
return ftRs != null && !ftRs.isEmpty();
case MarketOperationsPackage.FLOWGATE__LINES:
return lines != null && !lines.isEmpty();
case MarketOperationsPackage.FLOWGATE__COUNTER_FLOW_VALUE:
return counterFlowValue != COUNTER_FLOW_VALUE_EDEFAULT;
case MarketOperationsPackage.FLOWGATE__COORDINATION_STUDY_DATE:
return COORDINATION_STUDY_DATE_EDEFAULT == null ? coordinationStudyDate != null : !COORDINATION_STUDY_DATE_EDEFAULT.equals(coordinationStudyDate);
case MarketOperationsPackage.FLOWGATE__SUB_CONTROL_AREA:
return subControlArea != null;
case MarketOperationsPackage.FLOWGATE__IDC_TYPE:
return IDC_TYPE_EDEFAULT == null ? idcType != null : !IDC_TYPE_EDEFAULT.equals(idcType);
case MarketOperationsPackage.FLOWGATE__MANAGING_ENTITY_FLAG:
return managingEntityFlag != MANAGING_ENTITY_FLAG_EDEFAULT;
case MarketOperationsPackage.FLOWGATE__TRANSMISSION_PROVIDER:
return transmissionProvider != null && !transmissionProvider.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (AfcUseCode: ");
result.append(afcUseCode);
result.append(", IdcOperationalName: ");
result.append(idcOperationalName);
result.append(", inServiceDate: ");
result.append(inServiceDate);
result.append(", outOfServiceDate: ");
result.append(outOfServiceDate);
result.append(", coordinatedFlag: ");
result.append(coordinatedFlag);
result.append(", AtcFlag: ");
result.append(atcFlag);
result.append(", deletionDate: ");
result.append(deletionDate);
result.append(", reciprocalFlag: ");
result.append(reciprocalFlag);
result.append(", IdcAssignedId: ");
result.append(idcAssignedId);
result.append(", positiveImpactValue: ");
result.append(positiveImpactValue);
result.append(", counterFlowValue: ");
result.append(counterFlowValue);
result.append(", coordinationStudyDate: ");
result.append(coordinationStudyDate);
result.append(", IdcType: ");
result.append(idcType);
result.append(", managingEntityFlag: ");
result.append(managingEntityFlag);
result.append(')');
return result.toString();
}
} //FlowgateImpl
| |
/*
* 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.common.cli;
import com.google.common.base.Charsets;
import com.google.common.collect.Sets;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.*;
import java.util.Set;
import static org.hamcrest.Matchers.*;
/**
*
*/
public class CheckFileCommandTests extends ElasticsearchTestCase {
private CliToolTestCase.CaptureOutputTerminal captureOutputTerminal = new CliToolTestCase.CaptureOutputTerminal();
private Configuration jimFsConfiguration = Configuration.unix().toBuilder().setAttributeViews("basic", "owner", "posix", "unix").build();
private Configuration jimFsConfigurationWithoutPermissions = randomBoolean() ? Configuration.unix().toBuilder().setAttributeViews("basic").build() : Configuration.windows();
private enum Mode {
CHANGE, KEEP, DISABLED
}
@Test
public void testThatCommandLogsErrorMessageOnFail() throws Exception {
executeCommand(jimFsConfiguration, new PermissionCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.CHANGE));
assertThat(captureOutputTerminal.getTerminalOutput(), hasItem(containsString("Please ensure that the user account running Elasticsearch has read access to this file")));
}
@Test
public void testThatCommandLogsNothingWhenPermissionRemains() throws Exception {
executeCommand(jimFsConfiguration, new PermissionCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.KEEP));
assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
}
@Test
public void testThatCommandLogsNothingWhenDisabled() throws Exception {
executeCommand(jimFsConfiguration, new PermissionCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.DISABLED));
assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
}
@Test
public void testThatCommandLogsNothingIfFilesystemDoesNotSupportPermissions() throws Exception {
executeCommand(jimFsConfigurationWithoutPermissions, new PermissionCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.DISABLED));
assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
}
@Test
public void testThatCommandLogsOwnerChange() throws Exception {
executeCommand(jimFsConfiguration, new OwnerCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.CHANGE));
assertThat(captureOutputTerminal.getTerminalOutput(), hasItem(allOf(containsString("Owner of file ["), containsString("] used to be ["), containsString("], but now is ["))));
}
@Test
public void testThatCommandLogsNothingIfOwnerRemainsSame() throws Exception {
executeCommand(jimFsConfiguration, new OwnerCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.KEEP));
assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
}
@Test
public void testThatCommandLogsNothingIfOwnerIsDisabled() throws Exception {
executeCommand(jimFsConfiguration, new OwnerCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.DISABLED));
assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
}
@Test
public void testThatCommandLogsNothingIfFileSystemDoesNotSupportOwners() throws Exception {
executeCommand(jimFsConfigurationWithoutPermissions, new OwnerCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.DISABLED));
assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
}
@Test
public void testThatCommandLogsIfGroupChanges() throws Exception {
executeCommand(jimFsConfiguration, new GroupCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.CHANGE));
assertThat(captureOutputTerminal.getTerminalOutput(), hasItem(allOf(containsString("Group of file ["), containsString("] used to be ["), containsString("], but now is ["))));
}
@Test
public void testThatCommandLogsNothingIfGroupRemainsSame() throws Exception {
executeCommand(jimFsConfiguration, new GroupCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.KEEP));
assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
}
@Test
public void testThatCommandLogsNothingIfGroupIsDisabled() throws Exception {
executeCommand(jimFsConfiguration, new GroupCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.DISABLED));
assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
}
@Test
public void testThatCommandLogsNothingIfFileSystemDoesNotSupportGroups() throws Exception {
executeCommand(jimFsConfigurationWithoutPermissions, new GroupCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.DISABLED));
assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
}
@Test
public void testThatCommandDoesNotLogAnythingOnFileCreation() throws Exception {
Configuration configuration = randomBoolean() ? jimFsConfiguration : jimFsConfigurationWithoutPermissions;
try (FileSystem fs = Jimfs.newFileSystem(configuration)) {
Path path = fs.getPath(randomAsciiOfLength(10));
Settings settings = Settings.builder()
.put("path.home", createTempDir().toString())
.build();
new CreateFileCommand(captureOutputTerminal, path).execute(settings, new Environment(settings));
assertThat(Files.exists(path), is(true));
}
assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
}
@Test
public void testThatCommandWorksIfFileIsDeletedByCommand() throws Exception {
Configuration configuration = randomBoolean() ? jimFsConfiguration : jimFsConfigurationWithoutPermissions;
try (FileSystem fs = Jimfs.newFileSystem(configuration)) {
Path path = fs.getPath(randomAsciiOfLength(10));
Files.write(path, "anything".getBytes(Charsets.UTF_8));
Settings settings = Settings.builder()
.put("path.home", createTempDir().toString())
.build();
new DeleteFileCommand(captureOutputTerminal, path).execute(settings, new Environment(settings));
assertThat(Files.exists(path), is(false));
}
assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
}
private void executeCommand(Configuration configuration, AbstractTestCheckFileCommand command) throws Exception {
try (FileSystem fs = Jimfs.newFileSystem(configuration)) {
command.execute(fs);
}
}
abstract class AbstractTestCheckFileCommand extends CheckFileCommand {
protected final Mode mode;
protected FileSystem fs;
protected Path[] paths;
final Path baseDir;
public AbstractTestCheckFileCommand(Path baseDir, Terminal terminal, Mode mode) throws IOException {
super(terminal);
this.mode = mode;
this.baseDir = baseDir;
}
public CliTool.ExitStatus execute(FileSystem fs) throws Exception {
this.fs = fs;
this.paths = new Path[] { writePath(fs, "p1", "anything"), writePath(fs, "p2", "anything"), writePath(fs, "p3", "anything") };
Settings settings = Settings.settingsBuilder()
.put("path.home", baseDir.toString())
.build();
return super.execute(Settings.EMPTY, new Environment(settings));
}
private Path writePath(FileSystem fs, String name, String content) throws IOException {
Path path = fs.getPath(name);
Files.write(path, content.getBytes(Charsets.UTF_8));
return path;
}
@Override
protected Path[] pathsForPermissionsCheck(Settings settings, Environment env) {
return paths;
}
}
/**
* command that changes permissions from a file if enabled
*/
class PermissionCheckFileCommand extends AbstractTestCheckFileCommand {
public PermissionCheckFileCommand(Path baseDir, Terminal terminal, Mode mode) throws IOException {
super(baseDir, terminal, mode);
}
@Override
public CliTool.ExitStatus doExecute(Settings settings, Environment env) throws Exception {
int randomInt = randomInt(paths.length - 1);
Path randomPath = paths[randomInt];
switch (mode) {
case CHANGE:
Files.write(randomPath, randomAsciiOfLength(10).getBytes(Charsets.UTF_8));
Files.setPosixFilePermissions(randomPath, Sets.newHashSet(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OTHERS_EXECUTE, PosixFilePermission.GROUP_EXECUTE));
break;
case KEEP:
Files.write(randomPath, randomAsciiOfLength(10).getBytes(Charsets.UTF_8));
Set<PosixFilePermission> posixFilePermissions = Files.getPosixFilePermissions(randomPath);
Files.setPosixFilePermissions(randomPath, posixFilePermissions);
break;
}
return CliTool.ExitStatus.OK;
}
}
/**
* command that changes the owner of a file if enabled
*/
class OwnerCheckFileCommand extends AbstractTestCheckFileCommand {
public OwnerCheckFileCommand(Path baseDir, Terminal terminal, Mode mode) throws IOException {
super(baseDir, terminal, mode);
}
@Override
public CliTool.ExitStatus doExecute(Settings settings, Environment env) throws Exception {
int randomInt = randomInt(paths.length - 1);
Path randomPath = paths[randomInt];
switch (mode) {
case CHANGE:
Files.write(randomPath, randomAsciiOfLength(10).getBytes(Charsets.UTF_8));
UserPrincipal randomOwner = fs.getUserPrincipalLookupService().lookupPrincipalByName(randomAsciiOfLength(10));
Files.setOwner(randomPath, randomOwner);
break;
case KEEP:
Files.write(randomPath, randomAsciiOfLength(10).getBytes(Charsets.UTF_8));
UserPrincipal originalOwner = Files.getOwner(randomPath);
Files.setOwner(randomPath, originalOwner);
break;
}
return CliTool.ExitStatus.OK;
}
}
/**
* command that changes the group of a file if enabled
*/
class GroupCheckFileCommand extends AbstractTestCheckFileCommand {
public GroupCheckFileCommand(Path baseDir, Terminal terminal, Mode mode) throws IOException {
super(baseDir, terminal, mode);
}
@Override
public CliTool.ExitStatus doExecute(Settings settings, Environment env) throws Exception {
int randomInt = randomInt(paths.length - 1);
Path randomPath = paths[randomInt];
switch (mode) {
case CHANGE:
Files.write(randomPath, randomAsciiOfLength(10).getBytes(Charsets.UTF_8));
GroupPrincipal randomPrincipal = fs.getUserPrincipalLookupService().lookupPrincipalByGroupName(randomAsciiOfLength(10));
Files.getFileAttributeView(randomPath, PosixFileAttributeView.class).setGroup(randomPrincipal);
break;
case KEEP:
Files.write(randomPath, randomAsciiOfLength(10).getBytes(Charsets.UTF_8));
GroupPrincipal groupPrincipal = Files.readAttributes(randomPath, PosixFileAttributes.class).group();
Files.getFileAttributeView(randomPath, PosixFileAttributeView.class).setGroup(groupPrincipal);
break;
}
return CliTool.ExitStatus.OK;
}
}
/**
* A command that creates a non existing file
*/
class CreateFileCommand extends CheckFileCommand {
private final Path pathToCreate;
public CreateFileCommand(Terminal terminal, Path pathToCreate) {
super(terminal);
this.pathToCreate = pathToCreate;
}
@Override
public CliTool.ExitStatus doExecute(Settings settings, Environment env) throws Exception {
Files.write(pathToCreate, "anything".getBytes(Charsets.UTF_8));
return CliTool.ExitStatus.OK;
}
@Override
protected Path[] pathsForPermissionsCheck(Settings settings, Environment env) throws Exception {
return new Path[] { pathToCreate };
}
}
/**
* A command that deletes an existing file
*/
class DeleteFileCommand extends CheckFileCommand {
private final Path pathToDelete;
public DeleteFileCommand(Terminal terminal, Path pathToDelete) {
super(terminal);
this.pathToDelete = pathToDelete;
}
@Override
public CliTool.ExitStatus doExecute(Settings settings, Environment env) throws Exception {
Files.delete(pathToDelete);
return CliTool.ExitStatus.OK;
}
@Override
protected Path[] pathsForPermissionsCheck(Settings settings, Environment env) throws Exception {
return new Path[] {pathToDelete};
}
}
}
| |
/*
* 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.fontbox.ttf;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A table in a true type font.
*
* @author Ben Litchfield
*/
public class NamingTable extends TTFTable
{
/**
* A tag that identifies this table type.
*/
public static final String TAG = "name";
private List<NameRecord> nameRecords = new ArrayList<NameRecord>();
private Map<Integer, Map<Integer, Map<Integer, Map<Integer, String>>>> lookupTable =
new HashMap<Integer, Map<Integer, Map<Integer, Map<Integer, String>>>>();
private String fontFamily = null;
private String fontSubFamily = null;
private String psName = null;
/**
* This will read the required data from the stream.
*
* @param ttf The font that is being read.
* @param data The stream to read the data from.
* @throws IOException If there is an error reading the data.
*/
public void read(TrueTypeFont ttf, TTFDataStream data) throws IOException
{
int formatSelector = data.readUnsignedShort();
int numberOfNameRecords = data.readUnsignedShort();
int offsetToStartOfStringStorage = data.readUnsignedShort();
for (int i=0; i< numberOfNameRecords; i++)
{
NameRecord nr = new NameRecord();
nr.initData(ttf, data);
nameRecords.add(nr);
}
for (int i=0; i<numberOfNameRecords; i++)
{
NameRecord nr = nameRecords.get(i);
// don't try to read invalid offsets, see PDFBOX-2608
if (nr.getStringOffset() > getLength())
{
nr.setString(null);
continue;
}
data.seek(getOffset() + (2*3)+numberOfNameRecords*2*6+nr.getStringOffset());
int platform = nr.getPlatformId();
int encoding = nr.getPlatformEncodingId();
String charset = "ISO-8859-1";
if (platform == 3 && (encoding == 1 || encoding == 0))
{
charset = "UTF-16";
}
else if (platform == 2)
{
if (encoding == 0)
{
charset = "US-ASCII";
}
else if (encoding == 1)
{
//not sure is this is correct??
charset = "ISO-10646-1";
}
else if (encoding == 2)
{
charset = "ISO-8859-1";
}
}
String string = data.readString(nr.getStringLength(), charset);
nr.setString(string);
}
// build multi-dimensional lookup table
for (NameRecord nr : nameRecords)
{
// name id
if (!lookupTable.containsKey(nr.getNameId()))
{
lookupTable.put(nr.getNameId(),
new HashMap<Integer, Map<Integer, Map<Integer, String>>>());
}
Map<Integer, Map<Integer, Map<Integer, String>>> platformLookup =
lookupTable.get(nr.getNameId());
// platform id
if (!platformLookup.containsKey(nr.getPlatformId()))
{
platformLookup.put(nr.getPlatformId(),
new HashMap<Integer, Map<Integer, String>>());
}
Map<Integer, Map<Integer, String>> encodingLookup =
platformLookup.get(nr.getPlatformId());
// encoding id
if (!encodingLookup.containsKey(nr.getPlatformEncodingId()))
{
encodingLookup.put(nr.getPlatformEncodingId(),
new HashMap<Integer, String>());
}
Map<Integer, String> languageLookup = encodingLookup.get(nr.getPlatformEncodingId());
// language id / string
languageLookup.put(nr.getLanguageId(), nr.getString());
}
// extract strings of interest
fontFamily = getEnglishName(NameRecord.NAME_FONT_FAMILY_NAME);
fontSubFamily = getEnglishName(NameRecord.NAME_FONT_SUB_FAMILY_NAME);
// extract PostScript name, only these two formats are valid
psName = getName(NameRecord.NAME_POSTSCRIPT_NAME,
NameRecord.PLATFORM_MACINTOSH,
NameRecord.ENCODING_MACINTOSH_ROMAN,
NameRecord.LANGUGAE_MACINTOSH_ENGLISH);
if (psName == null)
{
psName = getName(NameRecord.NAME_POSTSCRIPT_NAME,
NameRecord.PLATFORM_WINDOWS,
NameRecord.ENCODING_WINDOWS_UNICODE_BMP,
NameRecord.LANGUGAE_WINDOWS_EN_US);
}
initialized = true;
}
/**
* Helper to get English names by best effort.
*/
private String getEnglishName(int nameId)
{
// Unicode, Full, BMP, 1.1, 1.0
for (int i = 4; i <= 0; i--)
{
String nameUni =
getName(nameId,
NameRecord.PLATFORM_UNICODE,
i,
NameRecord.LANGUGAE_UNICODE);
if (nameUni != null)
{
return nameUni;
}
}
// Windows, Unicode BMP, EN-US
String nameWin =
getName(nameId,
NameRecord.PLATFORM_WINDOWS,
NameRecord.ENCODING_WINDOWS_UNICODE_BMP,
NameRecord.LANGUGAE_WINDOWS_EN_US);
if (nameWin != null)
{
return nameWin;
}
// Macintosh, Roman, English
String nameMac =
getName(nameId,
NameRecord.PLATFORM_MACINTOSH,
NameRecord.ENCODING_MACINTOSH_ROMAN,
NameRecord.LANGUGAE_MACINTOSH_ENGLISH);
if (nameMac != null)
{
return nameMac;
}
return null;
}
/**
* Returns a name from the table, or null it it does not exist.
*
* @param nameId Name ID from NameRecord constants.
* @param platformId Platform ID from NameRecord constants.
* @param encodingId Platform Encoding ID from NameRecord constants.
* @param languageId Language ID from NameRecord constants.
* @return name, or null
*/
public String getName(int nameId, int platformId, int encodingId, int languageId)
{
Map<Integer, Map<Integer, Map<Integer, String>>> platforms = lookupTable.get(nameId);
if (platforms == null)
{
return null;
}
Map<Integer, Map<Integer, String>> encodings = platforms.get(platformId);
if (encodings == null)
{
return null;
}
Map<Integer, String> languages = encodings.get(encodingId);
if (languages == null)
{
return null;
}
return languages.get(languageId);
}
/**
* This will get the name records for this naming table.
*
* @return A list of NameRecord objects.
*/
public List<NameRecord> getNameRecords()
{
return nameRecords;
}
/**
* Returns the font family name, in English.
*
* @return the font family name, in English
*/
public String getFontFamily()
{
return fontFamily;
}
/**
* Returns the font sub family name, in English.
*
* @return the font sub family name, in English
*/
public String getFontSubFamily()
{
return fontSubFamily;
}
/**
* Returns the PostScript name.
*
* @return the PostScript name
*/
public String getPostScriptName()
{
return psName;
}
}
| |
package sample;
import java.io.FileInputStream;
import java.io.StringReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import com.neuronrobotics.sdk.common.Log;
import org.medcare.igtl.messages.ImageMessage;
import org.medcare.igtl.messages.NDArrayMessage;
import org.medcare.igtl.messages.StringMessage;
import org.medcare.igtl.messages.TransformMessage;
import org.medcare.igtl.network.GenericIGTLinkClient;
import org.medcare.igtl.network.GenericIGTLinkServer;
import org.medcare.igtl.network.IOpenIgtPacketListener;
import org.medcare.igtl.network.OpenIGTClient;
import org.medcare.igtl.util.Header;
import org.medcare.igtl.util.IGTImage;
import org.medcare.igtl.util.Status;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import Jama.Matrix;
import com.neuronrobotics.sdk.addons.kinematics.math.TransformNR;
import com.sun.xml.internal.ws.encoding.MtomCodec.ByteArrayBuffer;
public class ServerSample implements IOpenIgtPacketListener {
/**
* @param args
*/
public static void main(String[] args) {
GenericIGTLinkServer server;
Log.enableDebugPrint();
Log.enableSystemPrint(true);
try {
//Set up server
server = new GenericIGTLinkServer (18945);
//Add local event listener
server.addIOpenIgtOnPacket(new ServerSample());
while(!server.isConnected()){
Thread.sleep(100);
}
Log.debug("Pushing packet");
//Create an identify matrix
TransformNR t = new TransformNR();
//Push a transform object upstream
while(true){
Thread.sleep(1000);
if(!server.isConnected()){
//create an Image message from the PAR/REC file and send it to probably slicer
ImageMessage img = new ImageMessage("IMG_004");
long dims[] = {288,288,2};
double org[] = {dims[0]/2, dims[1]/2, dims[2]/2};
double norms[][] = new double[3][3];
norms[0][0] = 0.417;
norms[1][1] = 0.417;
norms[2][2] = 6;
long subOffset[] = new long[3]; // Unsigned int 16bits
long subDimensions[] = new long[3]; // Unsigned int 16bits
img.setImageHeader(1, ImageMessage.DTYPE_SCALAR, ImageMessage.TYPE_UINT16, ImageMessage.ENDIAN_LITTLE, ImageMessage.COORDINATE_RAS, dims , org, norms, subOffset, dims);
//read data from the file and set as Image Data
FileInputStream recFile = new FileInputStream("C:/ImageMsg/img001.REC");
/*byte imageData16[] = new byte[(int) (dims[0]*dims[1]*dims[2])];
for(int i=0;i<imageData16.length;i++){
imageData16[i] = (byte) (Math.random()*127);
}*/
byte imageData[] = new byte[(int)(dims[0]*dims[1]*dims[2])*Short.BYTES];
System.out.println("Size of ImageData=" + imageData.length);
// ByteBuffer.wrap(imageData).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(imageData16);
//int sliceSizeinBytes = (int)(1*dims[0]*dims[1]);
//recFile.skip(sliceSizeinBytes);
recFile.read(imageData,0, imageData.length);
System.out.println("PRINTG *********************************************");
//recFile.close();
System.out.println(";");
System.out.println("PRINTG *********************************************");
img.setImageData(imageData);
img.PackBody();
//Log.debug("Push");
// server.pushPose("TransformPush", t);
/*float data[] = {(float) 1.0, (float) 2.12231233, (float) 4.5};
//server.sendMessage(new StringMessage("CMD_001", "Hello World") );
double position[] = t.getPositionArray();
position[0] =position[0]+1;
position[1] =position[1]+1;
position[2] =Math.random()*100;
double rotation[][] = t.getRotationMatrixArray();
rotation[0][1] = Math.random();
server.sendMessage(new TransformMessage("TGT_001", position ,rotation ));*/
server.sendMessage(img);
}else{
//Log.debug("Wait");
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
HashMap<String, Object> IGTData = null;
public ServerSample(){
IGTData = new HashMap<String, Object>();
IGTData.put("theta", 0);
IGTData.put("insertion_depth", 2.0);
}
@Override
public void onRxTransform(String name, TransformNR t) {
Log.debug("Received Transform with name: " + name + "and transform:" +t);
if(name.equals("RegistrationTransform") || name.equals("CALIBRATION")){
System.err.println("Received Registration Transform");
Log.debug("Setting fiducial registration matrix: "+t);
return;
}else if(name.equals("TARGET")){
System.err.println("Received RAS Transform: TARGET");
Log.debug("Setting task space pose: "+t);
}else if(name.equals("myTransform")){
System.err.println("Received Transformation Matrix: myTransform");
Log.debug("Setting task space pose: "+t);
}else{
System.err.println("Received unidentified transform matrix");
Log.debug("Setting task space pose: "+t);
}
}
@Override
public TransformNR getTxTransform(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public Status onGetStatus(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onRxString(String name, String body) {
//check if its XML format message
if(body.startsWith("<") && body.endsWith("/>")){
// TODO Auto-generated method stub
System.out.println("Device Name = " + name + " body=" + body);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(body));
Document data = builder.parse(is);
Element xmlNode = data.getDocumentElement();
StringBuffer treeData = new StringBuffer();
traverseNode(xmlNode, treeData);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void traverseNode (Node n, StringBuffer treeData)
{
if( n.getNodeName().equalsIgnoreCase("command") ){
NamedNodeMap atts = n.getAttributes();
Node tempNode = atts.item(0);
if( tempNode.getNodeName().equalsIgnoreCase("Name")){
if( tempNode.getNodeValue().equalsIgnoreCase("setVar")){
for( int i=1;i<atts.getLength();i++){
tempNode = atts.item(i);
if( IGTData.containsKey(tempNode.getNodeName()) ){
System.out.println( "Name ="+ tempNode.getNodeName() + " : Value = " + tempNode.getNodeValue());
IGTData.put(tempNode.getNodeName(), tempNode.getNodeValue());
}
}
}
}
if (n.hasChildNodes()) {
NodeList nl = n.getChildNodes();
int size = nl.getLength();
for (int i=0; i<size; i++){
traverseNode (nl.item(i), treeData);
}
}
}
}
@Override
public String onTxString(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onRxDataArray(String name, Matrix data) {
// TODO Auto-generated method stub
}
@Override
public double[] onTxDataArray(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onRxImage(String name, ImageMessage image) {
try {
GenericIGTLinkClient clnt = new GenericIGTLinkClient("127.0.0.1", 18944);
ImageMessage img = new ImageMessage("IMG_004");
long dims[] = {288,288,1};
double org[] = {dims[0]/2, dims[1]/2, dims[2]/2};
double norms[][] = new double[3][3];
norms[0][0] = 0.417;
norms[1][1] = 0.417;
norms[2][2] = 6;
long subOffset[] = new long[3]; // Unsigned int 16bits
long subDimensions[] = new long[3]; // Unsigned int 16bits
img.setImageHeader(1, ImageMessage.DTYPE_SCALAR, ImageMessage.TYPE_UINT16, ImageMessage.ENDIAN_LITTLE, ImageMessage.COORDINATE_RAS, dims , org, norms, subOffset, dims);
//read data from the file and set as Image Data
FileInputStream recFile = new FileInputStream("C:/ImageMsg/img001.REC");
/*byte imageData16[] = new byte[(int) (dims[0]*dims[1]*dims[2])];
for(int i=0;i<imageData16.length;i++){
imageData16[i] = (byte) (Math.random()*127);
}*/
byte imageData[] = new byte[(int)(dims[0]*dims[1]*dims[2])*Short.BYTES];
System.out.println("Size of ImageData=" + imageData.length);
// ByteBuffer.wrap(imageData).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(imageData16);
//int sliceSizeinBytes = (int)(1*dims[0]*dims[1]);
//recFile.skip(sliceSizeinBytes);
recFile.read(imageData,0, imageData.length);
System.out.println("PRINTG *********************************************");
//recFile.close();
System.out.println(";");
System.out.println("PRINTG *********************************************");
img.setImageData(imageData);
img.PackBody();
//Log.debug("Push");
// server.pushPose("TransformPush", t);
/*float data[] = {(float) 1.0, (float) 2.12231233, (float) 4.5};
//server.sendMessage(new StringMessage("CMD_001", "Hello World") );
double position[] = t.getPositionArray();
position[0] =position[0]+1;
position[1] =position[1]+1;
position[2] =Math.random()*100;
double rotation[][] = t.getRotationMatrixArray();
rotation[0][1] = Math.random();
server.sendMessage(new TransformMessage("TGT_001", position ,rotation ));*/
//clnt.sendMessage(img);
image.PackBody();
clnt.sendMessage(image);
Thread.sleep(1000);
clnt.stopClient();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(image.toString());
}
@Override
public void onTxNDArray(String name) {
// TODO Auto-generated method stub
}
@Override
public void onRxNDArray(String name, float[] data) {
// TODO Auto-generated method stub
Log.debug("Name" + name);
for(int i=0;i<data.length;i++){
Log.debug("Data[" + i + "]=" + (double)data[i]);
}
}
}
| |
/*
* Copyright (C) 2009 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 vogar;
import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import vogar.tasks.BuildActionTask;
import vogar.tasks.PrepareTarget;
import vogar.tasks.PrepareUserDirTask;
import vogar.tasks.RetrieveFilesTask;
import vogar.tasks.RmTask;
import vogar.tasks.Task;
import vogar.util.TimeUtilities;
/**
* Compiles, installs, runs and reports on actions.
*/
public final class Driver {
private final Run run;
public Driver(Run run) {
this.run = run;
}
private int successes = 0;
private int failures = 0;
private int skipped = 0;
private Task prepareTargetTask;
private Set<Task> installVogarTasks;
private final Map<String, Action> actions = Collections.synchronizedMap(
new LinkedHashMap<String, Action>());
private final Map<String, Outcome> outcomes = Collections.synchronizedMap(
new LinkedHashMap<String, Outcome>());
public boolean recordResults = true;
/**
* Builds and executes the actions in the given files.
*/
public boolean buildAndRun(Collection<File> files, Collection<String> classes) {
if (!actions.isEmpty()) {
throw new IllegalStateException("Drivers are not reusable");
}
run.mkdir.mkdirs(run.localTemp);
filesToActions(files);
classesToActions(classes);
if (actions.isEmpty()) {
run.console.info("Nothing to do.");
return false;
}
run.console.info("Actions: " + actions.size());
final long t0 = System.currentTimeMillis();
prepareTargetTask = new PrepareTarget(run, run.target);
run.taskQueue.enqueue(prepareTargetTask);
installVogarTasks = run.mode.installTasks();
run.taskQueue.enqueueAll(installVogarTasks);
registerPrerequisites(Collections.singleton(prepareTargetTask), installVogarTasks);
for (Action action : actions.values()) {
action.setUserDir(new File(run.runnerDir, action.getName()));
Outcome outcome = outcomes.get(action.getName());
if (outcome != null) {
addEarlyResult(outcome);
} else if (run.expectationStore.get(action.getName()).getResult() == Result.UNSUPPORTED) {
addEarlyResult(new Outcome(action.getName(), Result.UNSUPPORTED,
"Unsupported according to expectations file"));
} else {
enqueueActionTasks(action);
}
}
if (run.cleanAfter) {
Set<Task> shutdownTasks = new HashSet<Task>();
shutdownTasks.add(new RmTask(run.rm, run.localTemp));
shutdownTasks.add(run.target.rmTask(run.runnerDir));
for (Task task : shutdownTasks) {
task.after(run.taskQueue.getTasks());
}
run.taskQueue.enqueueAll(shutdownTasks);
}
run.taskQueue.printTasks();
run.taskQueue.runTasks();
run.taskQueue.printProblemTasks();
if (run.reportPrinter.isReady()) {
run.console.info("Printing XML Reports... ");
int numFiles = run.reportPrinter.generateReports(outcomes.values());
run.console.info(numFiles + " XML files written.");
}
long t1 = System.currentTimeMillis();
Map<String, AnnotatedOutcome> annotatedOutcomes = run.outcomeStore.read(this.outcomes);
if (recordResults) {
run.outcomeStore.write(outcomes);
}
run.console.summarizeOutcomes(annotatedOutcomes.values());
List<String> jarStringList = run.jarSuggestions.getStringList();
if (!jarStringList.isEmpty()) {
run.console.warn(
"consider adding the following to the classpath:",
jarStringList);
}
if (failures > 0 || skipped > 0) {
run.console.info(String.format(
"Outcomes: %s. Passed: %d, Failed: %d, Skipped: %d. Took %s.",
(successes + failures + skipped), successes, failures, skipped,
TimeUtilities.msToString(t1 - t0)));
} else {
run.console.info(String.format("Outcomes: %s. All successful. Took %s.",
successes, TimeUtilities.msToString(t1 - t0)));
}
return failures == 0;
}
private void enqueueActionTasks(Action action) {
Expectation expectation = run.expectationStore.get(action.getName());
boolean useLargeTimeout = expectation.getTags().contains("large");
File jar = run.hostJar(action);
Task build = new BuildActionTask(run, action, this, jar);
run.taskQueue.enqueue(build);
Task prepareUserDir = new PrepareUserDirTask(run.target, action);
prepareUserDir.after(installVogarTasks);
run.taskQueue.enqueue(prepareUserDir);
Set<Task> install = run.mode.installActionTasks(action, jar);
registerPrerequisites(Collections.singleton(build), install);
registerPrerequisites(installVogarTasks, install);
registerPrerequisites(Collections.singleton(prepareTargetTask), install);
run.taskQueue.enqueueAll(install);
Task execute = run.mode.executeActionTask(action, useLargeTimeout)
.afterSuccess(installVogarTasks)
.afterSuccess(build)
.afterSuccess(prepareUserDir)
.afterSuccess(install);
run.taskQueue.enqueue(execute);
Task retrieveFiles = new RetrieveFilesTask(run, action.getUserDir()).after(execute);
run.taskQueue.enqueue(retrieveFiles);
if (run.cleanAfter) {
run.taskQueue.enqueue(new RmTask(run.rm, run.localFile(action))
.after(execute).after(retrieveFiles));
Set<Task> cleanupTasks = run.mode.cleanupTasks(action);
for (Task task : cleanupTasks) {
task.after(execute).after(retrieveFiles);
}
run.taskQueue.enqueueAll(cleanupTasks);
}
}
private void registerPrerequisites(Set<Task> allBefore, Set<Task> allAfter) {
for (Task task : allAfter) {
task.afterSuccess(allBefore);
}
}
private void classesToActions(Collection<String> classNames) {
for (String className : classNames) {
Action action = new Action(className, className, null, null, null);
actions.put(action.getName(), action);
}
}
private void filesToActions(Collection<File> files) {
for (File file : files) {
new ActionFinder(run.console, actions, outcomes).findActions(file);
}
}
public synchronized void addEarlyResult(Outcome earlyFailure) {
if (earlyFailure.getResult() == Result.UNSUPPORTED) {
run.console.verbose("skipped " + earlyFailure.getName());
skipped++;
} else {
for (String line : earlyFailure.getOutputLines()) {
run.console.streamOutput(earlyFailure.getName(), line + "\n");
}
recordOutcome(earlyFailure);
}
}
public synchronized void recordOutcome(Outcome outcome) {
outcomes.put(outcome.getName(), outcome);
Expectation expectation = run.expectationStore.get(outcome);
ResultValue resultValue = outcome.getResultValue(expectation);
if (resultValue == ResultValue.OK) {
successes++;
} else if (resultValue == ResultValue.FAIL) {
failures++;
} else { // ResultValue.IGNORE
skipped++;
}
Result result = outcome.getResult();
run.console.outcome(outcome.getName());
run.console.printResult(outcome.getName(), result, resultValue, expectation);
JarSuggestions singleOutcomeJarSuggestions = new JarSuggestions();
singleOutcomeJarSuggestions.addSuggestionsFromOutcome(outcome, run.classFileIndex,
run.classpath);
List<String> jarStringList = singleOutcomeJarSuggestions.getStringList();
if (!jarStringList.isEmpty()) {
run.console.warn(
"may have failed because some of these jars are missing from the classpath:",
jarStringList);
}
run.jarSuggestions.addSuggestions(singleOutcomeJarSuggestions);
}
}
| |
import java.text.NumberFormat; //imports number formatting for $$
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
/*
* calcJApplet.java
*
* Created on February 9, 2008, 8:50 PM
* Motagage Calculator Example Applet
*/
/**
*
* @author Dale Cox
*/
public class amortCalc extends javax.swing.JApplet {
/** Initializes the applet calcJApplet */
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
initComponents();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}//end init
/*@Override
public void start(){
initComponents();
}*/
/** This method is called from within the init() method to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabelPrincipalTitle = new javax.swing.JLabel();
jTextFieldPrincipal = new javax.swing.JTextField();
jLabelinterest = new javax.swing.JLabel();
jTextFieldInterest = new javax.swing.JTextField();
jLabelTerm = new javax.swing.JLabel();
jTextFieldTerm = new javax.swing.JTextField();
jSeparator1 = new javax.swing.JSeparator();
jLabelMoPay = new javax.swing.JLabel();
jTextFieldMoPay = new javax.swing.JTextField();
jSeparator2 = new javax.swing.JSeparator();
jButtonCalc = new javax.swing.JButton();
jButtonReset = new javax.swing.JButton();
ErrorLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
amortModel = new DefaultTableModel(columnNames, 0);
jTableAmort = new javax.swing.JTable();
setBackground(new java.awt.Color(204, 204, 204));
setStub(null);
jLabelPrincipalTitle.setLabelFor(jLabelPrincipalTitle);
jLabelPrincipalTitle.setText("Principal");
jLabelinterest.setLabelFor(jTextFieldInterest);
jLabelinterest.setText("Anual Interest Rate ");
jLabelTerm.setLabelFor(jTextFieldTerm);
jLabelTerm.setText("Term in Years");
jLabelMoPay.setText("Monthly Payment");
jTextFieldMoPay.setEditable(false);
jButtonCalc.setText("Calculate");
jButtonCalc.setToolTipText("Calculate Monthly Payments");
jButtonCalc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonCalcActionPerformed(evt);
}
});
jButtonReset.setText("Reset");
jButtonReset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonResetActionPerformed(evt);
}
});
ErrorLabel.setForeground(new java.awt.Color(255, 0, 51));
ErrorLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jTableAmort.setModel(amortModel);
jScrollPane1.setViewportView(jTableAmort);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 474, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelPrincipalTitle)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldPrincipal, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelinterest)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldInterest, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelTerm)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldTerm, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelMoPay)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldMoPay, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(70, 70, 70)
.addComponent(jButtonCalc)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 99, Short.MAX_VALUE)
.addComponent(jButtonReset))))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 474, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(69, 69, 69)
.addComponent(ErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 327, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 474, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jTextFieldTerm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelTerm)
.addComponent(jTextFieldInterest, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelinterest)
.addComponent(jTextFieldPrincipal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelPrincipalTitle))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabelMoPay)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldMoPay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButtonReset)
.addComponent(jButtonCalc)))
.addGap(13, 13, 13)
.addComponent(ErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 465, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void jButtonCalcActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCalcActionPerformed
/**This method calculates Monthly Mortgage Payment**/
/**Get Input**/
//Get the vlaue of the text fiels
sPrinciple = jTextFieldPrincipal.getText();
//add error checking
sAnualInterest = jTextFieldInterest.getText();
//add error checking
sTermYr = jTextFieldTerm.getText();
//error checking
if(sPrinciple.isEmpty()||sAnualInterest.isEmpty()||sTermYr.isEmpty()){
ErrorLabel.setText("Incorrect or missing value");
return;}
//convert strings to numbers
dPrinciple = Double.parseDouble(sPrinciple); //Amount Barrowed
dInterest = Double.parseDouble(sAnualInterest); //Anual interest Rate
iYearTerm = Integer.parseInt(sTermYr); // Loan Payback Period in Years
//TODO add error checking
//**get monthly payment info**//
//Calculate the number of months in the term
int iMonthterm = iYearTerm * 12;
//Calculate monthly interest
double dMonthInterest = dInterest / 1200;
//Calculate Monthly Payment
dMonthlyPayment = (dPrinciple * (Math.pow((1 + dMonthInterest) , iMonthterm))* dMonthInterest)/
((Math.pow((1 + dMonthInterest) , iMonthterm))-1);
//Formats Monthly Payment
currency = NumberFormat.getCurrencyInstance(); //creates currency
sMonthlyPayment=currency.format(dMonthlyPayment);
//write output
jTextFieldMoPay.setText(sMonthlyPayment);
//writes to Table
while (iMonthterm > 0){
iMonthterm = iMonthterm-1;//holds which months payment is on
dCurrentInterest = dPrinciple * dMonthInterest; //Shows current interest payed
dPrinciplePaid = dMonthlyPayment - dCurrentInterest; //shows principle paid
dPrinciple = dPrinciple - dPrinciplePaid; //shows remaining principle
++iPayment;
sPayment = Integer.toString(iPayment);//required for output reasons
String[] rowData ={sPayment,(currency.format(dMonthlyPayment)),(currency.format(dCurrentInterest)),
(currency.format(dPrinciplePaid)),(currency.format(dPrinciple))};
amortModel.addRow(rowData);
}//end while
}//GEN-LAST:event_jButtonCalcActionPerformed
private void jButtonResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonResetActionPerformed
//Resets Fields
clearFields();
}//GEN-LAST:event_jButtonResetActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel ErrorLabel;
private javax.swing.JButton jButtonCalc;
private javax.swing.JButton jButtonReset;
private javax.swing.JLabel jLabelMoPay;
private javax.swing.JLabel jLabelPrincipalTitle;
private javax.swing.JLabel jLabelTerm;
private javax.swing.JLabel jLabelinterest;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JTable jTableAmort;
private javax.swing.JTextField jTextFieldInterest;
private javax.swing.JTextField jTextFieldMoPay;
private javax.swing.JTextField jTextFieldPrincipal;
private javax.swing.JTextField jTextFieldTerm;
// End of variables declaration//GEN-END:variables
//Input Variables
String sPrinciple = null;
String sAnualInterest = null;
String sTermYr = null;
String sMonthlyPayment = null;
//calculation variables
double dPrinciple = 0.0; //Amount Barrowed
double dInterest = 0.0; //Anual interest Rate
int iYearTerm = 0; // Loan Payback Period in Years
double dMonthlyPayment =0.0; //Monthly Payment
NumberFormat currency;
//table variables
String[] columnNames= {"Payment #", "Payment Amount", "Interest Payment", "Principle Reduction", "Principle Balance"};
DefaultTableModel amortModel;
double dCurrentInterest =0.0;
double dPrinciplePaid = 0.0;
String sPayment=null;
int iPayment = 0;
private void clearFields()
{
//resets the fields
jTextFieldPrincipal.setText("");
jTextFieldInterest.setText("");
jTextFieldTerm.setText("");
jTextFieldMoPay.setText("");
amortModel = new DefaultTableModel(columnNames, 0);
jTableAmort.setModel(amortModel);
} //end of clearFields
}//end Class
| |
/*
* This file is part of the Heritrix web crawler (crawler.archive.org).
*
* Licensed to the Internet Archive (IA) by one or more individual
* contributors.
*
* The IA 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.archive.util;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.IOUtils;
import org.archive.format.gzip.GZIPDecoder;
import org.archive.format.gzip.GZIPFormatException;
/**
* Miscellaneous useful methods.
*
* @author gojomo & others
*/
public class ArchiveUtils {
private static final Logger LOGGER = Logger.getLogger(ArchiveUtils.class.getName());
final public static String VERSION = loadVersion();
/**
* Arc-style date stamp in the format yyyyMMddHHmm and UTC time zone.
*/
private static final ThreadLocal<SimpleDateFormat>
TIMESTAMP12 = threadLocalDateFormat("yyyyMMddHHmm");;
/**
* Arc-style date stamp in the format yyyyMMddHHmmss and UTC time zone.
*/
private static final ThreadLocal<SimpleDateFormat>
TIMESTAMP14 = threadLocalDateFormat("yyyyMMddHHmmss");
/**
* Arc-style date stamp in the format yyyyMMddHHmmssSSS and UTC time zone.
*/
private static final ThreadLocal<SimpleDateFormat>
TIMESTAMP17 = threadLocalDateFormat("yyyyMMddHHmmssSSS");
/**
* Log-style date stamp in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
* UTC time zone is assumed.
*/
private static final ThreadLocal<SimpleDateFormat>
TIMESTAMP17ISO8601Z = threadLocalDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
/**
* Log-style date stamp in the format yyyy-MM-dd'T'HH:mm:ss'Z'
* UTC time zone is assumed.
*/
private static final ThreadLocal<SimpleDateFormat>
TIMESTAMP14ISO8601Z = threadLocalDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
/**
* Default character to use padding strings.
*/
private static final char DEFAULT_PAD_CHAR = ' ';
/** milliseconds in an hour */
private static final int HOUR_IN_MS = 60 * 60 * 1000;
/** milliseconds in a day */
private static final int DAY_IN_MS = 24 * HOUR_IN_MS;
private static ThreadLocal<SimpleDateFormat> threadLocalDateFormat(final String pattern) {
ThreadLocal<SimpleDateFormat> tl = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
SimpleDateFormat df = new SimpleDateFormat(pattern, Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("GMT"));
return df;
}
};
return tl;
}
public static int MAX_INT_CHAR_WIDTH =
Integer.toString(Integer.MAX_VALUE).length();
/**
* Utility function for creating arc-style date stamps
* in the format yyyMMddHHmmssSSS.
* Date stamps are in the UTC time zone
* @return the date stamp
*/
public static String get17DigitDate(){
return TIMESTAMP17.get().format(new Date());
}
protected static long LAST_UNIQUE_NOW17 = 0;
protected static String LAST_TIMESTAMP17 = "";
/**
* Utility function for creating UNIQUE-from-this-class
* arc-style date stamps in the format yyyMMddHHmmssSSS.
* Rather than giving a duplicate datestamp on a
* subsequent call, will increment the milliseconds until a
* unique value is returned.
*
* Date stamps are in the UTC time zone
* @return the date stamp
*/
public synchronized static String getUnique17DigitDate(){
long effectiveNow = System.currentTimeMillis();
effectiveNow = Math.max(effectiveNow, LAST_UNIQUE_NOW17+1);
String candidate = get17DigitDate(effectiveNow);
while(candidate.equals(LAST_TIMESTAMP17)) {
effectiveNow++;
candidate = get17DigitDate(effectiveNow);
}
LAST_UNIQUE_NOW17 = effectiveNow;
LAST_TIMESTAMP17 = candidate;
return candidate;
}
/**
* Utility function for creating arc-style date stamps
* in the format yyyyMMddHHmmss.
* Date stamps are in the UTC time zone
* @return the date stamp
*/
public static String get14DigitDate(){
return TIMESTAMP14.get().format(new Date());
}
protected static long LAST_UNIQUE_NOW14 = 0;
protected static String LAST_TIMESTAMP14 = "";
/**
* Utility function for creating UNIQUE-from-this-class
* arc-style date stamps in the format yyyMMddHHmmss.
* Rather than giving a duplicate datestamp on a
* subsequent call, will increment the seconds until a
* unique value is returned.
*
* Date stamps are in the UTC time zone
* @return the date stamp
*/
public synchronized static String getUnique14DigitDate(){
long effectiveNow = System.currentTimeMillis();
effectiveNow = Math.max(effectiveNow, LAST_UNIQUE_NOW14+1);
String candidate = get14DigitDate(effectiveNow);
while(candidate.equals(LAST_TIMESTAMP14)) {
effectiveNow += 1000;
candidate = get14DigitDate(effectiveNow);
}
LAST_UNIQUE_NOW14 = effectiveNow;
LAST_TIMESTAMP14 = candidate;
return candidate;
}
/**
* Utility function for creating arc-style date stamps
* in the format yyyyMMddHHmm.
* Date stamps are in the UTC time zone
* @return the date stamp
*/
public static String get12DigitDate(){
return TIMESTAMP12.get().format(new Date());
}
/**
* Utility function for creating log timestamps, in
* W3C/ISO8601 format, assuming UTC. Use current time.
*
* Format is yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
*
* @return the date stamp
*/
public static String getLog17Date(){
return TIMESTAMP17ISO8601Z.get().format(new Date());
}
/**
* Utility function for creating log timestamps, in
* W3C/ISO8601 format, assuming UTC.
*
* Format is yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
* @param date Date to format.
*
* @return the date stamp
*/
public static String getLog17Date(long date){
return TIMESTAMP17ISO8601Z.get().format(new Date(date));
}
/**
* Utility function for creating log timestamps, in
* W3C/ISO8601 format, assuming UTC. Use current time.
*
* Format is yyyy-MM-dd'T'HH:mm:ss'Z'
*
* @return the date stamp
*/
public static String getLog14Date(){
return TIMESTAMP14ISO8601Z.get().format(new Date());
}
/**
* Utility function for creating log timestamps, in
* W3C/ISO8601 format, assuming UTC.
*
* Format is yyyy-MM-dd'T'HH:mm:ss'Z'
* @param date long timestamp to format.
*
* @return the date stamp
*/
public static String getLog14Date(long date){
return TIMESTAMP14ISO8601Z.get().format(new Date(date));
}
/**
* Utility function for creating log timestamps, in
* W3C/ISO8601 format, assuming UTC.
*
* Format is yyyy-MM-dd'T'HH:mm:ss'Z'
* @param date Date to format.
*
* @return the date stamp
*/
public static String getLog14Date(Date date){
return TIMESTAMP14ISO8601Z.get().format(date);
}
public static Date parse14DigitISODate(String datetime, Date defaultVal)
{
try {
return TIMESTAMP14ISO8601Z.get().parse(datetime);
} catch (ParseException e) {
return defaultVal;
}
}
/**
* Utility function for creating arc-style date stamps
* in the format yyyyMMddHHmmssSSS.
* Date stamps are in the UTC time zone
*
* @param date milliseconds since epoc
* @return the date stamp
*/
public static String get17DigitDate(long date){
return TIMESTAMP17.get().format(new Date(date));
}
public static String get17DigitDate(Date date){
return TIMESTAMP17.get().format(date);
}
/**
* Utility function for creating arc-style date stamps
* in the format yyyyMMddHHmmss.
* Date stamps are in the UTC time zone
*
* @param date milliseconds since epoc
* @return the date stamp
*/
public static String get14DigitDate(long date){
return TIMESTAMP14.get().format(new Date(date));
}
public static String get14DigitDate(Date d) {
return TIMESTAMP14.get().format(d);
}
/**
* Utility function for creating arc-style date stamps
* in the format yyyyMMddHHmm.
* Date stamps are in the UTC time zone
*
* @param date milliseconds since epoc
* @return the date stamp
*/
public static String get12DigitDate(long date){
return TIMESTAMP12.get().format(new Date(date));
}
public static String get12DigitDate(Date d) {
return TIMESTAMP12.get().format(d);
}
/**
* A version of getDate which returns the default instead of throwing an exception if parsing fails
*
* @param d
* @param defaultDate
* @return
* @throws ParseException
*/
public static Date getDate(String d, Date defaultDate)
{
if (d == null) {
return defaultDate;
}
try {
return getDate(d);
} catch (ParseException pe) {
return defaultDate;
}
}
/**
* Parses an ARC-style date. If passed String is < 12 characters in length,
* we pad. At a minimum, String should contain a year (>=4 characters).
* Parse will also fail if day or month are incompletely specified. Depends
* on the above getXXDigitDate methods.
* @param A 4-17 digit date in ARC style (<code>yyyy</code> to
* <code>yyyyMMddHHmmssSSS</code>) formatting.
* @return A Date object representing the passed String.
* @throws ParseException
*/
public static Date getDate(String d) throws ParseException {
Date date = null;
if (d == null) {
throw new IllegalArgumentException("Passed date is null");
}
switch (d.length()) {
case 14:
date = ArchiveUtils.parse14DigitDate(d);
break;
case 17:
date = ArchiveUtils.parse17DigitDate(d);
break;
case 12:
date = ArchiveUtils.parse12DigitDate(d);
break;
case 0:
case 1:
case 2:
case 3:
throw new ParseException("Date string must at least contain a" +
"year: " + d, d.length());
default:
if (!(d.startsWith("19") || d.startsWith("20"))) {
throw new ParseException("Unrecognized century: " + d, 0);
}
if (d.length() < 8 && (d.length() % 2) != 0) {
throw new ParseException("Incomplete month/date: " + d,
d.length());
}
StringBuilder sb = new StringBuilder(d);
while (sb.length() < 8) {
sb.append("01");
}
while (sb.length() < 12) {
sb.append("0");
}
date = ArchiveUtils.parse12DigitDate(sb.toString());
}
return date;
}
final static SimpleDateFormat dateToTimestampFormats[] =
{new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH),
new SimpleDateFormat("MM/yyyy", Locale.ENGLISH),
new SimpleDateFormat("yyyy", Locale.ENGLISH)};
/**
* Convert a user-entered date into a timestamp
* @param input
* @return
*/
public static String dateToTimestamp(String input) {
Date date = null;
if (input.isEmpty()) {
return null;
}
for (SimpleDateFormat format : dateToTimestampFormats) {
try {
date = format.parse(input);
break;
} catch (ParseException e) {
continue;
}
}
if (date == null) {
return null;
}
return get14DigitDate(date);
}
/**
* Utility function for parsing arc-style date stamps
* in the format yyyMMddHHmmssSSS.
* Date stamps are in the UTC time zone. The whole string will not be
* parsed, only the first 17 digits.
*
* @param date an arc-style formatted date stamp
* @return the Date corresponding to the date stamp string
* @throws ParseException if the inputstring was malformed
*/
public static Date parse17DigitDate(String date) throws ParseException {
return TIMESTAMP17.get().parse(date);
}
/**
* Utility function for parsing arc-style date stamps
* in the format yyyMMddHHmmss.
* Date stamps are in the UTC time zone. The whole string will not be
* parsed, only the first 14 digits.
*
* @param date an arc-style formatted date stamp
* @return the Date corresponding to the date stamp string
* @throws ParseException if the inputstring was malformed
*/
public static Date parse14DigitDate(String date) throws ParseException{
return TIMESTAMP14.get().parse(date);
}
/**
* Utility function for parsing arc-style date stamps
* in the format yyyMMddHHmm.
* Date stamps are in the UTC time zone. The whole string will not be
* parsed, only the first 12 digits.
*
* @param date an arc-style formatted date stamp
* @return the Date corresponding to the date stamp string
* @throws ParseException if the inputstring was malformed
*/
public static Date parse12DigitDate(String date) throws ParseException{
return TIMESTAMP12.get().parse(date);
}
/**
* @param timestamp A 14-digit timestamp or the suffix for a 14-digit
* timestamp: E.g. '20010909014640' or '20010101' or '1970'.
* @return Seconds since the epoch as a string zero-pre-padded so always
* Integer.MAX_VALUE wide (Makes it so sorting of resultant string works
* properly).
* @throws ParseException
*/
public static String secondsSinceEpoch(String timestamp)
throws ParseException {
return zeroPadInteger((int)
(getSecondsSinceEpoch(timestamp).getTime()/1000));
}
/**
* @param timestamp A 14-digit timestamp or the suffix for a 14-digit
* timestamp: E.g. '20010909014640' or '20010101' or '1970'.
* @return A date.
* @see #secondsSinceEpoch(String)
* @throws ParseException
*/
public static Date getSecondsSinceEpoch(String timestamp)
throws ParseException {
if (timestamp.length() < 14) {
if (timestamp.length() < 10 && (timestamp.length() % 2) == 1) {
throw new IllegalArgumentException("Must have year, " +
"month, date, hour or second granularity: " + timestamp);
}
if (timestamp.length() == 4) {
// Add first month and first date.
timestamp = timestamp + "01010000";
}
if (timestamp.length() == 6) {
// Add a date of the first.
timestamp = timestamp + "010000";
}
if (timestamp.length() < 14) {
timestamp = timestamp +
ArchiveUtils.padTo("", 14 - timestamp.length(), '0');
}
}
return ArchiveUtils.parse14DigitDate(timestamp);
}
/**
* @param i Integer to add prefix of zeros too. If passed
* 2005, will return the String <code>0000002005</code>. String
* width is the width of Integer.MAX_VALUE as a string (10
* digits).
* @return Padded String version of <code>i</code>.
*/
public static String zeroPadInteger(int i) {
return ArchiveUtils.padTo(Integer.toString(i),
MAX_INT_CHAR_WIDTH, '0');
}
/**
* Convert an <code>int</code> to a <code>String</code>, and pad it to
* <code>pad</code> spaces.
* @param i the int
* @param pad the width to pad to.
* @return String w/ padding.
*/
public static String padTo(final int i, final int pad) {
String n = Integer.toString(i);
return padTo(n, pad);
}
/**
* Pad the given <code>String</code> to <code>pad</code> characters wide
* by pre-pending spaces. <code>s</code> should not be <code>null</code>.
* If <code>s</code> is already wider than <code>pad</code> no change is
* done.
*
* @param s the String to pad
* @param pad the width to pad to.
* @return String w/ padding.
*/
public static String padTo(final String s, final int pad) {
return padTo(s, pad, DEFAULT_PAD_CHAR);
}
/**
* Pad the given <code>String</code> to <code>pad</code> characters wide
* by pre-pending <code>padChar</code>.
*
* <code>s</code> should not be <code>null</code>. If <code>s</code> is
* already wider than <code>pad</code> no change is done.
*
* @param s the String to pad
* @param pad the width to pad to.
* @param padChar The pad character to use.
* @return String w/ padding.
*/
public static String padTo(final String s, final int pad,
final char padChar) {
String result = s;
int l = s.length();
if (l < pad) {
StringBuffer sb = new StringBuffer(pad);
while(l < pad) {
sb.append(padChar);
l++;
}
sb.append(s);
result = sb.toString();
}
return result;
}
/** check that two byte arrays are equal. They may be <code>null</code>.
*
* @param lhs a byte array
* @param rhs another byte array.
* @return <code>true</code> if they are both equal (or both
* <code>null</code>)
*/
public static boolean byteArrayEquals(final byte[] lhs, final byte[] rhs) {
if (lhs == null && rhs != null || lhs != null && rhs == null) {
return false;
}
if (lhs==rhs) {
return true;
}
if (lhs.length != rhs.length) {
return false;
}
for(int i = 0; i<lhs.length; i++) {
if (lhs[i]!=rhs[i]) {
return false;
}
}
return true;
}
/**
* Converts a double to a string.
* @param val The double to convert
* @param precision How many characters to include after '.'
* @return the double as a string.
*/
public static String doubleToString(double val, int maxFractionDigits){
return doubleToString(val, maxFractionDigits, 0);
}
public static String doubleToString(double val, int maxFractionDigits, int minFractionDigits) {
// NumberFormat returns U+FFFD REPLACEMENT CHARACTER for NaN which looks
// like a bug in the UI
if (Double.isNaN(val)) {
return "NaN";
}
NumberFormat f = NumberFormat.getNumberInstance(Locale.US);
f.setMaximumFractionDigits(maxFractionDigits);
f.setMinimumFractionDigits(minFractionDigits);
return f.format(val);
}
/**
* Takes a byte size and formats it for display with 'friendly' units.
* <p>
* This involves converting it to the largest unit
* (of B, KiB, MiB, GiB, TiB) for which the amount will be > 1.
* <p>
* Additionally, at least 2 significant digits are always displayed.
* <p>
* Negative numbers will be returned as '0 B'.
*
* @param amount the amount of bytes
* @return A string containing the amount, properly formated.
*/
public static String formatBytesForDisplay(long amount) {
double displayAmount = (double) amount;
int unitPowerOf1024 = 0;
if(amount <= 0){
return "0 B";
}
final String[] units = { " B", " KiB", " MiB", " GiB", " TiB" };
while (displayAmount >= 1024 && unitPowerOf1024 < units.length - 1) {
displayAmount = displayAmount / 1024;
unitPowerOf1024++;
}
int fractionDigits;
if (unitPowerOf1024 == 0 || displayAmount >= 10) {
fractionDigits = 0;
} else {
// ensure at least 2 significant digits (#.#) for small displayValues
fractionDigits = 1;
}
return doubleToString(displayAmount, fractionDigits, fractionDigits)
+ units[unitPowerOf1024];
}
/**
* Convert milliseconds value to a human-readable duration
* @param time
* @return Human readable string version of passed <code>time</code>
*/
public static String formatMillisecondsToConventional(long time) {
return formatMillisecondsToConventional(time,5);
}
/**
* Convert milliseconds value to a human-readable duration of
* mixed units, using units no larger than days. For example,
* "5d12h13m12s113ms" or "19h51m".
*
* @param duration
* @param unitCount how many significant units to show, at most
* for example, a value of 2 would show days+hours or hours+seconds
* but not hours+second+milliseconds
* @return Human readable string version of passed <code>time</code>
*/
public static String formatMillisecondsToConventional(long duration, int unitCount) {
if(unitCount <=0) {
unitCount = 5;
}
if(duration==0) {
return "0ms";
}
StringBuffer sb = new StringBuffer();
if(duration<0) {
sb.append("-");
}
long absTime = Math.abs(duration);
long[] thresholds = {DAY_IN_MS, HOUR_IN_MS, 60000, 1000, 1};
String[] units = {"d","h","m","s","ms"};
for(int i = 0; i < thresholds.length; i++) {
if(absTime >= thresholds[i]) {
sb.append(absTime / thresholds[i] + units[i]);
absTime = absTime % thresholds[i];
unitCount--;
}
if(unitCount==0) {
break;
}
}
return sb.toString();
}
/**
* Copy the raw bytes of a long into a byte array, starting at
* the specified offset.
*
* @param l
* @param array
* @param offset
*/
public static void longIntoByteArray(long l, byte[] array, int offset) {
int i, shift;
for(i = 0, shift = 56; i < 8; i++, shift -= 8)
array[offset+i] = (byte)(0xFF & (l >> shift));
}
public static long byteArrayIntoLong(byte [] bytearray) {
return byteArrayIntoLong(bytearray, 0);
}
/**
* Byte array into long.
* @param bytearray Array to convert to a long.
* @param offset Offset into array at which we start decoding the long.
* @return Long made of the bytes of <code>array</code> beginning at
* offset <code>offset</code>.
* @see #longIntoByteArray(long, byte[], int)
*/
public static long byteArrayIntoLong(byte [] bytearray,
int offset) {
long result = 0;
for (int i = offset; i < 8 /*Bytes in long*/; i++) {
result = (result << 8 /*Bits in byte*/) |
(0xff & (byte)(bytearray[i] & 0xff));
}
return result;
}
/**
* Given a string that may be a plain host or host/path (without
* URI scheme), add an implied http:// if necessary.
*
* @param u string to evaluate
* @return string with http:// added if no scheme already present
*/
public static String addImpliedHttpIfNecessary(String u) {
int colon = u.indexOf(':');
int period = u.indexOf('.');
if (colon == -1 || (period >= 0) && (period < colon)) {
// No scheme present; prepend "http://"
u = "http://" + u;
}
return u;
}
/**
* Verify that the array begins with the prefix.
*
* @param array
* @param prefix
* @return true if array is identical to prefix for the first prefix.length
* positions
*/
public static boolean startsWith(byte[] array, byte[] prefix) {
if(prefix.length>array.length) {
return false;
}
for(int i = 0; i < prefix.length; i++) {
if(array[i]!=prefix[i]) {
return false;
}
}
return true;
}
/**
* Enhance given object's default String display for appearing
* nested in a pretty Map String.
*
* @param obj Object to prettify
* @return prettified String
*/
public static String prettyString(Object obj) {
// these things have to checked and casted unfortunately
if (obj instanceof Object[]) {
return prettyString((Object[]) obj);
} else if (obj instanceof Map) {
return prettyString((Map<?, ?>) obj);
} else {
return "<"+obj+">";
}
}
/**
* Provide a improved String of a Map's entries
*
* @param Map
* @return prettified (in curly brackets) string of Map contents
*/
public static String prettyString(Map<?, ?> map) {
StringBuilder builder = new StringBuilder();
builder.append("{ ");
boolean needsComma = false;
for( Object key : map.keySet()) {
if(needsComma) {
builder.append(", ");
}
builder.append(key);
builder.append(": ");
builder.append(prettyString(map.get(key)));
needsComma = true;
}
builder.append(" }");
return builder.toString();
}
/**
* Provide a slightly-improved String of Object[]
*
* @param Object[]
* @return prettified (in square brackets) of Object[]
*/
public static String prettyString(Object[] array) {
StringBuilder builder = new StringBuilder();
builder.append("[ ");
boolean needsComma = false;
for (Object o: array) {
if(o==null) continue;
if(needsComma) {
builder.append(", ");
}
builder.append(prettyString(o));
needsComma = true;
}
builder.append(" ]");
return builder.toString();
}
private static String loadVersion() {
InputStream input = ArchiveUtils.class.getResourceAsStream(
"/org/archive/util/version.txt");
if (input == null) {
return "UNKNOWN";
}
BufferedReader br = null;
String version;
try {
br = new BufferedReader(new InputStreamReader(input));
version = br.readLine();
br.readLine();
} catch (IOException e) {
return e.getMessage();
} finally {
closeQuietly(br);
}
version = version.trim();
if (!version.endsWith("SNAPSHOT")) {
return version;
}
input = ArchiveUtils.class.getResourceAsStream("/org/archive/util/timestamp.txt");
if (input == null) {
return version;
}
br = null;
String timestamp;
try {
br = new BufferedReader(new InputStreamReader(input));
timestamp = br.readLine();
} catch (IOException e) {
return version;
} finally {
closeQuietly(br);
}
if (timestamp.startsWith("timestamp=")) {
timestamp = timestamp.substring(10);
}
return version.trim() + "-" + timestamp.trim();
}
public static Set<String> TLDS;
static {
TLDS = new HashSet<String>();
InputStream is = ArchiveUtils.class.getResourceAsStream("tlds-alpha-by-domain.txt");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while((line = reader.readLine())!=null) {
if (line.startsWith("#")) {
continue;
}
TLDS.add(line.trim().toLowerCase());
}
} catch (Exception e) {
LOGGER.log(Level.SEVERE,"TLD list unavailable",e);
} finally {
IOUtils.closeQuietly(is);
}
}
/**
* Return whether the given string represents a known
* top-level-domain (like "com", "org", etc.) per IANA
* as of 20100419
*
* @param dom candidate string
* @return boolean true if recognized as TLD
*/
public static boolean isTld(String dom) {
return TLDS.contains(dom.toLowerCase());
}
public static void closeQuietly(Object input) {
if(input == null || ! (input instanceof Closeable)) {
return;
}
try {
((Closeable)input).close();
} catch (IOException ioe) {
// ignore
}
}
/**
* Perform checks as to whether normal execution should proceed.
*
* If an external interrupt is detected, throw an interrupted exception.
* Used before anything that should not be attempted by a 'zombie' thread
* that the Frontier/Crawl has given up on.
*
* @throws InterruptedException
*/
public static void continueCheck() throws InterruptedException {
if(Thread.interrupted()) {
throw new InterruptedException("interrupt detected");
}
}
/**
* Read stream into buf until EOF or buf full.
*
* @param input
* @param buf
* @throws IOException
*/
public static int readFully(InputStream input, byte[] buf)
throws IOException {
int max = buf.length;
int ofs = 0;
while (ofs < max) {
int l = input.read(buf, ofs, max - ofs);
if (l == 0) {
throw new EOFException();
}
ofs += l;
}
return ofs;
}
/** suffix to recognize gzipped files */
public static final String GZIP_SUFFIX = ".gz";
/**
* Get a BufferedReader on the crawler journal given
*
* TODO: move to a general utils class
*
* @param source File journal
* @return journal buffered reader.
* @throws IOException
*/
public static BufferedReader getBufferedReader(File source) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(source));
boolean isGzipped = source.getName().toLowerCase().
endsWith(GZIP_SUFFIX);
if(isGzipped) {
is = new GZIPInputStream(is);
}
return new BufferedReader(new InputStreamReader(is));
}
/**
* Get a BufferedReader on the crawler journal given.
*
* @param source URL journal
* @return journal buffered reader.
* @throws IOException
*/
public static BufferedReader getBufferedReader(URL source) throws IOException {
URLConnection conn = source.openConnection();
boolean isGzipped = conn.getContentType() != null && conn.getContentType().equalsIgnoreCase("application/x-gzip")
|| conn.getContentEncoding() != null && conn.getContentEncoding().equalsIgnoreCase("gzip");
InputStream uis = conn.getInputStream();
return new BufferedReader(isGzipped?
new InputStreamReader(new GZIPInputStream(uis)):
new InputStreamReader(uis));
}
/**
* Gzip passed bytes.
* Use only when bytes is small.
* @param bytes What to gzip.
* @return A gzip member of bytes.
* @throws IOException
*/
public static byte [] gzip(byte [] bytes) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzipOS = new GZIPOutputStream(baos);
gzipOS.write(bytes, 0, bytes.length);
gzipOS.close();
return baos.toByteArray();
}
/**
* Tests passed stream is gzip stream by reading in the HEAD.
* Does not mark/reset stream -- so this test actually makes
* stream unopenable within GZIP streams, unless reset.
* @param is An InputStream.
* @return True if compressed stream.
* @throws IOException
*/
public static boolean isGzipped(final InputStream is)
throws IOException {
try {
new GZIPDecoder().parseHeader(is);
return true;
} catch (GZIPFormatException e) {
return false;
}
}
}
| |
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver15;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;
class OFAsyncConfigPropContStatusMasterVer15 implements OFAsyncConfigPropContStatusMaster {
private static final Logger logger = LoggerFactory.getLogger(OFAsyncConfigPropContStatusMasterVer15.class);
// version: 1.5
final static byte WIRE_VERSION = 6;
final static int LENGTH = 8;
private final static long DEFAULT_MASK = 0x0L;
// OF message fields
private final long mask;
//
// Immutable default instance
final static OFAsyncConfigPropContStatusMasterVer15 DEFAULT = new OFAsyncConfigPropContStatusMasterVer15(
DEFAULT_MASK
);
// package private constructor - used by readers, builders, and factory
OFAsyncConfigPropContStatusMasterVer15(long mask) {
this.mask = mask;
}
// Accessors for OF message fields
@Override
public int getType() {
return 0xf;
}
@Override
public long getMask() {
return mask;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
public OFAsyncConfigPropContStatusMaster.Builder createBuilder() {
return new BuilderWithParent(this);
}
static class BuilderWithParent implements OFAsyncConfigPropContStatusMaster.Builder {
final OFAsyncConfigPropContStatusMasterVer15 parentMessage;
// OF message fields
private boolean maskSet;
private long mask;
BuilderWithParent(OFAsyncConfigPropContStatusMasterVer15 parentMessage) {
this.parentMessage = parentMessage;
}
@Override
public int getType() {
return 0xf;
}
@Override
public long getMask() {
return mask;
}
@Override
public OFAsyncConfigPropContStatusMaster.Builder setMask(long mask) {
this.mask = mask;
this.maskSet = true;
return this;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
@Override
public OFAsyncConfigPropContStatusMaster build() {
long mask = this.maskSet ? this.mask : parentMessage.mask;
//
return new OFAsyncConfigPropContStatusMasterVer15(
mask
);
}
}
static class Builder implements OFAsyncConfigPropContStatusMaster.Builder {
// OF message fields
private boolean maskSet;
private long mask;
@Override
public int getType() {
return 0xf;
}
@Override
public long getMask() {
return mask;
}
@Override
public OFAsyncConfigPropContStatusMaster.Builder setMask(long mask) {
this.mask = mask;
this.maskSet = true;
return this;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
//
@Override
public OFAsyncConfigPropContStatusMaster build() {
long mask = this.maskSet ? this.mask : DEFAULT_MASK;
return new OFAsyncConfigPropContStatusMasterVer15(
mask
);
}
}
final static Reader READER = new Reader();
static class Reader implements OFMessageReader<OFAsyncConfigPropContStatusMaster> {
@Override
public OFAsyncConfigPropContStatusMaster readFrom(ByteBuf bb) throws OFParseError {
int start = bb.readerIndex();
// fixed value property type == 0xf
short type = bb.readShort();
if(type != (short) 0xf)
throw new OFParseError("Wrong type: Expected=0xf(0xf), got="+type);
int length = U16.f(bb.readShort());
if(length != 8)
throw new OFParseError("Wrong length: Expected=8(8), got="+length);
if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
// Buffer does not have all data yet
bb.readerIndex(start);
return null;
}
if(logger.isTraceEnabled())
logger.trace("readFrom - length={}", length);
long mask = U32.f(bb.readInt());
OFAsyncConfigPropContStatusMasterVer15 asyncConfigPropContStatusMasterVer15 = new OFAsyncConfigPropContStatusMasterVer15(
mask
);
if(logger.isTraceEnabled())
logger.trace("readFrom - read={}", asyncConfigPropContStatusMasterVer15);
return asyncConfigPropContStatusMasterVer15;
}
}
public void putTo(PrimitiveSink sink) {
FUNNEL.funnel(this, sink);
}
final static OFAsyncConfigPropContStatusMasterVer15Funnel FUNNEL = new OFAsyncConfigPropContStatusMasterVer15Funnel();
static class OFAsyncConfigPropContStatusMasterVer15Funnel implements Funnel<OFAsyncConfigPropContStatusMasterVer15> {
private static final long serialVersionUID = 1L;
@Override
public void funnel(OFAsyncConfigPropContStatusMasterVer15 message, PrimitiveSink sink) {
// fixed value property type = 0xf
sink.putShort((short) 0xf);
// fixed value property length = 8
sink.putShort((short) 0x8);
sink.putLong(message.mask);
}
}
public void writeTo(ByteBuf bb) {
WRITER.write(bb, this);
}
final static Writer WRITER = new Writer();
static class Writer implements OFMessageWriter<OFAsyncConfigPropContStatusMasterVer15> {
@Override
public void write(ByteBuf bb, OFAsyncConfigPropContStatusMasterVer15 message) {
// fixed value property type = 0xf
bb.writeShort((short) 0xf);
// fixed value property length = 8
bb.writeShort((short) 0x8);
bb.writeInt(U32.t(message.mask));
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("OFAsyncConfigPropContStatusMasterVer15(");
b.append("mask=").append(mask);
b.append(")");
return b.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFAsyncConfigPropContStatusMasterVer15 other = (OFAsyncConfigPropContStatusMasterVer15) obj;
if( mask != other.mask)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * (int) (mask ^ (mask >>> 32));
return result;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package org.apache.polygene.runtime.query;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.apache.polygene.api.composite.Composite;
import org.apache.polygene.api.property.Property;
import org.apache.polygene.api.query.grammar.OrderBy;
import org.apache.polygene.spi.query.QuerySource;
import static java.util.stream.Collectors.toList;
import static org.apache.polygene.api.util.Classes.instanceOf;
/**
* JAVADOC
*/
public class IterableQuerySource
implements QuerySource
{
private final Iterable iterable;
/**
* Constructor.
*
* @param iterable iterable
*/
@SuppressWarnings( "raw" )
IterableQuerySource( final Iterable iterable )
{
this.iterable = iterable;
}
@Override
public <T> T find( Class<T> resultType,
Predicate<Composite> whereClause,
List<OrderBy> orderBySegments,
Integer firstResult,
Integer maxResults,
Map<String, Object> variables
)
{
return stream( resultType, whereClause, orderBySegments, firstResult, maxResults, variables )
.findFirst().orElse( null );
}
@Override
public <T> long count( Class<T> resultType,
Predicate<Composite> whereClause,
List<OrderBy> orderBySegments,
Integer firstResult,
Integer maxResults,
Map<String, Object> variables
)
{
return list( resultType, whereClause, orderBySegments, firstResult, maxResults, variables ).size();
}
@Override
public <T> Stream<T> stream( Class<T> resultType,
Predicate<Composite> whereClause,
List<OrderBy> orderBySegments,
Integer firstResult,
Integer maxResults,
Map<String, Object> variables
)
{
return list( resultType, whereClause, orderBySegments, firstResult, maxResults, variables ).stream();
}
@SuppressWarnings( {"raw", "unchecked"} )
private <T> List<T> list( Class<T> resultType,
Predicate<Composite> whereClause,
List<OrderBy> orderBySegments,
Integer firstResult,
Integer maxResults,
Map<String, Object> variables
)
{
// Ensure it's a list first
List<T> list = filter( resultType, whereClause );
// Order list
if( orderBySegments != null )
{
// Sort it
list.sort( new OrderByComparator( orderBySegments ) );
}
// Cut results
if( firstResult != null )
{
if( firstResult > list.size() )
{
return Collections.emptyList();
}
int toIdx;
if( maxResults != null )
{
toIdx = Math.min( firstResult + maxResults, list.size() );
}
else
{
toIdx = list.size();
}
list = list.subList( firstResult, toIdx );
}
else
{
int toIdx;
if( maxResults != null )
{
toIdx = Math.min( maxResults, list.size() );
}
else
{
toIdx = list.size();
}
list = list.subList( 0, toIdx );
}
return list;
}
@SuppressWarnings( {"raw", "unchecked"} )
private <T> List<T> filter( Class<T> resultType, Predicate whereClause )
{
Stream stream = StreamSupport.stream( iterable.spliterator(), false );
if( whereClause == null )
{
return List.class.cast( stream.filter( resultType::isInstance )
.collect( toList() ) );
}
else
{
return List.class.cast( stream.filter( instanceOf( resultType ).and( whereClause ) )
.collect( toList() ) );
}
}
@Override
public String toString()
{
return "IterableQuerySource{" + iterable + '}';
}
private static class OrderByComparator<T extends Composite>
implements Comparator<T>
{
private final Iterable<OrderBy> orderBySegments;
private OrderByComparator( Iterable<OrderBy> orderBySegments )
{
this.orderBySegments = orderBySegments;
}
@Override
@SuppressWarnings( {"raw", "unchecked"} )
public int compare( T o1, T o2 )
{
for( OrderBy orderBySegment : orderBySegments )
{
try
{
final Property prop1 = orderBySegment.property().apply( o1 );
final Property prop2 = orderBySegment.property().apply( o2 );
if( prop1 == null || prop2 == null )
{
if( prop1 == null && prop2 == null )
{
return 0;
}
else if( prop1 != null )
{
return 1;
}
return -1;
}
final Object value1 = prop1.get();
final Object value2 = prop2.get();
if( value1 == null || value2 == null )
{
if( value1 == null && value2 == null )
{
return 0;
}
else if( value1 != null )
{
return 1;
}
return -1;
}
if( value1 instanceof Comparable )
{
int result = ( (Comparable) value1 ).compareTo( value2 );
if( result != 0 )
{
if( orderBySegment.order() == OrderBy.Order.ASCENDING )
{
return result;
}
else
{
return -result;
}
}
}
}
catch( Exception e )
{
return 0;
}
}
return 0;
}
}
}
| |
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.contentproviderpaging;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
/**
* ContentProvider that demonstrates how the paging support works introduced in Android O.
* This class fetches the images from the local storage but the storage could be
* other locations such as a remote server.
*/
public class ImageProvider extends ContentProvider {
private static final String TAG = "ImageDocumentsProvider";
private static final int IMAGES = 1;
private static final int IMAGE_ID = 2;
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sUriMatcher.addURI(ImageContract.AUTHORITY, "images", IMAGES);
sUriMatcher.addURI(ImageContract.AUTHORITY, "images/#", IMAGE_ID);
}
// Indicated how many same images are going to be written as dummy images
private static final int REPEAT_COUNT_WRITE_FILES = 10;
private File mBaseDir;
@Override
public boolean onCreate() {
Log.d(TAG, "onCreate");
Context context = getContext();
if (context == null) {
return false;
}
mBaseDir = context.getFilesDir();
writeDummyFilesToStorage(context);
return true;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s,
@Nullable String[] strings1, @Nullable String s1) {
throw new UnsupportedOperationException();
}
@Override
public Cursor query(Uri uri, String[] projection, Bundle queryArgs,
CancellationSignal cancellationSignal) {
int match = sUriMatcher.match(uri);
// We only support a query for multiple images, return null for other form of queries
// including a query for a single image.
switch (match) {
case IMAGES:
break;
default:
return null;
}
MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));
File[] files = mBaseDir.listFiles();
int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MAX_VALUE);
Log.d(TAG, "queryChildDocuments with Bundle, Uri: " +
uri + ", offset: " + offset + ", limit: " + limit);
if (offset < 0) {
throw new IllegalArgumentException("Offset must not be less than 0");
}
if (limit < 0) {
throw new IllegalArgumentException("Limit must not be less than 0");
}
if (offset >= files.length) {
return result;
}
for (int i = offset, maxIndex = Math.min(offset + limit, files.length); i < maxIndex; i++) {
includeFile(result, files[i]);
}
Bundle bundle = new Bundle();
bundle.putInt(ContentResolver.EXTRA_TOTAL_SIZE, files.length);
String[] honoredArgs = new String[2];
int size = 0;
if (queryArgs.containsKey(ContentResolver.QUERY_ARG_OFFSET)) {
honoredArgs[size++] = ContentResolver.QUERY_ARG_OFFSET;
}
if (queryArgs.containsKey(ContentResolver.QUERY_ARG_LIMIT)) {
honoredArgs[size++] = ContentResolver.QUERY_ARG_LIMIT;
}
if (size != honoredArgs.length) {
honoredArgs = Arrays.copyOf(honoredArgs, size);
}
bundle.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, honoredArgs);
result.setExtras(bundle);
return result;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
int match = sUriMatcher.match(uri);
switch (match) {
case IMAGES:
return "vnd.android.cursor.dir/images";
case IMAGE_ID:
return "vnd.android.cursor.item/images";
default:
throw new IllegalArgumentException(String.format("Unknown URI: %s", uri));
}
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
throw new UnsupportedOperationException();
}
@Override
public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
throw new UnsupportedOperationException();
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s,
@Nullable String[] strings) {
throw new UnsupportedOperationException();
}
private static String[] resolveDocumentProjection(String[] projection) {
return projection != null ? projection : ImageContract.PROJECTION_ALL;
}
/**
* Add a representation of a file to a cursor.
*
* @param result the cursor to modify
* @param file the File object representing the desired file (may be null if given docID)
*/
private void includeFile(MatrixCursor result, File file) {
MatrixCursor.RowBuilder row = result.newRow();
row.add(ImageContract.Columns.DISPLAY_NAME, file.getName());
row.add(ImageContract.Columns.SIZE, file.length());
row.add(ImageContract.Columns.ABSOLUTE_PATH, file.getAbsolutePath());
}
/**
* Preload sample files packaged in the apk into the internal storage directory. This is a
* dummy function specific to this demo. The MyCloud mock cloud service doesn't actually
* have a backend, so it simulates by reading content from the device's internal storage.
*/
private void writeDummyFilesToStorage(Context context) {
if (mBaseDir.list().length > 0) {
return;
}
int[] imageResIds = getResourceIdArray(context, R.array.image_res_ids);
for (int i = 0; i < REPEAT_COUNT_WRITE_FILES; i++) {
for (int resId : imageResIds) {
writeFileToInternalStorage(context, resId, "-" + i + ".jpeg");
}
}
}
/**
* Write a file to internal storage. Used to set up our dummy "cloud server".
*
* @param context the Context
* @param resId the resource ID of the file to write to internal storage
* @param extension the file extension (ex. .png, .mp3)
*/
private void writeFileToInternalStorage(Context context, int resId, String extension) {
InputStream ins = context.getResources().openRawResource(resId);
int size;
byte[] buffer = new byte[1024];
try {
String filename = context.getResources().getResourceEntryName(resId) + extension;
FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
while ((size = ins.read(buffer, 0, 1024)) >= 0) {
fos.write(buffer, 0, size);
}
ins.close();
fos.write(buffer);
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private int[] getResourceIdArray(Context context, int arrayResId) {
TypedArray ar = context.getResources().obtainTypedArray(arrayResId);
int len = ar.length();
int[] resIds = new int[len];
for (int i = 0; i < len; i++) {
resIds[i] = ar.getResourceId(i, 0);
}
ar.recycle();
return resIds;
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.sql.planner.iterative.rule;
import io.trino.metadata.Metadata;
import io.trino.spi.type.Type;
import io.trino.sql.parser.ParsingOptions;
import io.trino.sql.parser.SqlParser;
import io.trino.sql.planner.LiteralEncoder;
import io.trino.sql.planner.Symbol;
import io.trino.sql.planner.SymbolAllocator;
import io.trino.sql.planner.SymbolsExtractor;
import io.trino.sql.planner.TypeAnalyzer;
import io.trino.sql.tree.Expression;
import io.trino.sql.tree.ExpressionRewriter;
import io.trino.sql.tree.ExpressionTreeRewriter;
import io.trino.sql.tree.LogicalBinaryExpression;
import org.testng.annotations.Test;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static io.trino.SessionTestUtils.TEST_SESSION;
import static io.trino.metadata.MetadataManager.createTestMetadataManager;
import static io.trino.spi.type.BigintType.BIGINT;
import static io.trino.spi.type.BooleanType.BOOLEAN;
import static io.trino.spi.type.DoubleType.DOUBLE;
import static io.trino.spi.type.IntegerType.INTEGER;
import static io.trino.spi.type.RealType.REAL;
import static io.trino.sql.ExpressionUtils.binaryExpression;
import static io.trino.sql.ExpressionUtils.extractPredicates;
import static io.trino.sql.ExpressionUtils.rewriteIdentifiersToSymbolReferences;
import static io.trino.sql.planner.iterative.rule.SimplifyExpressions.rewrite;
import static java.util.stream.Collectors.toList;
import static org.testng.Assert.assertEquals;
public class TestSimplifyExpressions
{
private static final SqlParser SQL_PARSER = new SqlParser();
private static final Metadata METADATA = createTestMetadataManager();
private static final LiteralEncoder LITERAL_ENCODER = new LiteralEncoder(METADATA);
@Test
public void testPushesDownNegations()
{
assertSimplifies("NOT X", "NOT X");
assertSimplifies("NOT NOT X", "X");
assertSimplifies("NOT NOT NOT X", "NOT X");
assertSimplifies("NOT NOT NOT X", "NOT X");
assertSimplifies("NOT (X > Y)", "X <= Y");
assertSimplifies("NOT (X > (NOT NOT Y))", "X <= Y");
assertSimplifies("X > (NOT NOT Y)", "X > Y");
assertSimplifies("NOT (X AND Y AND (NOT (Z OR V)))", "(NOT X) OR (NOT Y) OR (Z OR V)");
assertSimplifies("NOT (X OR Y OR (NOT (Z OR V)))", "(NOT X) AND (NOT Y) AND (Z OR V)");
assertSimplifies("NOT (X OR Y OR (Z OR V))", "(NOT X) AND (NOT Y) AND ((NOT Z) AND (NOT V))");
assertSimplifies("NOT (X IS DISTINCT FROM Y)", "NOT (X IS DISTINCT FROM Y)");
}
@Test
public void testExtractCommonPredicates()
{
assertSimplifies("X AND Y", "X AND Y");
assertSimplifies("X OR Y", "X OR Y");
assertSimplifies("X AND X", "X");
assertSimplifies("X OR X", "X");
assertSimplifies("(X OR Y) AND (X OR Y)", "X OR Y");
assertSimplifies("(A AND V) OR V", "V");
assertSimplifies("(A OR V) AND V", "V");
assertSimplifies("(A OR B OR C) AND (A OR B)", "A OR B");
assertSimplifies("(A AND B) OR (A AND B AND C)", "A AND B");
assertSimplifies("I = ((A OR B) AND (A OR B OR C))", "I = (A OR B)");
assertSimplifies("(X OR Y) AND (X OR Z)", "(X OR Y) AND (X OR Z)");
assertSimplifies("(X AND Y AND V) OR (X AND Y AND Z)", "(X AND Y) AND (V OR Z)");
assertSimplifies("((X OR Y OR V) AND (X OR Y OR Z)) = I", "((X OR Y) OR (V AND Z)) = I");
assertSimplifies("((X OR V) AND V) OR ((X OR V) AND V)", "V");
assertSimplifies("((X OR V) AND X) OR ((X OR V) AND V)", "X OR V");
assertSimplifies("((X OR V) AND Z) OR ((X OR V) AND V)", "(X OR V) AND (Z OR V)");
assertSimplifies("X AND ((Y AND Z) OR (Y AND V) OR (Y AND X))", "X AND Y AND (Z OR V OR X)");
assertSimplifies("(A AND B AND C AND D) OR (A AND B AND E) OR (A AND F)", "A AND ((B AND C AND D) OR (B AND E) OR F)");
assertSimplifies("((A AND B) OR (A AND C)) AND D", "A AND (B OR C) AND D");
assertSimplifies("((A OR B) AND (A OR C)) OR D", "(A OR B OR D) AND (A OR C OR D)");
assertSimplifies("(((A AND B) OR (A AND C)) AND D) OR E", "(A OR E) AND (B OR C OR E) AND (D OR E)");
assertSimplifies("(((A OR B) AND (A OR C)) OR D) AND E", "(A OR (B AND C) OR D) AND E");
assertSimplifies("(A AND B) OR (C AND D)", "(A OR C) AND (A OR D) AND (B OR C) AND (B OR D)");
// No distribution since it would add too many new terms
assertSimplifies("(A AND B) OR (C AND D) OR (E AND F)", "(A AND B) OR (C AND D) OR (E AND F)");
// Test overflow handling for large disjunct expressions
assertSimplifies("(A1 AND A2) OR (A3 AND A4) OR (A5 AND A6) OR (A7 AND A8) OR (A9 AND A10)" +
" OR (A11 AND A12) OR (A13 AND A14) OR (A15 AND A16) OR (A17 AND A18) OR (A19 AND A20)" +
" OR (A21 AND A22) OR (A23 AND A24) OR (A25 AND A26) OR (A27 AND A28) OR (A29 AND A30)" +
" OR (A31 AND A32) OR (A33 AND A34) OR (A35 AND A36) OR (A37 AND A38) OR (A39 AND A40)" +
" OR (A41 AND A42) OR (A43 AND A44) OR (A45 AND A46) OR (A47 AND A48) OR (A49 AND A50)" +
" OR (A51 AND A52) OR (A53 AND A54) OR (A55 AND A56) OR (A57 AND A58) OR (A59 AND A60)",
"(A1 AND A2) OR (A3 AND A4) OR (A5 AND A6) OR (A7 AND A8) OR (A9 AND A10)" +
" OR (A11 AND A12) OR (A13 AND A14) OR (A15 AND A16) OR (A17 AND A18) OR (A19 AND A20)" +
" OR (A21 AND A22) OR (A23 AND A24) OR (A25 AND A26) OR (A27 AND A28) OR (A29 AND A30)" +
" OR (A31 AND A32) OR (A33 AND A34) OR (A35 AND A36) OR (A37 AND A38) OR (A39 AND A40)" +
" OR (A41 AND A42) OR (A43 AND A44) OR (A45 AND A46) OR (A47 AND A48) OR (A49 AND A50)" +
" OR (A51 AND A52) OR (A53 AND A54) OR (A55 AND A56) OR (A57 AND A58) OR (A59 AND A60)");
}
private static void assertSimplifies(String expression, String expected)
{
ParsingOptions parsingOptions = new ParsingOptions();
Expression actualExpression = rewriteIdentifiersToSymbolReferences(SQL_PARSER.createExpression(expression, parsingOptions));
Expression expectedExpression = rewriteIdentifiersToSymbolReferences(SQL_PARSER.createExpression(expected, parsingOptions));
Expression rewritten = rewrite(actualExpression, TEST_SESSION, new SymbolAllocator(booleanSymbolTypeMapFor(actualExpression)), METADATA, LITERAL_ENCODER, new TypeAnalyzer(SQL_PARSER, METADATA));
assertEquals(
normalize(rewritten),
normalize(expectedExpression));
}
private static Map<Symbol, Type> booleanSymbolTypeMapFor(Expression expression)
{
return SymbolsExtractor.extractUnique(expression).stream()
.collect(Collectors.toMap(symbol -> symbol, symbol -> BOOLEAN));
}
@Test
public void testPushesDownNegationsNumericTypes()
{
assertSimplifiesNumericTypes("NOT (I1 = I2)", "I1 <> I2");
assertSimplifiesNumericTypes("NOT (I1 > I2)", "I1 <= I2");
assertSimplifiesNumericTypes("NOT ((I1 = I2) OR (I3 > I4))", "I1 <> I2 AND I3 <= I4");
assertSimplifiesNumericTypes("NOT NOT NOT (NOT NOT (I1 = I2) OR NOT(I3 > I4))", "I1 <> I2 AND I3 > I4");
assertSimplifiesNumericTypes("NOT ((I1 = I2) OR (B1 AND B2) OR NOT (B3 OR B4))", "I1 <> I2 AND (NOT B1 OR NOT B2) AND (B3 OR B4)");
assertSimplifiesNumericTypes("NOT (I1 IS DISTINCT FROM I2)", "NOT (I1 IS DISTINCT FROM I2)");
/*
Restricted rewrite for types having NaN
*/
assertSimplifiesNumericTypes("NOT (D1 = D2)", "D1 <> D2");
assertSimplifiesNumericTypes("NOT (D1 <> D2)", "D1 = D2");
assertSimplifiesNumericTypes("NOT (R1 = R2)", "R1 <> R2");
assertSimplifiesNumericTypes("NOT (R1 <> R2)", "R1 = R2");
assertSimplifiesNumericTypes("NOT (D1 IS DISTINCT FROM D2)", "NOT (D1 IS DISTINCT FROM D2)");
assertSimplifiesNumericTypes("NOT (R1 IS DISTINCT FROM R2)", "NOT (R1 IS DISTINCT FROM R2)");
// DOUBLE: no negation pushdown for inequalities
assertSimplifiesNumericTypes("NOT (D1 > D2)", "NOT (D1 > D2)");
assertSimplifiesNumericTypes("NOT (D1 >= D2)", "NOT (D1 >= D2)");
assertSimplifiesNumericTypes("NOT (D1 < D2)", "NOT (D1 < D2)");
assertSimplifiesNumericTypes("NOT (D1 <= D2)", "NOT (D1 <= D2)");
// REAL: no negation pushdown for inequalities
assertSimplifiesNumericTypes("NOT (R1 > R2)", "NOT (R1 > R2)");
assertSimplifiesNumericTypes("NOT (R1 >= R2)", "NOT (R1 >= R2)");
assertSimplifiesNumericTypes("NOT (R1 < R2)", "NOT (R1 < R2)");
assertSimplifiesNumericTypes("NOT (R1 <= R2)", "NOT (R1 <= R2)");
// Multiple negations
assertSimplifiesNumericTypes("NOT NOT NOT (D1 <= D2)", "NOT (D1 <= D2)");
assertSimplifiesNumericTypes("NOT NOT NOT NOT (D1 <= D2)", "D1 <= D2");
assertSimplifiesNumericTypes("NOT NOT NOT (R1 > R2)", "NOT (R1 > R2)");
assertSimplifiesNumericTypes("NOT NOT NOT NOT (R1 > R2)", "R1 > R2");
// Nested comparisons
assertSimplifiesNumericTypes("NOT ((I1 = I2) OR (D1 > D2))", "I1 <> I2 AND NOT (D1 > D2)");
assertSimplifiesNumericTypes("NOT NOT NOT (NOT NOT (R1 < R2) OR NOT(I1 > I2))", "NOT (R1 < R2) AND I1 > I2");
assertSimplifiesNumericTypes("NOT ((D1 > D2) OR (B1 AND B2) OR NOT (B3 OR B4))", "NOT (D1 > D2) AND (NOT B1 OR NOT B2) AND (B3 OR B4)");
assertSimplifiesNumericTypes("NOT (((D1 > D2) AND (I1 < I2)) OR ((B1 AND B2) AND (R1 > R2)))", "(NOT (D1 > D2) OR I1 >= I2) AND ((NOT B1 OR NOT B2) OR NOT (R1 > R2))");
assertSimplifiesNumericTypes("IF (NOT (I1 < I2), D1, D2)", "IF (I1 >= I2, D1, D2)");
// Symbol of type having NaN on either side of comparison
assertSimplifiesNumericTypes("NOT (D1 > 1)", "NOT (D1 > 1)");
assertSimplifiesNumericTypes("NOT (1 > D2)", "NOT (1 > D2)");
assertSimplifiesNumericTypes("NOT (R1 > 1)", "NOT (R1 > 1)");
assertSimplifiesNumericTypes("NOT (1 > R2)", "NOT (1 > R2)");
}
private static void assertSimplifiesNumericTypes(String expression, String expected)
{
ParsingOptions parsingOptions = new ParsingOptions();
Expression actualExpression = rewriteIdentifiersToSymbolReferences(SQL_PARSER.createExpression(expression, parsingOptions));
Expression expectedExpression = rewriteIdentifiersToSymbolReferences(SQL_PARSER.createExpression(expected, parsingOptions));
Expression rewritten = rewrite(actualExpression, TEST_SESSION, new SymbolAllocator(numericAndBooleanSymbolTypeMapFor(actualExpression)), METADATA, LITERAL_ENCODER, new TypeAnalyzer(SQL_PARSER, METADATA));
assertEquals(
normalize(rewritten),
normalize(expectedExpression));
}
private static Map<Symbol, Type> numericAndBooleanSymbolTypeMapFor(Expression expression)
{
return SymbolsExtractor.extractUnique(expression).stream()
.collect(Collectors.toMap(
symbol -> symbol,
symbol -> {
switch (symbol.getName().charAt(0)) {
case 'I':
return INTEGER;
case 'D':
return DOUBLE;
case 'R':
return REAL;
case 'B':
return BOOLEAN;
default:
return BIGINT;
}
}));
}
private static Expression normalize(Expression expression)
{
return ExpressionTreeRewriter.rewriteWith(new NormalizeExpressionRewriter(), expression);
}
private static class NormalizeExpressionRewriter
extends ExpressionRewriter<Void>
{
@Override
public Expression rewriteLogicalBinaryExpression(LogicalBinaryExpression node, Void context, ExpressionTreeRewriter<Void> treeRewriter)
{
List<Expression> predicates = extractPredicates(node.getOperator(), node).stream()
.map(p -> treeRewriter.rewrite(p, context))
.sorted(Comparator.comparing(Expression::toString))
.collect(toList());
return binaryExpression(node.getOperator(), predicates);
}
}
}
| |
/*
* 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.polygene.index.elasticsearch;
import org.apache.polygene.api.association.Association;
import org.apache.polygene.api.association.ManyAssociation;
import org.apache.polygene.api.common.UseDefaults;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.api.entity.Aggregated;
import org.apache.polygene.api.entity.EntityBuilder;
import org.apache.polygene.api.identity.HasIdentity;
import org.apache.polygene.api.property.Property;
import org.apache.polygene.api.query.Query;
import org.apache.polygene.api.query.QueryBuilder;
import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.api.unitofwork.UnitOfWorkCompletionException;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.index.elasticsearch.assembly.ESClientIndexQueryAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationOverride;
import org.apache.polygene.test.AbstractPolygeneTest;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.TemporaryFolder;
import org.apache.polygene.test.TestName;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.apache.polygene.api.query.QueryExpressions.eq;
import static org.apache.polygene.api.query.QueryExpressions.ne;
import static org.apache.polygene.api.query.QueryExpressions.not;
import static org.apache.polygene.api.query.QueryExpressions.templateFor;
import static org.apache.polygene.test.util.Assume.assumeNoIbmJdk;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNull.notNullValue;
@ExtendWith( { TemporaryFolder.class, EmbeddedElasticSearchExtension.class, TestName.class } )
public class ElasticSearchTest
extends AbstractPolygeneTest
{
@BeforeAll
public static void beforeClass_IBMJDK()
{
assumeNoIbmJdk();
}
public static EmbeddedElasticSearchExtension ELASTIC_SEARCH;
public TestName testName;
private TemporaryFolder tmpDir;
public interface Post
extends HasIdentity
{
Property<String> title();
@UseDefaults
Property<String> body();
Property<Tagline> tagline();
Association<Author> author();
@Aggregated
@UseDefaults
ManyAssociation<Comment> comments();
}
public interface Page
extends HasIdentity
{
Property<String> title();
@UseDefaults
Property<String> body();
Property<Tagline> tagline();
Association<Author> author();
}
public interface Tagline
{
@UseDefaults
Property<String> tags();
}
public interface Author
extends HasIdentity
{
Property<String> nickname();
}
public interface Comment
extends HasIdentity
{
Property<String> content();
}
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
// Config module
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
// EntityStore
new EntityTestAssembler().assemble( module );
// Index/Query
new ESClientIndexQueryAssembler( ELASTIC_SEARCH.client() )
.withConfig( config, Visibility.layer )
.assemble( module );
ElasticSearchIndexingConfiguration esConfig = config.forMixin( ElasticSearchIndexingConfiguration.class ).declareDefaults();
esConfig.index().set( ELASTIC_SEARCH.indexName( ElasticSearchQueryTest.class.getName(), testName.getMethodName() ) );
esConfig.indexNonAggregatedAssociations().set( Boolean.TRUE );
// FileConfig
new FileConfigurationAssembler()
.withOverride( new FileConfigurationOverride().withConventionalRoot( tmpDir.getRoot() ) )
.assemble( module );
// Entities & Values
module.entities( Post.class, Page.class, Author.class, Comment.class );
module.values( Tagline.class );
}
@Test
public void test()
throws UnitOfWorkCompletionException
{
String title = "Foo Bar Bazar!";
UnitOfWork uow = unitOfWorkFactory.newUnitOfWork();
EntityBuilder<Author> authorBuilder = uow.newEntityBuilder( Author.class );
Author author = authorBuilder.instance();
author.nickname().set( "eskatos" );
author = authorBuilder.newInstance();
EntityBuilder<Comment> commentBuilder = uow.newEntityBuilder( Comment.class );
Comment comment1 = commentBuilder.instance();
comment1.content().set( "Comment One" );
comment1 = commentBuilder.newInstance();
commentBuilder = uow.newEntityBuilder( Comment.class );
Comment comment2 = commentBuilder.instance();
comment2.content().set( "Comment Two" );
comment2 = commentBuilder.newInstance();
EntityBuilder<Post> postBuilder = uow.newEntityBuilder( Post.class );
Post post = postBuilder.instance();
post.title().set( title );
post.author().set( author );
post.tagline().set( valueBuilderFactory.newValue( Tagline.class ) );
post.comments().add( comment1 );
post.comments().add( comment2 );
post = postBuilder.newInstance();
EntityBuilder<Page> pageBuilder = uow.newEntityBuilder( Page.class );
Page page = pageBuilder.instance();
page.title().set( title );
page.author().set( author );
page.tagline().set( valueBuilderFactory.newValue( Tagline.class ) );
page = pageBuilder.newInstance();
System.out.println( "########################################" );
System.out.println( "Post Identity: " + post.identity().get() );
System.out.println( "Page Identity: " + page.identity().get() );
System.out.println( "########################################" );
uow.complete();
uow = unitOfWorkFactory.newUnitOfWork();
QueryBuilder<Post> queryBuilder = queryBuilderFactory.newQueryBuilder( Post.class );
Query<Post> query = uow.newQuery( queryBuilder );
assertThat( query.count(), equalTo( 1L ) );
post = query.find();
assertThat( post, notNullValue() );
assertThat( post.title().get(), equalTo( title ) );
post = templateFor( Post.class );
queryBuilder = queryBuilderFactory.newQueryBuilder( Post.class ).where( eq( post.title(), title ) );
query = uow.newQuery( queryBuilder );
assertThat( query.count(), equalTo( 1L ) );
post = query.find();
assertThat( post, notNullValue() );
assertThat( post.title().get(), equalTo( title ) );
post = templateFor( Post.class );
queryBuilder = queryBuilderFactory.newQueryBuilder( Post.class )
.where( eq( post.title(), "Not available" ) );
query = uow.newQuery( queryBuilder );
assertThat( query.count(), equalTo( 0L ) );
post = templateFor( Post.class );
queryBuilder = queryBuilderFactory.newQueryBuilder( Post.class )
.where( ne( post.title(), "Not available" ) );
query = uow.newQuery( queryBuilder );
assertThat( query.count(), equalTo( 1L ) );
post = templateFor( Post.class );
queryBuilder = queryBuilderFactory.newQueryBuilder( Post.class )
.where( not( eq( post.title(), "Not available" ) ) );
query = uow.newQuery( queryBuilder );
post = query.find();
assertThat( post, notNullValue() );
assertThat( post.title().get(), equalTo( title ) );
post = templateFor( Post.class );
queryBuilder = queryBuilderFactory.newQueryBuilder( Post.class )
.where( eq( post.author().get().nickname(), "eskatos" ) );
query = uow.newQuery( queryBuilder );
assertThat( query.count(), equalTo( 1L ) );
post = query.find();
assertThat( post, notNullValue() );
assertThat( post.title().get(), equalTo( title ) );
uow.discard();
}
}
| |
/**
* 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 groovy.util;
import groovy.lang.Closure;
import groovy.test.GroovyAssert;
import junit.framework.TestCase;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
/**
* A JUnit 3 {@link junit.framework.TestCase} base class in Groovy.
*
* In case JUnit 4 is used, see {@link groovy.test.GroovyAssert}.
*
* @see groovy.test.GroovyAssert
*
* @author <a href="mailto:bob@werken.com">bob mcwhirter</a>
* @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
* @author Dierk Koenig (the notYetImplemented feature, changes to shouldFail)
* @author Andre Steingress
*/
public class GroovyTestCase extends TestCase {
protected static Logger log = Logger.getLogger(GroovyTestCase.class.getName());
private static final AtomicInteger scriptFileNameCounter = new AtomicInteger(0);
public static final String TEST_SCRIPT_NAME_PREFIX = "TestScript";
private boolean useAgileDoxNaming = false;
/**
* Overload the getName() method to make the test cases look more like AgileDox
* (thanks to Joe Walnes for this tip!)
*/
public String getName() {
if (useAgileDoxNaming) {
return super.getName().substring(4).replaceAll("([A-Z])", " $1").toLowerCase();
} else {
return super.getName();
}
}
public String getMethodName() {
return super.getName();
}
/**
* Asserts that the arrays are equivalent and contain the same values
*
* @param expected
* @param value
*/
protected void assertArrayEquals(Object[] expected, Object[] value) {
String message =
"expected array: " + InvokerHelper.toString(expected) + " value array: " + InvokerHelper.toString(value);
assertNotNull(message + ": expected should not be null", expected);
assertNotNull(message + ": value should not be null", value);
assertEquals(message, expected.length, value.length);
for (int i = 0, size = expected.length; i < size; i++) {
assertEquals("value[" + i + "] when " + message, expected[i], value[i]);
}
}
/**
* Asserts that the array of characters has a given length
*
* @param length expected length
* @param array the array
*/
protected void assertLength(int length, char[] array) {
assertEquals(length, array.length);
}
/**
* Asserts that the array of ints has a given length
*
* @param length expected length
* @param array the array
*/
protected void assertLength(int length, int[] array) {
assertEquals(length, array.length);
}
/**
* Asserts that the array of objects has a given length
*
* @param length expected length
* @param array the array
*/
protected void assertLength(int length, Object[] array) {
assertEquals(length, array.length);
}
/**
* Asserts that the array of characters contains a given char
*
* @param expected expected character to be found
* @param array the array
*/
protected void assertContains(char expected, char[] array) {
for (int i = 0; i < array.length; ++i) {
if (array[i] == expected) {
return;
}
}
StringBuilder message = new StringBuilder();
message.append(expected).append(" not in {");
for (int i = 0; i < array.length; ++i) {
message.append("'").append(array[i]).append("'");
if (i < (array.length - 1)) {
message.append(", ");
}
}
message.append(" }");
fail(message.toString());
}
/**
* Asserts that the array of ints contains a given int
*
* @param expected expected int
* @param array the array
*/
protected void assertContains(int expected, int[] array) {
for (int anInt : array) {
if (anInt == expected) {
return;
}
}
StringBuilder message = new StringBuilder();
message.append(expected).append(" not in {");
for (int i = 0; i < array.length; ++i) {
message.append("'").append(array[i]).append("'");
if (i < (array.length - 1)) {
message.append(", ");
}
}
message.append(" }");
fail(message.toString());
}
/**
* Asserts that the value of toString() on the given object matches the
* given text string
*
* @param value the object to be output to the console
* @param expected the expected String representation
*/
protected void assertToString(Object value, String expected) {
Object console = InvokerHelper.invokeMethod(value, "toString", null);
assertEquals("toString() on value: " + value, expected, console);
}
/**
* Asserts that the value of inspect() on the given object matches the
* given text string
*
* @param value the object to be output to the console
* @param expected the expected String representation
*/
protected void assertInspect(Object value, String expected) {
Object console = InvokerHelper.invokeMethod(value, "inspect", null);
assertEquals("inspect() on value: " + value, expected, console);
}
/**
* see {@link groovy.test.GroovyAssert#assertScript(String)}
*/
protected void assertScript(final String script) throws Exception {
GroovyAssert.assertScript(script);
}
// TODO should this be synchronised?
protected String getTestClassName() {
return TEST_SCRIPT_NAME_PREFIX + getMethodName() + (scriptFileNameCounter.getAndIncrement()) + ".groovy";
}
/**
* see {@link groovy.test.GroovyAssert#shouldFail(groovy.lang.Closure)}
*/
protected String shouldFail(Closure code) {
return GroovyAssert.shouldFail(code).getMessage();
}
/**
* see {@link groovy.test.GroovyAssert#shouldFail(Class, groovy.lang.Closure)}
*/
protected String shouldFail(Class clazz, Closure code) {
return GroovyAssert.shouldFail(clazz, code).getMessage();
}
/**
* see {@link groovy.test.GroovyAssert#shouldFailWithCause(Class, groovy.lang.Closure)}
*/
protected String shouldFailWithCause(Class clazz, Closure code) {
return GroovyAssert.shouldFailWithCause(clazz, code).getMessage();
}
/**
* see {@link groovy.test.GroovyAssert#shouldFail(Class, String)}
*/
protected String shouldFail(Class clazz, String script) {
return GroovyAssert.shouldFail(clazz, script).getMessage();
}
/**
* see {@link groovy.test.GroovyAssert#shouldFail(String)}
*/
protected String shouldFail(String script) {
return GroovyAssert.shouldFail(script).getMessage();
}
/**
* Returns a copy of a string in which all EOLs are \n.
*/
protected String fixEOLs(String value) {
return value.replaceAll("(\\r\\n?)|\n", "\n");
}
/**
* see {@link groovy.test.GroovyAssert#notYetImplemented(java.lang.Object)}
*/
public static boolean notYetImplemented(Object caller) {
return GroovyAssert.notYetImplemented(caller);
}
/**
* Convenience method for subclasses of GroovyTestCase, identical to
* <pre> GroovyTestCase.notYetImplemented(this); </pre>.
*
* @return <false> when not itself already in the call stack
* @see #notYetImplemented(java.lang.Object)
*/
public boolean notYetImplemented() {
return notYetImplemented(this);
}
public static void assertEquals(String message, Object expected, Object actual) {
if (expected == null && actual == null)
return;
if (expected != null && DefaultTypeTransformation.compareEqual(expected, actual))
return;
TestCase.assertEquals(message, expected, actual);
}
public static void assertEquals(Object expected, Object actual) {
assertEquals(null, expected, actual);
}
public static void assertEquals(String expected, String actual) {
assertEquals(null, expected, actual);
}
}
| |
/*
* #%L
* =====================================================
* _____ _ ____ _ _ _ _
* |_ _|_ __ _ _ ___| |_ / __ \| | | | ___ | | | |
* | | | '__| | | / __| __|/ / _` | |_| |/ __|| |_| |
* | | | | | |_| \__ \ |_| | (_| | _ |\__ \| _ |
* |_| |_| \__,_|___/\__|\ \__,_|_| |_||___/|_| |_|
* \____/
*
* =====================================================
*
* Hochschule Hannover
* (University of Applied Sciences and Arts, Hannover)
* Faculty IV, Dept. of Computer Science
* Ricklinger Stadtweg 118, 30459 Hannover, Germany
*
* Email: trust@f4-i.fh-hannover.de
* Website: http://trust.f4.hs-hannover.de/
*
* This file is part of visitmeta-visualization, version 0.6.0,
* implemented by the Trust@HsH research group at the Hochschule Hannover.
* %%
* Copyright (C) 2012 - 2016 Trust@HsH
* %%
* 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 de.hshannover.f4.trust.visitmeta.graphCalculator.jung;
import java.awt.Dimension;
import org.apache.commons.collections15.Transformer;
import org.apache.log4j.Logger;
import de.hshannover.f4.trust.ironcommon.properties.Properties;
import de.hshannover.f4.trust.visitmeta.Main;
import de.hshannover.f4.trust.visitmeta.util.VisualizationConfig;
import edu.uci.ics.jung.algorithms.layout.SpringLayout;
/**
* <p>A spring-layout.</p>
* <p>Uses the SpringLayout of JUNG2.</p>
* <p>
* CAUTION: This class needs a revision. Use LayoutForceDirected2D (LayoutType.FORCE_DIRECTED)
* until this is done.
* </p>
*/
public class LayoutSpring2D extends Layout2D{
// ///////////////////////////////////////////////////////////////////////////////////// MEMBERS
protected SpringLayout<Node2D, Edge2D> mLayout;
private Properties mConfig = Main.getConfig();
/**
* Defines how the layout gets the length of an edge.
*/
private final Transformer<Edge2D, Integer> mLengthFunction = new Transformer<Edge2D, Integer>(){
@Override
public Integer transform(Edge2D edge){
return edge.getLength();
}
};
/**
* <p>
* The tendency of an edge to change its length.<br>
* Specifies how much the grade of an edge influences its movement.
* </p>
* <p>
* Positive values < 1.0: Low-grade nodes rather tend to move then high-grade nodes.<br>
* Positive values > 1.0: High-grade nodes rather tend to move then low-grade nodes.<br>
* Negative values: Not provided.<br>
* Default-value: 0.7
* </p>
*/
private double mStretch;
/**
* <p>
* How strongly an edge tries to maintain its length.<br>
* High values: Make sure that the node maintains its length.
* </p>
* <p>
* 0.0: Disables this functionality.<br>
* Negative values: Not provided.<br>
* Default-value: 1.0/3.0
* </p>
*/
private double mForceMultiplier;
/**
* <p>
* Repulsion-radius.<br>
* Outside this radius, nodes do not repel each other.
* </p>
* <p>
* Negative values: not provided<br>
* Default-value: 100
* </p>
*/
private int mRepulsionRange;
private Logger LOGGER = Logger.getLogger(LayoutSpring2D.class);
// //////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS
public LayoutSpring2D(Graph2D graph){
super(graph, false);
mDimension = new Dimension(1000, 1000);
mStretch = mConfig.getDouble(VisualizationConfig.KEY_CALCULATION_JUNG_SPRING_STRETCH, VisualizationConfig.DEFAULT_VALUE_CALCULATION_JUNG__SPRING_STRETCH);
mRepulsionRange = mConfig.getInt(VisualizationConfig.KEY_CALCULATION_JUNG_SPRING_REPULSIONRANGE, VisualizationConfig.DEFAULT_VALUE_CALCULATION_JUNG_SPRING_REPULSIONRANGE);
mForceMultiplier = mConfig.getDouble(VisualizationConfig.KEY_CALCULATION_JUNG_SPRING_FORCEMULTIPLIER, VisualizationConfig.DEFAULT_VALUE_CALCULATION_JUNG_SPRING_FORCEMULTIPLIER);
mLayout = new SpringLayout<>(mGraph.getGraph(), mLengthFunction);
mLayout.setStretch(mStretch);
mLayout.setRepulsionRange(mRepulsionRange);
mLayout.setForceMultiplier(mForceMultiplier);
mLayout.setSize(mDimension);
}
public LayoutSpring2D(Graph2D graph, boolean useIndividualEdgeLength, int dimensionX,
int dimensionY, double stretch, double forceMultiplier, int repulsionRange){
super(graph, useIndividualEdgeLength);
mDimension = new Dimension(dimensionX, dimensionY);
mStretch = stretch;
mForceMultiplier = forceMultiplier;
mRepulsionRange = repulsionRange;
mLayout = new SpringLayout<>(mGraph.getGraph(), mLengthFunction);
mLayout.setStretch(mStretch);
mLayout.setRepulsionRange(mRepulsionRange);
mLayout.setForceMultiplier(mForceMultiplier);
mLayout.setSize(mDimension);
}
// ////////////////////////////////////////////////////////////////////////////////////// PUBLIC
public void update(){
LOGGER.trace("Method update() called.");
mLayout.setStretch(mStretch);
mLayout.setRepulsionRange(mRepulsionRange);
mLayout.setForceMultiplier(mForceMultiplier);
mLayout.setSize(mDimension);
}
public void setStretch(double stretch){
LOGGER.trace("Method setStretch(" + stretch + ") called.");
mStretch = stretch;
mLayout.setStretch(mStretch);
}
public double getStretch(){
LOGGER.trace("Method getStretch() called.");
return mStretch;
}
public void setRepulsionRange(int repulsionRange){
LOGGER.trace("Method setRepulsionRange(" + repulsionRange + ") called.");
mRepulsionRange = repulsionRange;
mLayout.setRepulsionRange(mRepulsionRange);
}
public int getRepulsionRange(){
LOGGER.trace("Method getRepulsionRange() called.");
return mRepulsionRange;
}
public void setForceMultiplier(double forceMultiplier){
LOGGER.trace("Method setForceMultiplier(" + forceMultiplier + ") called.");
mForceMultiplier = forceMultiplier;
mLayout.setForceMultiplier(mForceMultiplier);
}
public double getForceMultiplier(){
LOGGER.trace("Method getForceMultiplier() called.");
return mForceMultiplier;
}
// /////////////////////////////////////////////////////////////////////////////////////// SUPER
/**
* Adjust (align) the graph.
* @param iterations Number of iterations the layout does to adjust the layout (nodes of the
* graph).
*/
@Override
public void adjust(int iterations){
LOGGER.trace("Method adjust(" + iterations + ") called.");
for(int i = 0; i < iterations; i++){
mLayout.step();
}
}
/**
* Calculate the uniform length for all edges.
*/
@Override
public void calculateUniformEdgeLength(){
LOGGER.trace("Method getUniformEdgeLength() called.");
double nodesPerLine = Math.sqrt(mGraph.getAllNodesCount());
mUniformEdgeLength = (int)((getDimensionX()/2.0)/nodesPerLine);
}
/**
* Reset the graph after adding/removing elements.
*/
@Override
public void reset(){
LOGGER.trace("Method reset() called.");
mLayout.reset();
}
@Override
public void setNodePosition(Node2D node2D, double x, double y){
LOGGER.trace("Method setNodePosition(" + node2D + ", " + x + ", " + y + ") called.");
mLayout.setLocation(node2D, x, y);
}
@Override
public double getNodePositionX(Node2D node2D){
LOGGER.trace("Method getNodePositionX("+node2D+") called.");
return mLayout.getX(node2D);
}
@Override
public double getNodePositionY(Node2D node2D){
LOGGER.trace("Method getNodePositionY("+node2D+") called.");
return mLayout.getY(node2D);
}
@Override
public void lockNode(Node2D node2D){
LOGGER.trace("Method lockNode("+node2D+") called.");
mLayout.lock(node2D, true);
}
@Override
public void unlockNode(Node2D node2D){
LOGGER.trace("Method unlockNode("+node2D+") called.");
mLayout.lock(node2D, false);
}
@Override
public void lockAllNodes(){
LOGGER.trace("Method lockAllNodes() called.");
mLayout.lock(true);
}
@Override
public void unlockAllNodes(){
LOGGER.trace("Method unlockAllNodes() called.");
mLayout.lock(false);
}
@Override
public void setMaxIterations(int maxIterations){
// Not necessary for Spring-Layout, it never stops autonomously.
}
@Override
public int getMaxIterations(){
// Not necessary for Spring-Layout, it never stops autonomously.
return 0;
}
// ///////////////////////////////////////////////////////////////////////////////////// PRIVATE
/**
* Determines the length of the edge with the maximum length.
*
* @return The length of the edge with the maximum length.
*/
@SuppressWarnings("unused")
private int calculateMaxEdgeLength(){
LOGGER.trace("Method calculateMaxEdgeLength() called.");
int maxEdgeLength = 0;
int curLength;
//MetadataCollocation expandedEdgeType = mGraph.getMetadataCollocationLink();
for(ExpandedLink2D ee : mGraph.getExpandedLinks2D()){
curLength = ee.getTotalLength();
if(curLength > maxEdgeLength){
maxEdgeLength = curLength;
}
}
return maxEdgeLength;
}
}
| |
/*
* 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.geode.cache.query.internal;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.apache.logging.log4j.Logger;
import org.apache.geode.cache.query.FunctionDomainException;
import org.apache.geode.cache.query.NameResolutionException;
import org.apache.geode.cache.query.QueryInvalidException;
import org.apache.geode.cache.query.QueryInvocationTargetException;
import org.apache.geode.cache.query.TypeMismatchException;
import org.apache.geode.cache.query.internal.parse.GemFireAST;
import org.apache.geode.cache.query.internal.parse.OQLLexer;
import org.apache.geode.cache.query.internal.parse.OQLLexerTokenTypes;
import org.apache.geode.cache.query.internal.parse.OQLParser;
import org.apache.geode.cache.query.internal.types.CollectionTypeImpl;
import org.apache.geode.cache.query.internal.types.MapTypeImpl;
import org.apache.geode.cache.query.internal.types.ObjectTypeImpl;
import org.apache.geode.cache.query.internal.types.TypeUtils;
import org.apache.geode.cache.query.types.CollectionType;
import org.apache.geode.cache.query.types.MapType;
import org.apache.geode.cache.query.types.ObjectType;
import org.apache.geode.internal.Assert;
import org.apache.geode.internal.InternalDataSerializer;
import org.apache.geode.internal.logging.LogService;
/**
* Class Description
*
* @version $Revision: 1.1 $s
*/
public class QCompiler implements OQLLexerTokenTypes {
private static final Logger logger = LogService.getLogger();
private Stack stack = new Stack();
private Map imports = new HashMap();
private final boolean isForIndexCompilation;
private boolean traceOn;
public QCompiler() {
this.isForIndexCompilation = false;
}
public QCompiler(boolean isForIndexCompilation) {
this.isForIndexCompilation = isForIndexCompilation;
}
/*
* compile the string into a Query (returns the root CompiledValue)
*/
public CompiledValue compileQuery(String oqlSource) {
try {
OQLLexer lexer = new OQLLexer(new StringReader(oqlSource));
OQLParser parser = new OQLParser(lexer);
// by default use Unsupported AST class, overridden for supported
// operators in the grammer proper
parser.setASTNodeClass("org.apache.geode.cache.query.internal.parse.ASTUnsupported");
parser.queryProgram();
GemFireAST n = (GemFireAST) parser.getAST();
n.compile(this);
} catch (Exception ex) { // This is to make sure that we are wrapping any antlr exception with
// GemFire Exception.
throw new QueryInvalidException(
String.format("Syntax error in query: %s", ex.getMessage()),
ex);
}
Assert.assertTrue(stackSize() == 1, "stack size = " + stackSize());
return (CompiledValue) pop();
}
/** Returns List<CompiledIteratorDef> */
public List compileFromClause(String fromClause) {
try {
OQLLexer lexer = new OQLLexer(new StringReader(fromClause));
OQLParser parser = new OQLParser(lexer);
// by default use Unsupported AST class, overridden for supported
// operators in the grammer proper
parser.setASTNodeClass("org.apache.geode.cache.query.internal.parse.ASTUnsupported");
parser.loneFromClause();
GemFireAST n = (GemFireAST) parser.getAST();
n.compile(this);
} catch (Exception ex) { // This is to make sure that we are wrapping any antlr exception with
// GemFire Exception.
throw new QueryInvalidException(
String.format("Syntax error in query: %s", ex.getMessage()),
ex);
}
Assert.assertTrue(stackSize() == 1, "stack size = " + stackSize());
return (List) pop();
}
/** Returns List<CompiledIteratorDef> or null if projectionAttrs is '*' */
public List compileProjectionAttributes(String projectionAttributes) {
try {
OQLLexer lexer = new OQLLexer(new StringReader(projectionAttributes));
OQLParser parser = new OQLParser(lexer);
// by default use Unsupported AST class, overridden for supported
// operators in the grammer proper
parser.setASTNodeClass("org.apache.geode.cache.query.internal.parse.ASTUnsupported");
parser.loneProjectionAttributes();
GemFireAST n = (GemFireAST) parser.getAST();
// don't compile TOK_STAR
if (n.getType() == TOK_STAR) {
return null;
}
n.compile(this);
} catch (Exception ex) { // This is to make sure that we are wrapping any antlr exception with
// GemFire Exception.
throw new QueryInvalidException(
String.format("Syntax error in query: %s", ex.getMessage()),
ex);
}
Assert.assertTrue(stackSize() == 1, "stack size = " + stackSize() + ";stack=" + this.stack);
return (List) pop();
}
/**
* Yogesh: compiles order by clause and push into the stack
*
*/
public void compileOrederByClause(int numOfChildren) {
List list = new ArrayList();
for (int i = 0; i < numOfChildren; i++) {
CompiledSortCriterion csc = (CompiledSortCriterion) this.stack.pop();
list.add(0, csc);
}
push(list);
}
public void compileGroupByClause(int numOfChildren) {
List list = new ArrayList();
for (int i = 0; i < numOfChildren; i++) {
Object csc = this.stack.pop();
list.add(0, csc);
}
push(list);
}
/**
* Yogesh: compiles sort criteria present in order by clause and push into the stack
*
*/
public void compileSortCriteria(String sortCriterion) {
CompiledValue obj = (CompiledValue) this.stack.pop();
boolean criterion = false;
if (sortCriterion.equals("desc"))
criterion = true;
CompiledSortCriterion csc = new CompiledSortCriterion(criterion, obj);
push(csc);
}
public void compileLimit(String limitNum) {
push(Integer.valueOf(limitNum));
}
/**
* Processes import statements only. This compiler instance remembers the imports and can be used
* to compile other strings with this context info
*/
public void compileImports(String imports) {
try {
OQLLexer lexer = new OQLLexer(new StringReader(imports));
OQLParser parser = new OQLParser(lexer);
// by default use Unsupported AST class, overridden for supported
// operators in the grammer proper
parser.setASTNodeClass("org.apache.geode.cache.query.internal.parse.ASTUnsupported");
parser.loneImports();
GemFireAST n = (GemFireAST) parser.getAST();
n.compile(this);
} catch (Exception ex) { // This is to make sure that we are wrapping any antlr exception with
// GemFire Exception.
throw new QueryInvalidException(
String.format("Syntax error in query: %s", ex.getMessage()),
ex);
}
Assert.assertTrue(stackSize() == 0, "stack size = " + stackSize() + ";stack=" + this.stack);
}
public void select(Map<Integer, Object> queryComponents) {
CompiledValue limit = null;
Object limitObject = queryComponents.remove(OQLLexerTokenTypes.LIMIT);
if (limitObject instanceof Integer) {
limit = new CompiledLiteral(limitObject);
} else {
limit = (CompiledBindArgument) limitObject;
}
List<CompiledSortCriterion> orderByAttrs =
(List<CompiledSortCriterion>) queryComponents.remove(OQLLexerTokenTypes.LITERAL_order);
List iterators = (List) queryComponents.remove(OQLLexerTokenTypes.LITERAL_from);
List projAttrs = (List) queryComponents.remove(OQLLexerTokenTypes.PROJECTION_ATTRS);
if (projAttrs == null) {
// remove any * or all attribute
queryComponents.remove(OQLLexerTokenTypes.TOK_STAR);
queryComponents.remove(OQLLexerTokenTypes.LITERAL_all);
}
// "COUNT" or null
/*
* String aggrExpr = (String) queryComponents .remove(OQLLexerTokenTypes.LITERAL_count);
*/
// "DISTINCT" or null
String distinct = (String) queryComponents.remove(OQLLexerTokenTypes.LITERAL_distinct);
List<String> hints = null;
Object hintObject = queryComponents.remove(OQLLexerTokenTypes.LITERAL_hint);
if (hintObject != null) {
hints = (List<String>) hintObject;
}
List<CompiledValue> groupByClause =
(List<CompiledValue>) queryComponents.remove(OQLLexerTokenTypes.LITERAL_group);
// whatever remains , treat it as where
// whereClause
CompiledValue where = null;
if (queryComponents.size() == 1) {
where = (CompiledValue) queryComponents.values().iterator().next();
} else if (queryComponents.size() > 1) {
throw new QueryInvalidException("Unexpected/unsupported query clauses found");
}
LinkedHashMap<Integer, CompiledAggregateFunction> aggMap =
identifyAggregateExpressions(projAttrs);
boolean isCountOnly = checkForCountOnly(aggMap, projAttrs, groupByClause);
if (isCountOnly) {
projAttrs = null;
}
CompiledSelect select = createSelect(distinct != null, isCountOnly, where, iterators, projAttrs,
orderByAttrs, limit, hints, groupByClause, aggMap);
push(select);
}
private boolean checkForCountOnly(Map<Integer, CompiledAggregateFunction> aggregateMap,
List projAttribs, List<CompiledValue> groupBy) {
if (aggregateMap != null && aggregateMap.size() == 1 && projAttribs.size() == 1
&& groupBy == null) {
for (Map.Entry<Integer, CompiledAggregateFunction> entry : aggregateMap.entrySet()) {
CompiledAggregateFunction caf = entry.getValue();
if (caf.getFunctionType() == OQLLexerTokenTypes.COUNT && caf.getParameter() == null) {
return true;
}
}
}
return false;
}
private CompiledSelect createSelect(boolean isDistinct, boolean isCountOnly, CompiledValue where,
List iterators, List projAttrs, List<CompiledSortCriterion> orderByAttrs, CompiledValue limit,
List<String> hints, List<CompiledValue> groupByClause,
LinkedHashMap<Integer, CompiledAggregateFunction> aggMap) {
if (isCountOnly || (groupByClause == null && aggMap == null)
|| (aggMap == null && orderByAttrs == null)) {
return new CompiledSelect(isDistinct, isCountOnly, where, iterators, projAttrs, orderByAttrs,
limit, hints, groupByClause);
} else {
return new CompiledGroupBySelect(isDistinct, isCountOnly, where, iterators, projAttrs,
orderByAttrs, limit, hints, groupByClause, aggMap);
}
}
private LinkedHashMap<Integer, CompiledAggregateFunction> identifyAggregateExpressions(
List projAttribs) {
if (projAttribs != null) {
LinkedHashMap<Integer, CompiledAggregateFunction> mapping =
new LinkedHashMap<Integer, CompiledAggregateFunction>();
int index = 0;
for (Object o : projAttribs) {
CompiledValue proj = (CompiledValue) ((Object[]) o)[1];
if (proj.getType() == OQLLexerTokenTypes.AGG_FUNC) {
mapping.put(index, (CompiledAggregateFunction) proj);
}
++index;
}
return mapping.size() == 0 ? null : mapping;
} else {
return null;
}
}
public void projection() {
// find an id or null on the stack, then an expr CompiledValue
// push an Object[2] on the stack. First element is id, second is CompiledValue
CompiledID id = (CompiledID) pop();
CompiledValue expr = (CompiledValue) pop();
push(new Object[] {id == null ? null : id.getId(), expr});
}
public void aggregateFunction(CompiledValue expr, int aggFuncType, boolean distinctOnly) {
push(new CompiledAggregateFunction(expr, aggFuncType, distinctOnly));
}
public void iteratorDef() {
// find type id and colln on the stack
ObjectType type = assembleType(); // can be null
CompiledID id = (CompiledID) TypeUtils.checkCast(pop(), CompiledID.class); // can be null
CompiledValue colln = (CompiledValue) TypeUtils.checkCast(pop(), CompiledValue.class);
if (type == null) {
type = TypeUtils.OBJECT_TYPE;
}
push(new CompiledIteratorDef(id == null ? null : id.getId(), type, colln));
}
public void undefinedExpr(boolean is_defined) {
CompiledValue value = (CompiledValue) pop();
push(new CompiledUndefined(value, is_defined));
}
public void function(int function, int numOfChildren) {
CompiledValue[] cvArr = new CompiledValue[numOfChildren];
for (int i = numOfChildren - 1; i >= 0; i--) {
cvArr[i] = (CompiledValue) pop();
}
push(new CompiledFunction(cvArr, function));
}
public void inExpr() {
CompiledValue collnExpr = (CompiledValue) TypeUtils.checkCast(pop(), CompiledValue.class);
CompiledValue elm = (CompiledValue) TypeUtils.checkCast(pop(), CompiledValue.class);
push(new CompiledIn(elm, collnExpr));
}
public void constructObject(Class clazz) {
// find argList on stack
// only support SET for now
Assert.assertTrue(clazz == ResultsSet.class);
List argList = (List) TypeUtils.checkCast(pop(), List.class);
push(new CompiledConstruction(clazz, argList));
}
public void pushId(String id) {
push(new CompiledID(id));
}
public void pushRegion(String regionPath) {
push(new CompiledRegion(regionPath));
}
public void appendPathComponent(String id) {
CompiledValue rcvr = (CompiledValue) pop();
push(new CompiledPath(rcvr, id));
}
public void pushBindArgument(int i) {
push(new CompiledBindArgument(i));
}
public void pushLiteral(Object obj) {
push(new CompiledLiteral(obj));
}
public void pushNull() // used as a placeholder for a missing clause
{
push(null);
}
public void combine(int num) {
List list = new ArrayList();
for (int i = 0; i < num; i++) {
list.add(0, pop());
}
push(list);
}
public void methodInvocation() {
// find on stack:
// argList, methodName, receiver (which may be null if receiver is implicit)
List argList = (List) TypeUtils.checkCast(pop(), List.class);
CompiledID methodName = (CompiledID) TypeUtils.checkCast(pop(), CompiledID.class);
CompiledValue rcvr = (CompiledValue) TypeUtils.checkCast(pop(), CompiledValue.class);
push(new CompiledOperation(rcvr, methodName.getId(), argList));
}
public void indexOp() {
// find the List of index expressions and the receiver on the stack
Object indexParams = pop();
final CompiledValue rcvr = (CompiledValue) TypeUtils.checkCast(pop(), CompiledValue.class);
CompiledValue indexExpr = CompiledValue.MAP_INDEX_ALL_KEYS;
if (indexParams != null) {
final List indexList = (List) TypeUtils.checkCast(indexParams, List.class);
if (!isForIndexCompilation && indexList.size() != 1) {
throw new UnsupportedOperationException(
"Only one index expression supported");
}
if (indexList.size() == 1) {
indexExpr = (CompiledValue) TypeUtils.checkCast(indexList.get(0), CompiledValue.class);
if (indexExpr.getType() == TOK_COLON) {
throw new UnsupportedOperationException(
"Ranges not supported in index operators");
}
indexExpr = (CompiledValue) TypeUtils.checkCast(indexList.get(0), CompiledValue.class);
push(new CompiledIndexOperation(rcvr, indexExpr));
} else {
assert this.isForIndexCompilation;
MapIndexable mi = new MapIndexOperation(rcvr, indexList);
push(mi);
}
} else {
if (!this.isForIndexCompilation) {
throw new QueryInvalidException(String.format("Syntax error in query: %s",
"* use incorrect"));
}
push(new CompiledIndexOperation(rcvr, indexExpr));
}
}
/**
* Creates appropriate CompiledValue for the like predicate based on the sargability of the String
* or otherwise. It also works on the last character to see if the sargable like predicate results
* in a CompiledJunction or a Comparison. Currently we are supporting only the '%' terminated
* "like" predicate.
*
* @param var The CompiledValue representing the variable
* @param patternOrBindParam The CompiledLiteral reprsenting the pattern of the like predicate
* @return CompiledValue representing the "like" predicate
*
*/
CompiledValue createCompiledValueForLikePredicate(CompiledValue var,
CompiledValue patternOrBindParam) {
if (!(patternOrBindParam.getType() == CompiledBindArgument.QUERY_PARAM)) {
CompiledLiteral pattern = (CompiledLiteral) patternOrBindParam;
if (pattern._obj == null) {
throw new UnsupportedOperationException(
"Null values are not supported with LIKE predicate.");
}
}
// From 6.6 Like is enhanced to support special character (% and _) at any
// position of the string.
return new CompiledLike(var, patternOrBindParam);
}
public void like() {
CompiledValue v2 = (CompiledValue) pop();
CompiledValue v1 = (CompiledValue) pop();
CompiledValue cv = createCompiledValueForLikePredicate(v1, v2);
push(cv);
}
public void compare(int opKind) {
CompiledValue v2 = (CompiledValue) pop();
CompiledValue v1 = (CompiledValue) pop();
push(new CompiledComparison(v1, v2, opKind));
}
public void mod(int opKind) {
CompiledValue v2 = (CompiledValue) pop();
CompiledValue v1 = (CompiledValue) pop();
push(new CompiledMod(v1, v2, opKind));
}
public void arithmetic(int opKind) {
switch (opKind) {
case TOK_PLUS:
addition(opKind);
break;
case TOK_MINUS:
subtraction(opKind);
break;
case TOK_SLASH:
division(opKind);
break;
case TOK_STAR:
multiplication(opKind);
break;
case LITERAL_mod:
mod(opKind);
break;
case TOK_PERCENTAGE:
mod(opKind);
break;
}
}
private void addition(int opKind) {
CompiledValue v2 = (CompiledValue) pop();
CompiledValue v1 = (CompiledValue) pop();
push(new CompiledAddition(v1, v2, opKind));
}
private void subtraction(int opKind) {
CompiledValue v2 = (CompiledValue) pop();
CompiledValue v1 = (CompiledValue) pop();
push(new CompiledSubtraction(v1, v2, opKind));
}
private void division(int opKind) {
CompiledValue v2 = (CompiledValue) pop();
CompiledValue v1 = (CompiledValue) pop();
push(new CompiledDivision(v1, v2, opKind));
}
private void multiplication(int opKind) {
CompiledValue v2 = (CompiledValue) pop();
CompiledValue v1 = (CompiledValue) pop();
push(new CompiledMultiplication(v1, v2, opKind));
}
public void or(int numTerms) {
junction(numTerms, LITERAL_or);
}
public void and(int numTerms) {
junction(numTerms, LITERAL_and);
}
private void junction(int numTerms, int operator) {
/*
* if any of the operands are junctions with same operator as this one then flatten
*/
List operands = new ArrayList(numTerms);
for (int i = 0; i < numTerms; i++) {
CompiledValue operand = (CompiledValue) pop();
// flatten if we can
if (operand instanceof CompiledJunction
&& ((CompiledJunction) operand).getOperator() == operator) {
CompiledJunction junction = (CompiledJunction) operand;
List jOperands = junction.getOperands();
for (int j = 0; j < jOperands.size(); j++)
operands.add(jOperands.get(j));
} else
operands.add(operand);
}
push(new CompiledJunction(
(CompiledValue[]) operands.toArray(new CompiledValue[operands.size()]), operator));
}
public void not() {
Object obj = this.stack.peek();
Assert.assertTrue(obj instanceof CompiledValue);
if (obj instanceof Negatable)
((Negatable) obj).negate();
else
push(new CompiledNegation((CompiledValue) pop()));
}
public void unaryMinus() {
Object obj = this.stack.peek();
Assert.assertTrue(obj instanceof CompiledValue);
push(new CompiledUnaryMinus((CompiledValue) pop()));
}
public void typecast() {
// pop expr and type, apply type, then push result
AbstractCompiledValue cmpVal =
(AbstractCompiledValue) TypeUtils.checkCast(pop(), AbstractCompiledValue.class);
ObjectType objType = assembleType();
cmpVal.setTypecast(objType);
push(cmpVal);
}
// returns null if null is on the stack
public ObjectType assembleType() {
ObjectType objType = (ObjectType) TypeUtils.checkCast(pop(), ObjectType.class);
if (objType instanceof CollectionType) {
// pop the elementType
ObjectType elementType = assembleType();
if (objType instanceof MapType) {
// pop the key type
ObjectType keyType = assembleType();
return new MapTypeImpl(objType.resolveClass(), keyType, elementType);
}
return new CollectionTypeImpl(objType.resolveClass(), elementType);
}
return objType;
}
public void traceRequest() {
this.traceOn = true;
}
public boolean isTraceRequested() {
return traceOn;
}
public void setHint(int numOfChildren) {
ArrayList list = new ArrayList();
for (int i = 0; i < numOfChildren; i++) {
String hi = (String) this.stack.pop();
list.add(0, hi);
}
push(list);
// setHints(list);
}
public void setHintIdentifier(String text) {
push(text);
}
public void importName(String qualifiedName, String asName) {
if (asName == null) {
// if no AS, then use the short name from qualifiedName
// as the AS
int idx = qualifiedName.lastIndexOf('.');
if (idx >= 0) {
asName = qualifiedName.substring(idx + 1);
} else {
asName = qualifiedName;
}
}
if (logger.isTraceEnabled()) {
logger.trace("QCompiler.importName: {},{}", asName, qualifiedName);
}
this.imports.put(asName, qualifiedName);
}
public Object pop() {
Object obj = this.stack.pop();
if (logger.isTraceEnabled()) {
logger.trace("QCompiler.pop: {}", obj);
}
return obj;
}
public void push(Object obj) {
if (logger.isTraceEnabled()) {
logger.trace("QCompiler.push: {}", obj);
}
this.stack.push(obj);
}
public int stackSize() {
return this.stack.size();
}
public ObjectType resolveType(String typeName) {
if (typeName == null) {
if (logger.isTraceEnabled()) {
logger.trace("QCompiler.resolveType= {}", Object.class.getName());
}
return TypeUtils.OBJECT_TYPE;
}
// resolve with imports
String as = null;
if (this.imports != null) {
as = (String) this.imports.get(typeName);
}
if (as != null)
typeName = as;
Class resultClass;
try {
resultClass = InternalDataSerializer.getCachedClass(typeName);
} catch (ClassNotFoundException e) {
throw new QueryInvalidException(
String.format("Type not found: %s", typeName), e);
}
if (logger.isTraceEnabled()) {
logger.trace("QCompiler.resolveType= {}", resultClass.getName());
}
return new ObjectTypeImpl(resultClass);
}
private static class MapIndexOperation extends AbstractCompiledValue implements MapIndexable {
private final CompiledValue rcvr;
private final List<CompiledValue> indexList;
public MapIndexOperation(CompiledValue rcvr, List<CompiledValue> indexList) {
this.rcvr = rcvr;
this.indexList = indexList;
}
@Override
public CompiledValue getReceiverSansIndexArgs() {
return rcvr;
}
@Override
public CompiledValue getMapLookupKey() {
throw new UnsupportedOperationException("Function invocation not expected");
}
@Override
public List<CompiledValue> getIndexingKeys() {
return (List<CompiledValue>) indexList;
}
@Override
public Object evaluate(ExecutionContext context) throws FunctionDomainException,
TypeMismatchException, NameResolutionException, QueryInvocationTargetException {
throw new UnsupportedOperationException("Method execution not expected");
}
@Override
public int getType() {
throw new UnsupportedOperationException("Method execution not expected");
}
}
}
| |
/**
* Copyright (c) 2011 Source Auditor Inc.
* 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.spdx.rdfparser;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.StringWriter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.spdx.rdfparser.SPDXAnalysis.SPDXPackage;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
/**
* @author Source Auditor
*
*/
public class TestSPDXDocument {
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}
/**
* Test method for {@link org.spdx.rdfparser.SPDXAnalysis#SPDXAnalysis(com.hp.hpl.jena.rdf.model.Model)}.
*/
@Test
public void testSPDXAnalysis() {
fail("Not yet implemented");
}
/**
* Test method for {@link org.spdx.rdfparser.SPDXAnalysis#getSpdxVersion()}.
*/
@Test
public void testGetSpdxVersion() {
fail("Not yet implemented");
}
/**
* Test method for {@link org.spdx.rdfparser.SPDXAnalysis#setSpdxVersion(java.lang.String)}.
* @throws InvalidSPDXAnalysisException
* @throws IOException
*/
@Test
public void testSetSpdxVersion() throws InvalidSPDXAnalysisException, IOException {
Model model = ModelFactory.createDefaultModel();
SPDXAnalysis doc = new SPDXAnalysis(model);
String testUri = "https://olex.openlogic.com/package_versions/download/4832?path=openlogic/zlib/1.2.3/zlib-1.2.3-all-src.zip&package_version_id=1082";
StringWriter writer = new StringWriter();
doc.getModel().write(writer);
String beforeCreate = writer.toString();
writer.close();
doc.createSpdxAnalysis(testUri);
String noVersion = doc.getSpdxVersion();
assertNull(noVersion);
String testVersion = "0.7.2";
doc.setSpdxVersion(testVersion);
String resultVersion = doc.getSpdxVersion();
assertEquals(testVersion, resultVersion);
writer = new StringWriter();
doc.getModel().write(writer);
String afterCreate = writer.toString();
String testVersion2 = "1.3.3";
doc.setSpdxVersion(testVersion2);
String resultVersion2 = doc.getSpdxVersion();
assertEquals(testVersion2, resultVersion2);
}
/**
* Test method for {@link org.spdx.rdfparser.SPDXAnalysis#getCreators()}.
*/
@Test
public void testGetCreatedBy() {
fail("Not yet implemented");
}
/**
* Test method for {@link org.spdx.rdfparser.SPDXAnalysis#setCreator(java.lang.String[])}.
* @throws InvalidSPDXAnalysisException
* @throws IOException
*/
@Test
public void testSetCreatedBy() throws InvalidSPDXAnalysisException, IOException {
Model model = ModelFactory.createDefaultModel();
SPDXAnalysis doc = new SPDXAnalysis(model);
String testUri = "https://olex.openlogic.com/package_versions/download/4832?path=openlogic/zlib/1.2.3/zlib-1.2.3-all-src.zip&package_version_id=1082";
StringWriter writer = new StringWriter();
doc.getModel().write(writer);
String beforeCreate = writer.toString();
writer.close();
doc.createSpdxAnalysis(testUri);
String[] noCreatedBy = doc.getCreators();
assertEquals(0, noCreatedBy.length);
String[] testCreatedBy = new String[] {"Created By Me"};
doc.setCreators(testCreatedBy);
String[] resultCreatedBy = doc.getCreators();
compareArrays(testCreatedBy, resultCreatedBy);
writer = new StringWriter();
doc.getModel().write(writer);
String afterCreate = writer.toString();
String[] testCreatedBy2 = new String[] {
"second created",
"another",
"and another"};
doc.setCreators(testCreatedBy2);
String[] resultCreatedBy2 = doc.getCreators();
compareArrays(testCreatedBy2, resultCreatedBy2);
}
@Test
public void testCreatorComment() throws InvalidSPDXAnalysisException, IOException {
Model model = ModelFactory.createDefaultModel();
SPDXAnalysis doc = new SPDXAnalysis(model);
String testUri = "https://olex.openlogic.com/package_versions/download/4832?path=openlogic/zlib/1.2.3/zlib-1.2.3-all-src.zip&package_version_id=1082";
StringWriter writer = new StringWriter();
doc.getModel().write(writer);
String beforeCreate = writer.toString();
writer.close();
doc.createSpdxAnalysis(testUri);
String creatorComment = doc.getCreatorComment();
if (creatorComment != null) {
if (!creatorComment.isEmpty()) {
fail("Comment should be empty");
}
}
String comment = "This is a comment";
doc.setCreatorComment(comment);
String result = doc.getCreatorComment();
assertEquals(comment, result);
}
private void compareArrays(Object[] a1,
Object[] a2) {
assertEquals(a1.length, a2.length);
for (int i = 0; i < a1.length; i++) {
boolean found = false;
for (int j = 0; j < a2.length; j++) {
if (a1[i].equals(a2[j])) {
found = true;
break;
}
}
assertTrue(found);
}
}
/**
* Test method for {@link org.spdx.rdfparser.SPDXAnalysis#getReviewers()}.
*/
@Test
public void testGetReviewers() {
fail("Not yet implemented");
}
/**
* Test method for {@link org.spdx.rdfparser.SPDXAnalysis#setReviewers(java.lang.String[])}.
* @throws InvalidSPDXAnalysisException
* @throws IOException
*/
@Test
public void testSetReviewers() throws InvalidSPDXAnalysisException, IOException {
Model model = ModelFactory.createDefaultModel();
SPDXAnalysis doc = new SPDXAnalysis(model);
String testUri = "https://olex.openlogic.com/package_versions/download/4832?path=openlogic/zlib/1.2.3/zlib-1.2.3-all-src.zip&package_version_id=1082";
StringWriter writer = new StringWriter();
doc.getModel().write(writer);
String beforeCreate = writer.toString();
writer.close();
doc.createSpdxAnalysis(testUri);
SPDXReview[] noReviewedBy = doc.getReviewers();
assertEquals(0, noReviewedBy.length);
SPDXReview[] testreviewedBy = new SPDXReview[] {new SPDXReview("reviewed By Me", "date1", "comment1")};
doc.setReviewers(testreviewedBy);
SPDXReview[] resultreviewedBy = doc.getReviewers();
compareArrays(testreviewedBy, resultreviewedBy);
SPDXReview[] testreviewedBy2 = new SPDXReview[] {new SPDXReview("review1", "date=1", "comment-1"),
new SPDXReview("review2", "date2", "comment2"),
new SPDXReview("review3", "date3", "comment3")};
doc.setReviewers(testreviewedBy2);
SPDXReview[] resultreviewedBy2 = doc.getReviewers();
compareArrays(testreviewedBy2, resultreviewedBy2);
writer = new StringWriter();
doc.getModel().write(writer);
String afterCreate = writer.toString();
}
/**
* Test method for {@link org.spdx.rdfparser.SPDXAnalysis#getCreated()}.
*/
@Test
public void testGetCreated() {
fail("Not yet implemented");
}
/**
* Test method for {@link org.spdx.rdfparser.SPDXAnalysis#setCreated(java.lang.String)}.
* @throws InvalidSPDXAnalysisException
* @throws IOException
*/
@Test
public void testSetCreated() throws InvalidSPDXAnalysisException, IOException {
Model model = ModelFactory.createDefaultModel();
SPDXAnalysis doc = new SPDXAnalysis(model);
String testUri = "https://olex.openlogic.com/package_versions/download/4832?path=openlogic/zlib/1.2.3/zlib-1.2.3-all-src.zip&package_version_id=1082";
StringWriter writer = new StringWriter();
doc.getModel().write(writer);
String beforeCreate = writer.toString();
writer.close();
doc.createSpdxAnalysis(testUri);
String noCreated = doc.getCreated();
assertNull(noCreated);
String testCreated = "Created By Me";
doc.setCreated(testCreated);
String resultCreated = doc.getCreated();
assertEquals(testCreated, resultCreated);
writer = new StringWriter();
doc.getModel().write(writer);
String afterCreate = writer.toString();
String testCreated2 = "second created";
doc.setCreated(testCreated2);
String resultCreated2 = doc.getCreated();
assertEquals(testCreated2, resultCreated2);
}
/**
* Test method for {@link org.spdx.rdfparser.SPDXAnalysis#getSpdxPackage()}.
* @throws InvalidSPDXAnalysisException
* @throws IOException
*/
@Test
public void testGetSpdxPackage() throws InvalidSPDXAnalysisException, IOException {
Model model = ModelFactory.createDefaultModel();
SPDXAnalysis doc = new SPDXAnalysis(model);
String testDocUri = "https://olex.openlogic.com/spdxdoc/package_versions/download/4832?path=openlogic/zlib/1.2.3/zlib-1.2.3-all-src.zip&package_version_id=1082";
StringWriter writer = new StringWriter();
doc.getModel().write(writer);
String beforeCreate = writer.toString();
writer.close();
doc.createSpdxAnalysis(testDocUri);
String testPkgUri = "https://olex.openlogic.com/package_versions/download/4832?path=openlogic/zlib/1.2.3/zlib-1.2.3-all-src.zip&uniquepackagename";
doc.createSpdxPackage(testPkgUri);
writer = new StringWriter();
doc.getModel().write(writer);
String afterCreate = writer.toString();
if (!afterCreate.contains("uniquepackagename")) {
fail("missing uri in RDF document");
}
SPDXPackage pkg = doc.getSpdxPackage();
}
/**
* Test method for {@link org.spdx.rdfparser.SPDXAnalysis#createSpdxPackage(String)}.
*/
@Test
public void testCreateSpdxPackage() {
}
/**
* Test method for {@link org.spdx.rdfparser.SPDXAnalysis#getNonStandardLicenses()}.
*/
@Test
public void testGetNonStandardLicenses() {
fail("Not yet implemented");
}
/**
* Test method for {@link org.spdx.rdfparser.SPDXAnalysis#setNonStandardLicenses(org.spdx.rdfparser.SPDXStandardLicense[])}.
* @throws InvalidSPDXAnalysisException
* @throws IOException
*/
@Test
public void testSetNonStandardLicenses() throws InvalidSPDXAnalysisException, IOException {
Model model = ModelFactory.createDefaultModel();
SPDXAnalysis doc = new SPDXAnalysis(model);
String testUri = "https://olex.openlogic.com/package_versions/download/4832?path=openlogic/zlib/1.2.3/zlib-1.2.3-all-src.zip&package_version_id=1082";
StringWriter writer = new StringWriter();
doc.getModel().write(writer);
String beforeCreate = writer.toString();
writer.close();
doc.createSpdxAnalysis(testUri);
SPDXStandardLicense[] noNonStdLic = doc.getNonStandardLicenses();
assertEquals(0, noNonStdLic.length);
SPDXStandardLicense[] testNonStdLic = new SPDXStandardLicense[] {new SPDXStandardLicense(
"name", "LicID1", "Licnese Text 1", "URL", "LicNotes1", "StdHeader", "Template")};
doc.setNonStandardLicenses(testNonStdLic);
SPDXStandardLicense[] resultNonStdLic = doc.getNonStandardLicenses();
assertEquals(1, resultNonStdLic.length);
assertEquals(testNonStdLic[0].getId(), resultNonStdLic[0].getId());
assertEquals(testNonStdLic[0].getText(), resultNonStdLic[0].getText());
SPDXStandardLicense[] testNonStdLic2 = new SPDXStandardLicense[] {new SPDXStandardLicense(
"name", "LicID2", "Licnese Text 2", "URL", "LicNotes1", "StdHeader", "Template"),
new SPDXStandardLicense(
"name", "LicID3", "Licnese Text 3", "URL", "LicNotes1", "StdHeader", "Template"),
new SPDXStandardLicense(
"name", "LicID4", "Licnese Text 4", "URL", "LicNotes1", "StdHeader", "Template")};
doc.setNonStandardLicenses(testNonStdLic2);
SPDXStandardLicense[] resultNonStdLic2 = doc.getNonStandardLicenses();
assertEquals(testNonStdLic2.length, resultNonStdLic2.length);
String[] testLicIds = new String[testNonStdLic2.length];
String[] testLicTexts = new String[testNonStdLic2.length];
String[] resultLicIds = new String[testNonStdLic2.length];
String[] resultLicTexts = new String[testNonStdLic2.length];
for (int i = 0; i < testLicIds.length; i++) {
testLicIds[i] = testNonStdLic2[i].getId();
testLicTexts[i] = testNonStdLic2[i].getText();
resultLicIds[i] = resultNonStdLic2[i].getId();
resultLicTexts[i] = resultNonStdLic2[i].getText();
}
compareArrays(testLicIds, resultLicIds);
compareArrays(testLicTexts, resultLicTexts);
writer = new StringWriter();
doc.getModel().write(writer);
String afterCreate = writer.toString();
}
/**
* Test method for {@link org.spdx.rdfparser.SPDXAnalysis#getName()}.
*/
@Test
public void testGetName() {
fail("Not yet implemented");
}
/**
* Test method for {@link org.spdx.rdfparser.SPDXAnalysis#createSpdxAnalysis(java.lang.String)}.
* @throws InvalidSPDXAnalysisException
* @throws IOException
*/
@Test
public void testcreateSpdxDocument() throws InvalidSPDXAnalysisException, IOException {
Model model = ModelFactory.createDefaultModel();
SPDXAnalysis doc = new SPDXAnalysis(model);
String testUri = "https://olex.openlogic.com/package_versions/download/4832?path=openlogic/zlib/1.2.3/zlib-1.2.3-all-src.zip&package_version_id=1082";
StringWriter writer = new StringWriter();
doc.getModel().write(writer);
String beforeCreate = writer.toString();
writer.close();
doc.createSpdxAnalysis(testUri);
writer = new StringWriter();
doc.getModel().write(writer);
String afterCreate = writer.toString();
if (!afterCreate.contains(testUri)) {
// fail("Uri string not present after spdx document create");
// these don't actually match becuase there is some extra escaping going on in the URL string
}
String uriResult = doc.getSpdxDocUri();
assertEquals(testUri, uriResult);
}
}
| |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.apigateway.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* Represents an AWS account that is associated with API Gateway.
* </p>
* <div class="remarks">
* <p>
* To view the account info, call <code>GET</code> on this resource.
* </p>
* <h4>Error Codes</h4>
* <p>
* The following exception may be thrown when the request fails.
* </p>
* <ul>
* <li>UnauthorizedException</li>
* <li>NotFoundException</li>
* <li>TooManyRequestsException</li>
* </ul>
* <p>
* For detailed error code information, including the corresponding HTTP Status Codes, see <a
* href="https://docs.aws.amazon.com/apigateway/api-reference/handling-errors/#api-error-codes">API Gateway Error
* Codes</a>
* </p>
* <h4>Example: Get the information about an account.</h4> <h5>Request</h5>
*
* <pre>
* <code>GET /account HTTP/1.1 Content-Type: application/json Host: apigateway.us-east-1.amazonaws.com X-Amz-Date: 20160531T184618Z Authorization: AWS4-HMAC-SHA256 Credential={access_key_ID}/us-east-1/apigateway/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature={sig4_hash} </code>
* </pre>
*
* <h5>Response</h5>
* <p>
* The successful response returns a <code>200 OK</code> status code and a payload similar to the following:
* </p>
*
* <pre>
* <code>{ "_links": { "curies": { "href": "https://docs.aws.amazon.com/apigateway/latest/developerguide/account-apigateway-{rel}.html", "name": "account", "templated": true }, "self": { "href": "/account" }, "account:update": { "href": "/account" } }, "cloudwatchRoleArn": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "throttleSettings": { "rateLimit": 500, "burstLimit": 1000 } } </code>
* </pre>
* <p>
* In addition to making the REST API call directly, you can use the AWS CLI and an AWS SDK to access this resource.
* </p>
* </div> <div class="seeAlso"> <a
* href="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-limits.html">API Gateway Limits</a> <a
* href="https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html">Developer Guide</a>, <a
* href="https://docs.aws.amazon.com/cli/latest/reference/apigateway/get-account.html">AWS CLI</a> </div>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateAccountResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The ARN of an Amazon CloudWatch role for the current <a>Account</a>.
* </p>
*/
private String cloudwatchRoleArn;
/**
* <p>
* Specifies the API request limits configured for the current <a>Account</a>.
* </p>
*/
private ThrottleSettings throttleSettings;
/**
* <p>
* A list of features supported for the account. When usage plans are enabled, the features list will include an
* entry of <code>"UsagePlans"</code>.
* </p>
*/
private java.util.List<String> features;
/**
* <p>
* The version of the API keys used for the account.
* </p>
*/
private String apiKeyVersion;
/**
* <p>
* The ARN of an Amazon CloudWatch role for the current <a>Account</a>.
* </p>
*
* @param cloudwatchRoleArn
* The ARN of an Amazon CloudWatch role for the current <a>Account</a>.
*/
public void setCloudwatchRoleArn(String cloudwatchRoleArn) {
this.cloudwatchRoleArn = cloudwatchRoleArn;
}
/**
* <p>
* The ARN of an Amazon CloudWatch role for the current <a>Account</a>.
* </p>
*
* @return The ARN of an Amazon CloudWatch role for the current <a>Account</a>.
*/
public String getCloudwatchRoleArn() {
return this.cloudwatchRoleArn;
}
/**
* <p>
* The ARN of an Amazon CloudWatch role for the current <a>Account</a>.
* </p>
*
* @param cloudwatchRoleArn
* The ARN of an Amazon CloudWatch role for the current <a>Account</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateAccountResult withCloudwatchRoleArn(String cloudwatchRoleArn) {
setCloudwatchRoleArn(cloudwatchRoleArn);
return this;
}
/**
* <p>
* Specifies the API request limits configured for the current <a>Account</a>.
* </p>
*
* @param throttleSettings
* Specifies the API request limits configured for the current <a>Account</a>.
*/
public void setThrottleSettings(ThrottleSettings throttleSettings) {
this.throttleSettings = throttleSettings;
}
/**
* <p>
* Specifies the API request limits configured for the current <a>Account</a>.
* </p>
*
* @return Specifies the API request limits configured for the current <a>Account</a>.
*/
public ThrottleSettings getThrottleSettings() {
return this.throttleSettings;
}
/**
* <p>
* Specifies the API request limits configured for the current <a>Account</a>.
* </p>
*
* @param throttleSettings
* Specifies the API request limits configured for the current <a>Account</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateAccountResult withThrottleSettings(ThrottleSettings throttleSettings) {
setThrottleSettings(throttleSettings);
return this;
}
/**
* <p>
* A list of features supported for the account. When usage plans are enabled, the features list will include an
* entry of <code>"UsagePlans"</code>.
* </p>
*
* @return A list of features supported for the account. When usage plans are enabled, the features list will
* include an entry of <code>"UsagePlans"</code>.
*/
public java.util.List<String> getFeatures() {
return features;
}
/**
* <p>
* A list of features supported for the account. When usage plans are enabled, the features list will include an
* entry of <code>"UsagePlans"</code>.
* </p>
*
* @param features
* A list of features supported for the account. When usage plans are enabled, the features list will include
* an entry of <code>"UsagePlans"</code>.
*/
public void setFeatures(java.util.Collection<String> features) {
if (features == null) {
this.features = null;
return;
}
this.features = new java.util.ArrayList<String>(features);
}
/**
* <p>
* A list of features supported for the account. When usage plans are enabled, the features list will include an
* entry of <code>"UsagePlans"</code>.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setFeatures(java.util.Collection)} or {@link #withFeatures(java.util.Collection)} if you want to override
* the existing values.
* </p>
*
* @param features
* A list of features supported for the account. When usage plans are enabled, the features list will include
* an entry of <code>"UsagePlans"</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateAccountResult withFeatures(String... features) {
if (this.features == null) {
setFeatures(new java.util.ArrayList<String>(features.length));
}
for (String ele : features) {
this.features.add(ele);
}
return this;
}
/**
* <p>
* A list of features supported for the account. When usage plans are enabled, the features list will include an
* entry of <code>"UsagePlans"</code>.
* </p>
*
* @param features
* A list of features supported for the account. When usage plans are enabled, the features list will include
* an entry of <code>"UsagePlans"</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateAccountResult withFeatures(java.util.Collection<String> features) {
setFeatures(features);
return this;
}
/**
* <p>
* The version of the API keys used for the account.
* </p>
*
* @param apiKeyVersion
* The version of the API keys used for the account.
*/
public void setApiKeyVersion(String apiKeyVersion) {
this.apiKeyVersion = apiKeyVersion;
}
/**
* <p>
* The version of the API keys used for the account.
* </p>
*
* @return The version of the API keys used for the account.
*/
public String getApiKeyVersion() {
return this.apiKeyVersion;
}
/**
* <p>
* The version of the API keys used for the account.
* </p>
*
* @param apiKeyVersion
* The version of the API keys used for the account.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateAccountResult withApiKeyVersion(String apiKeyVersion) {
setApiKeyVersion(apiKeyVersion);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getCloudwatchRoleArn() != null)
sb.append("CloudwatchRoleArn: ").append(getCloudwatchRoleArn()).append(",");
if (getThrottleSettings() != null)
sb.append("ThrottleSettings: ").append(getThrottleSettings()).append(",");
if (getFeatures() != null)
sb.append("Features: ").append(getFeatures()).append(",");
if (getApiKeyVersion() != null)
sb.append("ApiKeyVersion: ").append(getApiKeyVersion());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof UpdateAccountResult == false)
return false;
UpdateAccountResult other = (UpdateAccountResult) obj;
if (other.getCloudwatchRoleArn() == null ^ this.getCloudwatchRoleArn() == null)
return false;
if (other.getCloudwatchRoleArn() != null && other.getCloudwatchRoleArn().equals(this.getCloudwatchRoleArn()) == false)
return false;
if (other.getThrottleSettings() == null ^ this.getThrottleSettings() == null)
return false;
if (other.getThrottleSettings() != null && other.getThrottleSettings().equals(this.getThrottleSettings()) == false)
return false;
if (other.getFeatures() == null ^ this.getFeatures() == null)
return false;
if (other.getFeatures() != null && other.getFeatures().equals(this.getFeatures()) == false)
return false;
if (other.getApiKeyVersion() == null ^ this.getApiKeyVersion() == null)
return false;
if (other.getApiKeyVersion() != null && other.getApiKeyVersion().equals(this.getApiKeyVersion()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getCloudwatchRoleArn() == null) ? 0 : getCloudwatchRoleArn().hashCode());
hashCode = prime * hashCode + ((getThrottleSettings() == null) ? 0 : getThrottleSettings().hashCode());
hashCode = prime * hashCode + ((getFeatures() == null) ? 0 : getFeatures().hashCode());
hashCode = prime * hashCode + ((getApiKeyVersion() == null) ? 0 : getApiKeyVersion().hashCode());
return hashCode;
}
@Override
public UpdateAccountResult clone() {
try {
return (UpdateAccountResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| |
/*
* Copyright 2016-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.store.primitives.resources.impl;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
import org.onosproject.cluster.Leadership;
import org.onosproject.cluster.NodeId;
import org.onosproject.event.Change;
import io.atomix.Atomix;
import io.atomix.AtomixClient;
import io.atomix.resource.ResourceType;
/**
* Unit tests for {@link AtomixLeaderElector}.
*/
@Ignore
public class AtomixLeaderElectorTest extends AtomixTestBase {
NodeId node1 = new NodeId("node1");
NodeId node2 = new NodeId("node2");
NodeId node3 = new NodeId("node3");
@Override
protected ResourceType resourceType() {
return new ResourceType(AtomixLeaderElector.class);
}
@Test
public void testRun() throws Throwable {
leaderElectorRunTests(3);
}
private void leaderElectorRunTests(int numServers) throws Throwable {
createCopycatServers(numServers);
Atomix client1 = createAtomixClient();
AtomixLeaderElector elector1 = client1.getResource("test-elector", AtomixLeaderElector.class).join();
elector1.run("foo", node1).thenAccept(result -> {
assertEquals(node1, result.leaderNodeId());
assertEquals(1, result.leader().term());
assertEquals(1, result.candidates().size());
assertEquals(node1, result.candidates().get(0));
}).join();
Atomix client2 = createAtomixClient();
AtomixLeaderElector elector2 = client2.getResource("test-elector", AtomixLeaderElector.class).join();
elector2.run("foo", node2).thenAccept(result -> {
assertEquals(node1, result.leaderNodeId());
assertEquals(1, result.leader().term());
assertEquals(2, result.candidates().size());
assertEquals(node1, result.candidates().get(0));
assertEquals(node2, result.candidates().get(1));
}).join();
}
@Test
public void testWithdraw() throws Throwable {
leaderElectorWithdrawTests(3);
}
private void leaderElectorWithdrawTests(int numServers) throws Throwable {
createCopycatServers(numServers);
Atomix client1 = createAtomixClient();
AtomixLeaderElector elector1 = client1.getResource("test-elector", AtomixLeaderElector.class).join();
elector1.run("foo", node1).join();
Atomix client2 = createAtomixClient();
AtomixLeaderElector elector2 = client2.getResource("test-elector", AtomixLeaderElector.class).join();
elector2.run("foo", node2).join();
LeaderEventListener listener1 = new LeaderEventListener();
elector1.addChangeListener(listener1).join();
LeaderEventListener listener2 = new LeaderEventListener();
elector2.addChangeListener(listener2).join();
elector1.withdraw("foo").join();
listener1.nextEvent().thenAccept(result -> {
assertEquals(node2, result.newValue().leaderNodeId());
assertEquals(2, result.newValue().leader().term());
assertEquals(1, result.newValue().candidates().size());
assertEquals(node2, result.newValue().candidates().get(0));
}).join();
listener2.nextEvent().thenAccept(result -> {
assertEquals(node2, result.newValue().leaderNodeId());
assertEquals(2, result.newValue().leader().term());
assertEquals(1, result.newValue().candidates().size());
assertEquals(node2, result.newValue().candidates().get(0));
}).join();
}
@Test
public void testAnoint() throws Throwable {
leaderElectorAnointTests(3);
}
private void leaderElectorAnointTests(int numServers) throws Throwable {
createCopycatServers(numServers);
Atomix client1 = createAtomixClient();
AtomixLeaderElector elector1 = client1.getResource("test-elector", AtomixLeaderElector.class).join();
Atomix client2 = createAtomixClient();
AtomixLeaderElector elector2 = client2.getResource("test-elector", AtomixLeaderElector.class).join();
Atomix client3 = createAtomixClient();
AtomixLeaderElector elector3 = client3.getResource("test-elector", AtomixLeaderElector.class).join();
elector1.run("foo", node1).join();
elector2.run("foo", node2).join();
LeaderEventListener listener1 = new LeaderEventListener();
elector1.addChangeListener(listener1).join();
LeaderEventListener listener2 = new LeaderEventListener();
elector2.addChangeListener(listener2);
LeaderEventListener listener3 = new LeaderEventListener();
elector3.addChangeListener(listener3).join();
elector3.anoint("foo", node3).thenAccept(result -> {
assertFalse(result);
}).join();
assertFalse(listener1.hasEvent());
assertFalse(listener2.hasEvent());
assertFalse(listener3.hasEvent());
elector3.anoint("foo", node2).thenAccept(result -> {
assertTrue(result);
}).join();
listener1.nextEvent().thenAccept(result -> {
assertEquals(node2, result.newValue().leaderNodeId());
assertEquals(2, result.newValue().candidates().size());
assertEquals(node1, result.newValue().candidates().get(0));
assertEquals(node2, result.newValue().candidates().get(1));
}).join();
listener2.nextEvent().thenAccept(result -> {
assertEquals(node2, result.newValue().leaderNodeId());
assertEquals(2, result.newValue().candidates().size());
assertEquals(node1, result.newValue().candidates().get(0));
assertEquals(node2, result.newValue().candidates().get(1));
}).join();
listener3.nextEvent().thenAccept(result -> {
assertEquals(node2, result.newValue().leaderNodeId());
assertEquals(2, result.newValue().candidates().size());
assertEquals(node1, result.newValue().candidates().get(0));
assertEquals(node2, result.newValue().candidates().get(1));
}).join();
}
@Test
public void testPromote() throws Throwable {
leaderElectorPromoteTests(3);
}
private void leaderElectorPromoteTests(int numServers) throws Throwable {
createCopycatServers(numServers);
AtomixClient client1 = createAtomixClient();
AtomixLeaderElector elector1 = client1.getResource("test-elector", AtomixLeaderElector.class).join();
AtomixClient client2 = createAtomixClient();
AtomixLeaderElector elector2 = client2.getResource("test-elector", AtomixLeaderElector.class).join();
AtomixClient client3 = createAtomixClient();
AtomixLeaderElector elector3 = client3.getResource("test-elector", AtomixLeaderElector.class).join();
elector1.run("foo", node1).join();
elector2.run("foo", node2).join();
LeaderEventListener listener1 = new LeaderEventListener();
elector1.addChangeListener(listener1).join();
LeaderEventListener listener2 = new LeaderEventListener();
elector2.addChangeListener(listener2).join();
LeaderEventListener listener3 = new LeaderEventListener();
elector3.addChangeListener(listener3).join();
elector3.promote("foo", node3).thenAccept(result -> {
assertFalse(result);
}).join();
assertFalse(listener1.hasEvent());
assertFalse(listener2.hasEvent());
assertFalse(listener3.hasEvent());
elector3.run("foo", node3).join();
listener1.nextEvent().thenAccept(result -> {
assertEquals(node3, result.newValue().candidates().get(2));
}).join();
listener2.nextEvent().thenAccept(result -> {
assertEquals(node3, result.newValue().candidates().get(2));
}).join();
listener3.nextEvent().thenAccept(result -> {
assertEquals(node3, result.newValue().candidates().get(2));
}).join();
elector3.promote("foo", node3).thenAccept(result -> {
assertTrue(result);
}).join();
listener1.nextEvent().thenAccept(result -> {
assertEquals(node3, result.newValue().candidates().get(0));
}).join();
listener2.nextEvent().thenAccept(result -> {
assertEquals(node3, result.newValue().candidates().get(0));
}).join();
listener3.nextEvent().thenAccept(result -> {
assertEquals(node3, result.newValue().candidates().get(0));
}).join();
}
@Test
public void testLeaderSessionClose() throws Throwable {
leaderElectorLeaderSessionCloseTests(3);
}
private void leaderElectorLeaderSessionCloseTests(int numServers) throws Throwable {
createCopycatServers(numServers);
AtomixClient client1 = createAtomixClient();
AtomixLeaderElector elector1 = client1.getResource("test-elector", AtomixLeaderElector.class).join();
elector1.run("foo", node1).join();
Atomix client2 = createAtomixClient();
AtomixLeaderElector elector2 = client2.getResource("test-elector", AtomixLeaderElector.class).join();
LeaderEventListener listener = new LeaderEventListener();
elector2.run("foo", node2).join();
elector2.addChangeListener(listener).join();
client1.close();
listener.nextEvent().thenAccept(result -> {
assertEquals(node2, result.newValue().leaderNodeId());
assertEquals(1, result.newValue().candidates().size());
assertEquals(node2, result.newValue().candidates().get(0));
}).join();
}
@Test
public void testNonLeaderSessionClose() throws Throwable {
leaderElectorNonLeaderSessionCloseTests(3);
}
private void leaderElectorNonLeaderSessionCloseTests(int numServers) throws Throwable {
createCopycatServers(numServers);
Atomix client1 = createAtomixClient();
AtomixLeaderElector elector1 = client1.getResource("test-elector", AtomixLeaderElector.class).join();
elector1.run("foo", node1).join();
AtomixClient client2 = createAtomixClient();
AtomixLeaderElector elector2 = client2.getResource("test-elector", AtomixLeaderElector.class).join();
LeaderEventListener listener = new LeaderEventListener();
elector2.run("foo", node2).join();
elector1.addChangeListener(listener).join();
client2.close().join();
listener.nextEvent().thenAccept(result -> {
assertEquals(node1, result.newValue().leaderNodeId());
assertEquals(1, result.newValue().candidates().size());
assertEquals(node1, result.newValue().candidates().get(0));
}).join();
}
@Test
public void testQueries() throws Throwable {
leaderElectorQueryTests(3);
}
private void leaderElectorQueryTests(int numServers) throws Throwable {
createCopycatServers(numServers);
Atomix client1 = createAtomixClient();
Atomix client2 = createAtomixClient();
AtomixLeaderElector elector1 = client1.getResource("test-elector", AtomixLeaderElector.class).join();
AtomixLeaderElector elector2 = client2.getResource("test-elector", AtomixLeaderElector.class).join();
elector1.run("foo", node1).join();
elector2.run("foo", node2).join();
elector2.run("bar", node2).join();
elector1.getElectedTopics(node1).thenAccept(result -> {
assertEquals(1, result.size());
assertTrue(result.contains("foo"));
}).join();
elector2.getElectedTopics(node1).thenAccept(result -> {
assertEquals(1, result.size());
assertTrue(result.contains("foo"));
}).join();
elector1.getLeadership("foo").thenAccept(result -> {
assertEquals(node1, result.leaderNodeId());
assertEquals(node1, result.candidates().get(0));
assertEquals(node2, result.candidates().get(1));
}).join();
elector2.getLeadership("foo").thenAccept(result -> {
assertEquals(node1, result.leaderNodeId());
assertEquals(node1, result.candidates().get(0));
assertEquals(node2, result.candidates().get(1));
}).join();
elector1.getLeadership("bar").thenAccept(result -> {
assertEquals(node2, result.leaderNodeId());
assertEquals(node2, result.candidates().get(0));
}).join();
elector2.getLeadership("bar").thenAccept(result -> {
assertEquals(node2, result.leaderNodeId());
assertEquals(node2, result.candidates().get(0));
}).join();
elector1.getLeaderships().thenAccept(result -> {
assertEquals(2, result.size());
Leadership fooLeadership = result.get("foo");
assertEquals(node1, fooLeadership.leaderNodeId());
assertEquals(node1, fooLeadership.candidates().get(0));
assertEquals(node2, fooLeadership.candidates().get(1));
Leadership barLeadership = result.get("bar");
assertEquals(node2, barLeadership.leaderNodeId());
assertEquals(node2, barLeadership.candidates().get(0));
}).join();
elector2.getLeaderships().thenAccept(result -> {
assertEquals(2, result.size());
Leadership fooLeadership = result.get("foo");
assertEquals(node1, fooLeadership.leaderNodeId());
assertEquals(node1, fooLeadership.candidates().get(0));
assertEquals(node2, fooLeadership.candidates().get(1));
Leadership barLeadership = result.get("bar");
assertEquals(node2, barLeadership.leaderNodeId());
assertEquals(node2, barLeadership.candidates().get(0));
}).join();
}
private static class LeaderEventListener implements Consumer<Change<Leadership>> {
Queue<Change<Leadership>> eventQueue = new LinkedList<>();
CompletableFuture<Change<Leadership>> pendingFuture;
@Override
public void accept(Change<Leadership> change) {
synchronized (this) {
if (pendingFuture != null) {
pendingFuture.complete(change);
pendingFuture = null;
} else {
eventQueue.add(change);
}
}
}
public boolean hasEvent() {
return !eventQueue.isEmpty();
}
public void clearEvents() {
eventQueue.clear();
}
public CompletableFuture<Change<Leadership>> nextEvent() {
synchronized (this) {
if (eventQueue.isEmpty()) {
if (pendingFuture == null) {
pendingFuture = new CompletableFuture<>();
}
return pendingFuture;
} else {
return CompletableFuture.completedFuture(eventQueue.poll());
}
}
}
}
}
| |
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.server.coordination;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
import com.google.inject.Inject;
import com.metamx.emitter.EmittingLogger;
import com.metamx.emitter.service.ServiceEmitter;
import io.druid.client.CachingQueryRunner;
import io.druid.client.cache.Cache;
import io.druid.client.cache.CacheConfig;
import io.druid.collections.CountingMap;
import io.druid.guice.annotations.BackgroundCaching;
import io.druid.guice.annotations.Processing;
import io.druid.guice.annotations.Smile;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.guava.FunctionalIterable;
import io.druid.query.BySegmentQueryRunner;
import io.druid.query.CPUTimeMetricQueryRunner;
import io.druid.query.DataSource;
import io.druid.query.FinalizeResultsQueryRunner;
import io.druid.query.MetricsEmittingQueryRunner;
import io.druid.query.NoopQueryRunner;
import io.druid.query.Query;
import io.druid.query.QueryMetrics;
import io.druid.query.QueryRunner;
import io.druid.query.QueryRunnerFactory;
import io.druid.query.QueryRunnerFactoryConglomerate;
import io.druid.query.QuerySegmentWalker;
import io.druid.query.QueryToolChest;
import io.druid.query.ReferenceCountingSegmentQueryRunner;
import io.druid.query.ReportTimelineMissingSegmentQueryRunner;
import io.druid.query.SegmentDescriptor;
import io.druid.query.TableDataSource;
import io.druid.query.spec.SpecificSegmentQueryRunner;
import io.druid.query.spec.SpecificSegmentSpec;
import io.druid.segment.ReferenceCountingSegment;
import io.druid.segment.Segment;
import io.druid.segment.loading.SegmentLoader;
import io.druid.segment.loading.SegmentLoadingException;
import io.druid.timeline.DataSegment;
import io.druid.timeline.TimelineObjectHolder;
import io.druid.timeline.VersionedIntervalTimeline;
import io.druid.timeline.partition.PartitionChunk;
import io.druid.timeline.partition.PartitionHolder;
import org.joda.time.Interval;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicLong;
/**
*/
public class ServerManager implements QuerySegmentWalker
{
private static final EmittingLogger log = new EmittingLogger(ServerManager.class);
private final Object lock = new Object();
private final SegmentLoader segmentLoader;
private final QueryRunnerFactoryConglomerate conglomerate;
private final ServiceEmitter emitter;
private final ExecutorService exec;
private final ExecutorService cachingExec;
private final Map<String, VersionedIntervalTimeline<String, ReferenceCountingSegment>> dataSources;
private final CountingMap<String> dataSourceSizes = new CountingMap<String>();
private final CountingMap<String> dataSourceCounts = new CountingMap<String>();
private final Cache cache;
private final ObjectMapper objectMapper;
private final CacheConfig cacheConfig;
@Inject
public ServerManager(
SegmentLoader segmentLoader,
QueryRunnerFactoryConglomerate conglomerate,
ServiceEmitter emitter,
@Processing ExecutorService exec,
@BackgroundCaching ExecutorService cachingExec,
@Smile ObjectMapper objectMapper,
Cache cache,
CacheConfig cacheConfig
)
{
this.segmentLoader = segmentLoader;
this.conglomerate = conglomerate;
this.emitter = emitter;
this.exec = exec;
this.cachingExec = cachingExec;
this.cache = cache;
this.objectMapper = objectMapper;
this.dataSources = new HashMap<>();
this.cacheConfig = cacheConfig;
}
public Map<String, Long> getDataSourceSizes()
{
synchronized (dataSourceSizes) {
return dataSourceSizes.snapshot();
}
}
public Map<String, Long> getDataSourceCounts()
{
synchronized (dataSourceCounts) {
return dataSourceCounts.snapshot();
}
}
public boolean isSegmentCached(final DataSegment segment) throws SegmentLoadingException
{
return segmentLoader.isSegmentLoaded(segment);
}
/**
* Load a single segment.
*
* @param segment segment to load
*
* @return true if the segment was newly loaded, false if it was already loaded
*
* @throws SegmentLoadingException if the segment cannot be loaded
*/
public boolean loadSegment(final DataSegment segment) throws SegmentLoadingException
{
final Segment adapter;
try {
adapter = segmentLoader.getSegment(segment);
}
catch (SegmentLoadingException e) {
try {
segmentLoader.cleanup(segment);
}
catch (SegmentLoadingException e1) {
// ignore
}
throw e;
}
if (adapter == null) {
throw new SegmentLoadingException("Null adapter from loadSpec[%s]", segment.getLoadSpec());
}
synchronized (lock) {
String dataSource = segment.getDataSource();
VersionedIntervalTimeline<String, ReferenceCountingSegment> loadedIntervals = dataSources.get(dataSource);
if (loadedIntervals == null) {
loadedIntervals = new VersionedIntervalTimeline<>(Ordering.natural());
dataSources.put(dataSource, loadedIntervals);
}
PartitionHolder<ReferenceCountingSegment> entry = loadedIntervals.findEntry(
segment.getInterval(),
segment.getVersion()
);
if ((entry != null) && (entry.getChunk(segment.getShardSpec().getPartitionNum()) != null)) {
log.warn("Told to load a adapter for a segment[%s] that already exists", segment.getIdentifier());
return false;
}
loadedIntervals.add(
segment.getInterval(),
segment.getVersion(),
segment.getShardSpec().createChunk(new ReferenceCountingSegment(adapter))
);
synchronized (dataSourceSizes) {
dataSourceSizes.add(dataSource, segment.getSize());
}
synchronized (dataSourceCounts) {
dataSourceCounts.add(dataSource, 1L);
}
return true;
}
}
public void dropSegment(final DataSegment segment) throws SegmentLoadingException
{
String dataSource = segment.getDataSource();
synchronized (lock) {
VersionedIntervalTimeline<String, ReferenceCountingSegment> loadedIntervals = dataSources.get(dataSource);
if (loadedIntervals == null) {
log.info("Told to delete a queryable for a dataSource[%s] that doesn't exist.", dataSource);
return;
}
PartitionChunk<ReferenceCountingSegment> removed = loadedIntervals.remove(
segment.getInterval(),
segment.getVersion(),
segment.getShardSpec().createChunk((ReferenceCountingSegment) null)
);
ReferenceCountingSegment oldQueryable = (removed == null) ? null : removed.getObject();
if (oldQueryable != null) {
synchronized (dataSourceSizes) {
dataSourceSizes.add(dataSource, -segment.getSize());
}
synchronized (dataSourceCounts) {
dataSourceCounts.add(dataSource, -1L);
}
try {
log.info("Attempting to close segment %s", segment.getIdentifier());
oldQueryable.close();
}
catch (IOException e) {
log.makeAlert(e, "Exception closing segment")
.addData("dataSource", dataSource)
.addData("segmentId", segment.getIdentifier())
.emit();
}
} else {
log.info(
"Told to delete a queryable on dataSource[%s] for interval[%s] and version [%s] that I don't have.",
dataSource,
segment.getInterval(),
segment.getVersion()
);
}
}
segmentLoader.cleanup(segment);
}
@Override
public <T> QueryRunner<T> getQueryRunnerForIntervals(Query<T> query, Iterable<Interval> intervals)
{
final QueryRunnerFactory<T, Query<T>> factory = conglomerate.findFactory(query);
if (factory == null) {
throw new ISE("Unknown query type[%s].", query.getClass());
}
final QueryToolChest<T, Query<T>> toolChest = factory.getToolchest();
final AtomicLong cpuTimeAccumulator = new AtomicLong(0L);
DataSource dataSource = query.getDataSource();
if (!(dataSource instanceof TableDataSource)) {
throw new UnsupportedOperationException("data source type '" + dataSource.getClass().getName() + "' unsupported");
}
String dataSourceName = getDataSourceName(dataSource);
final VersionedIntervalTimeline<String, ReferenceCountingSegment> timeline = dataSources.get(dataSourceName);
if (timeline == null) {
return new NoopQueryRunner<T>();
}
FunctionalIterable<QueryRunner<T>> queryRunners = FunctionalIterable
.create(intervals)
.transformCat(
new Function<Interval, Iterable<TimelineObjectHolder<String, ReferenceCountingSegment>>>()
{
@Override
public Iterable<TimelineObjectHolder<String, ReferenceCountingSegment>> apply(Interval input)
{
return timeline.lookup(input);
}
}
)
.transformCat(
new Function<TimelineObjectHolder<String, ReferenceCountingSegment>, Iterable<QueryRunner<T>>>()
{
@Override
public Iterable<QueryRunner<T>> apply(
@Nullable
final TimelineObjectHolder<String, ReferenceCountingSegment> holder
)
{
if (holder == null) {
return null;
}
return FunctionalIterable
.create(holder.getObject())
.transform(
new Function<PartitionChunk<ReferenceCountingSegment>, QueryRunner<T>>()
{
@Override
public QueryRunner<T> apply(PartitionChunk<ReferenceCountingSegment> input)
{
return buildAndDecorateQueryRunner(
factory,
toolChest,
input.getObject(),
new SegmentDescriptor(
holder.getInterval(),
holder.getVersion(),
input.getChunkNumber()
),
cpuTimeAccumulator
);
}
}
);
}
}
);
return CPUTimeMetricQueryRunner.safeBuild(
new FinalizeResultsQueryRunner<T>(
toolChest.mergeResults(factory.mergeRunners(exec, queryRunners)),
toolChest
),
toolChest,
emitter,
cpuTimeAccumulator,
true
);
}
private String getDataSourceName(DataSource dataSource)
{
return Iterables.getOnlyElement(dataSource.getNames());
}
@Override
public <T> QueryRunner<T> getQueryRunnerForSegments(Query<T> query, Iterable<SegmentDescriptor> specs)
{
final QueryRunnerFactory<T, Query<T>> factory = conglomerate.findFactory(query);
if (factory == null) {
log.makeAlert("Unknown query type, [%s]", query.getClass())
.addData("dataSource", query.getDataSource())
.emit();
return new NoopQueryRunner<T>();
}
final QueryToolChest<T, Query<T>> toolChest = factory.getToolchest();
String dataSourceName = getDataSourceName(query.getDataSource());
final VersionedIntervalTimeline<String, ReferenceCountingSegment> timeline = dataSources.get(
dataSourceName
);
if (timeline == null) {
return new NoopQueryRunner<T>();
}
final AtomicLong cpuTimeAccumulator = new AtomicLong(0L);
FunctionalIterable<QueryRunner<T>> queryRunners = FunctionalIterable
.create(specs)
.transformCat(
new Function<SegmentDescriptor, Iterable<QueryRunner<T>>>()
{
@Override
@SuppressWarnings("unchecked")
public Iterable<QueryRunner<T>> apply(SegmentDescriptor input)
{
final PartitionHolder<ReferenceCountingSegment> entry = timeline.findEntry(
input.getInterval(), input.getVersion()
);
if (entry == null) {
return Arrays.<QueryRunner<T>>asList(new ReportTimelineMissingSegmentQueryRunner<T>(input));
}
final PartitionChunk<ReferenceCountingSegment> chunk = entry.getChunk(input.getPartitionNumber());
if (chunk == null) {
return Arrays.<QueryRunner<T>>asList(new ReportTimelineMissingSegmentQueryRunner<T>(input));
}
final ReferenceCountingSegment adapter = chunk.getObject();
return Arrays.asList(
buildAndDecorateQueryRunner(factory, toolChest, adapter, input, cpuTimeAccumulator)
);
}
}
);
return CPUTimeMetricQueryRunner.safeBuild(
new FinalizeResultsQueryRunner<>(
toolChest.mergeResults(factory.mergeRunners(exec, queryRunners)),
toolChest
),
toolChest,
emitter,
cpuTimeAccumulator,
true
);
}
private <T> QueryRunner<T> buildAndDecorateQueryRunner(
final QueryRunnerFactory<T, Query<T>> factory,
final QueryToolChest<T, Query<T>> toolChest,
final ReferenceCountingSegment adapter,
final SegmentDescriptor segmentDescriptor,
final AtomicLong cpuTimeAccumulator
)
{
SpecificSegmentSpec segmentSpec = new SpecificSegmentSpec(segmentDescriptor);
String segmentId = adapter.getIdentifier();
return CPUTimeMetricQueryRunner.safeBuild(
new SpecificSegmentQueryRunner<T>(
new MetricsEmittingQueryRunner<T>(
emitter,
toolChest,
new BySegmentQueryRunner<T>(
segmentId,
adapter.getDataInterval().getStart(),
new CachingQueryRunner<T>(
segmentId,
segmentDescriptor,
objectMapper,
cache,
toolChest,
new MetricsEmittingQueryRunner<T>(
emitter,
toolChest,
new ReferenceCountingSegmentQueryRunner<T>(factory, adapter, segmentDescriptor),
QueryMetrics::reportSegmentTime,
queryMetrics -> queryMetrics.segment(segmentId)
),
cachingExec,
cacheConfig
)
),
QueryMetrics::reportSegmentAndCacheTime,
queryMetrics -> queryMetrics.segment(segmentId)
).withWaitMeasuredFromNow(),
segmentSpec
),
toolChest,
emitter,
cpuTimeAccumulator,
false
);
}
}
| |
/*
* Copyright 2017 TWO SIGMA OPEN SOURCE, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.twosigma.beakerx.groovy.evaluator.autocomplete;
import com.twosigma.beakerx.autocomplete.AutocompleteResult;
import com.twosigma.beakerx.evaluator.BaseEvaluator;
import com.twosigma.beakerx.groovy.TestGroovyEvaluator;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
public class GroovyEvaluatorAutocompleteTest {
private static BaseEvaluator groovyEvaluator;
@BeforeClass
public static void setUpClass() throws Exception {
groovyEvaluator = TestGroovyEvaluator.groovyEvaluator();
}
@AfterClass
public static void tearDown() throws Exception {
groovyEvaluator.exit();
}
@Test
public void shouldReturnPrintlnForFirstLine() throws Exception {
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(
"System.out.printl\n" +
"System.out.print\n" +
"System.out.prin\n" +
"System.out.pri\n", 17);
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(11);
}
@Test
public void shouldReturnPrintlnForSecondLine() throws Exception {
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(
"System.out.printl\n" +
"System.out.print\n" +
"System.out.prin\n" +
"System.out.pri\n", 34);
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(29);
}
@Test
public void shouldReturnAutocompleteForPrintlnWithComment() throws Exception {
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(
"//comment\n" +
"System.out.printl\n" +
"System.out.printl", 27);
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(21);
}
@Test
public void autocompleteMatchesForSystemAfterDot() throws Exception {
String code = "System.";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
}
@Test
public void autocompleteMatchesForSystemOutAfterDot() throws Exception {
String code = "System.out.";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getMatches()).contains("println");
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length());
}
@Test
public void shouldReturnResultEqualToImport() throws Exception {
String code = "imp";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches().get(0)).isEqualToIgnoringCase("import");
}
@Test
public void shouldReturnResultEqualToToString() throws Exception {
String code = "def v = 'str'\nv.toS";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches().get(0)).isEqualToIgnoringCase("toString");
}
@Test
public void shouldReturnResultEqualToParamInt() throws Exception {
String code = "int paramInt = 10\n" +
"println par";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches().get(0)).isEqualToIgnoringCase("paramInt");
}
@Test
public void shouldReturnResultEqualToParamDouble() throws Exception {
String code = "def paramDouble = 10.0\n" +
"println par";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches().get(0)).isEqualToIgnoringCase("paramDouble");
}
@Test
public void shouldReturnResultEqualToParamString() throws Exception {
String code = "def paramString = 'str'\n" +
"println \"test ${par";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches().get(0)).isEqualToIgnoringCase("paramString");
}
@Test
public void shouldReturnResultEqualToParamArray() throws Exception {
String code = "def paramArray = [1, 3, 5]\n" +
"println par";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches().get(0)).isEqualToIgnoringCase("paramArray");
}
@Test
public void shouldReturnResultEqualToParamMap() throws Exception {
String code = "def paramMap = ['abc':1, 'def':2, 'xyz':3]\n" +
"println par";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches().get(0)).isEqualToIgnoringCase("paramMap");
}
@Test
public void shouldReturnResultEqualToBLUE() throws Exception {
String code = "import static java.awt.Color.BLUE\n" +
"println BL";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches().get(0)).isEqualToIgnoringCase("BLUE");
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length() - 2);
}
@Test
public void autocompleteForClass_shouldReturnResultEqualToCoordinates() throws Exception {
String code = "class Coordinates {\n" +
"double latitude\n" +
"double longitude }\n" +
"def coordinates = new Coordinates(latitude: 43.23, longitude: 3.67)\n" +
"this.class.co";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches().get(0)).isEqualToIgnoringCase("coordinates");
}
@Test
public void shouldReturnResultEqualToPackage() throws Exception {
String code = "pack";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(0);
}
@Test
public void shouldReturnImplements() throws Exception {
String code = "class Coordinates implemen";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches().get(0)).isEqualTo("implements");
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length() - 8);
}
@Test
public void shouldReturnExtends() throws Exception {
String code = "class Coordinates exten";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches().get(0)).isEqualTo("extends");
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length() - 5);
}
@Test
public void shouldReturnClass() throws Exception {
String code = "cla";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches().get(0)).isEqualTo("class");
assertThat(autocomplete.getStartIndex()).isEqualTo(0);
}
@Test
public void shouldAutocompleteToSystem() throws Exception {
String code = "Syste";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches().get(0)).isEqualTo("System");
assertThat(autocomplete.getStartIndex()).isEqualTo(0);
}
@Test
public void shouldAutocompleteToB() throws Exception {
String code = "import java.awt.Color\n" +
"println Color.B";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length() - 1);
}
@Test
public void shouldAutocompleteWithAsterisk() throws Exception {
String code = "import java.awt.*\n" +
"println Color.B";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length() - 1);
}
@Test
public void autocompleteShouldNotMatchForEmptyString() throws Exception {
String code = "";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(0);
}
@Test
public void defaultImportsAutocompleteToRED() throws Exception {
String code = "def colors = [ Color.RE";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length() - 2);
}
@Test
public void autocompleteMatchesForColorAfterDot() throws Exception {
String code = "Color.";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length());
}
@Test
public void autocompleteMatchesToColor() throws Exception {
String code = "Colo";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(0);
}
@Test
public void autocompleteMatchesToRED() throws Exception {
String code = "Color.R";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length() - 1);
}
@Test
public void autocompleteWithMagicCommands() throws Exception {
String code = "%classpath add jar demoResources/BeakerXClasspathTest.jar\n" +
"System.";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length());
}
@Test
public void autocompleteToArrayList() throws Exception {
String code = "ArrayLi";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(0);
}
@Test
public void autocompleteToList() throws Exception {
String code = "Li";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(0);
}
@Test
public void autocompleteArrayListAfterDot() throws Exception {
String code = "List myList = new ArrayList();\n" +
"myList.";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getMatches().stream().filter(x -> x.contains("add")).collect(Collectors.toList())).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length());
}
@Test
public void autocompleteMapAfterDot() throws Exception {
String code = "Map myMap = new HashMap<>();\n" +
"myMap.";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getMatches().stream().filter(x -> x.contains("put")).collect(Collectors.toList())).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length());
}
@Test
public void autocompleteArrayListWithGenericsAfterDot() throws Exception {
String code = "List<String> myList = new ArrayList();\n" +
"myList.";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getMatches().stream().filter(x -> x.contains("add")).collect(Collectors.toList())).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length());
}
@Test
public void autocompleteMapWithGenericsAfterDot() throws Exception {
String code = "Map<String,String> myMap = new HashMap<>();\n" +
"myMap.";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getMatches().stream().filter(x -> x.contains("put")).collect(Collectors.toList())).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length());
}
@Test
public void autocompleteForJavaAwtAfterDotPackage() throws Exception {
String code = "java.awt.";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length());
}
@Test
public void autocompleteForJavaAwtPackage() throws Exception {
String code = "java.aw";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length() - 2);
}
@Test
public void autocompleteForJavaPackage() throws Exception {
String code = "java.";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length());
}
@Test
public void autocompleteToJavaPackage() throws Exception {
String code = "jav";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(0);
}
@Test
public void autocompleteStringMethod() throws Exception {
String code = "a = \"ABC\";\n" +
"a.";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length());
}
@Test
public void autocompleteToMethodsForImportedClassesSeparatedByNewLine() throws Exception {
String code = "import com.twosigma.beakerx.mimetype.MIMEContainer\n" +
"import groovy.json.JsonSlurper\n" +
"def jsonSlurper = new JsonSlurper()\n" +
"def json = jsonSlurper.";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length());
}
@Test
public void autocompleteToMethodsForImportedClassesSeparatedBySemicolon() throws Exception {
String code = "import com.twosigma.beakerx.mimetype.MIMEContainer;" +
"import groovy.json.JsonSlurper\n" +
"def jsonSlurper = new JsonSlurper()\n" +
"def json = jsonSlurper.";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length());
}
@Test
public void autocompleteToFileMethods() throws Exception {
String code = "fname = \"demoResources/bar-chart.vg.json\"\n" +
"fileContents = new File(fname)\n" +
"fileContents.t";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isNotEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(code.length()-1);
}
@Test
public void shouldReturnEmptyResultForIncorrectCode() throws Exception {
String code = "]";
//when
AutocompleteResult autocomplete = groovyEvaluator.autocomplete(code, code.length());
//then
assertThat(autocomplete.getMatches()).isEmpty();
assertThat(autocomplete.getStartIndex()).isEqualTo(0);
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.search.nested;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.apache.lucene.search.join.BitDocIdSetFilter;
import org.apache.lucene.util.BitSet;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BitDocIdSet;
import org.apache.lucene.util.BytesRef;
import java.io.IOException;
import java.util.Collection;
import java.util.Set;
/**
* A special query that accepts a top level parent matching query, and returns the nested docs of the matching parent
* doc as well. This is handy when deleting by query, don't use it for other purposes.
*
* @elasticsearch.internal
*/
public class IncludeNestedDocsQuery extends Query {
private final BitDocIdSetFilter parentFilter;
private final Query parentQuery;
// If we are rewritten, this is the original childQuery we
// were passed; we use this for .equals() and
// .hashCode(). This makes rewritten query equal the
// original, so that user does not have to .rewrite() their
// query before searching:
private final Query origParentQuery;
public IncludeNestedDocsQuery(Query parentQuery, BitDocIdSetFilter parentFilter) {
this.origParentQuery = parentQuery;
this.parentQuery = parentQuery;
this.parentFilter = parentFilter;
}
// For rewriting
IncludeNestedDocsQuery(Query rewrite, Query originalQuery, IncludeNestedDocsQuery previousInstance) {
this.origParentQuery = originalQuery;
this.parentQuery = rewrite;
this.parentFilter = previousInstance.parentFilter;
setBoost(previousInstance.getBoost());
}
// For cloning
IncludeNestedDocsQuery(Query originalQuery, IncludeNestedDocsQuery previousInstance) {
this.origParentQuery = originalQuery;
this.parentQuery = originalQuery;
this.parentFilter = previousInstance.parentFilter;
}
@Override
public Weight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
return new IncludeNestedDocsWeight(this, parentQuery, parentQuery.createWeight(searcher, needsScores), parentFilter);
}
static class IncludeNestedDocsWeight extends Weight {
private final Query parentQuery;
private final Weight parentWeight;
private final BitDocIdSetFilter parentsFilter;
IncludeNestedDocsWeight(Query query, Query parentQuery, Weight parentWeight, BitDocIdSetFilter parentsFilter) {
super(query);
this.parentQuery = parentQuery;
this.parentWeight = parentWeight;
this.parentsFilter = parentsFilter;
}
@Override
public void extractTerms(Set<Term> terms) {
parentWeight.extractTerms(terms);
}
@Override
public void normalize(float norm, float topLevelBoost) {
parentWeight.normalize(norm, topLevelBoost);
}
@Override
public float getValueForNormalization() throws IOException {
return parentWeight.getValueForNormalization(); // this query is never boosted so just delegate...
}
@Override
public Scorer scorer(LeafReaderContext context, Bits acceptDocs) throws IOException {
final Scorer parentScorer = parentWeight.scorer(context, acceptDocs);
// no matches
if (parentScorer == null) {
return null;
}
BitDocIdSet parents = parentsFilter.getDocIdSet(context);
if (parents == null) {
// No matches
return null;
}
int firstParentDoc = parentScorer.nextDoc();
if (firstParentDoc == DocIdSetIterator.NO_MORE_DOCS) {
// No matches
return null;
}
return new IncludeNestedDocsScorer(this, parentScorer, parents, firstParentDoc);
}
@Override
public Explanation explain(LeafReaderContext context, int doc) throws IOException {
return null; //Query is used internally and not by users, so explain can be empty
}
}
static class IncludeNestedDocsScorer extends Scorer {
final Scorer parentScorer;
final BitSet parentBits;
int currentChildPointer = -1;
int currentParentPointer = -1;
int currentDoc = -1;
IncludeNestedDocsScorer(Weight weight, Scorer parentScorer, BitDocIdSet parentBits, int currentParentPointer) {
super(weight);
this.parentScorer = parentScorer;
this.parentBits = parentBits.bits();
this.currentParentPointer = currentParentPointer;
if (currentParentPointer == 0) {
currentChildPointer = 0;
} else {
this.currentChildPointer = this.parentBits.prevSetBit(currentParentPointer - 1);
if (currentChildPointer == -1) {
// no previous set parent, we delete from doc 0
currentChildPointer = 0;
} else {
currentChildPointer++; // we only care about children
}
}
currentDoc = currentChildPointer;
}
@Override
public Collection<ChildScorer> getChildren() {
return parentScorer.getChildren();
}
@Override
public int nextDoc() throws IOException {
if (currentParentPointer == NO_MORE_DOCS) {
return (currentDoc = NO_MORE_DOCS);
}
if (currentChildPointer == currentParentPointer) {
// we need to return the current parent as well, but prepare to return
// the next set of children
currentDoc = currentParentPointer;
currentParentPointer = parentScorer.nextDoc();
if (currentParentPointer != NO_MORE_DOCS) {
currentChildPointer = parentBits.prevSetBit(currentParentPointer - 1);
if (currentChildPointer == -1) {
// no previous set parent, just set the child to the current parent
currentChildPointer = currentParentPointer;
} else {
currentChildPointer++; // we only care about children
}
}
} else {
currentDoc = currentChildPointer++;
}
assert currentDoc != -1;
return currentDoc;
}
@Override
public int advance(int target) throws IOException {
if (target == NO_MORE_DOCS) {
return (currentDoc = NO_MORE_DOCS);
}
if (target == 0) {
return nextDoc();
}
if (target < currentParentPointer) {
currentDoc = currentParentPointer = parentScorer.advance(target);
if (currentParentPointer == NO_MORE_DOCS) {
return (currentDoc = NO_MORE_DOCS);
}
if (currentParentPointer == 0) {
currentChildPointer = 0;
} else {
currentChildPointer = parentBits.prevSetBit(currentParentPointer - 1);
if (currentChildPointer == -1) {
// no previous set parent, just set the child to 0 to delete all up to the parent
currentChildPointer = 0;
} else {
currentChildPointer++; // we only care about children
}
}
} else {
currentDoc = currentChildPointer++;
}
return currentDoc;
}
@Override
public float score() throws IOException {
return parentScorer.score();
}
@Override
public int freq() throws IOException {
return parentScorer.freq();
}
@Override
public int docID() {
return currentDoc;
}
@Override
public long cost() {
return parentScorer.cost();
}
}
@Override
public Query rewrite(IndexReader reader) throws IOException {
final Query parentRewrite = parentQuery.rewrite(reader);
if (parentRewrite != parentQuery) {
return new IncludeNestedDocsQuery(parentRewrite, parentQuery, this);
} else {
return this;
}
}
@Override
public String toString(String field) {
return "IncludeNestedDocsQuery (" + parentQuery.toString() + ")";
}
@Override
public boolean equals(Object _other) {
if (_other instanceof IncludeNestedDocsQuery) {
final IncludeNestedDocsQuery other = (IncludeNestedDocsQuery) _other;
return origParentQuery.equals(other.origParentQuery) && parentFilter.equals(other.parentFilter);
} else {
return false;
}
}
@Override
public int hashCode() {
final int prime = 31;
int hash = 1;
hash = prime * hash + origParentQuery.hashCode();
hash = prime * hash + parentFilter.hashCode();
return hash;
}
@Override
public Query clone() {
Query clonedQuery = origParentQuery.clone();
return new IncludeNestedDocsQuery(clonedQuery, this);
}
}
| |
/*
* 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.joda.time.DateTimeZone;
import org.junit.Before;
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;
@Before
public void setUp() {
DateTimeZone.setDefault(DateTimeZone.forOffsetMillis(DateTimeZone.UTC.getOffset(null)));
}
@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 = {"1", "-2345", "1234567", "1.1", "-23.45", ""};
Integer[] ia = {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 = {"1", "-2345", "123456789012345678", "1.1", "-23.45",
"21345345", "3422342", ""};
Long[] la = {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);
assertTrue(TestHelper.tupleEquals(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(TestHelper.bagEquals(b, convertedBag));
}
}
@Test
public void testBytesToMap() throws IOException
{
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());
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]";
Map<String, Object> m = ps.getLoadCaster().bytesToMap(s.getBytes());
assertNull(m);
s = "[a#b";
m = ps.getLoadCaster().bytesToMap(s.getBytes());
assertNull(m);
s = "[a#]";
m = ps.getLoadCaster().bytesToMap(s.getBytes());
Map.Entry<String, Object> entry = m.entrySet().iterator().next();
assertEquals("a", entry.getKey());
assertNull(entry.getValue());
s = "[#]";
m = ps.getLoadCaster().bytesToMap(s.getBytes());
assertNull(m);
s = "[a#}";
m = ps.getLoadCaster().bytesToMap(s.getBytes());
assertNull(m);
s = "[a#)";
m = ps.getLoadCaster().bytesToMap(s.getBytes());
assertNull(m);
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)]";
m = ps.getLoadCaster().bytesToMap(s.getBytes());
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));
}
}
| |
package org.waag.rdf.sesame;
import java.io.OutputStream;
import java.io.PrintStream;
import org.openrdf.model.Literal;
import org.openrdf.model.Value;
import org.openrdf.query.BindingSet;
import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.rio.RDFWriter;
import org.waag.rdf.ConfigurableRDFWriter;
import org.waag.rdf.QueryTask;
import org.waag.rdf.WriterConfig;
public abstract class AbstractQueryTask implements QueryTask {
// private static final Logger logger = LoggerFactory
// .getLogger(AbstractQueryTask.class);
private RepositoryConnection conn;
private OutputStream os;
private final QueryDefinition query;
private final WriterConfig config;
public AbstractQueryTask(RepositoryConnection conn, QueryDefinition query,
WriterConfig config, OutputStream os) {
this.conn = conn;
this.query = query;
this.config = config;
this.os = os;
}
@Override
public long getCount() throws UnsupportedOperationException,
MalformedQueryException, RepositoryException, QueryEvaluationException {
String countQuery = query.getCountQuery();
if (countQuery == null) {
throw new UnsupportedOperationException("No count query specified");
}
try {
TupleQuery tupleQuery = conn.prepareTupleQuery(
QueryLanguage.SPARQL, countQuery);
TupleQueryResult result = tupleQuery.evaluate();
if (result.hasNext()) {
BindingSet next = result.next();
if (next.hasBinding("count")) {
Value value = next.getValue("count");
if (value instanceof Literal) {
return ((Literal) value).longValue();
}
}
}
return 0;
} catch (MalformedQueryException e) {
throw e;
// } catch (Exception e) {
// e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (RepositoryException e) {
e.printStackTrace();
}
}
}
// return 0;
}
@Override
public Void call() throws Exception{
try {
String jsonpCallback = null;
PrintStream printStream = null;
if (config.isJSONP()) {
jsonpCallback = config.getJSONPCallback();
printStream = new PrintStream(os);
printStream.print(jsonpCallback + "(");
}
doQuery(query, config, conn, os);
if (config.isJSONP()) {
printStream.print(");");
}
// } catch (Exception e) {
// e.printStackTrace();
// logger.error(e.getMessage());
} finally {
try {
conn.close();
} catch (Exception e) {}
}
return null;
}
protected void applyConfig(RDFWriter writer) {
if (ConfigurableRDFWriter.class.isAssignableFrom(writer.getClass())) {
((ConfigurableRDFWriter) writer).setConfig(config);
}
}
protected abstract void doQuery(QueryDefinition query, WriterConfig config,
RepositoryConnection cxn, OutputStream os) throws Exception;
// protected BigdataSailQuery buildQuery() {
// AbstractQuery query = final AbstractQuery query = newQuery(cxn);
// applyBindings(query);
// return newQuery(cxn);
// }
// private SailQuery newQuery(SailConnection cxn) {
// final ASTContainer astContainer = ((BigdataParsedQuery) parsedQuery)
// .getASTContainer();
// final QueryType queryType = ((BigdataParsedQuery) parsedQuery)
// .getQueryType();
// switch (queryType) {
// case SELECT:
// return new BigdataSailTupleQuery(astContainer, cxn);
// case DESCRIBE:
// case CONSTRUCT:
// // return new BigdataSailGraphQuery(astContainer, cxn);
// TupleQuery tupleQuery = cxn.p
// return new SailGraphQuery(cxn);
// case ASK: {
// return new BigdataSailBooleanQuery(astContainer, cxn);
// }
// default:
// throw new RuntimeException("Unknown query type: " + queryType);
// }
// }
// public AbstractBigdataQueryTask(String namespace, long timestamp,
// String baseURI, ASTContainer astContainer, QueryType queryType,
// String defaultMIMEType, Charset charset, String defaultFileExtension,
// OutputStream os, RDFWriterConfig config) {
// super(namespace, timestamp, baseURI, astContainer, queryType,
// defaultMIMEType, charset, defaultFileExtension,
// new MockHttpServletRequest(), os);
// this.config = config;
// }
// public AbstractQueryTask(final String mimeType) {
// this.mimeType = mimeType;
// }
//
// abstract protected void doQuery(BigdataSailRepositoryConnection cxn,
// OutputStream os) throws Exception;
//
// public void setBinding(String key, Value value) {
// bindings.put(key, value);
// }
//
// protected AbstractQuery buildQuery(
// final BigdataSailRepositoryConnection cxn) {
// AbstractQuery query = setupQuery(cxn);
// applyBindings(query);
// return query;
// }
//
// final AbstractQuery setupQuery(final BigdataSailRepositoryConnection cxn)
// {
//
// // Note the begin time for the query.
// final long begin = System.nanoTime();
//
// final AbstractQuery query = newQuery(cxn);
//
// // Figure out the UUID under which the query will execute.
// final UUID queryId2 = setQueryId(((BigdataSailQuery) query)
// .getASTContainer());
//
// // Override query if data set protocol parameters were used.
// overrideDataset(query);
//
// if (analytic != null) {
//
// // Turn analytic query on/off as requested.
// // astContainer.getOriginalAST().setQueryHint(QueryHints.ANALYTIC,
// // analytic.toString());
// astContainer.setQueryHint(QueryHints.ANALYTIC,
// analytic.toString());
//
// }
//
// // Set the query object.
// this.sailQueryOrUpdate = query;
//
// // Set the IRunningQuery's UUID (volatile write!)
// this.queryId2 = queryId2;
//
// // Stuff it in the map of running queries.
// m_queries.put(queryId, new RunningQuery(queryId.longValue(),
// queryId2, begin, this));
//
// return query;
//
// }
//
// private void applyBindings(AbstractQuery query) {
// if (bindings.size() == 0) {
// return;
// }
// for (Entry<String, Value> binding : bindings.entrySet()) {
// query.setBinding(binding.getKey(), binding.getValue());
// }
// }
//
// protected void applyConfig(RDFWriter writer) {
// if (ConfigurableRDFWriter.class.isAssignableFrom(writer.getClass())) {
// ((ConfigurableRDFWriter) writer).setConfig(config);
// }
// }
}
| |
/*
* 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 br.com.devfest.norte;
import android.net.Uri;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import br.com.devfest.norte.util.ParserUtils;
public class Config {
// General configuration
// Is this an internal dogfood build?
public static final boolean IS_DOGFOOD_BUILD = false;
// Warning messages for dogfood build
public static final String DOGFOOD_BUILD_WARNING_TITLE = "Test build";
public static final String DOGFOOD_BUILD_WARNING_TEXT = "This is a test build.";
// Public data manifest URL
public static final String PROD_CONFERENCE_DATA_MANIFEST_URL = "";
// Manifest URL override for Debug (staging) builds:
public static final String MANIFEST_URL = PROD_CONFERENCE_DATA_MANIFEST_URL;
public static final String BOOTSTRAP_DATA_TIMESTAMP = "Sat, 01 Nov 2014 00:0:00 GMT";
// Conference hashtag
public static final String CONFERENCE_HASHTAG = "#devfestnorte";
// Patterns that, when absent from a hashtag, will trigger the addition of the
// CONFERENCE_HASHTAG on sharing snippets. Ex: "#Android" will be shared as "#io14 #Android",
// but "#iohunt" won't be modified.
public static final String CONFERENCE_HASHTAG_PREFIX = "#gdg";
// Hard-coded conference dates. This is hardcoded here instead of extracted from the conference
// data to avoid the Schedule UI breaking if some session is incorrectly set to a wrong date.
public static final int CONFERENCE_YEAR = 2014;
public static final long[][] CONFERENCE_DAYS = new long[][] {
// start and end of track 1
{ ParserUtils.parseTime("2014-11-01T08:00:00.000Z"),
ParserUtils.parseTime("2014-11-01T18:00:00.000Z") },
// start and end of track 2
{ ParserUtils.parseTime("2014-11-01T08:00:00.000Z"),
ParserUtils.parseTime("2014-11-01T18:00:00.000Z") }
};
public static final TimeZone CONFERENCE_TIMEZONE = TimeZone.getTimeZone("America/Sao_Paulo");
public static final long CONFERENCE_START_MILLIS = CONFERENCE_DAYS[0][0];
public static final long CONFERENCE_END_MILLIS = CONFERENCE_DAYS[CONFERENCE_DAYS.length-1][1];
// shorthand for some units of time
public static final long SECOND_MILLIS = 1000;
public static final long MINUTE_MILLIS = 60 * SECOND_MILLIS;
public static final long HOUR_MILLIS = 60 * MINUTE_MILLIS;
public static final long DAY_MILLIS = 24 * HOUR_MILLIS;
// OAuth 2.0 related config
public static final String APP_NAME = "GDGDevFestNorte";
public static final String API_KEY = "";
// Announcements
public static final String ANNOUNCEMENTS_PLUS_ID = "";
// YouTube API config
public static final String YOUTUBE_API_KEY = "";
// YouTube share URL
public static final String YOUTUBE_SHARE_URL_PREFIX = "http://youtu.be/";
// Live stream captions config
public static final String LIVESTREAM_CAPTIONS_DARK_THEME_URL_PARAM = "&theme=dark";
// Conference public WiFi AP parameters
public static final String WIFI_SSID = "";
public static final String WIFI_PASSPHRASE = "";
// GCM config
public static final String GCM_SERVER_PROD_URL = "";
public static final String GCM_SERVER_URL = "";
// the GCM sender ID is the ID of the app in Google Cloud Console
public static final String GCM_SENDER_ID = "";
// The registration api KEY in the gcm server (configured in the GCM
// server's AuthHelper.java file)
public static final String GCM_API_KEY = "";
// When do we start to offer to set up the user's wifi?
public static final long WIFI_SETUP_OFFER_START =
CONFERENCE_START_MILLIS - 30 * DAY_MILLIS; // 3 days before conference
// Format of the youtube link to a Video Library video
public static final String VIDEO_LIBRARY_URL_FMT = "https://www.youtube.com/watch?v=%s";
// Fallback URL to get a youtube video thumbnail in case one is not provided in the data
// (normally it should, but this is a safety fallback if it doesn't)
public static final String VIDEO_LIBRARY_FALLBACK_THUMB_URL_FMT =
"http://img.youtube.com/vi/%s/default.jpg";
// Link to Google I/O Extended events presented in Explore screen
public static final String IO_EXTENDED_LINK = "http://www.google.com/events/io/io-extended";
// 2014-07-25: Time of expiration for experts directory data.
// Represented as elapsed milliseconds since the epoch.
public static final long EXPERTS_DIRECTORY_EXPIRATION = 1406214000000L;
/**
* Check if the experts directory data expired.
*
* @return True if the experts directory data expired and should be removed.
*/
public static boolean hasExpertsDirectoryExpired() {
return EXPERTS_DIRECTORY_EXPIRATION < System.currentTimeMillis();
}
// URL to use for resolving NearbyDevice metadata.
public static final String METADATA_URL =
// "http://url-caster.appspot.com/resolve-scan"
rep("http://example-caster", "example", "url") + "."
+ rep("example.com", "example", "appspot")
+ rep("/resolve-link", "link", "scan");
// How long before a session we display "This session starts in N minutes." in the
// Session details page.
public static final long HINT_TIME_BEFORE_SESSION = 60 * MINUTE_MILLIS; // 60 min
// how long before the end of a session the user can give feedback
public static final long FEEDBACK_MILLIS_BEFORE_SESSION_END = 15 * MINUTE_MILLIS; // 15min
// Auto sync interval. Shouldn't be too small, or it might cause battery drain.
public static final long AUTO_SYNC_INTERVAL_LONG_BEFORE_CONFERENCE = 6 * HOUR_MILLIS;
public static final long AUTO_SYNC_INTERVAL_AROUND_CONFERENCE = 2 * HOUR_MILLIS;
public static final long AUTO_SYNC_INTERVAL_AFTER_CONFERENCE = 12 * HOUR_MILLIS;
// How many days before the conference we consider to be "around the conference date"
// for purposes of sync interval (at which point the AUTO_SYNC_INTERVAL_AROUND_CONFERENCE
// interval kicks in)
public static final long AUTO_SYNC_AROUND_CONFERENCE_THRESH = 3 * DAY_MILLIS;
// Minimum interval between two consecutive syncs. This is a safety mechanism to throttle
// syncs in case conference data gets updated too often or something else goes wrong that
// causes repeated syncs.
public static final long MIN_INTERVAL_BETWEEN_SYNCS = 10 * MINUTE_MILLIS;
// If data is not synced in this much time, we show the "data may be stale" warning
public static final long STALE_DATA_THRESHOLD_NOT_DURING_CONFERENCE = 2 * DAY_MILLIS;
public static final long STALE_DATA_THRESHOLD_DURING_CONFERENCE = 12 * HOUR_MILLIS;
// How long we snooze the stale data notification for after the user has acted on it
// (to keep from showing it repeatedly and being annoying)
public static final long STALE_DATA_WARNING_SNOOZE = 10 * MINUTE_MILLIS;
// Package name for the I/O Hunt game
public static final String IO_HUNT_PACKAGE_NAME = "com.google.wolff.androidhunt2";
// Play store URL prefix
public static final String PLAY_STORE_URL_PREFIX
= "https://play.google.com/store/apps/details?id=";
// Known session tags that induce special behaviors
public interface Tags {
// tag that indicates a session is a live session
public static final String SESSIONS = "TYPE_SESSIONS";
// the tag category that we use to group sessions together when displaying them
public static final String SESSION_GROUPING_TAG_CATEGORY = "TYPE";
// tag categories
public static final String CATEGORY_THEME = "THEME";
public static final String CATEGORY_TOPIC = "TOPIC";
public static final String CATEGORY_TYPE = "TYPE";
public static final Map<String, Integer> CATEGORY_DISPLAY_ORDERS
= new HashMap<String, Integer>();
public static final String SPECIAL_KEYNOTE = "FLAG_KEYNOTE";
public static final String[] EXPLORE_CATEGORIES =
{ CATEGORY_THEME, CATEGORY_TOPIC, CATEGORY_TYPE };
public static final int[] EXPLORE_CATEGORY_ALL_STRING = {
R.string.all_themes, R.string.all_topics, R.string.all_types
};
public static final int[] EXPLORE_CATEGORY_TITLE = {
R.string.themes, R.string.topics, R.string.types
};
}
static {
Tags.CATEGORY_DISPLAY_ORDERS.put(Tags.CATEGORY_THEME, 0);
Tags.CATEGORY_DISPLAY_ORDERS.put(Tags.CATEGORY_TOPIC, 1);
Tags.CATEGORY_DISPLAY_ORDERS.put(Tags.CATEGORY_TYPE, 2);
}
// Values for the EventPoint feedback API. Sync happens at the same time as schedule sync,
// and before that values are stored locally in the database.
public static final String FEEDBACK_API_CODE = "";
public static final String FEEDBACK_URL = "";
public static final String FEEDBACK_API_KEY = "";
public static final String FEEDBACK_DUMMY_REGISTRANT_ID = "";
public static final String FEEDBACK_SURVEY_ID = "";
// URL prefix for web links to session pages
public static final Uri SESSION_DETAIL_WEB_URL_PREFIX
= Uri.parse("https://www.google.com/events/io/schedule/session/");
// Profile URLs for simulated badge reads for the debug feature.
public static final String[] DEBUG_SIMULATED_BADGE_URLS = new String[] {};
private static String piece(String s, char start, char end) {
int startIndex = s.indexOf(start), endIndex = s.indexOf(end);
return s.substring(startIndex + 1, endIndex);
}
private static String piece(String s, char start) {
int startIndex = s.indexOf(start);
return s.substring(startIndex + 1);
}
private static String rep(String s, String orig, String replacement) {
return s.replaceAll(orig, replacement);
}
}
| |
/**
* Copyright (C) 2006-2013 phloc systems
* http://www.phloc.com
* office[at]phloc[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.phloc.commons.io.streams;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.charset.Charset;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.WillClose;
import javax.annotation.WillNotClose;
import com.phloc.commons.IHasSize;
import com.phloc.commons.annotations.ReturnsMutableCopy;
import com.phloc.commons.charset.CharsetManager;
import com.phloc.commons.collections.ArrayHelper;
import com.phloc.commons.string.ToStringGenerator;
/**
* A non-synchronized copy of the class {@link java.io.ByteArrayOutputStream}.
*
* @author Philip Helger
* @see java.io.ByteArrayOutputStream
*/
public class NonBlockingByteArrayOutputStream extends OutputStream implements IHasSize, Serializable
{
/**
* The buffer where data is stored.
*/
protected byte [] m_aBuf;
/**
* The number of valid bytes in the buffer.
*/
protected int m_nCount;
/**
* Creates a new byte array output stream. The buffer capacity is initially 32
* bytes, though its size increases if necessary.
*/
public NonBlockingByteArrayOutputStream ()
{
this (32);
}
/**
* Creates a new byte array output stream, with a buffer capacity of the
* specified size, in bytes.
*
* @param nSize
* the initial size.
* @exception IllegalArgumentException
* if size is negative.
*/
public NonBlockingByteArrayOutputStream (@Nonnegative final int nSize)
{
if (nSize < 0)
throw new IllegalArgumentException ("Negative initial size: " + nSize);
m_aBuf = new byte [nSize];
}
@Nonnull
private static byte [] _enlarge (@Nonnull final byte [] aBuf, @Nonnegative final int nNewSize)
{
final byte [] ret = new byte [nNewSize];
System.arraycopy (aBuf, 0, ret, 0, aBuf.length);
return ret;
}
/**
* Writes the specified byte to this byte array output stream.
*
* @param b
* the byte to be written.
*/
@Override
public void write (final int b)
{
final int nNewCount = m_nCount + 1;
if (nNewCount > m_aBuf.length)
m_aBuf = _enlarge (m_aBuf, Math.max (m_aBuf.length << 1, nNewCount));
m_aBuf[m_nCount] = (byte) b;
m_nCount = nNewCount;
}
/*
* Just overloaded to avoid the IOException in the generic OutputStream.write
* method.
*/
@Override
public void write (@Nonnull final byte [] aBuf)
{
write (aBuf, 0, aBuf.length);
}
/**
* Writes <code>nLen</code> bytes from the specified byte array starting at
* offset <code>nOfs</code> to this byte array output stream.
*
* @param aBuf
* the data.
* @param nOfs
* the start offset in the data.
* @param nLen
* the number of bytes to write.
*/
@Override
public void write (@Nonnull final byte [] aBuf, final int nOfs, final int nLen)
{
if (aBuf == null)
throw new NullPointerException ("buf");
if (nOfs < 0 || nLen < 0 || (nOfs + nLen) > aBuf.length)
throw new IllegalArgumentException ("ofs:" + nOfs + ";len=" + nLen + ";bufLen=" + aBuf.length);
if (nLen > 0)
{
final int nNewCount = m_nCount + nLen;
if (nNewCount > m_aBuf.length)
m_aBuf = _enlarge (m_aBuf, Math.max (m_aBuf.length << 1, nNewCount));
System.arraycopy (aBuf, nOfs, m_aBuf, m_nCount, nLen);
m_nCount = nNewCount;
}
}
/**
* Writes the complete contents of this byte array output stream to the
* specified output stream argument, as if by calling the output stream's
* write method using <code>out.write(buf, 0, count)</code>. The content of
* this stream is not altered by calling this method.
*
* @param aOS
* the output stream to which to write the data. May not be
* <code>null</code>.
* @exception IOException
* if an I/O error occurs.
*/
public void writeTo (@Nonnull @WillNotClose final OutputStream aOS) throws IOException
{
aOS.write (m_aBuf, 0, m_nCount);
}
/**
* Writes the complete contents of this byte array output stream to the
* specified output stream argument, as if by calling the output stream's
* write method using <code>out.write(buf, 0, count)</code> and afterwards
* closes the passed output stream. The content of this stream is not altered
* by calling this method.
*
* @param aOS
* the output stream to which to write the data. May not be
* <code>null</code>.
* @exception IOException
* if an I/O error occurs.
*/
public void writeToAndClose (@Nonnull @WillClose final OutputStream aOS) throws IOException
{
try
{
writeTo (aOS);
}
finally
{
StreamUtils.close (aOS);
}
}
/**
* Resets the <code>count</code> field of this byte array output stream to
* zero, so that all currently accumulated output in the output stream is
* discarded. The output stream can be used again, reusing the already
* allocated buffer space.
*/
public void reset ()
{
m_nCount = 0;
}
/**
* Creates a newly allocated byte array. Its size is the current size of this
* output stream and the valid contents of the buffer have been copied into
* it.
*
* @return the current contents of this output stream, as a byte array.
*/
@Nonnull
@ReturnsMutableCopy
public byte [] toByteArray ()
{
return ArrayHelper.getCopy (m_aBuf, m_nCount);
}
/**
* Get the byte at the specified index
*
* @param nIndex
* The index to use. Must be ≥ 0 and < count
* @return The byte at the specified position
*/
public byte getByteAt (@Nonnegative final int nIndex)
{
if (nIndex < 0 || nIndex >= m_nCount)
throw new IllegalArgumentException ("Illegal index passed!");
return m_aBuf[nIndex];
}
/**
* Returns the current size of the buffer.
*
* @return the value of the <code>count</code> field, which is the number of
* valid bytes in this output stream.
*/
@Nonnegative
public int size ()
{
return m_nCount;
}
/**
* @return The number of pre-allocated bytes. Always ≥ 0.
*/
@Nonnegative
public int getBufferSize ()
{
return m_aBuf.length;
}
public boolean isEmpty ()
{
return m_nCount == 0;
}
public boolean isNotEmpty ()
{
return m_nCount > 0;
}
public boolean startsWith (@Nonnull final byte [] aBytes)
{
return startsWith (aBytes, 0, aBytes.length);
}
public boolean startsWith (@Nonnull final byte [] aBytes, @Nonnegative final int nOfs, @Nonnegative final int nLen)
{
if (m_nCount < nLen)
return false;
for (int i = 0; i < nLen; ++i)
if (m_aBuf[i] != aBytes[nOfs + i])
return false;
return true;
}
/**
* Converts the buffer's contents into a string by decoding the bytes using
* the specified {@link java.nio.charset.Charset charsetName}. The length of
* the new <tt>String</tt> is a function of the charset, and hence may not be
* equal to the length of the byte array.
* <p>
* This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string. The
* {@link java.nio.charset.CharsetDecoder} class should be used when more
* control over the decoding process is required.
*
* @param sCharset
* the name of a supported {@linkplain java.nio.charset.Charset
* </code>charset<code>}
* @return String decoded from the buffer's contents.
*/
@Nonnull
@Deprecated
public String getAsString (@Nonnull final String sCharset)
{
return CharsetManager.getAsString (m_aBuf, 0, m_nCount, sCharset);
}
/**
* Converts the buffer's contents into a string by decoding the bytes using
* the specified {@link java.nio.charset.Charset charsetName}. The length of
* the new <tt>String</tt> is a function of the charset, and hence may not be
* equal to the length of the byte array.
* <p>
* This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string. The
* {@link java.nio.charset.CharsetDecoder} class should be used when more
* control over the decoding process is required.
*
* @param nLength
* The number of bytes to be converted to a String. Must be ≥ 0.
* @param sCharset
* the name of a supported {@linkplain java.nio.charset.Charset
* </code>charset<code>}
* @return String decoded from the buffer's contents.
*/
@Nonnull
@Deprecated
public String getAsString (@Nonnegative final int nLength, @Nonnull final String sCharset)
{
if (nLength < 0 || nLength > m_nCount)
throw new IllegalArgumentException ("Invalid length: " + nLength);
return CharsetManager.getAsString (m_aBuf, 0, nLength, sCharset);
}
/**
* Converts the buffer's contents into a string by decoding the bytes using
* the specified {@link java.nio.charset.Charset charsetName}. The length of
* the new <tt>String</tt> is a function of the charset, and hence may not be
* equal to the length of the byte array.
* <p>
* This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string. The
* {@link java.nio.charset.CharsetDecoder} class should be used when more
* control over the decoding process is required.
*
* @param nIndex
* The start index to use
* @param nLength
* The number of bytes to be converted to a String. Must be ≥ 0.
* @param sCharset
* the name of a supported {@linkplain java.nio.charset.Charset
* </code>charset<code>}
* @return String decoded from the buffer's contents.
*/
@Nonnull
@Deprecated
public String getAsString (@Nonnegative final int nIndex,
@Nonnegative final int nLength,
@Nonnull final String sCharset)
{
if (nIndex < 0)
throw new IllegalArgumentException ("Invalid index: " + nIndex);
if (nLength < 0 || nLength > m_nCount)
throw new IllegalArgumentException ("Invalid length: " + nLength);
return CharsetManager.getAsString (m_aBuf, nIndex, nLength, sCharset);
}
/**
* Converts the buffer's contents into a string by decoding the bytes using
* the specified {@link java.nio.charset.Charset charsetName}. The length of
* the new <tt>String</tt> is a function of the charset, and hence may not be
* equal to the length of the byte array.
* <p>
* This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string. The
* {@link java.nio.charset.CharsetDecoder} class should be used when more
* control over the decoding process is required.
*
* @param aCharset
* the charset to be used. May not be <code>null</code>.
* @return String decoded from the buffer's contents.
*/
@Nonnull
public String getAsString (@Nonnull final Charset aCharset)
{
return CharsetManager.getAsString (m_aBuf, 0, m_nCount, aCharset);
}
/**
* Converts the buffer's contents into a string by decoding the bytes using
* the specified {@link java.nio.charset.Charset charsetName}. The length of
* the new <tt>String</tt> is a function of the charset, and hence may not be
* equal to the length of the byte array.
* <p>
* This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string. The
* {@link java.nio.charset.CharsetDecoder} class should be used when more
* control over the decoding process is required.
*
* @param nLength
* The number of bytes to be converted to a String. Must be ≥ 0.
* @param aCharset
* the charset to be used. May not be <code>null</code>.
* @return String decoded from the buffer's contents.
*/
@Nonnull
public String getAsString (@Nonnegative final int nLength, @Nonnull final Charset aCharset)
{
if (nLength < 0 || nLength > m_nCount)
throw new IllegalArgumentException ("Invalid length: " + nLength);
return CharsetManager.getAsString (m_aBuf, 0, nLength, aCharset);
}
/**
* Converts the buffer's contents into a string by decoding the bytes using
* the specified {@link java.nio.charset.Charset charsetName}. The length of
* the new <tt>String</tt> is a function of the charset, and hence may not be
* equal to the length of the byte array.
* <p>
* This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string. The
* {@link java.nio.charset.CharsetDecoder} class should be used when more
* control over the decoding process is required.
*
* @param nIndex
* The start index to use
* @param nLength
* The number of bytes to be converted to a String. Must be ≥ 0.
* @param aCharset
* the charset to be used. May not be <code>null</code>.
* @return String decoded from the buffer's contents.
*/
@Nonnull
public String getAsString (@Nonnegative final int nIndex,
@Nonnegative final int nLength,
@Nonnull final Charset aCharset)
{
if (nIndex < 0)
throw new IllegalArgumentException ("Invalid index: " + nIndex);
if (nLength < 0 || nLength > m_nCount)
throw new IllegalArgumentException ("Invalid length: " + nLength);
return CharsetManager.getAsString (m_aBuf, nIndex, nLength, aCharset);
}
/**
* Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in this
* class can be called after the stream has been closed without generating an
* <tt>IOException</tt>.
* <p>
*/
@Override
public void close ()
{}
@Override
public String toString ()
{
return new ToStringGenerator (this).append ("buf#", ArrayHelper.getSize (m_aBuf))
.append ("size", m_nCount)
.toString ();
}
}
| |
/*
* $Id$
*/
/*
Copyright (c) 2000-2006 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
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
STANFORD UNIVERSITY 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.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.devtools.plugindef;
import java.util.*;
import org.lockss.daemon.*;
import org.lockss.util.Logger;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
/**
* <p>Title: </p>
* <p>@author Rebecca Illowsky</p>
* <p>@version 0.7</p>
* <p> </p>
* not attributable
*
*/
public class CrawlWindowEditor extends JDialog implements EDPEditor{
private static final int ACTION = 0;
private static final int FROM_HOUR = 1;
private static final int FROM_MINUTE = 2;
private static final int FROM_AMPM = 3;
private static final int TO_HOUR = 4;
private static final int TO_MINUTE = 5;
private static final int TO_AMPM = 6;
private static final int TIMEZONE = 7;
JPanel windowsPanel = new JPanel();
BorderLayout borderLayout1 = new BorderLayout();
JPanel buttonPanel = new JPanel();
// JButton deleteButton = new JButton();
JButton okButton = new JButton();
JButton cancelButton = new JButton();
CrawlWindowModel m_model = new CrawlWindowModel();
JTable windowsTable = new JTable(m_model);
// JButton addButton = new JButton();
JComboBox m_actionBox = new JComboBox(CrawlWindowTemplate.WINDOW_ACTION_STRINGS);
JComboBox m_fromHourBox = new JComboBox(CrawlWindowTemplate.WINDOW_HOUR_STRINGS);
JComboBox m_fromMinuteBox = new JComboBox(CrawlWindowTemplate.WINDOW_MINUTE_STRINGS);
JComboBox m_fromAmPmBox = new JComboBox(CrawlWindowTemplate.WINDOW_AMPM_STRINGS);
JComboBox m_toHourBox = new JComboBox(CrawlWindowTemplate.WINDOW_HOUR_STRINGS);
JComboBox m_toMinuteBox = new JComboBox(CrawlWindowTemplate.WINDOW_MINUTE_STRINGS);
JComboBox m_toAmPmBox = new JComboBox(CrawlWindowTemplate.WINDOW_AMPM_STRINGS);
JComboBox m_timezoneBox = new JComboBox(CrawlWindowTemplate.WINDOW_TIMEZONE_STRINGS);
protected static Logger logger = Logger.getLogger("CrawlWindowEditor");
// JButton upButton = new JButton();
//JButton dnButton = new JButton();
private Frame m_frame;
JScrollPane windowsScrollPane = new JScrollPane();
public CrawlWindowEditor(Frame frame, String title, boolean modal) {
super(frame, title, modal);
try {
jbInit();
pack();
}
catch (Exception exc) {
String logMessage = "Could not set up the crawl window editor";
logger.critical(logMessage, exc);
JOptionPane.showMessageDialog(frame,
logMessage,
"Crawl Window Editor",
JOptionPane.ERROR_MESSAGE);
}
}
public CrawlWindowEditor(Frame frame) {
this(frame, "Crawl Window Editor", false);
m_frame = frame;
}
private void jbInit() throws Exception {
windowsPanel.setLayout(borderLayout1);
// deleteButton.setText("Delete");
// deleteButton.addActionListener(new CrawlWindowEditor_deleteButton_actionAdapter(this));
okButton.setText("OK");
okButton.addActionListener(new CrawlWindowEditor_okButton_actionAdapter(this));
cancelButton.setText("Cancel");
cancelButton.addActionListener(new CrawlWindowEditor_cancelButton_actionAdapter(this));
windowsTable.setBorder(BorderFactory.createRaisedBevelBorder());
windowsTable.setRowHeight(20);
windowsTable.setModel(m_model);
windowsPanel.setMinimumSize(new Dimension(150, 50));
windowsPanel.setPreferredSize(new Dimension(525, 100));
buttonPanel.setMinimumSize(new Dimension(150, 34));
buttonPanel.setPreferredSize(new Dimension(525, 40));
// addButton.setText("Add");
// addButton.addActionListener(new CrawlWindowEditor_addButton_actionAdapter(this));
// upButton.setText("Up");
// upButton.addActionListener(new CrawlWindowEditor_upButton_actionAdapter(this));
// dnButton.setText("Down");
// dnButton.addActionListener(new CrawlWindowEditor_dnButton_actionAdapter(this));
getContentPane().add(windowsPanel);
windowsPanel.add(windowsScrollPane, BorderLayout.CENTER);
windowsPanel.add(buttonPanel, BorderLayout.SOUTH);
windowsScrollPane.getViewport().add(windowsTable, null);
// buttonPanel.add(upButton, null);
// buttonPanel.add(dnButton, null);
// buttonPanel.add(addButton, null);
// buttonPanel.add(deleteButton, null);
buttonPanel.add(okButton, null);
buttonPanel.add(cancelButton, null);
}
/*
void deleteButton_actionPerformed(ActionEvent e) {
CrawlWindowModel model = (CrawlWindowModel) windowsTable.getModel();
int row = windowsTable.getSelectedRow();
model.removeRowData(row);
}
void addButton_actionPerformed(ActionEvent e) {
CrawlWindowModel model = (CrawlWindowModel) windowsTable.getModel();
int row = windowsTable.getSelectedRow();
model.addNewRow(row);
}
*/
void okButton_actionPerformed(ActionEvent e) {
CrawlWindowModel model = (CrawlWindowModel) windowsTable.getModel();
model.updateData();
setVisible(false);
}
void cancelButton_actionPerformed(ActionEvent e) {
setVisible(false);
}
/*
void dnButton_actionPerformed(ActionEvent e) {
int row = windowsTable.getSelectedRow();
CrawlWindowModel model = (CrawlWindowModel) windowsTable.getModel();
model.moveData(row, row + 1);
}
void upButton_actionPerformed(ActionEvent e) {
int row = windowsTable.getSelectedRow();
CrawlWindowModel model = (CrawlWindowModel) windowsTable.getModel();
model.moveData(row, row - 1);
}*/
/**
* setCellData
*
* @param data DPCellData
*/
public void setCellData(EDPCellData data) {
m_model.setData(data);
TableColumn col = windowsTable.getColumnModel().getColumn(ACTION);
col.setCellEditor(new DefaultCellEditor(m_actionBox));
col = windowsTable.getColumnModel().getColumn(FROM_HOUR);
col.setCellEditor(new DefaultCellEditor(m_fromHourBox));
col = windowsTable.getColumnModel().getColumn(FROM_MINUTE);
col.setCellEditor(new DefaultCellEditor(m_fromMinuteBox));
col = windowsTable.getColumnModel().getColumn(FROM_AMPM);
col.setCellEditor(new DefaultCellEditor(m_fromAmPmBox));
col = windowsTable.getColumnModel().getColumn(TO_HOUR);
col.setCellEditor(new DefaultCellEditor(m_toHourBox));
col = windowsTable.getColumnModel().getColumn(TO_MINUTE);
col.setCellEditor(new DefaultCellEditor(m_toMinuteBox));
col = windowsTable.getColumnModel().getColumn(TO_AMPM);
col.setCellEditor(new DefaultCellEditor(m_toAmPmBox));
col = windowsTable.getColumnModel().getColumn(TIMEZONE);
col.setCellEditor(new DefaultCellEditor(m_timezoneBox));
}
class CrawlWindowModel extends AbstractTableModel {
String[] m_columns = {"Action",
"From",
"",
"AM/PM",
"To",
"",
"AM/PM",
"Timezone"};
EDPCellData m_data;
CrawlWindow m_window;
Vector m_tableData;
CrawlWindowModel() {
m_tableData = new Vector();
}
void setData(EDPCellData data) {
m_data = data;
m_window = data.getPlugin().getAuCrawlWindowSer();
m_tableData.clear();
Object[] entry;
entry = new Object[m_columns.length];
if(m_window!=null){
if(m_window instanceof CrawlWindows.Interval){
entry[ACTION] = CrawlWindowTemplate.WINDOW_ACTION_STRINGS[0];
}
else if(m_window instanceof CrawlWindows.Not){
entry[ACTION] = CrawlWindowTemplate.WINDOW_ACTION_STRINGS[1];
m_window = ((CrawlWindows.Not)m_window).getCrawlWindow();
}
else{
entry[ACTION] = CrawlWindowTemplate.WINDOW_ACTION_STRINGS[0];
}
Calendar start= ((CrawlWindows.Interval)m_window).getStartCalendar();
Calendar end = ((CrawlWindows.Interval)m_window).getEndCalendar();
TimeZone timezone = ((CrawlWindows.Interval)m_window).getTimeZone();
int startHour = start.get(Calendar.HOUR_OF_DAY);
if(startHour > 12){
startHour -=12;
if(startHour == 0)
startHour = 12;
entry[FROM_AMPM] = CrawlWindowTemplate.WINDOW_AMPM_STRINGS[1];
}
else{
entry[FROM_AMPM] = CrawlWindowTemplate.WINDOW_AMPM_STRINGS[0];
}
entry[FROM_HOUR] = startHour + "";
entry[FROM_MINUTE] = CrawlWindowTemplate.WINDOW_MINUTE_STRINGS[start.get(Calendar.MINUTE)];
int endHour = end.get(Calendar.HOUR_OF_DAY);
if(endHour > 12){
endHour -=12;
if(endHour == 0)
endHour = 12;
entry[TO_AMPM] = CrawlWindowTemplate.WINDOW_AMPM_STRINGS[1];
}
else{
entry[TO_AMPM] = CrawlWindowTemplate.WINDOW_AMPM_STRINGS[0];
}
entry[TO_HOUR] = endHour + "";
entry[TO_MINUTE] = CrawlWindowTemplate.WINDOW_MINUTE_STRINGS[end.get(Calendar.MINUTE)];
entry[TIMEZONE] = timezone.getID();
}
else{
entry[ACTION] = CrawlWindowTemplate.WINDOW_ACTION_STRINGS[0];
entry[FROM_HOUR] = CrawlWindowTemplate.WINDOW_HOUR_STRINGS[0];
entry[FROM_MINUTE] = CrawlWindowTemplate.WINDOW_MINUTE_STRINGS[0];
entry[FROM_AMPM] = CrawlWindowTemplate.WINDOW_AMPM_STRINGS[0];
entry[TO_HOUR] = CrawlWindowTemplate.WINDOW_HOUR_STRINGS[11];
entry[TO_MINUTE] = CrawlWindowTemplate.WINDOW_MINUTE_STRINGS[59];
entry[TO_AMPM] = CrawlWindowTemplate.WINDOW_AMPM_STRINGS[1];
entry[TIMEZONE] = CrawlWindowTemplate.WINDOW_TIMEZONE_STRINGS[0];
}
m_tableData.add(entry);
}
void updateData() {
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
TimeZone timezone;
Object[] entry = (Object[])m_tableData.elementAt(0);
boolean crawl = (entry[ACTION].toString() == "Crawl");
int startHour = Integer.parseInt(entry[FROM_HOUR].toString());
if(entry[FROM_AMPM].toString() == "PM")
startHour += 12;
start.set(Calendar.HOUR_OF_DAY,startHour);
start.set(Calendar.MINUTE,Integer.parseInt(entry[FROM_MINUTE].toString().substring(1)));
int endHour = Integer.parseInt(entry[TO_HOUR].toString());
if(entry[TO_AMPM].toString() == "PM")
endHour += 12;
end.set(Calendar.HOUR_OF_DAY,endHour);
end.set(Calendar.MINUTE,Integer.parseInt(entry[TO_MINUTE].toString().substring(1)));
timezone = TimeZone.getTimeZone(entry[7].toString());
CrawlWindows.Interval window = new CrawlWindows.Interval(start,end,CrawlWindows.TIME,timezone);
if(crawl)
m_data.getPlugin().setAuCrawlWindowSer(window);
else
m_data.getPlugin().setAuCrawlWindowSer(new CrawlWindows.Not(window));
}
/**
* getColumnCount
*
* @return int
*/
public int getColumnCount() {
return m_columns.length;
}
public String getColumnName(int col) {
return m_columns[col];
}
/**
* getRowCount
*
* @return int
*/
public int getRowCount() {
return m_tableData.size();
}
/**
* getValueAt
*
* @param rowIndex int
* @param columnIndex int
* @return Object
*/
public Object getValueAt(int rowIndex, int columnIndex) {
return ((Object[])m_tableData.elementAt(rowIndex))[columnIndex];
}
public boolean isCellEditable(int row, int col) {
return true;
}
public void setValueAt(Object value, int row, int col) {
if(m_tableData.size() > row && row >=0) {
Object[] data = (Object[]) m_tableData.get(row);
data[col] = value;
}
fireTableCellUpdated(row, col);
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public void addRowData(int row , Object[] data) {
/* if(row < 0) {
m_tableData.add(data);
}
else {
m_tableData.add(row, data);
}
fireTableDataChanged();*/
}
/**
* addRow
*
* @param row int
*/
private void addNewRow(int row) {
}
public void removeRowData(int row) {
/* if(m_tableData.size() > row && row >=0) {
m_tableData.remove(row);
}
fireTableDataChanged();*/
}
/**
* moveData
*
* @param curRow Old row for the data
* @param newRow New row for the data
*/
private void moveData(int curRow, int newRow) {
/* int lastRow = m_tableData.size() -1;
if(curRow >=0 && curRow <= lastRow && newRow >=0 &&
newRow <= lastRow) {
Object[] curData = (Object[])m_tableData.elementAt(curRow);
m_tableData.removeElementAt(curRow);
m_tableData.insertElementAt(curData, newRow);
fireTableDataChanged();
}*/
}
}
class CrawlWindowCellEditor
extends AbstractCellEditor
implements TableCellEditor, ActionListener, ChangeListener {
static final String CMD_STRING = "Edit";
JButton m_button;
PrintfEditor m_editor;
EDPCellData m_data;
CrawlWindowCellEditor() {
m_button = makeButton(CMD_STRING);
}
public Object getCellEditorValue() {
return m_data.getData();
}
/**
* getTableCellEditorComponent
*
* @param table JTable
* @param value Object
* @param isSelected boolean
* @param row int
* @param column int
* @return Component
*/
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row,
int column) {
Object obj = m_model.getValueAt(row, column);
CrawlWindowTemplate template = (CrawlWindowTemplate) obj;
m_data = new EDPCellData(m_model.m_data.getPlugin(),
m_model.m_data.getKey(),
template,
null);
m_data.addChangeListener(this);
m_editor.setCellData(m_data);
Rectangle r = table.getCellRect(row, column, true);
Dimension dlgSize = m_editor.getPreferredSize();
m_editor.setLocation(r.x + dlgSize.width, r.y + dlgSize.height);
m_editor.pack();
m_button.setText(template.getTemplateString());
/* position dialog */
return m_button;
}
/**
* actionPerformed
*
* @param e ActionEvent
*/
public void actionPerformed(ActionEvent e) {
if (CMD_STRING.equals(e.getActionCommand())) {
m_editor.setVisible(true);
fireEditingStopped();
}
}
JButton makeButton(String command) {
JButton button = new JButton();
button.setActionCommand(command);
button.addActionListener(this);
button.setBorderPainted(false);
return button;
}
/**
* stateChanged
*
* @param e ChangeEvent
*/
public void stateChanged(ChangeEvent e) {
m_data = null;
m_model.fireTableDataChanged();
}
}
}
/*
class CrawlWindowEditor_deleteButton_actionAdapter implements java.awt.event.ActionListener {
CrawlWindowEditor adaptee;
CrawlWindowEditor_deleteButton_actionAdapter(CrawlWindowEditor adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.deleteButton_actionPerformed(e);
}
}
*/
class CrawlWindowEditor_okButton_actionAdapter implements java.awt.event.ActionListener {
CrawlWindowEditor adaptee;
CrawlWindowEditor_okButton_actionAdapter(CrawlWindowEditor adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.okButton_actionPerformed(e);
}
}
class CrawlWindowEditor_cancelButton_actionAdapter implements java.awt.event.ActionListener {
CrawlWindowEditor adaptee;
CrawlWindowEditor_cancelButton_actionAdapter(CrawlWindowEditor adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.cancelButton_actionPerformed(e);
}
}
/*
class CrawlWindowEditor_addButton_actionAdapter implements java.awt.event.ActionListener {
CrawlWindowEditor adaptee;
CrawlWindowEditor_addButton_actionAdapter(CrawlWindowEditor adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.addButton_actionPerformed(e);
}
}
class CrawlWindowEditor_upButton_actionAdapter implements java.awt.event.ActionListener {
CrawlWindowEditor adaptee;
CrawlWindowEditor_upButton_actionAdapter(CrawlWindowEditor adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.upButton_actionPerformed(e);
}
}
class CrawlWindowEditor_dnButton_actionAdapter implements java.awt.event.ActionListener {
CrawlWindowEditor adaptee;
CrawlWindowEditor_dnButton_actionAdapter(CrawlWindowEditor adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.dnButton_actionPerformed(e);
}
}
*/
| |
package ca.uhn.fhir.rest.method;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* 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%
*/
import static org.apache.commons.lang3.StringUtils.*;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.IdentityHashMap;
import java.util.List;
import org.hl7.fhir.instance.model.api.IBaseBundle;
import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.Bundle;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum;
import ca.uhn.fhir.model.base.resource.BaseOperationOutcome;
import ca.uhn.fhir.model.dstu.valueset.RestfulOperationSystemEnum;
import ca.uhn.fhir.model.dstu.valueset.RestfulOperationTypeEnum;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.valueset.BundleTypeEnum;
import ca.uhn.fhir.rest.annotation.Transaction;
import ca.uhn.fhir.rest.annotation.TransactionParam;
import ca.uhn.fhir.rest.api.RequestTypeEnum;
import ca.uhn.fhir.rest.client.BaseHttpClientInvocation;
import ca.uhn.fhir.rest.method.TransactionParamBinder.ParamStyle;
import ca.uhn.fhir.rest.server.IBundleProvider;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
public class TransactionMethodBinding extends BaseResourceReturningMethodBinding {
private int myTransactionParamIndex;
private ParamStyle myTransactionParamStyle;
public TransactionMethodBinding(Method theMethod, FhirContext theConetxt, Object theProvider) {
super(null, theMethod, theConetxt, theProvider);
myTransactionParamIndex = -1;
int index = 0;
for (IParameter next : getParameters()) {
if (next instanceof TransactionParamBinder) {
if (myTransactionParamIndex != -1) {
throw new ConfigurationException("Method '" + theMethod.getName() + "' in type " + theMethod.getDeclaringClass().getCanonicalName() + " has multiple parameters annotated with the @" + TransactionParam.class + " annotation, exactly one is required for @" + Transaction.class
+ " methods");
}
myTransactionParamIndex = index;
myTransactionParamStyle = ((TransactionParamBinder) next).getParamStyle();
}
index++;
}
if (myTransactionParamIndex == -1) {
throw new ConfigurationException("Method '" + theMethod.getName() + "' in type " + theMethod.getDeclaringClass().getCanonicalName() + " does not have a parameter annotated with the @" + TransactionParam.class + " annotation");
}
}
@Override
public RestfulOperationTypeEnum getResourceOperationType() {
return null;
}
@Override
protected BundleTypeEnum getResponseBundleType() {
return BundleTypeEnum.TRANSACTION_RESPONSE;
}
@Override
public ReturnTypeEnum getReturnType() {
return ReturnTypeEnum.BUNDLE;
}
@Override
public RestfulOperationSystemEnum getSystemOperationType() {
return RestfulOperationSystemEnum.TRANSACTION;
}
@Override
public boolean incomingServerRequestMatchesMethod(Request theRequest) {
if (theRequest.getRequestType() != RequestTypeEnum.POST) {
return false;
}
if (isNotBlank(theRequest.getOperation())) {
return false;
}
if (isNotBlank(theRequest.getResourceName())) {
return false;
}
return true;
}
@Override
public BaseHttpClientInvocation invokeClient(Object[] theArgs) throws InternalErrorException {
FhirContext context = getContext();
if (theArgs[myTransactionParamIndex] instanceof Bundle) {
Bundle bundle = (Bundle) theArgs[myTransactionParamIndex];
return createTransactionInvocation(bundle, context);
} else {
@SuppressWarnings("unchecked")
List<IResource> resources = (List<IResource>) theArgs[myTransactionParamIndex];
return createTransactionInvocation(resources, context);
}
}
@SuppressWarnings("unchecked")
@Override
public Object invokeServer(RequestDetails theRequest, Object[] theMethodParams) throws InvalidRequestException, InternalErrorException {
/*
* The design of HAPI's transaction method for DSTU1 support assumed that a transaction was just an update on a
* bunch of resources (because that's what it was), but in DSTU2 transaction has become much more broad, so we
* no longer hold the user's hand much here.
*/
if (myTransactionParamStyle == ParamStyle.RESOURCE_BUNDLE) {
// This is the DSTU2 style
Object response = invokeServerMethod(theMethodParams);
return response;
}
// Grab the IDs of all of the resources in the transaction
List<IResource> resources;
if (theMethodParams[myTransactionParamIndex] instanceof Bundle) {
resources = ((Bundle) theMethodParams[myTransactionParamIndex]).toListOfResources();
} else {
resources = (List<IResource>) theMethodParams[myTransactionParamIndex];
}
IdentityHashMap<IResource, IdDt> oldIds = new IdentityHashMap<IResource, IdDt>();
for (IResource next : resources) {
oldIds.put(next, next.getId());
}
// Call the server implementation method
Object response = invokeServerMethod(theMethodParams);
IBundleProvider retVal = toResourceList(response);
/*
* int offset = 0; if (retVal.size() != resources.size()) { if (retVal.size() > 0 && retVal.getResources(0,
* 1).get(0) instanceof OperationOutcome) { offset = 1; } else { throw new
* InternalErrorException("Transaction bundle contained " + resources.size() +
* " entries, but server method response contained " + retVal.size() + " entries (must be the same)"); } }
*/
List<IResource> retResources = retVal.getResources(0, retVal.size());
for (int i = 0; i < retResources.size(); i++) {
IdDt oldId = oldIds.get(retResources.get(i));
IResource newRes = retResources.get(i);
if (newRes.getId() == null || newRes.getId().isEmpty()) {
if (!(newRes instanceof BaseOperationOutcome)) {
throw new InternalErrorException("Transaction method returned resource at index " + i + " with no id specified - IResource#setId(IdDt)");
}
}
if (oldId != null && !oldId.isEmpty()) {
if (!oldId.equals(newRes.getId())) {
newRes.getResourceMetadata().put(ResourceMetadataKeyEnum.PREVIOUS_ID, oldId);
}
}
}
return retVal;
}
@Override
protected Object parseRequestObject(Request theRequest) throws IOException {
return null; // This is parsed in TransactionParamBinder
}
public static BaseHttpClientInvocation createTransactionInvocation(Bundle theBundle, FhirContext theContext) {
return new HttpPostClientInvocation(theContext, theBundle);
}
public static BaseHttpClientInvocation createTransactionInvocation(IBaseBundle theBundle, FhirContext theContext) {
return new HttpPostClientInvocation(theContext, theBundle);
}
public static BaseHttpClientInvocation createTransactionInvocation(List<IResource> theResources, FhirContext theContext) {
return new HttpPostClientInvocation(theContext, theResources, BundleTypeEnum.TRANSACTION);
}
public static BaseHttpClientInvocation createTransactionInvocation(String theRawBundle, FhirContext theContext) {
return new HttpPostClientInvocation(theContext, theRawBundle, true, "");
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/ml/v1beta1/model_service.proto
package com.google.cloud.ml.api.v1beta1;
/**
* <pre>
* Request message for the DeleteModel method.
* </pre>
*
* Protobuf type {@code google.cloud.ml.v1beta1.DeleteModelRequest}
*/
public final class DeleteModelRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.cloud.ml.v1beta1.DeleteModelRequest)
DeleteModelRequestOrBuilder {
// Use DeleteModelRequest.newBuilder() to construct.
private DeleteModelRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DeleteModelRequest() {
name_ = "";
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private DeleteModelRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!input.skipField(tag)) {
done = true;
}
break;
}
case 10: {
java.lang.String s = input.readStringRequireUtf8();
name_ = s;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.ml.api.v1beta1.ModelServiceProto.internal_static_google_cloud_ml_v1beta1_DeleteModelRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.ml.api.v1beta1.ModelServiceProto.internal_static_google_cloud_ml_v1beta1_DeleteModelRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.ml.api.v1beta1.DeleteModelRequest.class, com.google.cloud.ml.api.v1beta1.DeleteModelRequest.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object name_;
/**
* <pre>
* Required. The name of the model.
* Authorization: requires `Editor` role on the parent project.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
* <pre>
* Required. The name of the model.
* Authorization: requires `Editor` role on the parent project.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!getNameBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getNameBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
memoizedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.ml.api.v1beta1.DeleteModelRequest)) {
return super.equals(obj);
}
com.google.cloud.ml.api.v1beta1.DeleteModelRequest other = (com.google.cloud.ml.api.v1beta1.DeleteModelRequest) obj;
boolean result = true;
result = result && getName()
.equals(other.getName());
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptorForType().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.ml.api.v1beta1.DeleteModelRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.ml.api.v1beta1.DeleteModelRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.ml.api.v1beta1.DeleteModelRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.ml.api.v1beta1.DeleteModelRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.ml.api.v1beta1.DeleteModelRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.ml.api.v1beta1.DeleteModelRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.cloud.ml.api.v1beta1.DeleteModelRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.ml.api.v1beta1.DeleteModelRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.cloud.ml.api.v1beta1.DeleteModelRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.ml.api.v1beta1.DeleteModelRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.ml.api.v1beta1.DeleteModelRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Request message for the DeleteModel method.
* </pre>
*
* Protobuf type {@code google.cloud.ml.v1beta1.DeleteModelRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.cloud.ml.v1beta1.DeleteModelRequest)
com.google.cloud.ml.api.v1beta1.DeleteModelRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.ml.api.v1beta1.ModelServiceProto.internal_static_google_cloud_ml_v1beta1_DeleteModelRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.ml.api.v1beta1.ModelServiceProto.internal_static_google_cloud_ml_v1beta1_DeleteModelRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.ml.api.v1beta1.DeleteModelRequest.class, com.google.cloud.ml.api.v1beta1.DeleteModelRequest.Builder.class);
}
// Construct using com.google.cloud.ml.api.v1beta1.DeleteModelRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
name_ = "";
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.cloud.ml.api.v1beta1.ModelServiceProto.internal_static_google_cloud_ml_v1beta1_DeleteModelRequest_descriptor;
}
public com.google.cloud.ml.api.v1beta1.DeleteModelRequest getDefaultInstanceForType() {
return com.google.cloud.ml.api.v1beta1.DeleteModelRequest.getDefaultInstance();
}
public com.google.cloud.ml.api.v1beta1.DeleteModelRequest build() {
com.google.cloud.ml.api.v1beta1.DeleteModelRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.google.cloud.ml.api.v1beta1.DeleteModelRequest buildPartial() {
com.google.cloud.ml.api.v1beta1.DeleteModelRequest result = new com.google.cloud.ml.api.v1beta1.DeleteModelRequest(this);
result.name_ = name_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.ml.api.v1beta1.DeleteModelRequest) {
return mergeFrom((com.google.cloud.ml.api.v1beta1.DeleteModelRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.ml.api.v1beta1.DeleteModelRequest other) {
if (other == com.google.cloud.ml.api.v1beta1.DeleteModelRequest.getDefaultInstance()) return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.ml.api.v1beta1.DeleteModelRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.ml.api.v1beta1.DeleteModelRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object name_ = "";
/**
* <pre>
* Required. The name of the model.
* Authorization: requires `Editor` role on the parent project.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Required. The name of the model.
* Authorization: requires `Editor` role on the parent project.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Required. The name of the model.
* Authorization: requires `Editor` role on the parent project.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public Builder setName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
* <pre>
* Required. The name of the model.
* Authorization: requires `Editor` role on the parent project.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <pre>
* Required. The name of the model.
* Authorization: requires `Editor` role on the parent project.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public Builder setNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
// @@protoc_insertion_point(builder_scope:google.cloud.ml.v1beta1.DeleteModelRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.ml.v1beta1.DeleteModelRequest)
private static final com.google.cloud.ml.api.v1beta1.DeleteModelRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.ml.api.v1beta1.DeleteModelRequest();
}
public static com.google.cloud.ml.api.v1beta1.DeleteModelRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DeleteModelRequest>
PARSER = new com.google.protobuf.AbstractParser<DeleteModelRequest>() {
public DeleteModelRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new DeleteModelRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<DeleteModelRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DeleteModelRequest> getParserForType() {
return PARSER;
}
public com.google.cloud.ml.api.v1beta1.DeleteModelRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
/*
* Copyright 2011 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.workbench.models.guided.dtable.backend;
import org.drools.workbench.models.datamodel.rule.BaseSingleFieldConstraint;
import org.drools.workbench.models.guided.dtable.backend.util.GuidedDecisionTableUpgradeHelper1;
import org.drools.workbench.models.guided.dtable.shared.model.ActionInsertFactCol52;
import org.drools.workbench.models.guided.dtable.shared.model.ActionRetractFactCol52;
import org.drools.workbench.models.guided.dtable.shared.model.ActionSetFieldCol52;
import org.drools.workbench.models.guided.dtable.shared.model.DTCellValue52;
import org.drools.workbench.models.guided.dtable.shared.model.GuidedDecisionTable52;
import org.drools.workbench.models.guided.dtable.shared.model.legacy.ActionInsertFactCol;
import org.drools.workbench.models.guided.dtable.shared.model.legacy.ActionRetractFactCol;
import org.drools.workbench.models.guided.dtable.shared.model.legacy.ActionSetFieldCol;
import org.drools.workbench.models.guided.dtable.shared.model.legacy.AttributeCol;
import org.drools.workbench.models.guided.dtable.shared.model.legacy.ConditionCol;
import org.drools.workbench.models.guided.dtable.shared.model.legacy.GuidedDecisionTable;
import org.drools.workbench.models.guided.dtable.shared.model.legacy.MetadataCol;
import org.junit.Test;
import org.kie.soup.project.datamodel.oracle.DataType;
import java.util.List;
import static org.junit.Assert.*;
@SuppressWarnings("deprecation")
public class GuidedDTModelConversionTest {
private GuidedDecisionTableUpgradeHelper1 upgrader = new GuidedDecisionTableUpgradeHelper1();
@Test
public void testConversion() {
GuidedDecisionTable dt = new GuidedDecisionTable();
dt.tableName = "michael";
MetadataCol md = new MetadataCol();
md.attr = "legacy";
md.defaultValue = "yes";
dt.metadataCols.add(md);
AttributeCol attr = new AttributeCol();
attr.attr = "salience";
attr.defaultValue = "66";
dt.attributeCols.add(attr);
ConditionCol con = new ConditionCol();
con.boundName = "f1";
con.constraintValueType = BaseSingleFieldConstraint.TYPE_LITERAL;
con.factField = "age";
con.factType = "Driver";
con.header = "Driver f1 age";
con.operator = "==";
dt.conditionCols.add(con);
ConditionCol con2 = new ConditionCol();
con2.boundName = "f1";
con2.constraintValueType = BaseSingleFieldConstraint.TYPE_LITERAL;
con2.factField = "name";
con2.factType = "Driver";
con2.header = "Driver f1 name";
con2.operator = "==";
dt.conditionCols.add(con2);
ConditionCol con3 = new ConditionCol();
con3.boundName = "f1";
con3.constraintValueType = BaseSingleFieldConstraint.TYPE_RET_VALUE;
con3.factField = "rating";
con3.factType = "Driver";
con3.header = "Driver rating";
con3.operator = "==";
dt.conditionCols.add(con3);
ConditionCol con4 = new ConditionCol();
con4.boundName = "f2";
con4.constraintValueType = BaseSingleFieldConstraint.TYPE_PREDICATE;
con4.factType = "Driver";
con4.header = "Driver 2 pimp";
con4.factField = "(not needed)";
dt.conditionCols.add(con4);
ActionInsertFactCol ins = new ActionInsertFactCol();
ins.boundName = "ins";
ins.factType = "Cheese";
ins.factField = "price";
ins.type = DataType.TYPE_NUMERIC_INTEGER;
dt.actionCols.add(ins);
ActionRetractFactCol ret = new ActionRetractFactCol();
ret.boundName = "ret1";
dt.actionCols.add(ret);
ActionSetFieldCol set = new ActionSetFieldCol();
set.boundName = "f1";
set.factField = "goo1";
set.type = DataType.TYPE_STRING;
dt.actionCols.add(set);
ActionSetFieldCol set2 = new ActionSetFieldCol();
set2.boundName = "f1";
set2.factField = "goo2";
set2.defaultValue = "whee";
set2.type = DataType.TYPE_STRING;
dt.actionCols.add(set2);
dt.data = new String[][]{
new String[]{"1", "desc", "metar1", "saliencer1", "c1r1", "c2r1", "c3r1", "c4r1", "a1r1", "a2r1", "a3r1", "a4r1"},
new String[]{"2", "desc", "metar2", "saliencer2", "c1r2", "c2r2", "c3r2", "c4r2", "a1r2", "a2r2", "a3r2", "a4r2"}
};
String[][] expected = new String[][]{
new String[]{"1", "desc", "metar1", "saliencer1", "c1r1", "c2r1", "c3r1", "c4r1", "a1r1", "ret1", "a3r1", "a4r1"},
new String[]{"2", "desc", "metar2", "saliencer2", "c1r2", "c2r2", "c3r2", "c4r2", "a1r2", "ret1", "a3r2", "a4r2"}
};
GuidedDecisionTable52 tsdt = upgrader.upgrade(dt);
assertEquals("michael",
tsdt.getTableName());
assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY,
tsdt.getTableFormat());
assertEquals(1,
tsdt.getMetadataCols().size());
assertEquals("legacy",
tsdt.getMetadataCols().get(0).getMetadata());
assertEquals("yes",
tsdt.getMetadataCols().get(0).getDefaultValue().getStringValue());
assertEquals(1,
tsdt.getAttributeCols().size());
assertEquals("salience",
tsdt.getAttributeCols().get(0).getAttribute());
assertEquals("66",
tsdt.getAttributeCols().get(0).getDefaultValue().getStringValue());
assertEquals(2,
tsdt.getConditions().size());
assertEquals("f1",
tsdt.getConditionPattern("f1").getBoundName());
assertEquals("Driver",
tsdt.getConditionPattern("f1").getFactType());
assertEquals("f2",
tsdt.getConditionPattern("f2").getBoundName());
assertEquals("Driver",
tsdt.getConditionPattern("f2").getFactType());
assertEquals(3,
tsdt.getConditionPattern("f1").getChildColumns().size());
assertEquals(1,
tsdt.getConditionPattern("f2").getChildColumns().size());
assertEquals(BaseSingleFieldConstraint.TYPE_LITERAL,
tsdt.getConditionPattern("f1").getChildColumns().get(0).getConstraintValueType());
assertEquals("age",
tsdt.getConditionPattern("f1").getChildColumns().get(0).getFactField());
assertEquals("Driver",
tsdt.getPattern(tsdt.getConditionPattern("f1").getChildColumns().get(0)).getFactType());
assertEquals("Driver f1 age",
tsdt.getConditionPattern("f1").getChildColumns().get(0).getHeader());
assertEquals("==",
tsdt.getConditionPattern("f1").getChildColumns().get(0).getOperator());
assertEquals(BaseSingleFieldConstraint.TYPE_LITERAL,
tsdt.getConditionPattern("f1").getChildColumns().get(1).getConstraintValueType());
assertEquals("name",
tsdt.getConditionPattern("f1").getChildColumns().get(1).getFactField());
assertEquals("Driver",
tsdt.getPattern(tsdt.getConditionPattern("f1").getChildColumns().get(1)).getFactType());
assertEquals("Driver f1 name",
tsdt.getConditionPattern("f1").getChildColumns().get(1).getHeader());
assertEquals("==",
tsdt.getConditionPattern("f1").getChildColumns().get(1).getOperator());
assertEquals(BaseSingleFieldConstraint.TYPE_RET_VALUE,
tsdt.getConditionPattern("f1").getChildColumns().get(2).getConstraintValueType());
assertEquals("rating",
tsdt.getConditionPattern("f1").getChildColumns().get(2).getFactField());
assertEquals("Driver",
tsdt.getPattern(tsdt.getConditionPattern("f1").getChildColumns().get(2)).getFactType());
assertEquals("Driver rating",
tsdt.getConditionPattern("f1").getChildColumns().get(2).getHeader());
assertEquals("==",
tsdt.getConditionPattern("f1").getChildColumns().get(2).getOperator());
assertEquals(BaseSingleFieldConstraint.TYPE_PREDICATE,
tsdt.getConditionPattern("f2").getChildColumns().get(0).getConstraintValueType());
assertEquals("(not needed)",
tsdt.getConditionPattern("f2").getChildColumns().get(0).getFactField());
assertEquals("Driver",
tsdt.getPattern(tsdt.getConditionPattern("f2").getChildColumns().get(0)).getFactType());
assertEquals("Driver 2 pimp",
tsdt.getConditionPattern("f2").getChildColumns().get(0).getHeader());
assertEquals(4,
tsdt.getActionCols().size());
ActionInsertFactCol52 a1 = (ActionInsertFactCol52) tsdt.getActionCols().get(0);
assertEquals("ins",
a1.getBoundName());
assertEquals("Cheese",
a1.getFactType());
assertEquals("price",
a1.getFactField());
assertEquals(DataType.TYPE_NUMERIC_INTEGER,
a1.getType());
ActionRetractFactCol52 a2 = (ActionRetractFactCol52) tsdt.getActionCols().get(1);
assertNotNull(a2);
ActionSetFieldCol52 a3 = (ActionSetFieldCol52) tsdt.getActionCols().get(2);
assertEquals("f1",
a3.getBoundName());
assertEquals("goo1",
a3.getFactField());
assertEquals(DataType.TYPE_STRING,
a3.getType());
ActionSetFieldCol52 a4 = (ActionSetFieldCol52) tsdt.getActionCols().get(3);
assertEquals("f1",
a4.getBoundName());
assertEquals("goo2",
a4.getFactField());
assertEquals("whee",
a4.getDefaultValue().getStringValue());
assertEquals(DataType.TYPE_STRING,
a4.getType());
assertEquals(2,
tsdt.getData().size());
isRowEquivalent(tsdt.getData().get(0),
expected[0]);
isRowEquivalent(tsdt.getData().get(1),
expected[1]);
}
@Test
public void testConversionPatternGrouping() {
GuidedDecisionTable dt = new GuidedDecisionTable();
dt.tableName = "michael";
MetadataCol md = new MetadataCol();
md.attr = "legacy";
md.defaultValue = "yes";
dt.metadataCols.add(md);
AttributeCol attr = new AttributeCol();
attr.attr = "salience";
attr.defaultValue = "66";
dt.attributeCols.add(attr);
ConditionCol con = new ConditionCol();
con.boundName = "f1";
con.constraintValueType = BaseSingleFieldConstraint.TYPE_LITERAL;
con.factField = "age";
con.factType = "Driver";
con.header = "Driver f1 age";
con.operator = "==";
dt.conditionCols.add(con);
ConditionCol con2 = new ConditionCol();
con2.boundName = "f2";
con2.constraintValueType = BaseSingleFieldConstraint.TYPE_LITERAL;
con2.factField = "name";
con2.factType = "Person";
con2.header = "Person f2 name";
con2.operator = "==";
dt.conditionCols.add(con2);
ConditionCol con3 = new ConditionCol();
con3.boundName = "f1";
con3.constraintValueType = BaseSingleFieldConstraint.TYPE_RET_VALUE;
con3.factField = "rating";
con3.factType = "Driver";
con3.header = "Driver rating";
con3.operator = "==";
dt.conditionCols.add(con3);
ConditionCol con4 = new ConditionCol();
con4.boundName = "f2";
con4.constraintValueType = BaseSingleFieldConstraint.TYPE_PREDICATE;
con4.factType = "Person";
con4.header = "Person f2 not needed";
con4.factField = "(not needed)";
dt.conditionCols.add(con4);
ActionInsertFactCol ins = new ActionInsertFactCol();
ins.boundName = "ins";
ins.factType = "Cheese";
ins.factField = "price";
ins.type = DataType.TYPE_NUMERIC_INTEGER;
dt.actionCols.add(ins);
ActionRetractFactCol ret = new ActionRetractFactCol();
ret.boundName = "ret1";
dt.actionCols.add(ret);
ActionSetFieldCol set = new ActionSetFieldCol();
set.boundName = "f1";
set.factField = "goo1";
set.type = DataType.TYPE_STRING;
dt.actionCols.add(set);
ActionSetFieldCol set2 = new ActionSetFieldCol();
set2.boundName = "f1";
set2.factField = "goo2";
set2.defaultValue = "whee";
set2.type = DataType.TYPE_STRING;
dt.actionCols.add(set2);
dt.data = new String[][]{
new String[]{"1", "desc", "metar1", "saliencer1", "f1c1r1", "f2c1r1", "f1c2r1", "f2c2r1", "a1r1", "a2r1", "a3r1", "a4r1"},
new String[]{"2", "desc", "metar2", "saliencer2", "f1c1r2", "f2c1r2", "f1c2r2", "f2c2r2", "a1r2", "a2r2", "a3r2", "a4r2"}
};
String[][] expected = new String[][]{
new String[]{"1", "desc", "metar1", "saliencer1", "f1c1r1", "f1c2r1", "f2c1r1", "f2c2r1", "a1r1", "ret1", "a3r1", "a4r1"},
new String[]{"2", "desc", "metar2", "saliencer2", "f1c1r2", "f1c2r2", "f2c1r2", "f2c2r2", "a1r2", "ret1", "a3r2", "a4r2"}
};
GuidedDecisionTable52 tsdt = upgrader.upgrade(dt);
assertEquals("michael",
tsdt.getTableName());
assertEquals(1,
tsdt.getMetadataCols().size());
assertEquals("legacy",
tsdt.getMetadataCols().get(0).getMetadata());
assertEquals("yes",
tsdt.getMetadataCols().get(0).getDefaultValue().getStringValue());
assertEquals(1,
tsdt.getAttributeCols().size());
assertEquals("salience",
tsdt.getAttributeCols().get(0).getAttribute());
assertEquals("66",
tsdt.getAttributeCols().get(0).getDefaultValue().getStringValue());
assertEquals(2,
tsdt.getConditions().size());
assertEquals("f1",
tsdt.getConditionPattern("f1").getBoundName());
assertEquals("Driver",
tsdt.getConditionPattern("f1").getFactType());
assertEquals("f2",
tsdt.getConditionPattern("f2").getBoundName());
assertEquals("Person",
tsdt.getConditionPattern("f2").getFactType());
assertEquals(2,
tsdt.getConditionPattern("f1").getChildColumns().size());
assertEquals(2,
tsdt.getConditionPattern("f2").getChildColumns().size());
assertEquals(BaseSingleFieldConstraint.TYPE_LITERAL,
tsdt.getConditionPattern("f1").getChildColumns().get(0).getConstraintValueType());
assertEquals("age",
tsdt.getConditionPattern("f1").getChildColumns().get(0).getFactField());
assertEquals("Driver",
tsdt.getPattern(tsdt.getConditionPattern("f1").getChildColumns().get(0)).getFactType());
assertEquals("Driver f1 age",
tsdt.getConditionPattern("f1").getChildColumns().get(0).getHeader());
assertEquals("==",
tsdt.getConditionPattern("f1").getChildColumns().get(0).getOperator());
assertEquals(BaseSingleFieldConstraint.TYPE_RET_VALUE,
tsdt.getConditionPattern("f1").getChildColumns().get(1).getConstraintValueType());
assertEquals("rating",
tsdt.getConditionPattern("f1").getChildColumns().get(1).getFactField());
assertEquals("Driver",
tsdt.getPattern(tsdt.getConditionPattern("f1").getChildColumns().get(1)).getFactType());
assertEquals("Driver rating",
tsdt.getConditionPattern("f1").getChildColumns().get(1).getHeader());
assertEquals("==",
tsdt.getConditionPattern("f1").getChildColumns().get(1).getOperator());
assertEquals(BaseSingleFieldConstraint.TYPE_LITERAL,
tsdt.getConditionPattern("f2").getChildColumns().get(0).getConstraintValueType());
assertEquals("name",
tsdt.getConditionPattern("f2").getChildColumns().get(0).getFactField());
assertEquals("Person",
tsdt.getPattern(tsdt.getConditionPattern("f2").getChildColumns().get(0)).getFactType());
assertEquals("Person f2 name",
tsdt.getConditionPattern("f2").getChildColumns().get(0).getHeader());
assertEquals("==",
tsdt.getConditionPattern("f2").getChildColumns().get(0).getOperator());
assertEquals(BaseSingleFieldConstraint.TYPE_PREDICATE,
tsdt.getConditionPattern("f2").getChildColumns().get(1).getConstraintValueType());
assertEquals("(not needed)",
tsdt.getConditionPattern("f2").getChildColumns().get(1).getFactField());
assertEquals("Person",
tsdt.getPattern(tsdt.getConditionPattern("f2").getChildColumns().get(1)).getFactType());
assertEquals("Person f2 not needed",
tsdt.getConditionPattern("f2").getChildColumns().get(1).getHeader());
assertEquals(null,
tsdt.getConditionPattern("f2").getChildColumns().get(1).getOperator());
assertEquals(4,
tsdt.getActionCols().size());
ActionInsertFactCol52 a1 = (ActionInsertFactCol52) tsdt.getActionCols().get(0);
assertEquals("ins",
a1.getBoundName());
assertEquals("Cheese",
a1.getFactType());
assertEquals("price",
a1.getFactField());
assertEquals(DataType.TYPE_NUMERIC_INTEGER,
a1.getType());
ActionRetractFactCol52 a2 = (ActionRetractFactCol52) tsdt.getActionCols().get(1);
assertNotNull(a2);
ActionSetFieldCol52 a3 = (ActionSetFieldCol52) tsdt.getActionCols().get(2);
assertEquals("f1",
a3.getBoundName());
assertEquals("goo1",
a3.getFactField());
assertEquals(DataType.TYPE_STRING,
a3.getType());
ActionSetFieldCol52 a4 = (ActionSetFieldCol52) tsdt.getActionCols().get(3);
assertEquals("f1",
a4.getBoundName());
assertEquals("goo2",
a4.getFactField());
assertEquals("whee",
a4.getDefaultValue().getStringValue());
assertEquals(DataType.TYPE_STRING,
a4.getType());
assertEquals(2,
tsdt.getData().size());
for (int i = 0; i < 2; i++) {
System.out.println("Row-" + i);
StringBuilder sb = new StringBuilder();
for (DTCellValue52 c : tsdt.getData().get(i)) {
sb.append(c.getStringValue() + ", ");
}
sb.delete(sb.lastIndexOf(","),
sb.length());
System.out.println(sb.toString());
}
assertEquals(new Integer(1),
(Integer) tsdt.getData().get(0).get(0).getNumericValue());
assertEquals("desc",
tsdt.getData().get(0).get(1).getStringValue());
assertEquals("metar1",
tsdt.getData().get(0).get(2).getStringValue());
assertEquals("saliencer1",
tsdt.getData().get(0).get(3).getStringValue());
assertEquals("f1c1r1",
tsdt.getData().get(0).get(4).getStringValue());
assertEquals("f1c2r1",
tsdt.getData().get(0).get(5).getStringValue());
assertEquals("f2c1r1",
tsdt.getData().get(0).get(6).getStringValue());
assertEquals("f2c2r1",
tsdt.getData().get(0).get(7).getStringValue());
assertEquals("a1r1",
tsdt.getData().get(0).get(8).getStringValue());
assertEquals("ret1",
tsdt.getData().get(0).get(9).getStringValue());
assertEquals("a3r1",
tsdt.getData().get(0).get(10).getStringValue());
assertEquals("a4r1",
tsdt.getData().get(0).get(11).getStringValue());
assertEquals(new Integer(2),
(Integer) tsdt.getData().get(1).get(0).getNumericValue());
assertEquals("desc",
tsdt.getData().get(1).get(1).getStringValue());
assertEquals("metar2",
tsdt.getData().get(1).get(2).getStringValue());
assertEquals("saliencer2",
tsdt.getData().get(1).get(3).getStringValue());
assertEquals("f1c1r2",
tsdt.getData().get(1).get(4).getStringValue());
assertEquals("f1c2r2",
tsdt.getData().get(1).get(5).getStringValue());
assertEquals("f2c1r2",
tsdt.getData().get(1).get(6).getStringValue());
assertEquals("f2c2r2",
tsdt.getData().get(1).get(7).getStringValue());
assertEquals("a1r2",
tsdt.getData().get(1).get(8).getStringValue());
assertEquals("ret1",
tsdt.getData().get(1).get(9).getStringValue());
assertEquals("a3r2",
tsdt.getData().get(1).get(10).getStringValue());
assertEquals("a4r2",
tsdt.getData().get(1).get(11).getStringValue());
isRowEquivalent(tsdt.getData().get(0),
expected[0]);
isRowEquivalent(tsdt.getData().get(1),
expected[1]);
}
private void isRowEquivalent(List<DTCellValue52> row,
String[] array) {
assertEquals(row.size(),
array.length);
int newRowNum = (Integer) row.get(0).getNumericValue();
int oldRowNum = Integer.valueOf(array[0]);
assertEquals(newRowNum,
oldRowNum);
for (int iCol = 1; iCol < row.size(); iCol++) {
DTCellValue52 cell = row.get(iCol);
String v1 = cell.getStringValue();
String v2 = array[iCol];
assertTrue(isEqualOrNull(v1,
v2));
assertEquals(v1,
v2);
}
}
@Test
public void testConversionPatternGrouping2() {
GuidedDecisionTable dt = new GuidedDecisionTable();
dt.tableName = "michael";
ConditionCol con = new ConditionCol();
con.boundName = "z1";
con.constraintValueType = BaseSingleFieldConstraint.TYPE_LITERAL;
con.factField = "age";
con.factType = "Driver";
con.header = "Driver z1 age";
con.operator = "==";
dt.conditionCols.add(con);
ConditionCol con2 = new ConditionCol();
con2.boundName = "f1";
con2.constraintValueType = BaseSingleFieldConstraint.TYPE_LITERAL;
con2.factField = "name";
con2.factType = "Person";
con2.header = "Person f1 name";
con2.operator = "==";
dt.conditionCols.add(con2);
ConditionCol con3 = new ConditionCol();
con3.boundName = "z1";
con3.constraintValueType = BaseSingleFieldConstraint.TYPE_RET_VALUE;
con3.factField = "rating";
con3.factType = "Driver";
con3.header = "Driver rating";
con3.operator = "==";
dt.conditionCols.add(con3);
ConditionCol con4 = new ConditionCol();
con4.boundName = "f2";
con4.constraintValueType = BaseSingleFieldConstraint.TYPE_PREDICATE;
con4.factType = "Person2";
con4.header = "Person2 f2 not needed";
con4.factField = "(not needed)";
dt.conditionCols.add(con4);
dt.data = new String[][]{
new String[]{"1", "desc", "z1c1r1", "f1c1r1", "z1c2r1", "f2c1r1"},
new String[]{"2", "desc", "z1c1r2", "f1c1r2", "z1c2r2", "f2c1r2"}
};
String[][] expected = new String[][]{
new String[]{"1", "desc", "z1c1r1", "z1c2r1", "f1c1r1", "f2c1r1"},
new String[]{"2", "desc", "z1c1r2", "z1c2r2", "f1c1r2", "f2c1r2"}
};
GuidedDecisionTable52 tsdt = upgrader.upgrade(dt);
assertEquals("michael",
tsdt.getTableName());
assertEquals(0,
tsdt.getMetadataCols().size());
assertEquals(0,
tsdt.getAttributeCols().size());
assertEquals(3,
tsdt.getConditions().size());
assertEquals("z1",
tsdt.getConditionPattern("z1").getBoundName());
assertEquals("Driver",
tsdt.getConditionPattern("z1").getFactType());
assertEquals("f1",
tsdt.getConditionPattern("f1").getBoundName());
assertEquals("Person",
tsdt.getConditionPattern("f1").getFactType());
assertEquals("f2",
tsdt.getConditionPattern("f2").getBoundName());
assertEquals("Person2",
tsdt.getConditionPattern("f2").getFactType());
assertEquals(2,
tsdt.getConditionPattern("z1").getChildColumns().size());
assertEquals(1,
tsdt.getConditionPattern("f1").getChildColumns().size());
assertEquals(1,
tsdt.getConditionPattern("f2").getChildColumns().size());
assertEquals(BaseSingleFieldConstraint.TYPE_LITERAL,
tsdt.getConditionPattern("z1").getChildColumns().get(0).getConstraintValueType());
assertEquals("age",
tsdt.getConditionPattern("z1").getChildColumns().get(0).getFactField());
assertEquals("Driver",
tsdt.getPattern(tsdt.getConditionPattern("z1").getChildColumns().get(0)).getFactType());
assertEquals("Driver z1 age",
tsdt.getConditionPattern("z1").getChildColumns().get(0).getHeader());
assertEquals("==",
tsdt.getConditionPattern("z1").getChildColumns().get(0).getOperator());
assertEquals(BaseSingleFieldConstraint.TYPE_RET_VALUE,
tsdt.getConditionPattern("z1").getChildColumns().get(1).getConstraintValueType());
assertEquals("rating",
tsdt.getConditionPattern("z1").getChildColumns().get(1).getFactField());
assertEquals("Driver",
tsdt.getPattern(tsdt.getConditionPattern("z1").getChildColumns().get(1)).getFactType());
assertEquals("Driver rating",
tsdt.getConditionPattern("z1").getChildColumns().get(1).getHeader());
assertEquals("==",
tsdt.getConditionPattern("z1").getChildColumns().get(1).getOperator());
assertEquals(BaseSingleFieldConstraint.TYPE_LITERAL,
tsdt.getConditionPattern("f1").getChildColumns().get(0).getConstraintValueType());
assertEquals("name",
tsdt.getConditionPattern("f1").getChildColumns().get(0).getFactField());
assertEquals("Person",
tsdt.getPattern(tsdt.getConditionPattern("f1").getChildColumns().get(0)).getFactType());
assertEquals("Person f1 name",
tsdt.getConditionPattern("f1").getChildColumns().get(0).getHeader());
assertEquals("==",
tsdt.getConditionPattern("f1").getChildColumns().get(0).getOperator());
assertEquals(BaseSingleFieldConstraint.TYPE_PREDICATE,
tsdt.getConditionPattern("f2").getChildColumns().get(0).getConstraintValueType());
assertEquals("(not needed)",
tsdt.getConditionPattern("f2").getChildColumns().get(0).getFactField());
assertEquals("Person2",
tsdt.getPattern(tsdt.getConditionPattern("f2").getChildColumns().get(0)).getFactType());
assertEquals("Person2 f2 not needed",
tsdt.getConditionPattern("f2").getChildColumns().get(0).getHeader());
assertEquals(null,
tsdt.getConditionPattern("f2").getChildColumns().get(0).getOperator());
assertEquals(2,
tsdt.getData().size());
for (int i = 0; i < 2; i++) {
System.out.println("Row-" + i);
StringBuilder sb = new StringBuilder();
for (DTCellValue52 c : tsdt.getData().get(i)) {
sb.append(c.getStringValue() + ", ");
}
sb.delete(sb.lastIndexOf(","),
sb.length());
System.out.println(sb.toString());
}
assertEquals(new Integer(1),
(Integer) tsdt.getData().get(0).get(0).getNumericValue());
assertEquals("desc",
tsdt.getData().get(0).get(1).getStringValue());
assertEquals("z1c1r1",
tsdt.getData().get(0).get(2).getStringValue());
assertEquals("z1c2r1",
tsdt.getData().get(0).get(3).getStringValue());
assertEquals("f1c1r1",
tsdt.getData().get(0).get(4).getStringValue());
assertEquals("f2c1r1",
tsdt.getData().get(0).get(5).getStringValue());
assertEquals(new Integer(2),
(Integer) tsdt.getData().get(1).get(0).getNumericValue());
assertEquals("desc",
tsdt.getData().get(1).get(1).getStringValue());
assertEquals("z1c1r2",
tsdt.getData().get(1).get(2).getStringValue());
assertEquals("z1c2r2",
tsdt.getData().get(1).get(3).getStringValue());
assertEquals("f1c1r2",
tsdt.getData().get(1).get(4).getStringValue());
assertEquals("f2c1r2",
tsdt.getData().get(1).get(5).getStringValue());
isRowEquivalent(tsdt.getData().get(0),
expected[0]);
isRowEquivalent(tsdt.getData().get(1),
expected[1]);
}
private boolean isEqualOrNull(Object v1,
Object v2) {
if (v1 == null && v2 == null) {
return true;
}
if (v1 != null && v2 == null) {
return false;
}
if (v1 == null && v2 != null) {
return false;
}
return v1.equals(v2);
}
}
| |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.io.hfile;
import static org.apache.hadoop.hbase.io.compress.Compression.Algorithm.GZ;
import static org.apache.hadoop.hbase.io.compress.Compression.Algorithm.NONE;
import static org.junit.Assert.*;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.KeyValueUtil;
import org.apache.hadoop.hbase.fs.HFileSystem;
import org.apache.hadoop.hbase.io.FSDataInputStreamWrapper;
import org.apache.hadoop.hbase.io.compress.Compression;
import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
import org.apache.hadoop.hbase.io.encoding.HFileBlockDefaultEncodingContext;
import org.apache.hadoop.hbase.io.encoding.HFileBlockEncodingContext;
import org.apache.hadoop.hbase.io.hfile.HFileBlock.BlockWritable;
import org.apache.hadoop.hbase.testclassification.IOTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.ChecksumType;
import org.apache.hadoop.io.WritableUtils;
import org.apache.hadoop.io.compress.Compressor;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.google.common.base.Preconditions;
/**
* This class has unit tests to prove that older versions of
* HFiles (without checksums) are compatible with current readers.
*/
@Category({IOTests.class, SmallTests.class})
@RunWith(Parameterized.class)
public class TestHFileBlockCompatibility {
private static final Log LOG = LogFactory.getLog(TestHFileBlockCompatibility.class);
private static final Compression.Algorithm[] COMPRESSION_ALGORITHMS = {
NONE, GZ };
private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
private HFileSystem fs;
private final boolean includesMemstoreTS;
private final boolean includesTag;
public TestHFileBlockCompatibility(boolean includesMemstoreTS, boolean includesTag) {
this.includesMemstoreTS = includesMemstoreTS;
this.includesTag = includesTag;
}
@Parameters
public static Collection<Object[]> parameters() {
return HBaseTestingUtility.MEMSTORETS_TAGS_PARAMETRIZED;
}
@Before
public void setUp() throws IOException {
fs = (HFileSystem)HFileSystem.get(TEST_UTIL.getConfiguration());
}
public byte[] createTestV1Block(Compression.Algorithm algo)
throws IOException {
Compressor compressor = algo.getCompressor();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream os = algo.createCompressionStream(baos, compressor, 0);
DataOutputStream dos = new DataOutputStream(os);
BlockType.META.write(dos); // Let's make this a meta block.
TestHFileBlock.writeTestBlockContents(dos);
dos.flush();
algo.returnCompressor(compressor);
return baos.toByteArray();
}
private Writer createTestV2Block(Compression.Algorithm algo)
throws IOException {
final BlockType blockType = BlockType.DATA;
Writer hbw = new Writer(algo, null,
includesMemstoreTS, includesTag);
DataOutputStream dos = hbw.startWriting(blockType);
TestHFileBlock.writeTestBlockContents(dos);
// make sure the block is ready by calling hbw.getHeaderAndData()
hbw.getHeaderAndData();
assertEquals(1000 * 4, hbw.getUncompressedSizeWithoutHeader());
hbw.releaseCompressor();
return hbw;
}
private String createTestBlockStr(Compression.Algorithm algo,
int correctLength) throws IOException {
Writer hbw = createTestV2Block(algo);
byte[] testV2Block = hbw.getHeaderAndData();
int osOffset = HConstants.HFILEBLOCK_HEADER_SIZE_NO_CHECKSUM + 9;
if (testV2Block.length == correctLength) {
// Force-set the "OS" field of the gzip header to 3 (Unix) to avoid
// variations across operating systems.
// See http://www.gzip.org/zlib/rfc-gzip.html for gzip format.
testV2Block[osOffset] = 3;
}
return Bytes.toStringBinary(testV2Block);
}
@Test
public void testNoCompression() throws IOException {
assertEquals(4000, createTestV2Block(NONE).getBlockForCaching().
getUncompressedSizeWithoutHeader());
}
@Test
public void testGzipCompression() throws IOException {
final String correctTestBlockStr =
"DATABLK*\\x00\\x00\\x00:\\x00\\x00\\x0F\\xA0\\xFF\\xFF\\xFF\\xFF"
+ "\\xFF\\xFF\\xFF\\xFF"
// gzip-compressed block: http://www.gzip.org/zlib/rfc-gzip.html
+ "\\x1F\\x8B" // gzip magic signature
+ "\\x08" // Compression method: 8 = "deflate"
+ "\\x00" // Flags
+ "\\x00\\x00\\x00\\x00" // mtime
+ "\\x00" // XFL (extra flags)
// OS (0 = FAT filesystems, 3 = Unix). However, this field
// sometimes gets set to 0 on Linux and Mac, so we reset it to 3.
+ "\\x03"
+ "\\xED\\xC3\\xC1\\x11\\x00 \\x08\\xC00DD\\xDD\\x7Fa"
+ "\\xD6\\xE8\\xA3\\xB9K\\x84`\\x96Q\\xD3\\xA8\\xDB\\xA8e\\xD4c"
+ "\\xD46\\xEA5\\xEA3\\xEA7\\xE7\\x00LI\\x5Cs\\xA0\\x0F\\x00\\x00";
final int correctGzipBlockLength = 82;
String returnedStr = createTestBlockStr(GZ, correctGzipBlockLength);
assertEquals(correctTestBlockStr, returnedStr);
}
@Test
public void testReaderV2() throws IOException {
if(includesTag) {
TEST_UTIL.getConfiguration().setInt("hfile.format.version", 3);
}
for (Compression.Algorithm algo : COMPRESSION_ALGORITHMS) {
for (boolean pread : new boolean[] { false, true }) {
LOG.info("testReaderV2: Compression algorithm: " + algo +
", pread=" + pread);
Path path = new Path(TEST_UTIL.getDataTestDir(), "blocks_v2_"
+ algo);
FSDataOutputStream os = fs.create(path);
Writer hbw = new Writer(algo, null,
includesMemstoreTS, includesTag);
long totalSize = 0;
for (int blockId = 0; blockId < 2; ++blockId) {
DataOutputStream dos = hbw.startWriting(BlockType.DATA);
for (int i = 0; i < 1234; ++i)
dos.writeInt(i);
hbw.writeHeaderAndData(os);
totalSize += hbw.getOnDiskSizeWithHeader();
}
os.close();
FSDataInputStream is = fs.open(path);
HFileContext meta = new HFileContextBuilder()
.withHBaseCheckSum(false)
.withIncludesMvcc(includesMemstoreTS)
.withIncludesTags(includesTag)
.withCompression(algo)
.build();
HFileBlock.FSReader hbr =
new HFileBlock.FSReaderImpl(new FSDataInputStreamWrapper(is), totalSize, fs, path, meta);
HFileBlock b = hbr.readBlockData(0, -1, -1, pread);
is.close();
b.sanityCheck();
assertEquals(4936, b.getUncompressedSizeWithoutHeader());
assertEquals(algo == GZ ? 2173 : 4936,
b.getOnDiskSizeWithoutHeader() - b.totalChecksumBytes());
HFileBlock expected = b;
if (algo == GZ) {
is = fs.open(path);
hbr = new HFileBlock.FSReaderImpl(new FSDataInputStreamWrapper(is), totalSize, fs, path,
meta);
b = hbr.readBlockData(0, 2173 + HConstants.HFILEBLOCK_HEADER_SIZE_NO_CHECKSUM +
b.totalChecksumBytes(), -1, pread);
assertEquals(expected, b);
int wrongCompressedSize = 2172;
try {
b = hbr.readBlockData(0, wrongCompressedSize
+ HConstants.HFILEBLOCK_HEADER_SIZE_NO_CHECKSUM, -1, pread);
fail("Exception expected");
} catch (IOException ex) {
String expectedPrefix = "On-disk size without header provided is "
+ wrongCompressedSize + ", but block header contains "
+ b.getOnDiskSizeWithoutHeader() + ".";
assertTrue("Invalid exception message: '" + ex.getMessage()
+ "'.\nMessage is expected to start with: '" + expectedPrefix
+ "'", ex.getMessage().startsWith(expectedPrefix));
}
is.close();
}
}
}
}
/**
* Test encoding/decoding data blocks.
* @throws IOException a bug or a problem with temporary files.
*/
@Test
public void testDataBlockEncoding() throws IOException {
if(includesTag) {
TEST_UTIL.getConfiguration().setInt("hfile.format.version", 3);
}
final int numBlocks = 5;
for (Compression.Algorithm algo : COMPRESSION_ALGORITHMS) {
for (boolean pread : new boolean[] { false, true }) {
for (DataBlockEncoding encoding : DataBlockEncoding.values()) {
LOG.info("testDataBlockEncoding algo " + algo +
" pread = " + pread +
" encoding " + encoding);
Path path = new Path(TEST_UTIL.getDataTestDir(), "blocks_v2_"
+ algo + "_" + encoding.toString());
FSDataOutputStream os = fs.create(path);
HFileDataBlockEncoder dataBlockEncoder = (encoding != DataBlockEncoding.NONE) ?
new HFileDataBlockEncoderImpl(encoding) : NoOpDataBlockEncoder.INSTANCE;
TestHFileBlockCompatibility.Writer hbw =
new TestHFileBlockCompatibility.Writer(algo,
dataBlockEncoder, includesMemstoreTS, includesTag);
long totalSize = 0;
final List<Integer> encodedSizes = new ArrayList<Integer>();
final List<ByteBuffer> encodedBlocks = new ArrayList<ByteBuffer>();
for (int blockId = 0; blockId < numBlocks; ++blockId) {
hbw.startWriting(BlockType.DATA);
TestHFileBlock.writeTestKeyValues(hbw, blockId, pread, includesTag);
hbw.writeHeaderAndData(os);
int headerLen = HConstants.HFILEBLOCK_HEADER_SIZE_NO_CHECKSUM;
byte[] encodedResultWithHeader = hbw.getUncompressedDataWithHeader();
final int encodedSize = encodedResultWithHeader.length - headerLen;
if (encoding != DataBlockEncoding.NONE) {
// We need to account for the two-byte encoding algorithm ID that
// comes after the 24-byte block header but before encoded KVs.
headerLen += DataBlockEncoding.ID_SIZE;
}
byte[] encodedDataSection =
new byte[encodedResultWithHeader.length - headerLen];
System.arraycopy(encodedResultWithHeader, headerLen,
encodedDataSection, 0, encodedDataSection.length);
final ByteBuffer encodedBuf =
ByteBuffer.wrap(encodedDataSection);
encodedSizes.add(encodedSize);
encodedBlocks.add(encodedBuf);
totalSize += hbw.getOnDiskSizeWithHeader();
}
os.close();
FSDataInputStream is = fs.open(path);
HFileContext meta = new HFileContextBuilder()
.withHBaseCheckSum(false)
.withIncludesMvcc(includesMemstoreTS)
.withIncludesTags(includesTag)
.withCompression(algo)
.build();
HFileBlock.FSReaderImpl hbr = new HFileBlock.FSReaderImpl(new FSDataInputStreamWrapper(is),
totalSize, fs, path, meta);
hbr.setDataBlockEncoder(dataBlockEncoder);
hbr.setIncludesMemstoreTS(includesMemstoreTS);
HFileBlock b;
int pos = 0;
for (int blockId = 0; blockId < numBlocks; ++blockId) {
b = hbr.readBlockData(pos, -1, -1, pread);
b.sanityCheck();
if (meta.isCompressedOrEncrypted()) {
assertFalse(b.isUnpacked());
b = b.unpack(meta, hbr);
}
pos += b.getOnDiskSizeWithHeader();
assertEquals((int) encodedSizes.get(blockId),
b.getUncompressedSizeWithoutHeader());
ByteBuffer actualBuffer = b.getBufferWithoutHeader();
if (encoding != DataBlockEncoding.NONE) {
// We expect a two-byte big-endian encoding id.
assertEquals(0, actualBuffer.get(0));
assertEquals(encoding.getId(), actualBuffer.get(1));
actualBuffer.position(2);
actualBuffer = actualBuffer.slice();
}
ByteBuffer expectedBuffer = encodedBlocks.get(blockId);
expectedBuffer.rewind();
// test if content matches, produce nice message
TestHFileBlock.assertBuffersEqual(expectedBuffer, actualBuffer,
algo, encoding, pread);
}
is.close();
}
}
}
}
/**
* This is the version of the HFileBlock.Writer that is used to
* create V2 blocks with minor version 0. These blocks do not
* have hbase-level checksums. The code is here to test
* backward compatibility. The reason we do not inherit from
* HFileBlock.Writer is because we never ever want to change the code
* in this class but the code in HFileBlock.Writer will continually
* evolve.
*/
public static final class Writer extends HFileBlock.Writer {
// These constants are as they were in minorVersion 0.
private static final int HEADER_SIZE = HConstants.HFILEBLOCK_HEADER_SIZE_NO_CHECKSUM;
private static final boolean DONT_FILL_HEADER = HFileBlock.DONT_FILL_HEADER;
private static final byte[] DUMMY_HEADER =
HFileBlock.DUMMY_HEADER_NO_CHECKSUM;
private enum State {
INIT,
WRITING,
BLOCK_READY
};
/** Writer state. Used to ensure the correct usage protocol. */
private State state = State.INIT;
/** Compression algorithm for all blocks this instance writes. */
private final Compression.Algorithm compressAlgo;
/** Data block encoder used for data blocks */
private final HFileDataBlockEncoder dataBlockEncoder;
private HFileBlockEncodingContext dataBlockEncodingCtx;
/** block encoding context for non-data blocks */
private HFileBlockDefaultEncodingContext defaultBlockEncodingCtx;
/**
* The stream we use to accumulate data in uncompressed format for each
* block. We reset this stream at the end of each block and reuse it. The
* header is written as the first {@link #HEADER_SIZE} bytes into this
* stream.
*/
private ByteArrayOutputStream baosInMemory;
/** Compressor, which is also reused between consecutive blocks. */
private Compressor compressor;
/**
* Current block type. Set in {@link #startWriting(BlockType)}. Could be
* changed in {@link #encodeDataBlockForDisk()} from {@link BlockType#DATA}
* to {@link BlockType#ENCODED_DATA}.
*/
private BlockType blockType;
/**
* A stream that we write uncompressed bytes to, which compresses them and
* writes them to {@link #baosInMemory}.
*/
private DataOutputStream userDataStream;
/**
* Bytes to be written to the file system, including the header. Compressed
* if compression is turned on.
*/
private byte[] onDiskBytesWithHeader;
/**
* Valid in the READY state. Contains the header and the uncompressed (but
* potentially encoded, if this is a data block) bytes, so the length is
* {@link #uncompressedSizeWithoutHeader} + {@link org.apache.hadoop.hbase.HConstants#HFILEBLOCK_HEADER_SIZE}.
*/
private byte[] uncompressedBytesWithHeader;
/**
* Current block's start offset in the {@link HFile}. Set in
* {@link #writeHeaderAndData(FSDataOutputStream)}.
*/
private long startOffset;
/**
* Offset of previous block by block type. Updated when the next block is
* started.
*/
private long[] prevOffsetByType;
/** The offset of the previous block of the same type */
private long prevOffset;
private int unencodedDataSizeWritten;
public Writer(Compression.Algorithm compressionAlgorithm,
HFileDataBlockEncoder dataBlockEncoder, boolean includesMemstoreTS, boolean includesTag) {
this(dataBlockEncoder, new HFileContextBuilder().withHBaseCheckSum(false)
.withIncludesMvcc(includesMemstoreTS).withIncludesTags(includesTag)
.withCompression(compressionAlgorithm).build());
}
public Writer(HFileDataBlockEncoder dataBlockEncoder, HFileContext meta) {
super(dataBlockEncoder, meta);
compressAlgo = meta.getCompression() == null ? NONE : meta.getCompression();
this.dataBlockEncoder = dataBlockEncoder != null ? dataBlockEncoder
: NoOpDataBlockEncoder.INSTANCE;
defaultBlockEncodingCtx = new HFileBlockDefaultEncodingContext(null, DUMMY_HEADER, meta);
dataBlockEncodingCtx = this.dataBlockEncoder.newDataBlockEncodingContext(DUMMY_HEADER, meta);
baosInMemory = new ByteArrayOutputStream();
prevOffsetByType = new long[BlockType.values().length];
for (int i = 0; i < prevOffsetByType.length; ++i)
prevOffsetByType[i] = -1;
}
/**
* Starts writing into the block. The previous block's data is discarded.
*
* @return the stream the user can write their data into
* @throws IOException
*/
public DataOutputStream startWriting(BlockType newBlockType)
throws IOException {
if (state == State.BLOCK_READY && startOffset != -1) {
// We had a previous block that was written to a stream at a specific
// offset. Save that offset as the last offset of a block of that type.
prevOffsetByType[blockType.getId()] = startOffset;
}
startOffset = -1;
blockType = newBlockType;
baosInMemory.reset();
baosInMemory.write(DUMMY_HEADER);
state = State.WRITING;
// We will compress it later in finishBlock()
userDataStream = new DataOutputStream(baosInMemory);
if (newBlockType == BlockType.DATA) {
this.dataBlockEncoder.startBlockEncoding(dataBlockEncodingCtx, userDataStream);
}
this.unencodedDataSizeWritten = 0;
return userDataStream;
}
@Override
public void write(Cell c) throws IOException {
KeyValue kv = KeyValueUtil.ensureKeyValue(c);
expectState(State.WRITING);
this.dataBlockEncoder.encode(kv, dataBlockEncodingCtx, this.userDataStream);
this.unencodedDataSizeWritten += kv.getLength();
if (dataBlockEncodingCtx.getHFileContext().isIncludesMvcc()) {
this.unencodedDataSizeWritten += WritableUtils.getVIntSize(kv.getMvccVersion());
}
}
/**
* Returns the stream for the user to write to. The block writer takes care
* of handling compression and buffering for caching on write. Can only be
* called in the "writing" state.
*
* @return the data output stream for the user to write to
*/
DataOutputStream getUserDataStream() {
expectState(State.WRITING);
return userDataStream;
}
/**
* Transitions the block writer from the "writing" state to the "block
* ready" state. Does nothing if a block is already finished.
*/
void ensureBlockReady() throws IOException {
Preconditions.checkState(state != State.INIT,
"Unexpected state: " + state);
if (state == State.BLOCK_READY)
return;
// This will set state to BLOCK_READY.
finishBlock();
}
/**
* An internal method that flushes the compressing stream (if using
* compression), serializes the header, and takes care of the separate
* uncompressed stream for caching on write, if applicable. Sets block
* write state to "block ready".
*/
void finishBlock() throws IOException {
if (blockType == BlockType.DATA) {
this.dataBlockEncoder.endBlockEncoding(dataBlockEncodingCtx, userDataStream,
baosInMemory.toByteArray(), blockType);
blockType = dataBlockEncodingCtx.getBlockType();
}
userDataStream.flush();
// This does an array copy, so it is safe to cache this byte array.
uncompressedBytesWithHeader = baosInMemory.toByteArray();
prevOffset = prevOffsetByType[blockType.getId()];
// We need to set state before we can package the block up for
// cache-on-write. In a way, the block is ready, but not yet encoded or
// compressed.
state = State.BLOCK_READY;
if (blockType == BlockType.DATA || blockType == BlockType.ENCODED_DATA) {
onDiskBytesWithHeader = dataBlockEncodingCtx
.compressAndEncrypt(uncompressedBytesWithHeader);
} else {
onDiskBytesWithHeader = defaultBlockEncodingCtx
.compressAndEncrypt(uncompressedBytesWithHeader);
}
// put the header for on disk bytes
putHeader(onDiskBytesWithHeader, 0,
onDiskBytesWithHeader.length,
uncompressedBytesWithHeader.length);
//set the header for the uncompressed bytes (for cache-on-write)
putHeader(uncompressedBytesWithHeader, 0,
onDiskBytesWithHeader.length,
uncompressedBytesWithHeader.length);
}
/**
* Put the header into the given byte array at the given offset.
* @param onDiskSize size of the block on disk
* @param uncompressedSize size of the block after decompression (but
* before optional data block decoding)
*/
private void putHeader(byte[] dest, int offset, int onDiskSize,
int uncompressedSize) {
offset = blockType.put(dest, offset);
offset = Bytes.putInt(dest, offset, onDiskSize - HEADER_SIZE);
offset = Bytes.putInt(dest, offset, uncompressedSize - HEADER_SIZE);
Bytes.putLong(dest, offset, prevOffset);
}
/**
* Similar to {@link #writeHeaderAndData(FSDataOutputStream)}, but records
* the offset of this block so that it can be referenced in the next block
* of the same type.
*
* @param out
* @throws IOException
*/
public void writeHeaderAndData(FSDataOutputStream out) throws IOException {
long offset = out.getPos();
if (startOffset != -1 && offset != startOffset) {
throw new IOException("A " + blockType + " block written to a "
+ "stream twice, first at offset " + startOffset + ", then at "
+ offset);
}
startOffset = offset;
writeHeaderAndData((DataOutputStream) out);
}
/**
* Writes the header and the compressed data of this block (or uncompressed
* data when not using compression) into the given stream. Can be called in
* the "writing" state or in the "block ready" state. If called in the
* "writing" state, transitions the writer to the "block ready" state.
*
* @param out the output stream to write the
* @throws IOException
*/
private void writeHeaderAndData(DataOutputStream out) throws IOException {
ensureBlockReady();
out.write(onDiskBytesWithHeader);
}
/**
* Returns the header or the compressed data (or uncompressed data when not
* using compression) as a byte array. Can be called in the "writing" state
* or in the "block ready" state. If called in the "writing" state,
* transitions the writer to the "block ready" state.
*
* @return header and data as they would be stored on disk in a byte array
* @throws IOException
*/
public byte[] getHeaderAndData() throws IOException {
ensureBlockReady();
return onDiskBytesWithHeader;
}
/**
* Releases the compressor this writer uses to compress blocks into the
* compressor pool. Needs to be called before the writer is discarded.
*/
public void releaseCompressor() {
if (compressor != null) {
compressAlgo.returnCompressor(compressor);
compressor = null;
}
}
/**
* Returns the on-disk size of the data portion of the block. This is the
* compressed size if compression is enabled. Can only be called in the
* "block ready" state. Header is not compressed, and its size is not
* included in the return value.
*
* @return the on-disk size of the block, not including the header.
*/
public int getOnDiskSizeWithoutHeader() {
expectState(State.BLOCK_READY);
return onDiskBytesWithHeader.length - HEADER_SIZE;
}
/**
* Returns the on-disk size of the block. Can only be called in the
* "block ready" state.
*
* @return the on-disk size of the block ready to be written, including the
* header size
*/
public int getOnDiskSizeWithHeader() {
expectState(State.BLOCK_READY);
return onDiskBytesWithHeader.length;
}
/**
* The uncompressed size of the block data. Does not include header size.
*/
public int getUncompressedSizeWithoutHeader() {
expectState(State.BLOCK_READY);
return uncompressedBytesWithHeader.length - HEADER_SIZE;
}
/**
* The uncompressed size of the block data, including header size.
*/
public int getUncompressedSizeWithHeader() {
expectState(State.BLOCK_READY);
return uncompressedBytesWithHeader.length;
}
/** @return true if a block is being written */
public boolean isWriting() {
return state == State.WRITING;
}
/**
* Returns the number of bytes written into the current block so far, or
* zero if not writing the block at the moment. Note that this will return
* zero in the "block ready" state as well.
*
* @return the number of bytes written
*/
public int blockSizeWritten() {
if (state != State.WRITING)
return 0;
return this.unencodedDataSizeWritten;
}
/**
* Returns the header followed by the uncompressed data, even if using
* compression. This is needed for storing uncompressed blocks in the block
* cache. Can be called in the "writing" state or the "block ready" state.
*
* @return uncompressed block bytes for caching on write
*/
private byte[] getUncompressedDataWithHeader() {
expectState(State.BLOCK_READY);
return uncompressedBytesWithHeader;
}
private void expectState(State expectedState) {
if (state != expectedState) {
throw new IllegalStateException("Expected state: " + expectedState +
", actual state: " + state);
}
}
/**
* Similar to {@link #getUncompressedBufferWithHeader()} but returns a byte
* buffer.
*
* @return uncompressed block for caching on write in the form of a buffer
*/
public ByteBuffer getUncompressedBufferWithHeader() {
byte[] b = getUncompressedDataWithHeader();
return ByteBuffer.wrap(b, 0, b.length);
}
/**
* Takes the given {@link BlockWritable} instance, creates a new block of
* its appropriate type, writes the writable into this block, and flushes
* the block into the output stream. The writer is instructed not to buffer
* uncompressed bytes for cache-on-write.
*
* @param bw the block-writable object to write as a block
* @param out the file system output stream
* @throws IOException
*/
public void writeBlock(BlockWritable bw, FSDataOutputStream out)
throws IOException {
bw.writeToBlock(startWriting(bw.getBlockType()));
writeHeaderAndData(out);
}
/**
* Creates a new HFileBlock.
*/
public HFileBlock getBlockForCaching() {
HFileContext meta = new HFileContextBuilder()
.withHBaseCheckSum(false)
.withChecksumType(ChecksumType.NULL)
.withBytesPerCheckSum(0)
.build();
return new HFileBlock(blockType, getOnDiskSizeWithoutHeader(),
getUncompressedSizeWithoutHeader(), prevOffset,
getUncompressedBufferWithHeader(), DONT_FILL_HEADER, startOffset,
getOnDiskSizeWithoutHeader(), meta);
}
}
}
| |
/*******************************************************************************
* Copyright (c) 2006-2013 Bruno Ranschaert
* Released under the MIT License: http://opensource.org/licenses/MIT
* Library "jsontools"
******************************************************************************/
package com.sdicons.json.serializer;
import java.awt.Color;
import java.awt.Font;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.swing.JPanel;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@SuppressWarnings({"unchecked"})
public class HelpersTest
{
JSONSerializer serializer;
@Before
public void setUp()
throws Exception
{
serializer = new JSONSerializer();
}
@Test
public void testByte() throws SerializerException
{
Byte lByte = (byte) 5;
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lByte));
Assert.assertTrue(SerializerValue.REFERENCE == lResult.getType());
Byte lByte2 = (Byte) lResult.getReference();
Assert.assertTrue(lByte2.equals(lByte));
}
@Test
public void testShort() throws SerializerException
{
Short lShort = (short) 3;
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lShort));
Assert.assertTrue(SerializerValue.REFERENCE == lResult.getType());
Short lShort2 = (Short) lResult.getReference();
Assert.assertTrue(lShort2.equals(lShort));
}
@Test
public void testChar() throws SerializerException
{
Character lchar = 'x';
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lchar));
Assert.assertTrue(SerializerValue.REFERENCE == lResult.getType());
Character lChar2 = (Character) lResult.getReference();
Assert.assertTrue(lChar2.equals(lchar));
}
@Test
public void testInteger() throws SerializerException
{
Integer lInt = 17;
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lInt));
Assert.assertTrue(SerializerValue.REFERENCE == lResult.getType());
Integer lInt2 = (Integer) lResult.getReference();
Assert.assertTrue(lInt2.equals(lInt));
}
@Test
public void testLong() throws SerializerException
{
Long lLong = (long) 21;
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lLong));
Assert.assertTrue(SerializerValue.REFERENCE == lResult.getType());
Long lLong2 = (Long) lResult.getReference();
Assert.assertTrue(lLong2.equals(lLong));
}
@Test
public void testFloat() throws SerializerException
{
Float lFloat = new Float(21.331);
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lFloat));
Assert.assertTrue(SerializerValue.REFERENCE == lResult.getType());
Float lFloat2 = (Float) lResult.getReference();
Assert.assertTrue(lFloat2.equals(lFloat));
}
@Test
public void testDouble() throws SerializerException
{
Double lDouble = 21.156331;
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lDouble));
Assert.assertTrue(SerializerValue.REFERENCE == lResult.getType());
Double lDouble2 = (Double) lResult.getReference();
Assert.assertTrue(lDouble2.equals(lDouble));
}
@Test
public void testBigDecimal() throws SerializerException
{
BigDecimal lDecimal = new BigDecimal(21.331);
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lDecimal));
Assert.assertTrue(SerializerValue.REFERENCE == lResult.getType());
BigDecimal lDecimal2 = (BigDecimal) lResult.getReference();
Assert.assertTrue(lDecimal2.equals(lDecimal));
}
@Test
public void testBigInteger() throws SerializerException
{
BigInteger lBigInt = new BigInteger("123456789123456789123456789123456789");
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lBigInt));
Assert.assertTrue(SerializerValue.REFERENCE == lResult.getType());
BigInteger lBigInt2 = (BigInteger) lResult.getReference();
Assert.assertTrue(lBigInt2.equals(lBigInt));
}
@Test
public void testDate() throws SerializerException
{
final Date lDate = new Date();
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lDate));
Assert.assertTrue(SerializerValue.REFERENCE == lResult.getType());
final Date lDate2 = (Date) lResult.getReference();
Assert.assertTrue(lDate2.getTime() == lDate.getTime());
}
@SuppressWarnings("rawtypes")
@Test
public void testCollections() throws SerializerException
{
{
// Linked lists.
// //////////////
final List lLinkedList = new LinkedList();
lLinkedList.add("uno");
lLinkedList.add("duo");
lLinkedList.add("tres");
final List lNestedLinkedList = new LinkedList();
lNestedLinkedList.add("one");
lNestedLinkedList.add("two");
lNestedLinkedList.add("three");
lLinkedList.add(lNestedLinkedList);
// This will not work! See java bug 4756334.
// A container cannot contain itself when the hashcode is
// calculated, this generates a
// StackOverflow. According to Sun this behaviour is wanted.
// lLinkedList.add(lLinkedList);
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lLinkedList));
Assert.assertTrue(SerializerValue.REFERENCE == lResult.getType());
final List lLinkedList2 = (LinkedList) lResult.getReference();
Assert.assertTrue(lLinkedList.size() == lLinkedList2.size());
}
// Array lists.
// /////////////
{
final List lArrayList = new ArrayList();
lArrayList.add("uno");
lArrayList.add("duo");
lArrayList.add("tres");
final List lNestedArrayList = new ArrayList();
lNestedArrayList.add("one");
lNestedArrayList.add("two");
lNestedArrayList.add("three");
lArrayList.add(lNestedArrayList);
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lArrayList));
Assert.assertTrue(SerializerValue.REFERENCE == lResult.getType());
final List lArrayList2 = (ArrayList) lResult.getReference();
Assert.assertTrue(lArrayList.size() == lArrayList2.size());
}
// TreeSet.
// /////////
{
final Set lTreeSet = new TreeSet();
lTreeSet.add("uno");
lTreeSet.add("duo");
lTreeSet.add("tres");
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lTreeSet));
Assert.assertTrue(SerializerValue.REFERENCE == lResult.getType());
final Set lTreeSet2 = (TreeSet) lResult.getReference();
Assert.assertTrue(lTreeSet.size() == lTreeSet2.size());
}
}
@SuppressWarnings("rawtypes")
@Test
public void testMaps() throws SerializerException
{
{
// HashMap.
// //////////////
final Map lHashMap = new HashMap();
lHashMap.put("uno", "one");
lHashMap.put("duo", "two");
lHashMap.put("tres", "three");
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lHashMap));
Assert.assertTrue(SerializerValue.REFERENCE == lResult.getType());
final Map lHashMap2 = (HashMap) lResult.getReference();
Assert.assertTrue(lHashMap.size() == lHashMap2.size());
}
{
// TreeMap.
// //////////////
final Map lTreeMap = new TreeMap();
lTreeMap.put("uno", "one");
lTreeMap.put("duo", "two");
lTreeMap.put("tres", "three");
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lTreeMap));
Assert.assertTrue(SerializerValue.REFERENCE == lResult.getType());
final Map lTreeMap2 = (TreeMap) lResult.getReference();
Assert.assertTrue(lTreeMap.size() == lTreeMap2.size());
}
}
@Test
public void testColors() throws SerializerException
{
{
final Color lColor = Color.WHITE;
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lColor));
Assert.assertTrue(lResult.getReference().equals(lColor));
}
{
final Color lColor = Color.RED;
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lColor));
Assert.assertTrue(lResult.getReference().equals(lColor));
}
{
final Color lColor = Color.GREEN;
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lColor));
Assert.assertTrue(lResult.getReference().equals(lColor));
}
{
final Color lColor = Color.BLUE;
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lColor));
Assert.assertTrue(lResult.getReference().equals(lColor));
}
}
@Test
public void testFonts() throws SerializerException
{
final Font lFont = new JPanel().getFont();
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lFont));
Assert.assertTrue(lResult.getReference().equals(lFont));
}
static enum SimpsonEnum {HOMER, MARGE, LISA, BART, MAGGY}
@Test
public void testEnums() throws SerializerException
{
for (SimpsonEnum lSimpson : SimpsonEnum.values()) {
SerializerValue lResult = serializer.unmarshal(serializer.marshal(lSimpson));
Assert.assertTrue(lResult.getReference() == lSimpson);
}
}
}
| |
package com.sachin.filemanager.adapters;
import android.content.Context;
import android.graphics.Color;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.sachin.filemanager.FileManager;
import com.sachin.filemanager.R;
import com.sachin.filemanager.utils.FileUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class FileListAdapter extends ArrayAdapter<String> {
private List<String> fileArrayList;
private ArrayList<String> selectedFiles; //mMultiSelectData
private ArrayList<Integer> selectedFilePosition; //positions
private Context context;
private FileManager fileManager;
private boolean multiSelect;
// private ThumbnailCreator thumbnailCreator;
//private ApkIconCreator iconCreator;
private int thumbnailSize;
private boolean thumbsAllowed;
private boolean showFilePermissions;
private int lastPosition = -1;
public FileListAdapter(Context context, int resource, List<String> objects, FileManager manager) {
super(context, resource, objects);
this.context = context;
fileManager = manager;
multiSelect = false;
thumbsAllowed = true;
selectedFilePosition = new ArrayList<>();
thumbnailSize = (int) context.getResources().getDimension(R.dimen.folder_icon_size);
if (objects != null) {
fileArrayList = objects;
} else {
fileArrayList = new ArrayList<>(fileManager.setHomeDir
(Environment.getExternalStorageDirectory().getPath()));
}
}
public List<String> getFileArrayList() {
return fileArrayList;
}
public FileManager getFileManager() {
return fileManager;
}
public boolean hasMultiSelectData() {
return (selectedFiles != null && selectedFiles.size() > 0);
}
public void setThumbsAllowed(boolean value) {
this.thumbsAllowed = value;
notifyDataSetChanged();
}
public void setShowFilePermissions(boolean enable) {
this.showFilePermissions = enable;
notifyDataSetChanged();
}
public boolean isMultiSelect() {
return multiSelect;
}
public void setMultiSelect(boolean multiSelect) {
this.multiSelect = multiSelect;
if (!multiSelect)
dismissMultiSelect(true);
notifyDataSetChanged();
}
public int getSelectedItemCount() {
if (selectedFiles != null && selectedFiles.size() > 0) {
return selectedFiles.size();
} else {
return 0;
}
}
public void selectItem(int position, String path) {
if (selectedFilePosition == null)
selectedFilePosition = new ArrayList<>();
if (selectedFiles == null) {
selectedFilePosition.add(position);
addToMultiSelectFile(path);
} else if (selectedFiles.contains(path)) {
if (selectedFilePosition.contains(position))
selectedFilePosition.remove(new Integer(position));
selectedFiles.remove(path);
} else {
selectedFilePosition.add(position);
addToMultiSelectFile(path);
}
notifyDataSetChanged();
}
private void addToMultiSelectFile(String src) {
if (selectedFiles == null)
selectedFiles = new ArrayList<>();
selectedFiles.add(src);
}
private void dismissMultiSelect(boolean clearData) {
multiSelect = false;
if (selectedFilePosition != null && !selectedFilePosition.isEmpty())
selectedFilePosition.clear();
if (clearData)
if (selectedFiles != null && !selectedFiles.isEmpty())
selectedFiles.clear();
notifyDataSetChanged();
}
@Nullable
@Override
public String getItem(int position) {
return fileArrayList.get(position);
}
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
lastPosition = -1;
}
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder viewHolder;
String currentDir = fileManager.getCurrentDir();
final File file = new File(currentDir + "/" + fileArrayList.get(position));
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_layout_item_list, parent, false);
viewHolder = new ViewHolder();
viewHolder.itemIcon = (ImageView) convertView.findViewById(R.id.row_image);
viewHolder.itemName = (TextView) convertView.findViewById(R.id.top_view);
viewHolder.itemDetails = (TextView) convertView.findViewById(R.id.bottom_view);
viewHolder.itemOptions = (ImageView) convertView.findViewById(R.id.more_file_options);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
lastPosition = position;
if (selectedFilePosition != null && selectedFilePosition.contains(position))
//convertView.setBackgroundColor(context.getResources().getColor(R.color.selected));
//else
convertView.setBackgroundColor(Color.TRANSPARENT);
//Drawable drawable = FileUtil.getFileIcon(context,file);
//viewHolder.itemIcon.setImageDrawable(drawable);
if (thumbsAllowed && file != null && file.isFile()) {
String ext = file.toString();
String sub_ext = ext.substring(ext.lastIndexOf(".") + 1);
/* if (thumbnailCreator == null) {
thumbnailCreator = new ThumbnailCreator(thumbnailSize, thumbnailSize);
}
*/
// if (iconCreator == null) {
// iconCreator = new ApkIconCreator(context);
//}
if (FileUtil.identify(sub_ext).equals(FileUtil.TYPE_IMAGE)) {
if (file.length() != 0) {
// Bitmap thumb = thumbnailCreator.isBitmapCached(file.getPath());
/* if (thumb == null) {
final Handler handle = new Handler(new Handler.Callback() {
public boolean handleMessage(Message msg) {
notifyDataSetChanged();
return true;
}
});
//thumbnailCreator.createNewThumbnail(fileArrayList, fileManager.getCurrentDir(), handle);
if (!thumbnailCreator.isAlive()) {
if (thumbnailCreator.isInterrupted()) {
thumbnailCreator.start();
}
}
} else {
viewHolder.itemIcon.setImageBitmap(thumb);
}
} else {
//viewHolder.itemIcon.setImageResource(R.drawable.myfiles_file_images);
}
*/
} else if (FileUtil.identify(sub_ext).equals(FileUtil.TYPE_APK)) {
// Drawable appIcon = iconCreator.isApkIconCached(file.getPath());
if (file.length() != 0) {
/*if (appIcon == null) {
final Handler handler = new Handler(new Handler.Callback() {
public boolean handleMessage(Message msg) {
notifyDataSetChanged();
return true;
}
});
//iconCreator.createIcon(fileArrayList, fileManager.getCurrentDir(), handler);
if (!iconCreator.isAlive()) {
if (iconCreator.isInterrupted()) {
iconCreator.start();
}
}
} else {
viewHolder.itemIcon.setImageDrawable(appIcon);
}*/
} else {
// viewHolder.itemIcon.setImageResource(R.drawable.ic_file_apk_mtrl);
}
//viewHolder.itemIcon.setImageDrawable(iconCreator.getApkIcon(file));
}
}
}
String fileSize = FileUtil.calculateSize(file);
if (showFilePermissions)
viewHolder.itemDetails.setText(fileSize + FileUtil.getFilePermissions(file));
else
viewHolder.itemDetails.setText(fileSize);
viewHolder.itemName.setText(file.getName());
return convertView;
}
private class ViewHolder {
private ImageView itemIcon;
private TextView itemName;
private TextView itemDetails;
private ImageView itemOptions;
}
}
| |
/**
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.core;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.SecureRandom;
import org.adicoin.core.Utils;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1OutputStream;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERSequenceGenerator;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.asn1.sec.SECNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.signers.ECDSASigner;
/**
* Represents an elliptic curve keypair that we own and can use for signing transactions. Currently,
* Bouncy Castle is used. In future this may become an interface with multiple implementations using different crypto
* libraries. The class also provides a static method that can verify a signature with just the public key.<p>
*/
public class ECKey implements Serializable {
private static final ECDomainParameters ecParams;
private static final SecureRandom secureRandom;
private static final long serialVersionUID = -728224901792295832L;
static {
// All clients must agree on the curve to use by agreement. BitCoin uses secp256k1.
X9ECParameters params = SECNamedCurves.getByName("secp256k1");
ecParams = new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH());
secureRandom = new SecureRandom();
}
private final BigInteger priv;
private final byte[] pub;
transient private byte[] pubKeyHash;
/** Generates an entirely new keypair. */
public ECKey() {
ECKeyPairGenerator generator = new ECKeyPairGenerator();
ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(ecParams, secureRandom);
generator.init(keygenParams);
AsymmetricCipherKeyPair keypair = generator.generateKeyPair();
ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate();
ECPublicKeyParameters pubParams = (ECPublicKeyParameters) keypair.getPublic();
priv = privParams.getD();
// The public key is an encoded point on the elliptic curve. It has no meaning independent of the curve.
pub = pubParams.getQ().getEncoded();
}
/**
* Construct an ECKey from an ASN.1 encoded private key. These are produced by OpenSSL and stored by the BitCoin
* reference implementation in its wallet.
*/
public static ECKey fromASN1(byte[] asn1privkey) {
return new ECKey(extractPrivateKeyFromASN1(asn1privkey));
}
/**
* Output this ECKey as an ASN.1 encoded private key, as understood by OpenSSL or used by the BitCoin reference
* implementation in its wallet storage format.
*/
public byte[] toASN1(){
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream(400);
ASN1OutputStream encoder = new ASN1OutputStream(baos);
// ASN1_SEQUENCE(EC_PRIVATEKEY) = {
// ASN1_SIMPLE(EC_PRIVATEKEY, version, LONG),
// ASN1_SIMPLE(EC_PRIVATEKEY, privateKey, ASN1_OCTET_STRING),
// ASN1_EXP_OPT(EC_PRIVATEKEY, parameters, ECPKPARAMETERS, 0),
// ASN1_EXP_OPT(EC_PRIVATEKEY, publicKey, ASN1_BIT_STRING, 1)
// } ASN1_SEQUENCE_END(EC_PRIVATEKEY)
DERSequenceGenerator seq = new DERSequenceGenerator(encoder);
seq.addObject(new DERInteger(1)); // version
seq.addObject(new DEROctetString(priv.toByteArray()));
seq.addObject(new DERTaggedObject(0, SECNamedCurves.getByName("secp256k1").getDERObject()));
seq.addObject(new DERTaggedObject(1, new DERBitString(getPubKey())));
seq.close();
encoder.close();
return baos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen, writing to memory stream.
}
}
/**
* Creates an ECKey given only the private key. This works because EC public keys are derivable from their
* private keys by doing a multiply with the generator value.
*/
public ECKey(BigInteger privKey) {
this.priv = privKey;
this.pub = publicKeyFromPrivate(privKey);
}
/** Derive the public key by doing a point multiply of G * priv. */
private static byte[] publicKeyFromPrivate(BigInteger privKey) {
return ecParams.getG().multiply(privKey).getEncoded();
}
/** Gets the hash160 form of the public key (as seen in addresses). */
public byte[] getPubKeyHash() {
if (pubKeyHash == null)
pubKeyHash = Utils.sha256hash160(this.pub);
return pubKeyHash;
}
/**
* Gets the raw public key value. This appears in transaction scriptSigs. Note that this is <b>not</b> the same
* as the pubKeyHash/address.
*/
public byte[] getPubKey() {
return pub;
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append("pub:").append(Utils.bytesToHexString(pub));
b.append(" priv:").append(Utils.bytesToHexString(priv.toByteArray()));
return b.toString();
}
/**
* Calcuates an ECDSA signature in DER format for the given input hash. Note that the input is expected to be
* 32 bytes long.
*/
public byte[] sign(byte[] input) {
ECDSASigner signer = new ECDSASigner();
ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(priv, ecParams);
signer.init(true, privKey);
BigInteger[] sigs = signer.generateSignature(input);
// What we get back from the signer are the two components of a signature, r and s. To get a flat byte stream
// of the type used by BitCoin we have to encode them using DER encoding, which is just a way to pack the two
// components into a structure.
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DERSequenceGenerator seq = new DERSequenceGenerator(bos);
seq.addObject(new DERInteger(sigs[0]));
seq.addObject(new DERInteger(sigs[1]));
seq.close();
return bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
}
/**
* Verifies the given ASN.1 encoded ECDSA signature against a hash using the public key.
* @param data Hash of the data to verify.
* @param signature ASN.1 encoded signature.
* @param pub The public key bytes to use.
*/
public static boolean verify(byte[] data, byte[] signature, byte[] pub) {
ECDSASigner signer = new ECDSASigner();
ECPublicKeyParameters params = new ECPublicKeyParameters(ecParams.getCurve().decodePoint(pub), ecParams);
signer.init(false, params);
try {
ASN1InputStream decoder = new ASN1InputStream(signature);
DERSequence seq = (DERSequence) decoder.readObject();
DERInteger r = (DERInteger) seq.getObjectAt(0);
DERInteger s = (DERInteger) seq.getObjectAt(1);
decoder.close();
return signer.verifySignature(data, r.getValue(), s.getValue());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Verifies the given ASN.1 encoded ECDSA signature against a hash using the public key.
* @param data Hash of the data to verify.
* @param signature ASN.1 encoded signature.
*/
public boolean verify(byte[] data, byte[] signature) {
return ECKey.verify(data, signature, pub);
}
private static BigInteger extractPrivateKeyFromASN1(byte[] asn1privkey) {
// To understand this code, see the definition of the ASN.1 format for EC private keys in the OpenSSL source
// code in ec_asn1.c:
//
// ASN1_SEQUENCE(EC_PRIVATEKEY) = {
// ASN1_SIMPLE(EC_PRIVATEKEY, version, LONG),
// ASN1_SIMPLE(EC_PRIVATEKEY, privateKey, ASN1_OCTET_STRING),
// ASN1_EXP_OPT(EC_PRIVATEKEY, parameters, ECPKPARAMETERS, 0),
// ASN1_EXP_OPT(EC_PRIVATEKEY, publicKey, ASN1_BIT_STRING, 1)
// } ASN1_SEQUENCE_END(EC_PRIVATEKEY)
//
try {
ASN1InputStream decoder = new ASN1InputStream(asn1privkey);
DERSequence seq = (DERSequence) decoder.readObject();
assert seq.size() == 4 : "Input does not appear to be an ASN.1 OpenSSL EC private key";
assert ((DERInteger) seq.getObjectAt(0)).getValue().equals(BigInteger.ONE) : "Input is of wrong version";
DEROctetString key = (DEROctetString) seq.getObjectAt(1);
decoder.close();
return new BigInteger(key.getOctets());
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen, reading from memory stream.
}
}
}
| |
/*
* Copyright 2018 LinkedIn Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package com.github.ambry.frontend;
import com.codahale.metrics.MetricRegistry;
import com.github.ambry.account.Account;
import com.github.ambry.account.Container;
import com.github.ambry.account.InMemAccountService;
import com.github.ambry.account.InMemAccountServiceFactory;
import com.github.ambry.clustermap.ClusterMap;
import com.github.ambry.clustermap.MockClusterMap;
import com.github.ambry.commons.ByteBufferReadableStreamChannel;
import com.github.ambry.config.FrontendConfig;
import com.github.ambry.config.VerifiableProperties;
import com.github.ambry.messageformat.BlobProperties;
import com.github.ambry.rest.MockRestRequest;
import com.github.ambry.rest.MockRestResponseChannel;
import com.github.ambry.rest.ResponseStatus;
import com.github.ambry.rest.RestRequest;
import com.github.ambry.rest.RestResponseChannel;
import com.github.ambry.rest.RestServiceErrorCode;
import com.github.ambry.rest.RestServiceException;
import com.github.ambry.rest.RestUtils;
import com.github.ambry.router.GetBlobOptionsBuilder;
import com.github.ambry.router.GetBlobResult;
import com.github.ambry.router.InMemoryRouter;
import com.github.ambry.router.PutBlobOptionsBuilder;
import com.github.ambry.router.ReadableStreamChannel;
import com.github.ambry.utils.TestUtils;
import com.github.ambry.utils.Utils;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;
import static com.github.ambry.utils.TestUtils.*;
import static org.junit.Assert.*;
/**
* Tests for {@link TtlUpdateHandler}.
*/
public class TtlUpdateHandlerTest {
private static final InMemAccountService ACCOUNT_SERVICE =
new InMemAccountServiceFactory(false, true).getAccountService();
private static final Account REF_ACCOUNT = ACCOUNT_SERVICE.createAndAddRandomAccount();
private static final Container REF_CONTAINER = REF_ACCOUNT.getContainerById(Container.DEFAULT_PRIVATE_CONTAINER_ID);
private static final ClusterMap CLUSTER_MAP;
private static final String SERVICE_ID = "TtlUpdateHandlerTest";
private static final BlobProperties BLOB_PROPERTIES =
new BlobProperties(100, SERVICE_ID, null, null, false, TTL_SECS, REF_ACCOUNT.getId(), REF_CONTAINER.getId(),
false, null);
private static final byte[] BLOB_DATA = TestUtils.getRandomBytes(100);
static {
try {
CLUSTER_MAP = new MockClusterMap();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private final TtlUpdateHandler ttlUpdateHandler;
private final String blobId;
private final InMemoryRouter router = new InMemoryRouter(new VerifiableProperties(new Properties()), CLUSTER_MAP);
private final FrontendTestSecurityServiceFactory securityServiceFactory = new FrontendTestSecurityServiceFactory();
private final FrontendTestIdConverterFactory idConverterFactory = new FrontendTestIdConverterFactory();
public TtlUpdateHandlerTest() throws Exception {
FrontendMetrics metrics = new FrontendMetrics(new MetricRegistry());
FrontendConfig config = new FrontendConfig(new VerifiableProperties(new Properties()));
AccountAndContainerInjector accountAndContainerInjector =
new AccountAndContainerInjector(ACCOUNT_SERVICE, metrics, config);
ttlUpdateHandler =
new TtlUpdateHandler(router, securityServiceFactory.getSecurityService(), idConverterFactory.getIdConverter(),
accountAndContainerInjector, metrics, CLUSTER_MAP);
ReadableStreamChannel channel = new ByteBufferReadableStreamChannel(ByteBuffer.wrap(BLOB_DATA));
blobId = router.putBlob(BLOB_PROPERTIES, new byte[0], channel, new PutBlobOptionsBuilder().build())
.get(1, TimeUnit.SECONDS);
idConverterFactory.translation = blobId;
}
/**
* Tests the case where TTL update succeeds
* @throws Exception
*/
@Test
public void handleGoodCaseTest() throws Exception {
RestRequest restRequest = new MockRestRequest(MockRestRequest.DUMMY_DATA, null);
restRequest.setArg(RestUtils.Headers.BLOB_ID, blobId);
restRequest.setArg(RestUtils.Headers.SERVICE_ID, SERVICE_ID);
verifyTtlUpdate(restRequest, REF_ACCOUNT, REF_CONTAINER);
}
/**
* Tests for cases when downstream services fail or return an exception
* @throws Exception
*/
@Test
public void downstreamServicesFailureTest() throws Exception {
securityServiceFailureTest();
idConverterFailureTest();
routerFailureTest();
badArgsTest();
}
// helpers
/**
* Sends the given {@link RestRequest} to the {@link TtlUpdateHandler} and waits for the response and returns it.
* @param restRequest the {@link RestRequest} to send.
* @param restResponseChannel the {@link RestResponseChannel} where headers will be set.
* @throws Exception
*/
private void sendRequestGetResponse(RestRequest restRequest, RestResponseChannel restResponseChannel)
throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Exception> exceptionRef = new AtomicReference<>();
ttlUpdateHandler.handle(restRequest, restResponseChannel, (result, exception) -> {
exceptionRef.set(exception);
latch.countDown();
});
assertTrue("Latch did not count down in time", latch.await(1, TimeUnit.SECONDS));
if (exceptionRef.get() != null) {
throw exceptionRef.get();
}
}
/**
* Verifies that the TTL is {@code expectedTtlSecs}
* @param expectedTtlSecs the expected TTL (in secs) of the blob
* @throws Exception
*/
private void assertTtl(long expectedTtlSecs) throws Exception {
GetBlobResult result = router.getBlob(blobId, new GetBlobOptionsBuilder().build()).get(1, TimeUnit.SECONDS);
assertEquals("TTL not as expected", expectedTtlSecs,
result.getBlobInfo().getBlobProperties().getTimeToLiveInSeconds());
}
// handleGoodCaseTest()
/**
* Verifies that the TTL of the blob is updated
* @param restRequest the {@link RestRequest} to get a signed URL.
* @param expectedAccount the {@link Account} that should be populated in {@link RestRequest}.
* @param expectedContainer the {@link Container} that should be populated in {@link RestRequest}.
* @throws Exception
*/
private void verifyTtlUpdate(RestRequest restRequest, Account expectedAccount, Container expectedContainer)
throws Exception {
assertTtl(TTL_SECS);
RestResponseChannel restResponseChannel = new MockRestResponseChannel();
sendRequestGetResponse(restRequest, restResponseChannel);
assertEquals("ResponseStatus not as expected", ResponseStatus.Ok, restResponseChannel.getStatus());
assertNotNull("Date has not been set", restResponseChannel.getHeader(RestUtils.Headers.DATE));
assertEquals("Content-length is not as expected", 0,
Integer.parseInt((String) restResponseChannel.getHeader(RestUtils.Headers.CONTENT_LENGTH)));
assertEquals("Account not as expected", expectedAccount,
restRequest.getArgs().get(RestUtils.InternalKeys.TARGET_ACCOUNT_KEY));
assertEquals("Container not as expected", expectedContainer,
restRequest.getArgs().get(RestUtils.InternalKeys.TARGET_CONTAINER_KEY));
assertTtl(Utils.Infinite_Time);
}
// downstreamServicesFailureTest()
/**
* Tests the case where the {@link SecurityService} denies the request.
* @throws Exception
*/
private void securityServiceFailureTest() throws Exception {
String msg = "@@security-service-expected@@";
securityServiceFactory.exceptionToReturn = new IllegalStateException(msg);
securityServiceFactory.mode = FrontendTestSecurityServiceFactory.Mode.ProcessRequest;
verifyFailureWithMsg(msg);
securityServiceFactory.mode = FrontendTestSecurityServiceFactory.Mode.PostProcessRequest;
verifyFailureWithMsg(msg);
securityServiceFactory.mode = FrontendTestSecurityServiceFactory.Mode.ProcessResponse;
verifyFailureWithMsg(msg);
securityServiceFactory.exceptionToThrow = new IllegalStateException(msg);
securityServiceFactory.exceptionToReturn = null;
securityServiceFactory.mode = FrontendTestSecurityServiceFactory.Mode.ProcessRequest;
verifyFailureWithMsg(msg);
securityServiceFactory.mode = FrontendTestSecurityServiceFactory.Mode.PostProcessRequest;
verifyFailureWithMsg(msg);
securityServiceFactory.mode = FrontendTestSecurityServiceFactory.Mode.ProcessResponse;
verifyFailureWithMsg(msg);
securityServiceFactory.exceptionToThrow = null;
}
/**
* Tests the case where the {@link IdConverter} fails or returns an exception.
* @throws Exception
*/
private void idConverterFailureTest() throws Exception {
String msg = "@@id-converter-expected@@";
idConverterFactory.exceptionToReturn = new IllegalStateException(msg);
verifyFailureWithMsg(msg);
idConverterFactory.exceptionToReturn = null;
idConverterFactory.exceptionToThrow = new IllegalStateException(msg);
verifyFailureWithMsg(msg);
idConverterFactory.exceptionToThrow = null;
}
/**
* Tests the case where the {@link com.github.ambry.router.Router} fails or returns an exception
* @throws Exception
*/
private void routerFailureTest() throws Exception {
// get the router to throw a RuntimeException
Properties properties = new Properties();
properties.setProperty(InMemoryRouter.OPERATION_THROW_EARLY_RUNTIME_EXCEPTION, "true");
router.setVerifiableProperties(new VerifiableProperties(properties));
verifyFailureWithMsg(InMemoryRouter.OPERATION_THROW_EARLY_RUNTIME_EXCEPTION);
// get the router to return a RuntimeException
properties = new Properties();
properties.setProperty(InMemoryRouter.OPERATION_THROW_LATE_RUNTIME_EXCEPTION, "true");
router.setVerifiableProperties(new VerifiableProperties(properties));
verifyFailureWithMsg(InMemoryRouter.OPERATION_THROW_LATE_RUNTIME_EXCEPTION);
router.setVerifiableProperties(new VerifiableProperties(new Properties()));
}
/**
* Tests for expected failures with bad arguments
* @throws Exception
*/
private void badArgsTest() throws Exception {
RestRequest restRequest = new MockRestRequest(MockRestRequest.DUMMY_DATA, null);
restRequest.setArg(RestUtils.Headers.BLOB_ID, blobId);
// no service ID
verifyFailureWithErrorCode(restRequest, RestServiceErrorCode.MissingArgs);
restRequest = new MockRestRequest(MockRestRequest.DUMMY_DATA, null);
restRequest.setArg(RestUtils.Headers.SERVICE_ID, SERVICE_ID);
// no blob ID
verifyFailureWithErrorCode(restRequest, RestServiceErrorCode.MissingArgs);
restRequest = new MockRestRequest(MockRestRequest.DUMMY_DATA, null);
// not a valid blob ID
restRequest.setArg(RestUtils.Headers.BLOB_ID, "abcd");
idConverterFactory.translation = "abcd";
restRequest.setArg(RestUtils.Headers.SERVICE_ID, SERVICE_ID);
verifyFailureWithErrorCode(restRequest, RestServiceErrorCode.BadRequest);
}
/**
* Verifies that attempting to update TTL fails with the provided {@code msg}.
* @param msg the message in the {@link Exception} that will be thrown.
* @throws Exception
*/
private void verifyFailureWithMsg(String msg) throws Exception {
RestRequest restRequest = new MockRestRequest(MockRestRequest.DUMMY_DATA, null);
restRequest.setArg(RestUtils.Headers.BLOB_ID, blobId);
restRequest.setArg(RestUtils.Headers.SERVICE_ID, SERVICE_ID);
try {
sendRequestGetResponse(restRequest, new MockRestResponseChannel());
fail("Request should have failed");
} catch (Exception e) {
if (!msg.equals(e.getMessage())) {
throw e;
}
}
}
/**
* Verifies that processing {@code restRequest} fails with {@code errorCode}
* @param restRequest the {@link RestRequest} that is expected to fail
* @param errorCode the {@link RestServiceErrorCode} that it should fail with
* @throws Exception
*/
private void verifyFailureWithErrorCode(RestRequest restRequest, RestServiceErrorCode errorCode) throws Exception {
try {
sendRequestGetResponse(restRequest, new MockRestResponseChannel());
fail("Request should have failed");
} catch (RestServiceException e) {
assertEquals("Unexpected RestServiceErrorCode", errorCode, e.getErrorCode());
}
}
}
| |
/*
* Copyright 2004-2010 the Seasar Foundation and the Others.
*
* 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 example.dao;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Connection;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;
import javax.annotation.Generated;
import javax.sql.DataSource;
import org.seasar.doma.internal.jdbc.command.EntityResultListHandler;
import org.seasar.doma.internal.jdbc.command.EntitySingleResultHandler;
import org.seasar.doma.internal.jdbc.command.EntityStreamHandler;
import org.seasar.doma.internal.jdbc.dao.AbstractDao;
import org.seasar.doma.internal.jdbc.util.SqlFileUtil;
import org.seasar.doma.jdbc.IterationCallback;
import org.seasar.doma.jdbc.SelectOptions;
import org.seasar.doma.jdbc.command.DeleteCommand;
import org.seasar.doma.jdbc.command.InsertCommand;
import org.seasar.doma.jdbc.command.ScriptCommand;
import org.seasar.doma.jdbc.command.SelectCommand;
import org.seasar.doma.jdbc.command.UpdateCommand;
import org.seasar.doma.jdbc.query.AutoDeleteQuery;
import org.seasar.doma.jdbc.query.AutoInsertQuery;
import org.seasar.doma.jdbc.query.AutoUpdateQuery;
import org.seasar.doma.jdbc.query.SqlFileScriptQuery;
import org.seasar.doma.jdbc.query.SqlFileSelectQuery;
import example.entity.Emp;
import example.entity._Emp;
/**
* @author taedium
*
*/
@Generated("")
public class EmpDaoImpl extends AbstractDao implements EmpDao {
private static Method method0 = getDeclaredMethod(EmpDaoImpl.class,
"selectById", Integer.class, SelectOptions.class);
private static Method method1 = getDeclaredMethod(EmpDaoImpl.class,
"selectByNameAndSalary", String.class, BigDecimal.class,
SelectOptions.class);
private static Method method2 = getDeclaredMethod(EmpDaoImpl.class,
"selectByExample", Emp.class);
private static Method method3 = getDeclaredMethod(EmpDaoImpl.class,
"insert", Emp.class);
private static Method method4 = getDeclaredMethod(EmpDaoImpl.class,
"update", Emp.class);
private static Method method5 = getDeclaredMethod(EmpDaoImpl.class,
"delete", Emp.class);
private static Method method6 = getDeclaredMethod(EmpDaoImpl.class,
"iterate", IterationCallback.class);
private static Method method7 = getDeclaredMethod(EmpDaoImpl.class,
"execute");
public EmpDaoImpl() {
super(new ExampleConfig());
}
public EmpDaoImpl(Connection connection) {
super(new ExampleConfig(), connection);
}
public EmpDaoImpl(DataSource dataSource) {
super(new ExampleConfig(), dataSource);
}
@Override
public Emp selectById(Integer id, SelectOptions option) {
SqlFileSelectQuery query = getQueryImplementors()
.createSqlFileSelectQuery(method0);
query.setConfig(__config);
query.setSqlFilePath(SqlFileUtil.buildPath("example.dao.EmpDao",
"selectById"));
query.addParameter("id", Integer.class, id);
query.setOptions(option);
query.setCallerClassName("example.dao.EmpDao");
query.setCallerMethodName("selectById");
query.prepare();
SelectCommand<Emp> command = getCommandImplementors()
.createSelectCommand(
method0,
query,
new EntitySingleResultHandler<Emp>(_Emp
.getSingletonInternal()));
return command.execute();
}
@Override
public List<Emp> selectByNameAndSalary(String name, BigDecimal salary,
SelectOptions option) {
SqlFileSelectQuery query = getQueryImplementors()
.createSqlFileSelectQuery(method1);
query.setConfig(__config);
query.setSqlFilePath(SqlFileUtil.buildPath("example.dao.EmpDao",
"selectByNameAndSalary"));
query.addParameter("name", String.class, name);
query.addParameter("salary", BigDecimal.class, salary);
query.setOptions(option);
query.setCallerClassName("example.dao.EmpDao");
query.setCallerMethodName("selectByNameAndSalary");
query.prepare();
SelectCommand<List<Emp>> command = getCommandImplementors()
.createSelectCommand(
method1,
query,
new EntityResultListHandler<Emp>(_Emp
.getSingletonInternal()));
return command.execute();
}
@Override
public List<Emp> selectByExample(Emp emp) {
SqlFileSelectQuery query = getQueryImplementors()
.createSqlFileSelectQuery(method2);
query.setConfig(__config);
query.setSqlFilePath(SqlFileUtil.buildPath("example.dao.EmpDao",
"selectByNameAndSalary"));
query.addParameter("emp", Emp.class, emp);
query.setCallerClassName("example.dao.EmpDao");
query.setCallerMethodName("selectByNameAndSalary");
query.prepare();
SelectCommand<List<Emp>> command = getCommandImplementors()
.createSelectCommand(
method2,
query,
new EntityResultListHandler<Emp>(_Emp
.getSingletonInternal()));
return command.execute();
}
@Override
public int insert(Emp entity) {
AutoInsertQuery<Emp> query = getQueryImplementors()
.createAutoInsertQuery(method3, _Emp.getSingletonInternal());
query.setConfig(__config);
query.setEntity(entity);
query.setCallerClassName("example.dao.EmpDao");
query.setCallerMethodName("insert");
query.prepare();
InsertCommand command = getCommandImplementors().createInsertCommand(
method3, query);
return command.execute();
}
@Override
public int update(Emp entity) {
AutoUpdateQuery<Emp> query = getQueryImplementors()
.createAutoUpdateQuery(method4, _Emp.getSingletonInternal());
query.setConfig(__config);
query.setEntity(entity);
query.setCallerClassName("example.dao.EmpDao");
query.setCallerMethodName("update");
query.prepare();
UpdateCommand command = getCommandImplementors().createUpdateCommand(
method4, query);
return command.execute();
}
@Override
public int delete(Emp entity) {
AutoDeleteQuery<Emp> query = getQueryImplementors()
.createAutoDeleteQuery(method5, _Emp.getSingletonInternal());
query.setConfig(__config);
query.setEntity(entity);
query.setCallerClassName("example.dao.EmpDao");
query.setCallerMethodName("delete");
query.prepare();
DeleteCommand command = getCommandImplementors().createDeleteCommand(
method5, query);
return command.execute();
}
@Override
public Integer stream(Function<Stream<Emp>, Integer> mapper) {
SqlFileSelectQuery query = getQueryImplementors()
.createSqlFileSelectQuery(method6);
query.setConfig(__config);
query.setSqlFilePath(SqlFileUtil.buildPath("example.dao.EmpDao",
"iterate"));
query.setCallerClassName("example.dao.EmpDao");
query.setCallerMethodName("iterate");
query.prepare();
SelectCommand<Integer> command = getCommandImplementors()
.createSelectCommand(
method6,
query,
new EntityStreamHandler<Emp, Integer>(_Emp
.getSingletonInternal(), mapper));
return command.execute();
}
@Override
public void execute() {
SqlFileScriptQuery query = getQueryImplementors()
.createSqlFileScriptQuery(method7);
query.setConfig(__config);
query.setScriptFilePath(SqlFileUtil.buildPath("example.dao.EmpDao",
"execute"));
query.setCallerClassName("example.dao.EmpDao");
query.setCallerMethodName("execute");
query.prepare();
ScriptCommand command = getCommandImplementors().createScriptCommand(
method7, query);
command.execute();
}
}
| |
// Copyright (c) Keith D Gregory
//
// 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.kdgregory.pathfinder.core;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.junit.Test;
import static org.junit.Assert.*;
import com.kdgregory.pathfinder.core.impl.PathRepoImpl;
public class TestPathRepo
{
//----------------------------------------------------------------------------
// Test Data
//----------------------------------------------------------------------------
private final static String BOGUS_URL = "/blahblahblah";
private final static String URL_1 = "/foo";
private final static String URL_2 = "/bar";
private final static String URL_3 = "/baz";
private final static MyDestination DEST_1 = new MyDestination();
private final static MyDestination DEST_2 = new MyDestination();
//----------------------------------------------------------------------------
// Support Code
//----------------------------------------------------------------------------
private static class MyDestination
implements Destination
{
@Override
public boolean isDisplayed(Map<InvocationOptions,Boolean> options)
{
throw new IllegalStateException("we shouldn't be testing output");
}
@Override
public String toString(Map<InvocationOptions,Boolean> options)
{
throw new IllegalStateException("we shouldn't be testing output");
}
}
//----------------------------------------------------------------------------
// TestCases
//----------------------------------------------------------------------------
@Test
public void testMethodStrings() throws Exception
{
assertEquals("ALL", "", HttpMethod.ALL.toString());
assertEquals("GET", "GET", HttpMethod.GET.toString());
assertEquals("POST", "POST", HttpMethod.POST.toString());
assertEquals("PUT", "PUT", HttpMethod.PUT.toString());
assertEquals("DELETE", "DELETE", HttpMethod.DELETE.toString());
}
@Test
public void testPutAndGetWithExplicitMethod() throws Exception
{
PathRepoImpl repo = new PathRepoImpl();
repo.put(URL_1, HttpMethod.GET, DEST_1);
assertSame("can retrive", DEST_1, repo.get(URL_1, HttpMethod.GET));
assertNull("no entry for arbitrary method", repo.get(URL_1, HttpMethod.POST));
repo.put(URL_1, HttpMethod.POST, DEST_2);
assertSame("first destination not affected", DEST_1, repo.get(URL_1, HttpMethod.GET));
assertSame("can retrieve new destination", DEST_2, repo.get(URL_1, HttpMethod.POST));
assertNull("no entry for arbitrary method", repo.get(URL_1, HttpMethod.DELETE));
repo.put(URL_1, HttpMethod.GET, DEST_2);
assertSame("first destination overwritten", DEST_2, repo.get(URL_1, HttpMethod.GET));
repo.put(URL_2, HttpMethod.GET, DEST_1);
assertSame("second url written", DEST_1, repo.get(URL_2, HttpMethod.GET));
assertSame("doesn't affect first", DEST_2, repo.get(URL_1, HttpMethod.GET));
assertNull("no entry for arbitrary", repo.get(URL_2, HttpMethod.POST));
// getting nonexistent URL shouldn't throw NPE
assertNull(repo.get(BOGUS_URL, HttpMethod.GET));
}
@Test
public void testPutAndGetAll() throws Exception
{
PathRepoImpl repo = new PathRepoImpl();
repo.put(URL_1, DEST_1);
assertEquals("retrieve via ALL", DEST_1, repo.get(URL_1, HttpMethod.ALL));
assertEquals("retrieve via GET", DEST_1, repo.get(URL_1, HttpMethod.GET));
assertEquals("retrieve via POST", DEST_1, repo.get(URL_1, HttpMethod.POST));
assertEquals("retrieve via PUT", DEST_1, repo.get(URL_1, HttpMethod.PUT));
assertEquals("retrieve via DELETE", DEST_1, repo.get(URL_1, HttpMethod.DELETE));
}
@Test
public void testPutExplicitOverridesAll() throws Exception
{
PathRepoImpl repo = new PathRepoImpl();
repo.put(URL_1, DEST_1);
repo.put(URL_1, HttpMethod.GET, DEST_2);
assertEquals("retrieve via ALL", DEST_1, repo.get(URL_1, HttpMethod.ALL));
assertEquals("retrieve via GET", DEST_2, repo.get(URL_1, HttpMethod.GET));
assertEquals("retrieve via POST", DEST_1, repo.get(URL_1, HttpMethod.POST));
assertEquals("retrieve via PUT", DEST_1, repo.get(URL_1, HttpMethod.PUT));
assertEquals("retrieve via DELETE", DEST_1, repo.get(URL_1, HttpMethod.DELETE));
}
@Test
public void testPutAllOverridesExplicit() throws Exception
{
PathRepoImpl repo = new PathRepoImpl();
repo.put(URL_1, HttpMethod.GET, DEST_2);
repo.put(URL_1, DEST_1);
assertEquals("retrieve via ALL", DEST_1, repo.get(URL_1, HttpMethod.ALL));
assertEquals("retrieve via GET", DEST_1, repo.get(URL_1, HttpMethod.GET));
assertEquals("retrieve via POST", DEST_1, repo.get(URL_1, HttpMethod.POST));
assertEquals("retrieve via PUT", DEST_1, repo.get(URL_1, HttpMethod.PUT));
assertEquals("retrieve via DELETE", DEST_1, repo.get(URL_1, HttpMethod.DELETE));
}
@Test
public void testGetDestinationMap() throws Exception
{
PathRepoImpl repo = new PathRepoImpl();
repo.put(URL_1, DEST_1);
repo.put(URL_1, HttpMethod.GET, DEST_2);
Map<HttpMethod,Destination> destMap1 = repo.get(URL_1);
assertEquals("url 1 entry count", 2, destMap1.size());
assertSame("contains ALL", DEST_1, destMap1.get(HttpMethod.ALL));
assertSame("contains GET", DEST_2, destMap1.get(HttpMethod.GET));
Map<HttpMethod,Destination> destMap2 = repo.get(URL_2);
assertEquals("url 2 entry count", 0, destMap2.size());
}
@Test
public void testPutDestinationMap() throws Exception
{
PathRepoImpl repo = new PathRepoImpl();
repo.put(URL_1, DEST_2);
repo.put(URL_1, HttpMethod.GET, DEST_1);
Map<HttpMethod,Destination> destMap = new HashMap<HttpMethod,Destination>();
destMap.put(HttpMethod.GET, DEST_2);
destMap.put(HttpMethod.POST, DEST_1);
repo.put(URL_1, destMap);
assertNull("retrieve via ALL", repo.get(URL_1, HttpMethod.ALL));
assertEquals("retrieve via GET", DEST_2, repo.get(URL_1, HttpMethod.GET));
assertEquals("retrieve via POST", DEST_1, repo.get(URL_1, HttpMethod.POST));
assertNull("retrieve via PUT", repo.get(URL_1, HttpMethod.PUT));
assertNull("retrieve via DELETE", repo.get(URL_1, HttpMethod.DELETE));
}
@Test
public void testPutDestinationMapMakesCopy() throws Exception
{
PathRepoImpl repo = new PathRepoImpl();
Map<HttpMethod,Destination> destMap = new HashMap<HttpMethod,Destination>();
destMap.put(HttpMethod.GET, DEST_1);
repo.put(URL_1, destMap);
assertNull("retrieve via ALL", repo.get(URL_1, HttpMethod.ALL));
assertEquals("retrieve via GET", DEST_1, repo.get(URL_1, HttpMethod.GET));
assertNull("retrieve via POST", repo.get(URL_1, HttpMethod.POST));
assertNull("retrieve via PUT", repo.get(URL_1, HttpMethod.PUT));
assertNull("retrieve via DELETE", repo.get(URL_1, HttpMethod.DELETE));
destMap.put(HttpMethod.POST, DEST_1);
assertNull("retrieve via ALL", repo.get(URL_1, HttpMethod.ALL));
assertEquals("retrieve via GET", DEST_1, repo.get(URL_1, HttpMethod.GET));
assertNull("retrieve via POST", repo.get(URL_1, HttpMethod.POST));
assertNull("retrieve via PUT", repo.get(URL_1, HttpMethod.PUT));
assertNull("retrieve via DELETE", repo.get(URL_1, HttpMethod.DELETE));
}
@Test
public void testRemove() throws Exception
{
PathRepoImpl repo = new PathRepoImpl();
repo.put(URL_1, HttpMethod.GET, DEST_1);
repo.put(URL_1, HttpMethod.POST, DEST_2);
repo.put(URL_2, HttpMethod.GET, DEST_1);
repo.put(URL_2, HttpMethod.POST, DEST_2);
repo.put(URL_3, HttpMethod.ALL, DEST_2);
// test 0: make sure we don't blow up when removing nonexistent entries
repo.remove(BOGUS_URL, HttpMethod.ALL);
repo.remove(URL_1, HttpMethod.DELETE);
// test 1: explicit entries, remove one of them
repo.remove(URL_1, HttpMethod.GET);
assertNull("removed url-1/dest-1", repo.get(URL_1, HttpMethod.GET));
assertSame("left url-1/dest-2", DEST_2, repo.get(URL_1, HttpMethod.POST));
// test 2: explicit entries, bulk remove
repo.remove(URL_2, HttpMethod.ALL);
assertNull("removed url-2/dest-1", repo.get(URL_2, HttpMethod.GET));
assertNull("removed url-2/dest-1", repo.get(URL_2, HttpMethod.POST));
// test 3: generic entry, specific delete
repo.remove(URL_3, HttpMethod.GET);
assertNull("removed url-3/generic", repo.get(URL_3, HttpMethod.ALL));
assertNull("removed url-3/get", repo.get(URL_3, HttpMethod.GET));
assertSame("left url-3/post", DEST_2, repo.get(URL_3, HttpMethod.POST));
assertSame("left url-3/put", DEST_2, repo.get(URL_3, HttpMethod.PUT));
assertSame("left url-3/delete", DEST_2, repo.get(URL_3, HttpMethod.DELETE));
}
@Test
public void testIterator() throws Exception
{
PathRepoImpl repo = new PathRepoImpl();
repo.put(URL_1, DEST_1);
repo.put(URL_2, HttpMethod.GET, DEST_1);
repo.put(URL_3, HttpMethod.POST, DEST_1);
Iterator<String> urlItx = repo.iterator();
assertEquals(URL_2, urlItx.next());
assertEquals(URL_3, urlItx.next());
assertEquals(URL_1, urlItx.next());
assertFalse(urlItx.hasNext());
}
@Test
public void testIteratorAfterRemoval() throws Exception
{
PathRepoImpl repo = new PathRepoImpl();
repo.put(URL_1, DEST_1);
repo.put(URL_2, HttpMethod.GET, DEST_1);
repo.put(URL_3, HttpMethod.POST, DEST_1);
repo.remove(URL_2, HttpMethod.GET);
Iterator<String> urlItx = repo.iterator();
assertEquals(URL_3, urlItx.next());
assertEquals(URL_1, urlItx.next());
assertFalse(urlItx.hasNext());
}
@Test
public void testUrlCount() throws Exception
{
PathRepo repo = new PathRepoImpl();
repo.put(URL_1, DEST_1);
assertEquals("after first add", 1, repo.urlCount());
repo.put(URL_2, HttpMethod.GET, DEST_2);
repo.put(URL_2, HttpMethod.POST, DEST_2);
assertEquals("same URL, multiple methods", 2, repo.urlCount());
repo.put(URL_3, HttpMethod.ALL, DEST_2);
assertEquals("added \"all\" mapping", 3, repo.urlCount());
repo.remove(URL_3, HttpMethod.POST);
assertEquals("removed one method from \"all\" mapping", 3, repo.urlCount());
repo.remove(URL_2, HttpMethod.ALL);
assertEquals("removed entire mapping", 2, repo.urlCount());
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.builder.endpoint.dsl;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import javax.annotation.Generated;
import org.apache.camel.ExchangePattern;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;
import org.apache.camel.spi.ExceptionHandler;
/**
* For reading/writing from/to Infinispan distributed key/value store and data
* grid.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface InfinispanEndpointBuilderFactory {
/**
* Builder for endpoint consumers for the Infinispan component.
*/
public interface InfinispanEndpointConsumerBuilder
extends
EndpointConsumerBuilder {
default AdvancedInfinispanEndpointConsumerBuilder advanced() {
return (AdvancedInfinispanEndpointConsumerBuilder) this;
}
/**
* Specifies the host of the cache on Infinispan instance.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default InfinispanEndpointConsumerBuilder hosts(String hosts) {
doSetProperty("hosts", hosts);
return this;
}
/**
* Specifies the query builder.
*
* The option is a:
* <code>org.apache.camel.component.infinispan.InfinispanQueryBuilder</code> type.
*
* Group: common
*/
default InfinispanEndpointConsumerBuilder queryBuilder(
Object queryBuilder) {
doSetProperty("queryBuilder", queryBuilder);
return this;
}
/**
* Specifies the query builder.
*
* The option will be converted to a
* <code>org.apache.camel.component.infinispan.InfinispanQueryBuilder</code> type.
*
* Group: common
*/
default InfinispanEndpointConsumerBuilder queryBuilder(
String queryBuilder) {
doSetProperty("queryBuilder", queryBuilder);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option is a: <code>boolean</code> type.
*
* Group: consumer
*/
default InfinispanEndpointConsumerBuilder bridgeErrorHandler(
boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: consumer
*/
default InfinispanEndpointConsumerBuilder bridgeErrorHandler(
String bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* If true, the listener will be installed for the entire cluster.
*
* The option is a: <code>boolean</code> type.
*
* Group: consumer
*/
default InfinispanEndpointConsumerBuilder clusteredListener(
boolean clusteredListener) {
doSetProperty("clusteredListener", clusteredListener);
return this;
}
/**
* If true, the listener will be installed for the entire cluster.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: consumer
*/
default InfinispanEndpointConsumerBuilder clusteredListener(
String clusteredListener) {
doSetProperty("clusteredListener", clusteredListener);
return this;
}
/**
* The operation to perform.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*/
@Deprecated
default InfinispanEndpointConsumerBuilder command(String command) {
doSetProperty("command", command);
return this;
}
/**
* Returns the custom listener in use, if provided.
*
* The option is a:
* <code>org.apache.camel.component.infinispan.InfinispanCustomListener</code> type.
*
* Group: consumer
*/
default InfinispanEndpointConsumerBuilder customListener(
Object customListener) {
doSetProperty("customListener", customListener);
return this;
}
/**
* Returns the custom listener in use, if provided.
*
* The option will be converted to a
* <code>org.apache.camel.component.infinispan.InfinispanCustomListener</code> type.
*
* Group: consumer
*/
default InfinispanEndpointConsumerBuilder customListener(
String customListener) {
doSetProperty("customListener", customListener);
return this;
}
/**
* Specifies the set of event types to register by the consumer.
* Multiple event can be separated by comma. The possible event types
* are: CACHE_ENTRY_ACTIVATED, CACHE_ENTRY_PASSIVATED,
* CACHE_ENTRY_VISITED, CACHE_ENTRY_LOADED, CACHE_ENTRY_EVICTED,
* CACHE_ENTRY_CREATED, CACHE_ENTRY_REMOVED, CACHE_ENTRY_MODIFIED,
* TRANSACTION_COMPLETED, TRANSACTION_REGISTERED,
* CACHE_ENTRY_INVALIDATED, DATA_REHASHED, TOPOLOGY_CHANGED,
* PARTITION_STATUS_CHANGED.
*
* The option is a: <code>java.util.Set<java.lang.String></code>
* type.
*
* Group: consumer
*/
default InfinispanEndpointConsumerBuilder eventTypes(
Set<String> eventTypes) {
doSetProperty("eventTypes", eventTypes);
return this;
}
/**
* Specifies the set of event types to register by the consumer.
* Multiple event can be separated by comma. The possible event types
* are: CACHE_ENTRY_ACTIVATED, CACHE_ENTRY_PASSIVATED,
* CACHE_ENTRY_VISITED, CACHE_ENTRY_LOADED, CACHE_ENTRY_EVICTED,
* CACHE_ENTRY_CREATED, CACHE_ENTRY_REMOVED, CACHE_ENTRY_MODIFIED,
* TRANSACTION_COMPLETED, TRANSACTION_REGISTERED,
* CACHE_ENTRY_INVALIDATED, DATA_REHASHED, TOPOLOGY_CHANGED,
* PARTITION_STATUS_CHANGED.
*
* The option will be converted to a
* <code>java.util.Set<java.lang.String></code> type.
*
* Group: consumer
*/
default InfinispanEndpointConsumerBuilder eventTypes(String eventTypes) {
doSetProperty("eventTypes", eventTypes);
return this;
}
/**
* If true, the consumer will receive notifications synchronously.
*
* The option is a: <code>boolean</code> type.
*
* Group: consumer
*/
default InfinispanEndpointConsumerBuilder sync(boolean sync) {
doSetProperty("sync", sync);
return this;
}
/**
* If true, the consumer will receive notifications synchronously.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: consumer
*/
default InfinispanEndpointConsumerBuilder sync(String sync) {
doSetProperty("sync", sync);
return this;
}
}
/**
* Advanced builder for endpoint consumers for the Infinispan component.
*/
public interface AdvancedInfinispanEndpointConsumerBuilder
extends
EndpointConsumerBuilder {
default InfinispanEndpointConsumerBuilder basic() {
return (InfinispanEndpointConsumerBuilder) this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option is a: <code>org.apache.camel.spi.ExceptionHandler</code>
* type.
*
* Group: consumer (advanced)
*/
default AdvancedInfinispanEndpointConsumerBuilder exceptionHandler(
ExceptionHandler exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option will be converted to a
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*/
default AdvancedInfinispanEndpointConsumerBuilder exceptionHandler(
String exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option is a: <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*/
default AdvancedInfinispanEndpointConsumerBuilder exchangePattern(
ExchangePattern exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option will be converted to a
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*/
default AdvancedInfinispanEndpointConsumerBuilder exchangePattern(
String exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointConsumerBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointConsumerBuilder basicPropertyBinding(
String basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Specifies the cache Container to connect.
*
* The option is a:
* <code>org.infinispan.commons.api.BasicCacheContainer</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointConsumerBuilder cacheContainer(
Object cacheContainer) {
doSetProperty("cacheContainer", cacheContainer);
return this;
}
/**
* Specifies the cache Container to connect.
*
* The option will be converted to a
* <code>org.infinispan.commons.api.BasicCacheContainer</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointConsumerBuilder cacheContainer(
String cacheContainer) {
doSetProperty("cacheContainer", cacheContainer);
return this;
}
/**
* The CacheContainer configuration. Uses if the cacheContainer is not
* defined. Must be the following types:
* org.infinispan.client.hotrod.configuration.Configuration - for remote
* cache interaction configuration;
* org.infinispan.configuration.cache.Configuration - for embedded cache
* interaction configuration;.
*
* The option is a: <code>java.lang.Object</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointConsumerBuilder cacheContainerConfiguration(
Object cacheContainerConfiguration) {
doSetProperty("cacheContainerConfiguration", cacheContainerConfiguration);
return this;
}
/**
* The CacheContainer configuration. Uses if the cacheContainer is not
* defined. Must be the following types:
* org.infinispan.client.hotrod.configuration.Configuration - for remote
* cache interaction configuration;
* org.infinispan.configuration.cache.Configuration - for embedded cache
* interaction configuration;.
*
* The option will be converted to a <code>java.lang.Object</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointConsumerBuilder cacheContainerConfiguration(
String cacheContainerConfiguration) {
doSetProperty("cacheContainerConfiguration", cacheContainerConfiguration);
return this;
}
/**
* Implementation specific properties for the CacheManager.
*
* The option is a: <code>java.util.Map<java.lang.String,
* java.lang.String></code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointConsumerBuilder configurationProperties(
Map<String, String> configurationProperties) {
doSetProperty("configurationProperties", configurationProperties);
return this;
}
/**
* Implementation specific properties for the CacheManager.
*
* The option will be converted to a
* <code>java.util.Map<java.lang.String, java.lang.String></code>
* type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointConsumerBuilder configurationProperties(
String configurationProperties) {
doSetProperty("configurationProperties", configurationProperties);
return this;
}
/**
* An implementation specific URI for the CacheManager.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointConsumerBuilder configurationUri(
String configurationUri) {
doSetProperty("configurationUri", configurationUri);
return this;
}
/**
* A comma separated list of Flag to be applied by default on each cache
* invocation, not applicable to remote caches.
*
* The option is a: <code>org.infinispan.context.Flag[]</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointConsumerBuilder flags(Flag[] flags) {
doSetProperty("flags", flags);
return this;
}
/**
* A comma separated list of Flag to be applied by default on each cache
* invocation, not applicable to remote caches.
*
* The option will be converted to a
* <code>org.infinispan.context.Flag[]</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointConsumerBuilder flags(String flags) {
doSetProperty("flags", flags);
return this;
}
/**
* Set a specific remappingFunction to use in a compute operation.
*
* The option is a: <code>java.util.function.BiFunction</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointConsumerBuilder remappingFunction(
BiFunction remappingFunction) {
doSetProperty("remappingFunction", remappingFunction);
return this;
}
/**
* Set a specific remappingFunction to use in a compute operation.
*
* The option will be converted to a
* <code>java.util.function.BiFunction</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointConsumerBuilder remappingFunction(
String remappingFunction) {
doSetProperty("remappingFunction", remappingFunction);
return this;
}
/**
* Store the operation result in a header instead of the message body.
* By default, resultHeader == null and the query result is stored in
* the message body, any existing content in the message body is
* discarded. If resultHeader is set, the value is used as the name of
* the header to store the query result and the original message body is
* preserved. This value can be overridden by an in message header
* named: CamelInfinispanOperationResultHeader.
*
* The option is a: <code>java.lang.Object</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointConsumerBuilder resultHeader(
Object resultHeader) {
doSetProperty("resultHeader", resultHeader);
return this;
}
/**
* Store the operation result in a header instead of the message body.
* By default, resultHeader == null and the query result is stored in
* the message body, any existing content in the message body is
* discarded. If resultHeader is set, the value is used as the name of
* the header to store the query result and the original message body is
* preserved. This value can be overridden by an in message header
* named: CamelInfinispanOperationResultHeader.
*
* The option will be converted to a <code>java.lang.Object</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointConsumerBuilder resultHeader(
String resultHeader) {
doSetProperty("resultHeader", resultHeader);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointConsumerBuilder synchronous(
boolean synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointConsumerBuilder synchronous(
String synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
}
/**
* Builder for endpoint producers for the Infinispan component.
*/
public interface InfinispanEndpointProducerBuilder
extends
EndpointProducerBuilder {
default AdvancedInfinispanEndpointProducerBuilder advanced() {
return (AdvancedInfinispanEndpointProducerBuilder) this;
}
/**
* Specifies the host of the cache on Infinispan instance.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default InfinispanEndpointProducerBuilder hosts(String hosts) {
doSetProperty("hosts", hosts);
return this;
}
/**
* Specifies the query builder.
*
* The option is a:
* <code>org.apache.camel.component.infinispan.InfinispanQueryBuilder</code> type.
*
* Group: common
*/
default InfinispanEndpointProducerBuilder queryBuilder(
Object queryBuilder) {
doSetProperty("queryBuilder", queryBuilder);
return this;
}
/**
* Specifies the query builder.
*
* The option will be converted to a
* <code>org.apache.camel.component.infinispan.InfinispanQueryBuilder</code> type.
*
* Group: common
*/
default InfinispanEndpointProducerBuilder queryBuilder(
String queryBuilder) {
doSetProperty("queryBuilder", queryBuilder);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Group: producer
*/
default InfinispanEndpointProducerBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: producer
*/
default InfinispanEndpointProducerBuilder lazyStartProducer(
String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* The operation to perform.
*
* The option is a:
* <code>org.apache.camel.component.infinispan.InfinispanOperation</code> type.
*
* Group: producer
*/
default InfinispanEndpointProducerBuilder operation(
InfinispanOperation operation) {
doSetProperty("operation", operation);
return this;
}
/**
* The operation to perform.
*
* The option will be converted to a
* <code>org.apache.camel.component.infinispan.InfinispanOperation</code> type.
*
* Group: producer
*/
default InfinispanEndpointProducerBuilder operation(String operation) {
doSetProperty("operation", operation);
return this;
}
}
/**
* Advanced builder for endpoint producers for the Infinispan component.
*/
public interface AdvancedInfinispanEndpointProducerBuilder
extends
EndpointProducerBuilder {
default InfinispanEndpointProducerBuilder basic() {
return (InfinispanEndpointProducerBuilder) this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointProducerBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointProducerBuilder basicPropertyBinding(
String basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Specifies the cache Container to connect.
*
* The option is a:
* <code>org.infinispan.commons.api.BasicCacheContainer</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointProducerBuilder cacheContainer(
Object cacheContainer) {
doSetProperty("cacheContainer", cacheContainer);
return this;
}
/**
* Specifies the cache Container to connect.
*
* The option will be converted to a
* <code>org.infinispan.commons.api.BasicCacheContainer</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointProducerBuilder cacheContainer(
String cacheContainer) {
doSetProperty("cacheContainer", cacheContainer);
return this;
}
/**
* The CacheContainer configuration. Uses if the cacheContainer is not
* defined. Must be the following types:
* org.infinispan.client.hotrod.configuration.Configuration - for remote
* cache interaction configuration;
* org.infinispan.configuration.cache.Configuration - for embedded cache
* interaction configuration;.
*
* The option is a: <code>java.lang.Object</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointProducerBuilder cacheContainerConfiguration(
Object cacheContainerConfiguration) {
doSetProperty("cacheContainerConfiguration", cacheContainerConfiguration);
return this;
}
/**
* The CacheContainer configuration. Uses if the cacheContainer is not
* defined. Must be the following types:
* org.infinispan.client.hotrod.configuration.Configuration - for remote
* cache interaction configuration;
* org.infinispan.configuration.cache.Configuration - for embedded cache
* interaction configuration;.
*
* The option will be converted to a <code>java.lang.Object</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointProducerBuilder cacheContainerConfiguration(
String cacheContainerConfiguration) {
doSetProperty("cacheContainerConfiguration", cacheContainerConfiguration);
return this;
}
/**
* Implementation specific properties for the CacheManager.
*
* The option is a: <code>java.util.Map<java.lang.String,
* java.lang.String></code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointProducerBuilder configurationProperties(
Map<String, String> configurationProperties) {
doSetProperty("configurationProperties", configurationProperties);
return this;
}
/**
* Implementation specific properties for the CacheManager.
*
* The option will be converted to a
* <code>java.util.Map<java.lang.String, java.lang.String></code>
* type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointProducerBuilder configurationProperties(
String configurationProperties) {
doSetProperty("configurationProperties", configurationProperties);
return this;
}
/**
* An implementation specific URI for the CacheManager.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointProducerBuilder configurationUri(
String configurationUri) {
doSetProperty("configurationUri", configurationUri);
return this;
}
/**
* A comma separated list of Flag to be applied by default on each cache
* invocation, not applicable to remote caches.
*
* The option is a: <code>org.infinispan.context.Flag[]</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointProducerBuilder flags(Flag[] flags) {
doSetProperty("flags", flags);
return this;
}
/**
* A comma separated list of Flag to be applied by default on each cache
* invocation, not applicable to remote caches.
*
* The option will be converted to a
* <code>org.infinispan.context.Flag[]</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointProducerBuilder flags(String flags) {
doSetProperty("flags", flags);
return this;
}
/**
* Set a specific remappingFunction to use in a compute operation.
*
* The option is a: <code>java.util.function.BiFunction</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointProducerBuilder remappingFunction(
BiFunction remappingFunction) {
doSetProperty("remappingFunction", remappingFunction);
return this;
}
/**
* Set a specific remappingFunction to use in a compute operation.
*
* The option will be converted to a
* <code>java.util.function.BiFunction</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointProducerBuilder remappingFunction(
String remappingFunction) {
doSetProperty("remappingFunction", remappingFunction);
return this;
}
/**
* Store the operation result in a header instead of the message body.
* By default, resultHeader == null and the query result is stored in
* the message body, any existing content in the message body is
* discarded. If resultHeader is set, the value is used as the name of
* the header to store the query result and the original message body is
* preserved. This value can be overridden by an in message header
* named: CamelInfinispanOperationResultHeader.
*
* The option is a: <code>java.lang.Object</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointProducerBuilder resultHeader(
Object resultHeader) {
doSetProperty("resultHeader", resultHeader);
return this;
}
/**
* Store the operation result in a header instead of the message body.
* By default, resultHeader == null and the query result is stored in
* the message body, any existing content in the message body is
* discarded. If resultHeader is set, the value is used as the name of
* the header to store the query result and the original message body is
* preserved. This value can be overridden by an in message header
* named: CamelInfinispanOperationResultHeader.
*
* The option will be converted to a <code>java.lang.Object</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointProducerBuilder resultHeader(
String resultHeader) {
doSetProperty("resultHeader", resultHeader);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointProducerBuilder synchronous(
boolean synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointProducerBuilder synchronous(
String synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
}
/**
* Builder for endpoint for the Infinispan component.
*/
public interface InfinispanEndpointBuilder
extends
InfinispanEndpointConsumerBuilder, InfinispanEndpointProducerBuilder {
default AdvancedInfinispanEndpointBuilder advanced() {
return (AdvancedInfinispanEndpointBuilder) this;
}
/**
* Specifies the host of the cache on Infinispan instance.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default InfinispanEndpointBuilder hosts(String hosts) {
doSetProperty("hosts", hosts);
return this;
}
/**
* Specifies the query builder.
*
* The option is a:
* <code>org.apache.camel.component.infinispan.InfinispanQueryBuilder</code> type.
*
* Group: common
*/
default InfinispanEndpointBuilder queryBuilder(Object queryBuilder) {
doSetProperty("queryBuilder", queryBuilder);
return this;
}
/**
* Specifies the query builder.
*
* The option will be converted to a
* <code>org.apache.camel.component.infinispan.InfinispanQueryBuilder</code> type.
*
* Group: common
*/
default InfinispanEndpointBuilder queryBuilder(String queryBuilder) {
doSetProperty("queryBuilder", queryBuilder);
return this;
}
}
/**
* Advanced builder for endpoint for the Infinispan component.
*/
public interface AdvancedInfinispanEndpointBuilder
extends
AdvancedInfinispanEndpointConsumerBuilder, AdvancedInfinispanEndpointProducerBuilder {
default InfinispanEndpointBuilder basic() {
return (InfinispanEndpointBuilder) this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointBuilder basicPropertyBinding(
String basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Specifies the cache Container to connect.
*
* The option is a:
* <code>org.infinispan.commons.api.BasicCacheContainer</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointBuilder cacheContainer(
Object cacheContainer) {
doSetProperty("cacheContainer", cacheContainer);
return this;
}
/**
* Specifies the cache Container to connect.
*
* The option will be converted to a
* <code>org.infinispan.commons.api.BasicCacheContainer</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointBuilder cacheContainer(
String cacheContainer) {
doSetProperty("cacheContainer", cacheContainer);
return this;
}
/**
* The CacheContainer configuration. Uses if the cacheContainer is not
* defined. Must be the following types:
* org.infinispan.client.hotrod.configuration.Configuration - for remote
* cache interaction configuration;
* org.infinispan.configuration.cache.Configuration - for embedded cache
* interaction configuration;.
*
* The option is a: <code>java.lang.Object</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointBuilder cacheContainerConfiguration(
Object cacheContainerConfiguration) {
doSetProperty("cacheContainerConfiguration", cacheContainerConfiguration);
return this;
}
/**
* The CacheContainer configuration. Uses if the cacheContainer is not
* defined. Must be the following types:
* org.infinispan.client.hotrod.configuration.Configuration - for remote
* cache interaction configuration;
* org.infinispan.configuration.cache.Configuration - for embedded cache
* interaction configuration;.
*
* The option will be converted to a <code>java.lang.Object</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointBuilder cacheContainerConfiguration(
String cacheContainerConfiguration) {
doSetProperty("cacheContainerConfiguration", cacheContainerConfiguration);
return this;
}
/**
* Implementation specific properties for the CacheManager.
*
* The option is a: <code>java.util.Map<java.lang.String,
* java.lang.String></code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointBuilder configurationProperties(
Map<String, String> configurationProperties) {
doSetProperty("configurationProperties", configurationProperties);
return this;
}
/**
* Implementation specific properties for the CacheManager.
*
* The option will be converted to a
* <code>java.util.Map<java.lang.String, java.lang.String></code>
* type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointBuilder configurationProperties(
String configurationProperties) {
doSetProperty("configurationProperties", configurationProperties);
return this;
}
/**
* An implementation specific URI for the CacheManager.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointBuilder configurationUri(
String configurationUri) {
doSetProperty("configurationUri", configurationUri);
return this;
}
/**
* A comma separated list of Flag to be applied by default on each cache
* invocation, not applicable to remote caches.
*
* The option is a: <code>org.infinispan.context.Flag[]</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointBuilder flags(Flag[] flags) {
doSetProperty("flags", flags);
return this;
}
/**
* A comma separated list of Flag to be applied by default on each cache
* invocation, not applicable to remote caches.
*
* The option will be converted to a
* <code>org.infinispan.context.Flag[]</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointBuilder flags(String flags) {
doSetProperty("flags", flags);
return this;
}
/**
* Set a specific remappingFunction to use in a compute operation.
*
* The option is a: <code>java.util.function.BiFunction</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointBuilder remappingFunction(
BiFunction remappingFunction) {
doSetProperty("remappingFunction", remappingFunction);
return this;
}
/**
* Set a specific remappingFunction to use in a compute operation.
*
* The option will be converted to a
* <code>java.util.function.BiFunction</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointBuilder remappingFunction(
String remappingFunction) {
doSetProperty("remappingFunction", remappingFunction);
return this;
}
/**
* Store the operation result in a header instead of the message body.
* By default, resultHeader == null and the query result is stored in
* the message body, any existing content in the message body is
* discarded. If resultHeader is set, the value is used as the name of
* the header to store the query result and the original message body is
* preserved. This value can be overridden by an in message header
* named: CamelInfinispanOperationResultHeader.
*
* The option is a: <code>java.lang.Object</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointBuilder resultHeader(
Object resultHeader) {
doSetProperty("resultHeader", resultHeader);
return this;
}
/**
* Store the operation result in a header instead of the message body.
* By default, resultHeader == null and the query result is stored in
* the message body, any existing content in the message body is
* discarded. If resultHeader is set, the value is used as the name of
* the header to store the query result and the original message body is
* preserved. This value can be overridden by an in message header
* named: CamelInfinispanOperationResultHeader.
*
* The option will be converted to a <code>java.lang.Object</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointBuilder resultHeader(
String resultHeader) {
doSetProperty("resultHeader", resultHeader);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointBuilder synchronous(
boolean synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedInfinispanEndpointBuilder synchronous(String synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
}
/**
* Proxy enum for
* <code>org.apache.camel.component.infinispan.InfinispanOperation</code>
* enum.
*/
enum InfinispanOperation {
PUT,
PUTASYNC,
PUTALL,
PUTALLASYNC,
PUTIFABSENT,
PUTIFABSENTASYNC,
GET,
GETORDEFAULT,
CONTAINSKEY,
CONTAINSVALUE,
REMOVE,
REMOVEASYNC,
REPLACE,
REPLACEASYNC,
SIZE,
CLEAR,
CLEARASYNC,
QUERY,
STATS,
COMPUTE,
COMPUTEASYNC;
}
/**
* Proxy enum for <code>org.infinispan.context.Flag</code> enum.
*/
enum Flag {
ZERO_LOCK_ACQUISITION_TIMEOUT,
CACHE_MODE_LOCAL,
SKIP_LOCKING,
FORCE_WRITE_LOCK,
SKIP_CACHE_STATUS_CHECK,
FORCE_ASYNCHRONOUS,
FORCE_SYNCHRONOUS,
SKIP_CACHE_STORE,
SKIP_CACHE_LOAD,
FAIL_SILENTLY,
SKIP_REMOTE_LOOKUP,
SKIP_INDEXING,
PUT_FOR_EXTERNAL_READ,
PUT_FOR_STATE_TRANSFER,
PUT_FOR_X_SITE_STATE_TRANSFER,
SKIP_SHARED_CACHE_STORE,
SKIP_OWNERSHIP_CHECK,
IGNORE_RETURN_VALUES,
SKIP_XSITE_BACKUP,
SKIP_LISTENER_NOTIFICATION,
SKIP_STATISTICS,
OPERATION_HOTROD,
OPERATION_MEMCACHED,
SKIP_INDEX_CLEANUP,
COMMAND_RETRY,
ROLLING_UPGRADE,
REMOTE_ITERATION,
SKIP_SIZE_OPTIMIZATION;
}
/**
* Infinispan (camel-infinispan)
* For reading/writing from/to Infinispan distributed key/value store and
* data grid.
*
* Category: cache,datagrid,clustering
* Since: 2.13
* Maven coordinates: org.apache.camel:camel-infinispan
*
* Syntax: <code>infinispan:cacheName</code>
*
* Path parameter: cacheName (required)
* The cache to use
*/
default InfinispanEndpointBuilder infinispan(String path) {
class InfinispanEndpointBuilderImpl extends AbstractEndpointBuilder implements InfinispanEndpointBuilder, AdvancedInfinispanEndpointBuilder {
public InfinispanEndpointBuilderImpl(String path) {
super("infinispan", path);
}
}
return new InfinispanEndpointBuilderImpl(path);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.accumulo.server;
import static com.google.common.base.Preconditions.checkArgument;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.apache.accumulo.fate.util.UtilWaitThread.sleepUninterruptibly;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.clientImpl.ClientContext;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.conf.DefaultConfiguration;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.conf.SiteConfiguration;
import org.apache.accumulo.core.crypto.CryptoServiceFactory;
import org.apache.accumulo.core.crypto.CryptoServiceFactory.ClassloaderType;
import org.apache.accumulo.core.data.InstanceId;
import org.apache.accumulo.core.data.NamespaceId;
import org.apache.accumulo.core.data.TableId;
import org.apache.accumulo.core.metadata.schema.Ample;
import org.apache.accumulo.core.rpc.SslConnectionParams;
import org.apache.accumulo.core.singletons.SingletonReservation;
import org.apache.accumulo.core.spi.crypto.CryptoService;
import org.apache.accumulo.core.util.AddressUtil;
import org.apache.accumulo.core.util.Pair;
import org.apache.accumulo.core.util.threads.ThreadPools;
import org.apache.accumulo.fate.zookeeper.ZooCache;
import org.apache.accumulo.fate.zookeeper.ZooReader;
import org.apache.accumulo.fate.zookeeper.ZooReaderWriter;
import org.apache.accumulo.server.conf.NamespaceConfiguration;
import org.apache.accumulo.server.conf.ServerConfigurationFactory;
import org.apache.accumulo.server.conf.TableConfiguration;
import org.apache.accumulo.server.conf.ZooConfiguration;
import org.apache.accumulo.server.fs.VolumeManager;
import org.apache.accumulo.server.metadata.ServerAmpleImpl;
import org.apache.accumulo.server.rpc.SaslServerConnectionParams;
import org.apache.accumulo.server.rpc.ThriftServerType;
import org.apache.accumulo.server.security.SecurityUtil;
import org.apache.accumulo.server.security.delegation.AuthenticationTokenSecretManager;
import org.apache.accumulo.server.tables.TableManager;
import org.apache.accumulo.server.tablets.UniqueNameAllocator;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides a server context for Accumulo server components that operate with the system credentials
* and have access to the system files and configuration.
*/
public class ServerContext extends ClientContext {
private static final Logger log = LoggerFactory.getLogger(ServerContext.class);
private final ServerInfo info;
private final ZooReaderWriter zooReaderWriter;
private final ServerDirs serverDirs;
private TableManager tableManager;
private UniqueNameAllocator nameAllocator;
private ServerConfigurationFactory serverConfFactory = null;
private DefaultConfiguration defaultConfig = null;
private AccumuloConfiguration systemConfig = null;
private AuthenticationTokenSecretManager secretManager;
private CryptoService cryptoService = null;
private ScheduledThreadPoolExecutor sharedScheduledThreadPool = null;
public ServerContext(SiteConfiguration siteConfig) {
this(new ServerInfo(siteConfig));
}
private ServerContext(ServerInfo info) {
super(SingletonReservation.noop(), info, info.getSiteConfiguration());
this.info = info;
zooReaderWriter = new ZooReaderWriter(info.getSiteConfiguration());
serverDirs = info.getServerDirs();
}
/**
* Used during initialization to set the instance name and ID.
*/
public static ServerContext initialize(SiteConfiguration siteConfig, String instanceName,
InstanceId instanceID) {
return new ServerContext(new ServerInfo(siteConfig, instanceName, instanceID));
}
/**
* Override properties for testing
*/
public static ServerContext override(SiteConfiguration siteConfig, String instanceName,
String zooKeepers, int zkSessionTimeOut) {
return new ServerContext(
new ServerInfo(siteConfig, instanceName, zooKeepers, zkSessionTimeOut));
}
@Override
public InstanceId getInstanceID() {
return info.getInstanceID();
}
/**
* Should only be called by the Tablet server
*/
public synchronized void setupCrypto() throws CryptoService.CryptoException {
if (cryptoService != null) {
throw new CryptoService.CryptoException("Crypto Service " + cryptoService.getClass().getName()
+ " already exists and cannot be setup again");
}
AccumuloConfiguration acuConf = getConfiguration();
cryptoService = CryptoServiceFactory.newInstance(acuConf, ClassloaderType.ACCUMULO);
}
public SiteConfiguration getSiteConfiguration() {
return info.getSiteConfiguration();
}
public synchronized ServerConfigurationFactory getServerConfFactory() {
if (serverConfFactory == null) {
serverConfFactory = new ServerConfigurationFactory(this, info.getSiteConfiguration());
}
return serverConfFactory;
}
@Override
public AccumuloConfiguration getConfiguration() {
if (systemConfig == null) {
// system configuration uses its own instance of ZooCache
// this could be useful to keep its update counter independent
ZooCache propCache = new ZooCache(getZooReader(), null);
systemConfig = new ZooConfiguration(this, propCache, getSiteConfiguration());
}
return systemConfig;
}
public TableConfiguration getTableConfiguration(TableId id) {
return getServerConfFactory().getTableConfiguration(id);
}
public NamespaceConfiguration getNamespaceConfiguration(NamespaceId namespaceId) {
return getServerConfFactory().getNamespaceConfiguration(namespaceId);
}
public DefaultConfiguration getDefaultConfiguration() {
if (defaultConfig == null) {
defaultConfig = DefaultConfiguration.getInstance();
}
return defaultConfig;
}
public ServerDirs getServerDirs() {
return serverDirs;
}
/**
* A "client-side" assertion for servers to validate that they are logged in as the expected user,
* per the configuration, before performing any RPC
*/
// Should be private, but package-protected so EasyMock will work
void enforceKerberosLogin() {
final AccumuloConfiguration conf = getServerConfFactory().getSiteConfiguration();
// Unwrap _HOST into the FQDN to make the kerberos principal we'll compare against
final String kerberosPrincipal =
SecurityUtil.getServerPrincipal(conf.get(Property.GENERAL_KERBEROS_PRINCIPAL));
UserGroupInformation loginUser;
try {
// The system user should be logged in via keytab when the process is started, not the
// currentUser() like KerberosToken
loginUser = UserGroupInformation.getLoginUser();
} catch (IOException e) {
throw new RuntimeException("Could not get login user", e);
}
checkArgument(loginUser.hasKerberosCredentials(), "Server does not have Kerberos credentials");
checkArgument(kerberosPrincipal.equals(loginUser.getUserName()),
"Expected login user to be " + kerberosPrincipal + " but was " + loginUser.getUserName());
}
public VolumeManager getVolumeManager() {
return info.getVolumeManager();
}
@Override
public ZooReader getZooReader() {
return getZooReaderWriter();
}
public ZooReaderWriter getZooReaderWriter() {
return zooReaderWriter;
}
/**
* Retrieve the SSL/TLS configuration for starting up a listening service
*/
public SslConnectionParams getServerSslParams() {
return SslConnectionParams.forServer(getConfiguration());
}
@Override
public SaslServerConnectionParams getSaslParams() {
AccumuloConfiguration conf = getServerConfFactory().getSiteConfiguration();
if (!conf.getBoolean(Property.INSTANCE_RPC_SASL_ENABLED)) {
return null;
}
return new SaslServerConnectionParams(conf, getCredentials().getToken(), secretManager);
}
/**
* Determine the type of Thrift server to instantiate given the server's configuration.
*
* @return A {@link ThriftServerType} value to denote the type of Thrift server to construct
*/
public ThriftServerType getThriftServerType() {
AccumuloConfiguration conf = getConfiguration();
if (conf.getBoolean(Property.INSTANCE_RPC_SSL_ENABLED)) {
if (conf.getBoolean(Property.INSTANCE_RPC_SASL_ENABLED)) {
throw new IllegalStateException(
"Cannot create a Thrift server capable of both SASL and SSL");
}
return ThriftServerType.SSL;
} else if (conf.getBoolean(Property.INSTANCE_RPC_SASL_ENABLED)) {
if (conf.getBoolean(Property.INSTANCE_RPC_SSL_ENABLED)) {
throw new IllegalStateException(
"Cannot create a Thrift server capable of both SASL and SSL");
}
return ThriftServerType.SASL;
} else {
// Lets us control the type of Thrift server created, primarily for benchmarking purposes
String serverTypeName = conf.get(Property.GENERAL_RPC_SERVER_TYPE);
return ThriftServerType.get(serverTypeName);
}
}
public void setSecretManager(AuthenticationTokenSecretManager secretManager) {
this.secretManager = secretManager;
}
public AuthenticationTokenSecretManager getSecretManager() {
return secretManager;
}
public synchronized TableManager getTableManager() {
if (tableManager == null) {
tableManager = new TableManager(this);
}
return tableManager;
}
public synchronized UniqueNameAllocator getUniqueNameAllocator() {
if (nameAllocator == null) {
nameAllocator = new UniqueNameAllocator(this);
}
return nameAllocator;
}
public CryptoService getCryptoService() {
if (cryptoService == null) {
throw new CryptoService.CryptoException("Crypto service not initialized.");
}
return cryptoService;
}
@Override
public Ample getAmple() {
return new ServerAmpleImpl(this);
}
public Set<String> getBaseUris() {
return serverDirs.getBaseUris();
}
public List<Pair<Path,Path>> getVolumeReplacements() {
return serverDirs.getVolumeReplacements();
}
public Set<String> getTablesDirs() {
return serverDirs.getTablesDirs();
}
public Set<String> getRecoveryDirs() {
return serverDirs.getRecoveryDirs();
}
/**
* Check to see if this version of Accumulo can run against or upgrade the passed in data version.
*/
public static void ensureDataVersionCompatible(int dataVersion) {
if (!AccumuloDataVersion.CAN_RUN.contains(dataVersion)) {
throw new IllegalStateException("This version of accumulo (" + Constants.VERSION
+ ") is not compatible with files stored using data version " + dataVersion);
}
}
public void waitForZookeeperAndHdfs() {
log.info("Attempting to talk to zookeeper");
while (true) {
try {
getZooReaderWriter().getChildren(Constants.ZROOT);
break;
} catch (InterruptedException | KeeperException ex) {
log.info("Waiting for accumulo to be initialized");
sleepUninterruptibly(1, SECONDS);
}
}
log.info("ZooKeeper connected and initialized, attempting to talk to HDFS");
long sleep = 1000;
int unknownHostTries = 3;
while (true) {
try {
if (getVolumeManager().isReady())
break;
log.warn("Waiting for the NameNode to leave safemode");
} catch (IOException ex) {
log.warn("Unable to connect to HDFS", ex);
} catch (IllegalArgumentException e) {
/* Unwrap the UnknownHostException so we can deal with it directly */
if (e.getCause() instanceof UnknownHostException) {
if (unknownHostTries > 0) {
log.warn("Unable to connect to HDFS, will retry. cause: ", e.getCause());
/*
* We need to make sure our sleep period is long enough to avoid getting a cached
* failure of the host lookup.
*/
int ttl = AddressUtil.getAddressCacheNegativeTtl((UnknownHostException) e.getCause());
sleep = Math.max(sleep, (ttl + 1) * 1000L);
} else {
log.error("Unable to connect to HDFS and exceeded the maximum number of retries.", e);
throw e;
}
unknownHostTries--;
} else {
throw e;
}
}
log.info("Backing off due to failure; current sleep period is {} seconds", sleep / 1000.);
sleepUninterruptibly(sleep, TimeUnit.MILLISECONDS);
/* Back off to give transient failures more time to clear. */
sleep = Math.min(MINUTES.toMillis(1), sleep * 2);
}
log.info("Connected to HDFS");
}
/**
* Wait for ZK and hdfs, check data version and some properties, and start thread to monitor
* swappiness. Should only be called once during server start up.
*/
public void init(String application) {
final AccumuloConfiguration conf = getConfiguration();
log.info("{} starting", application);
log.info("Instance {}", getInstanceID());
// It doesn't matter which Volume is used as they should all have the data version stored
int dataVersion = serverDirs.getAccumuloPersistentVersion(getVolumeManager().getFirst());
log.info("Data Version {}", dataVersion);
waitForZookeeperAndHdfs();
ensureDataVersionCompatible(dataVersion);
TreeMap<String,String> sortedProps = new TreeMap<>();
for (Map.Entry<String,String> entry : conf)
sortedProps.put(entry.getKey(), entry.getValue());
for (Map.Entry<String,String> entry : sortedProps.entrySet()) {
String key = entry.getKey();
log.info("{} = {}", key, (Property.isSensitive(key) ? "<hidden>" : entry.getValue()));
Property prop = Property.getPropertyByKey(key);
if (prop != null && conf.isPropertySet(prop, false)) {
if (prop.isDeprecated()) {
Property replacedBy = prop.replacedBy();
if (replacedBy != null) {
log.warn("{} is deprecated, use {} instead.", prop.getKey(), replacedBy.getKey());
} else {
log.warn("{} is deprecated", prop.getKey());
}
}
}
}
monitorSwappiness();
// Encourage users to configure TLS
final String SSL = "SSL";
for (Property sslProtocolProperty : Arrays.asList(Property.RPC_SSL_CLIENT_PROTOCOL,
Property.RPC_SSL_ENABLED_PROTOCOLS, Property.MONITOR_SSL_INCLUDE_PROTOCOLS)) {
String value = conf.get(sslProtocolProperty);
if (value.contains(SSL)) {
log.warn("It is recommended that {} only allow TLS", sslProtocolProperty);
}
}
}
private void monitorSwappiness() {
ScheduledFuture<?> future = getScheduledExecutor().scheduleWithFixedDelay(() -> {
try {
String procFile = "/proc/sys/vm/swappiness";
File swappiness = new File(procFile);
if (swappiness.exists() && swappiness.canRead()) {
try (InputStream is = new FileInputStream(procFile)) {
byte[] buffer = new byte[10];
int bytes = is.read(buffer);
String setting = new String(buffer, 0, bytes, UTF_8);
setting = setting.trim();
if (bytes > 0 && Integer.parseInt(setting) > 10) {
log.warn("System swappiness setting is greater than ten ({})"
+ " which can cause time-sensitive operations to be delayed."
+ " Accumulo is time sensitive because it needs to maintain"
+ " distributed lock agreement.", setting);
}
}
}
} catch (Exception t) {
log.error("", t);
}
}, SECONDS.toMillis(1), MINUTES.toMillis(10), TimeUnit.MILLISECONDS);
ThreadPools.watchNonCriticalScheduledTask(future);
}
/**
* return a shared scheduled executor
*/
public synchronized ScheduledThreadPoolExecutor getScheduledExecutor() {
if (sharedScheduledThreadPool == null) {
sharedScheduledThreadPool =
(ScheduledThreadPoolExecutor) ThreadPools.createExecutorService(getConfiguration(),
Property.GENERAL_SIMPLETIMER_THREADPOOL_SIZE, true);
}
return sharedScheduledThreadPool;
}
}
| |
package com.esotericsoftware.kryo.io;
import java.io.IOException;
import java.io.OutputStream;
import com.esotericsoftware.kryo.KryoException;
/** An OutputStream that buffers data in a byte array and optionally flushes to another OutputStream. Utility methods are provided
* for efficiently writing primitive types and strings.
*
* Encoding of integers: BIG_ENDIAN is used for storing fixed native size integer values LITTLE_ENDIAN is used for a variable
* length encoding of integer values
*
* @author Nathan Sweet <misc@n4te.com> */
public class Output extends OutputStream {
protected int maxCapacity, total;
protected int position;
protected int capacity;
protected byte[] buffer;
protected OutputStream outputStream;
/** Creates an uninitialized Output. {@link #setBuffer(byte[], int)} must be called before the Output is used. */
public Output () {
}
/** Creates a new Output for writing to a byte array.
* @param bufferSize The initial and maximum size of the buffer. An exception is thrown if this size is exceeded. */
public Output (int bufferSize) {
this(bufferSize, bufferSize);
}
/** Creates a new Output for writing to a byte array.
* @param bufferSize The initial size of the buffer.
* @param maxBufferSize The buffer is doubled as needed until it exceeds maxBufferSize and an exception is thrown. Can be -1
* for no maximum. */
public Output (int bufferSize, int maxBufferSize) {
if (maxBufferSize < -1) throw new IllegalArgumentException("maxBufferSize cannot be < -1: " + maxBufferSize);
this.capacity = bufferSize;
this.maxCapacity = maxBufferSize == -1 ? Integer.MAX_VALUE : maxBufferSize;
buffer = new byte[bufferSize];
}
/** Creates a new Output for writing to a byte array.
* @see #setBuffer(byte[]) */
public Output (byte[] buffer) {
this(buffer, buffer.length);
}
/** Creates a new Output for writing to a byte array.
* @see #setBuffer(byte[], int) */
public Output (byte[] buffer, int maxBufferSize) {
if (buffer == null) throw new IllegalArgumentException("buffer cannot be null.");
setBuffer(buffer, maxBufferSize);
}
/** Creates a new Output for writing to an OutputStream. A buffer size of 4096 is used. */
public Output (OutputStream outputStream) {
this(4096, 4096);
if (outputStream == null) throw new IllegalArgumentException("outputStream cannot be null.");
this.outputStream = outputStream;
}
/** Creates a new Output for writing to an OutputStream. */
public Output (OutputStream outputStream, int bufferSize) {
this(bufferSize, bufferSize);
if (outputStream == null) throw new IllegalArgumentException("outputStream cannot be null.");
this.outputStream = outputStream;
}
public OutputStream getOutputStream () {
return outputStream;
}
/** Sets a new OutputStream. The position and total are reset, discarding any buffered bytes.
* @param outputStream May be null. */
public void setOutputStream (OutputStream outputStream) {
this.outputStream = outputStream;
position = 0;
total = 0;
}
/** Sets the buffer that will be written to. {@link #setBuffer(byte[], int)} is called with the specified buffer's length as the
* maxBufferSize. */
public void setBuffer (byte[] buffer) {
setBuffer(buffer, buffer.length);
}
/** Sets the buffer that will be written to. The position and total are reset, discarding any buffered bytes. The
* {@link #setOutputStream(OutputStream) OutputStream} is set to null.
* @param maxBufferSize The buffer is doubled as needed until it exceeds maxBufferSize and an exception is thrown. */
public void setBuffer (byte[] buffer, int maxBufferSize) {
if (buffer == null) throw new IllegalArgumentException("buffer cannot be null.");
if (maxBufferSize < -1) throw new IllegalArgumentException("maxBufferSize cannot be < -1: " + maxBufferSize);
this.buffer = buffer;
this.maxCapacity = maxBufferSize == -1 ? Integer.MAX_VALUE : maxBufferSize;
capacity = buffer.length;
position = 0;
total = 0;
outputStream = null;
}
/** Returns the buffer. The bytes between zero and {@link #position()} are the data that has been written. */
public byte[] getBuffer () {
return buffer;
}
/** Returns a new byte array containing the bytes currently in the buffer between zero and {@link #position()}. */
public byte[] toBytes () {
byte[] newBuffer = new byte[position];
System.arraycopy(buffer, 0, newBuffer, 0, position);
return newBuffer;
}
/** Returns the current position in the buffer. This is the number of bytes that have not been flushed. */
final public int position () {
return position;
}
/** Sets the current position in the buffer. */
public void setPosition (int position) {
this.position = position;
}
/** Returns the total number of bytes written. This may include bytes that have not been flushed. */
final public int total () {
return total + position;
}
/** Sets the position and total to zero. */
public void clear () {
position = 0;
total = 0;
}
/** @return true if the buffer has been resized. */
protected boolean require (int required) throws KryoException {
if (capacity - position >= required) return false;
if (required > maxCapacity)
throw new KryoException("Buffer overflow. Max capacity: " + maxCapacity + ", required: " + required);
flush();
while (capacity - position < required) {
if (capacity == maxCapacity)
throw new KryoException("Buffer overflow. Available: " + (capacity - position) + ", required: " + required);
// Grow buffer.
capacity = Math.min(capacity * 2, maxCapacity);
if (capacity < 0) capacity = maxCapacity;
byte[] newBuffer = new byte[capacity];
System.arraycopy(buffer, 0, newBuffer, 0, position);
buffer = newBuffer;
}
return true;
}
// OutputStream
/** Writes the buffered bytes to the underlying OutputStream, if any. */
public void flush () throws KryoException {
if (outputStream == null) return;
try {
outputStream.write(buffer, 0, position);
} catch (IOException ex) {
throw new KryoException(ex);
}
total += position;
position = 0;
}
/** Flushes any buffered bytes and closes the underlying OutputStream, if any. */
public void close () throws KryoException {
flush();
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ignored) {
}
}
}
/** Writes a byte. */
public void write (int value) throws KryoException {
if (position == capacity) require(1);
buffer[position++] = (byte)value;
}
/** Writes the bytes. Note the byte[] length is not written. */
public void write (byte[] bytes) throws KryoException {
if (bytes == null) throw new IllegalArgumentException("bytes cannot be null.");
writeBytes(bytes, 0, bytes.length);
}
/** Writes the bytes. Note the byte[] length is not written. */
public void write (byte[] bytes, int offset, int length) throws KryoException {
writeBytes(bytes, offset, length);
}
// byte
public void writeByte (byte value) throws KryoException {
if (position == capacity) require(1);
buffer[position++] = value;
}
public void writeByte (int value) throws KryoException {
if (position == capacity) require(1);
buffer[position++] = (byte)value;
}
/** Writes the bytes. Note the byte[] length is not written. */
public void writeBytes (byte[] bytes) throws KryoException {
if (bytes == null) throw new IllegalArgumentException("bytes cannot be null.");
writeBytes(bytes, 0, bytes.length);
}
/** Writes the bytes. Note the byte[] length is not written. */
public void writeBytes (byte[] bytes, int offset, int count) throws KryoException {
if (bytes == null) throw new IllegalArgumentException("bytes cannot be null.");
int copyCount = Math.min(capacity - position, count);
while (true) {
System.arraycopy(bytes, offset, buffer, position, copyCount);
position += copyCount;
count -= copyCount;
if (count == 0) return;
offset += copyCount;
copyCount = Math.min(capacity, count);
require(copyCount);
}
}
// int
/** Writes a 4 byte int. Uses BIG_ENDIAN byte order. */
public void writeInt (int value) throws KryoException {
require(4);
byte[] buffer = this.buffer;
buffer[position++] = (byte)(value >> 24);
buffer[position++] = (byte)(value >> 16);
buffer[position++] = (byte)(value >> 8);
buffer[position++] = (byte)value;
}
/** Writes a 1-5 byte int. This stream may consider such a variable length encoding request as a hint. It is not guaranteed that
* a variable length encoding will be really used. The stream may decide to use native-sized integer representation for
* efficiency reasons.
*
* @param optimizePositive If true, small positive numbers will be more efficient (1 byte) and small negative numbers will be
* inefficient (5 bytes). */
public int writeInt (int value, boolean optimizePositive) throws KryoException {
return writeVarInt(value, optimizePositive);
}
/** Writes a 1-5 byte int. It is guaranteed that a varible length encoding will be used.
*
* @param optimizePositive If true, small positive numbers will be more efficient (1 byte) and small negative numbers will be
* inefficient (5 bytes). */
public int writeVarInt (int value, boolean optimizePositive) throws KryoException {
if (!optimizePositive) value = (value << 1) ^ (value >> 31);
if (value >>> 7 == 0) {
require(1);
buffer[position++] = (byte)value;
return 1;
}
if (value >>> 14 == 0) {
require(2);
buffer[position++] = (byte)((value & 0x7F) | 0x80);
buffer[position++] = (byte)(value >>> 7);
return 2;
}
if (value >>> 21 == 0) {
require(3);
buffer[position++] = (byte)((value & 0x7F) | 0x80);
buffer[position++] = (byte)(value >>> 7 | 0x80);
buffer[position++] = (byte)(value >>> 14);
return 3;
}
if (value >>> 28 == 0) {
require(4);
buffer[position++] = (byte)((value & 0x7F) | 0x80);
buffer[position++] = (byte)(value >>> 7 | 0x80);
buffer[position++] = (byte)(value >>> 14 | 0x80);
buffer[position++] = (byte)(value >>> 21);
return 4;
}
require(5);
buffer[position++] = (byte)((value & 0x7F) | 0x80);
buffer[position++] = (byte)(value >>> 7 | 0x80);
buffer[position++] = (byte)(value >>> 14 | 0x80);
buffer[position++] = (byte)(value >>> 21 | 0x80);
buffer[position++] = (byte)(value >>> 28);
return 5;
}
// string
/** Writes the length and string, or null. Short strings are checked and if ASCII they are written more efficiently, else they
* are written as UTF8. If a string is known to be ASCII, {@link #writeAscii(String)} may be used. The string can be read using
* {@link Input#readString()} or {@link Input#readStringBuilder()}.
* @param value May be null. */
public void writeString (String value) throws KryoException {
if (value == null) {
writeByte(0x80); // 0 means null, bit 8 means UTF8.
return;
}
int charCount = value.length();
if (charCount == 0) {
writeByte(1 | 0x80); // 1 means empty string, bit 8 means UTF8.
return;
}
// Detect ASCII.
boolean ascii = false;
if (charCount > 1 && charCount < 64) {
ascii = true;
for (int i = 0; i < charCount; i++) {
int c = value.charAt(i);
if (c > 127) {
ascii = false;
break;
}
}
}
if (ascii) {
if (capacity - position < charCount)
writeAscii_slow(value, charCount);
else {
value.getBytes(0, charCount, buffer, position);
position += charCount;
}
buffer[position - 1] |= 0x80;
} else {
writeUtf8Length(charCount + 1);
int charIndex = 0;
if (capacity - position >= charCount) {
// Try to write 8 bit chars.
byte[] buffer = this.buffer;
int position = this.position;
for (; charIndex < charCount; charIndex++) {
int c = value.charAt(charIndex);
if (c > 127) break;
buffer[position++] = (byte)c;
}
this.position = position;
}
if (charIndex < charCount) writeString_slow(value, charCount, charIndex);
}
}
/** Writes the length and CharSequence as UTF8, or null. The string can be read using {@link Input#readString()} or
* {@link Input#readStringBuilder()}.
* @param value May be null. */
public void writeString (CharSequence value) throws KryoException {
if (value == null) {
writeByte(0x80); // 0 means null, bit 8 means UTF8.
return;
}
int charCount = value.length();
if (charCount == 0) {
writeByte(1 | 0x80); // 1 means empty string, bit 8 means UTF8.
return;
}
writeUtf8Length(charCount + 1);
int charIndex = 0;
if (capacity - position >= charCount) {
// Try to write 8 bit chars.
byte[] buffer = this.buffer;
int position = this.position;
for (; charIndex < charCount; charIndex++) {
int c = value.charAt(charIndex);
if (c > 127) break;
buffer[position++] = (byte)c;
}
this.position = position;
}
if (charIndex < charCount) writeString_slow(value, charCount, charIndex);
}
/** Writes a string that is known to contain only ASCII characters. Non-ASCII strings passed to this method will be corrupted.
* Each byte is a 7 bit character with the remaining byte denoting if another character is available. This is slightly more
* efficient than {@link #writeString(String)}. The string can be read using {@link Input#readString()} or
* {@link Input#readStringBuilder()}.
* @param value May be null. */
public void writeAscii (String value) throws KryoException {
if (value == null) {
writeByte(0x80); // 0 means null, bit 8 means UTF8.
return;
}
int charCount = value.length();
if (charCount == 0) {
writeByte(1 | 0x80); // 1 means empty string, bit 8 means UTF8.
return;
}
if (capacity - position < charCount)
writeAscii_slow(value, charCount);
else {
value.getBytes(0, charCount, buffer, position);
position += charCount;
}
buffer[position - 1] |= 0x80; // Bit 8 means end of ASCII.
}
/** Writes the length of a string, which is a variable length encoded int except the first byte uses bit 8 to denote UTF8 and
* bit 7 to denote if another byte is present. */
private void writeUtf8Length (int value) {
if (value >>> 6 == 0) {
require(1);
buffer[position++] = (byte)(value | 0x80); // Set bit 8.
} else if (value >>> 13 == 0) {
require(2);
byte[] buffer = this.buffer;
buffer[position++] = (byte)(value | 0x40 | 0x80); // Set bit 7 and 8.
buffer[position++] = (byte)(value >>> 6);
} else if (value >>> 20 == 0) {
require(3);
byte[] buffer = this.buffer;
buffer[position++] = (byte)(value | 0x40 | 0x80); // Set bit 7 and 8.
buffer[position++] = (byte)((value >>> 6) | 0x80); // Set bit 8.
buffer[position++] = (byte)(value >>> 13);
} else if (value >>> 27 == 0) {
require(4);
byte[] buffer = this.buffer;
buffer[position++] = (byte)(value | 0x40 | 0x80); // Set bit 7 and 8.
buffer[position++] = (byte)((value >>> 6) | 0x80); // Set bit 8.
buffer[position++] = (byte)((value >>> 13) | 0x80); // Set bit 8.
buffer[position++] = (byte)(value >>> 20);
} else {
require(5);
byte[] buffer = this.buffer;
buffer[position++] = (byte)(value | 0x40 | 0x80); // Set bit 7 and 8.
buffer[position++] = (byte)((value >>> 6) | 0x80); // Set bit 8.
buffer[position++] = (byte)((value >>> 13) | 0x80); // Set bit 8.
buffer[position++] = (byte)((value >>> 20) | 0x80); // Set bit 8.
buffer[position++] = (byte)(value >>> 27);
}
}
private void writeString_slow (CharSequence value, int charCount, int charIndex) {
for (; charIndex < charCount; charIndex++) {
if (position == capacity) require(Math.min(capacity, charCount - charIndex));
int c = value.charAt(charIndex);
if (c <= 0x007F) {
buffer[position++] = (byte)c;
} else if (c > 0x07FF) {
buffer[position++] = (byte)(0xE0 | c >> 12 & 0x0F);
require(2);
buffer[position++] = (byte)(0x80 | c >> 6 & 0x3F);
buffer[position++] = (byte)(0x80 | c & 0x3F);
} else {
buffer[position++] = (byte)(0xC0 | c >> 6 & 0x1F);
require(1);
buffer[position++] = (byte)(0x80 | c & 0x3F);
}
}
}
private void writeAscii_slow (String value, int charCount) throws KryoException {
byte[] buffer = this.buffer;
int charIndex = 0;
int charsToWrite = Math.min(charCount, capacity - position);
while (charIndex < charCount) {
value.getBytes(charIndex, charIndex + charsToWrite, buffer, position);
charIndex += charsToWrite;
position += charsToWrite;
charsToWrite = Math.min(charCount - charIndex, capacity);
if (require(charsToWrite)) buffer = this.buffer;
}
}
// float
/** Writes a 4 byte float. */
public void writeFloat (float value) throws KryoException {
writeInt(Float.floatToIntBits(value));
}
/** Writes a 1-5 byte float with reduced precision.
* @param optimizePositive If true, small positive numbers will be more efficient (1 byte) and small negative numbers will be
* inefficient (5 bytes). */
public int writeFloat (float value, float precision, boolean optimizePositive) throws KryoException {
return writeInt((int)(value * precision), optimizePositive);
}
// short
/** Writes a 2 byte short. Uses BIG_ENDIAN byte order. */
public void writeShort (int value) throws KryoException {
require(2);
buffer[position++] = (byte)(value >>> 8);
buffer[position++] = (byte)value;
}
// long
/** Writes an 8 byte long. Uses BIG_ENDIAN byte order. */
public void writeLong (long value) throws KryoException {
require(8);
byte[] buffer = this.buffer;
buffer[position++] = (byte)(value >>> 56);
buffer[position++] = (byte)(value >>> 48);
buffer[position++] = (byte)(value >>> 40);
buffer[position++] = (byte)(value >>> 32);
buffer[position++] = (byte)(value >>> 24);
buffer[position++] = (byte)(value >>> 16);
buffer[position++] = (byte)(value >>> 8);
buffer[position++] = (byte)value;
}
/** Writes a 1-9 byte long. This stream may consider such a variable length encoding request as a hint. It is not guaranteed
* that a variable length encoding will be really used. The stream may decide to use native-sized integer representation for
* efficiency reasons.
*
* @param optimizePositive If true, small positive numbers will be more efficient (1 byte) and small negative numbers will be
* inefficient (9 bytes). */
public int writeLong (long value, boolean optimizePositive) throws KryoException {
return writeVarLong(value, optimizePositive);
}
/** Writes a 1-9 byte long. It is guaranteed that a varible length encoding will be used.
* @param optimizePositive If true, small positive numbers will be more efficient (1 byte) and small negative numbers will be
* inefficient (9 bytes). */
public int writeVarLong (long value, boolean optimizePositive) throws KryoException {
if (!optimizePositive) value = (value << 1) ^ (value >> 63);
if (value >>> 7 == 0) {
require(1);
buffer[position++] = (byte)value;
return 1;
}
if (value >>> 14 == 0) {
require(2);
buffer[position++] = (byte)((value & 0x7F) | 0x80);
buffer[position++] = (byte)(value >>> 7);
return 2;
}
if (value >>> 21 == 0) {
require(3);
buffer[position++] = (byte)((value & 0x7F) | 0x80);
buffer[position++] = (byte)(value >>> 7 | 0x80);
buffer[position++] = (byte)(value >>> 14);
return 3;
}
if (value >>> 28 == 0) {
require(4);
buffer[position++] = (byte)((value & 0x7F) | 0x80);
buffer[position++] = (byte)(value >>> 7 | 0x80);
buffer[position++] = (byte)(value >>> 14 | 0x80);
buffer[position++] = (byte)(value >>> 21);
return 4;
}
if (value >>> 35 == 0) {
require(5);
buffer[position++] = (byte)((value & 0x7F) | 0x80);
buffer[position++] = (byte)(value >>> 7 | 0x80);
buffer[position++] = (byte)(value >>> 14 | 0x80);
buffer[position++] = (byte)(value >>> 21 | 0x80);
buffer[position++] = (byte)(value >>> 28);
return 5;
}
if (value >>> 42 == 0) {
require(6);
buffer[position++] = (byte)((value & 0x7F) | 0x80);
buffer[position++] = (byte)(value >>> 7 | 0x80);
buffer[position++] = (byte)(value >>> 14 | 0x80);
buffer[position++] = (byte)(value >>> 21 | 0x80);
buffer[position++] = (byte)(value >>> 28 | 0x80);
buffer[position++] = (byte)(value >>> 35);
return 6;
}
if (value >>> 49 == 0) {
require(7);
buffer[position++] = (byte)((value & 0x7F) | 0x80);
buffer[position++] = (byte)(value >>> 7 | 0x80);
buffer[position++] = (byte)(value >>> 14 | 0x80);
buffer[position++] = (byte)(value >>> 21 | 0x80);
buffer[position++] = (byte)(value >>> 28 | 0x80);
buffer[position++] = (byte)(value >>> 35 | 0x80);
buffer[position++] = (byte)(value >>> 42);
return 7;
}
if (value >>> 56 == 0) {
require(8);
buffer[position++] = (byte)((value & 0x7F) | 0x80);
buffer[position++] = (byte)(value >>> 7 | 0x80);
buffer[position++] = (byte)(value >>> 14 | 0x80);
buffer[position++] = (byte)(value >>> 21 | 0x80);
buffer[position++] = (byte)(value >>> 28 | 0x80);
buffer[position++] = (byte)(value >>> 35 | 0x80);
buffer[position++] = (byte)(value >>> 42 | 0x80);
buffer[position++] = (byte)(value >>> 49);
return 8;
}
require(9);
buffer[position++] = (byte)((value & 0x7F) | 0x80);
buffer[position++] = (byte)(value >>> 7 | 0x80);
buffer[position++] = (byte)(value >>> 14 | 0x80);
buffer[position++] = (byte)(value >>> 21 | 0x80);
buffer[position++] = (byte)(value >>> 28 | 0x80);
buffer[position++] = (byte)(value >>> 35 | 0x80);
buffer[position++] = (byte)(value >>> 42 | 0x80);
buffer[position++] = (byte)(value >>> 49 | 0x80);
buffer[position++] = (byte)(value >>> 56);
return 9;
}
// boolean
/** Writes a 1 byte boolean. */
public void writeBoolean (boolean value) throws KryoException {
if (position == capacity) require(1);
buffer[position++] = (byte)(value ? 1 : 0);
}
// char
/** Writes a 2 byte char. Uses BIG_ENDIAN byte order. */
public void writeChar (char value) throws KryoException {
require(2);
buffer[position++] = (byte)(value >>> 8);
buffer[position++] = (byte)value;
}
// double
/** Writes an 8 byte double. */
public void writeDouble (double value) throws KryoException {
writeLong(Double.doubleToLongBits(value));
}
/** Writes a 1-9 byte double with reduced precision.
* @param optimizePositive If true, small positive numbers will be more efficient (1 byte) and small negative numbers will be
* inefficient (9 bytes). */
public int writeDouble (double value, double precision, boolean optimizePositive) throws KryoException {
return writeLong((long)(value * precision), optimizePositive);
}
/** Returns the number of bytes that would be written with {@link #writeInt(int, boolean)}. */
static public int intLength (int value, boolean optimizePositive) {
if (!optimizePositive) value = (value << 1) ^ (value >> 31);
if (value >>> 7 == 0) return 1;
if (value >>> 14 == 0) return 2;
if (value >>> 21 == 0) return 3;
if (value >>> 28 == 0) return 4;
return 5;
}
/** Returns the number of bytes that would be written with {@link #writeLong(long, boolean)}. */
static public int longLength (long value, boolean optimizePositive) {
if (!optimizePositive) value = (value << 1) ^ (value >> 63);
if (value >>> 7 == 0) return 1;
if (value >>> 14 == 0) return 2;
if (value >>> 21 == 0) return 3;
if (value >>> 28 == 0) return 4;
if (value >>> 35 == 0) return 5;
if (value >>> 42 == 0) return 6;
if (value >>> 49 == 0) return 7;
if (value >>> 56 == 0) return 8;
return 9;
}
// Methods implementing bulk operations on arrays of primitive types
/** Bulk output of an int array. */
public void writeInts (int[] object, boolean optimizePositive) throws KryoException {
for (int i = 0, n = object.length; i < n; i++)
writeInt(object[i], optimizePositive);
}
/** Bulk output of an long array. */
public void writeLongs (long[] object, boolean optimizePositive) throws KryoException {
for (int i = 0, n = object.length; i < n; i++)
writeLong(object[i], optimizePositive);
}
/** Bulk output of an int array. */
public void writeInts (int[] object) throws KryoException {
for (int i = 0, n = object.length; i < n; i++)
writeInt(object[i]);
}
/** Bulk output of an long array. */
public void writeLongs (long[] object) throws KryoException {
for (int i = 0, n = object.length; i < n; i++)
writeLong(object[i]);
}
/** Bulk output of a float array. */
public void writeFloats (float[] object) throws KryoException {
for (int i = 0, n = object.length; i < n; i++)
writeFloat(object[i]);
}
/** Bulk output of a short array. */
public void writeShorts (short[] object) throws KryoException {
for (int i = 0, n = object.length; i < n; i++)
writeShort(object[i]);
}
/** Bulk output of a char array. */
public void writeChars (char[] object) throws KryoException {
for (int i = 0, n = object.length; i < n; i++)
writeChar(object[i]);
}
/** Bulk output of a double array. */
public void writeDoubles (double[] object) throws KryoException {
for (int i = 0, n = object.length; i < n; i++)
writeDouble(object[i]);
}
}
| |
/*
Copyright 2012 Software Freedom Conservancy
Copyright 2007-2012 Selenium committers
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import static org.openqa.selenium.TestWaiter.waitFor;
import static org.openqa.selenium.WaitingConditions.alertToBePresent;
import static org.openqa.selenium.WaitingConditions.elementTextToEqual;
import static org.openqa.selenium.WaitingConditions.newWindowIsOpened;
import static org.openqa.selenium.WaitingConditions.windowHandleCountToBe;
import static org.openqa.selenium.WaitingConditions.windowToBeSwitchedToWithName;
import static org.openqa.selenium.testing.Ignore.Driver.ANDROID;
import static org.openqa.selenium.testing.Ignore.Driver.CHROME;
import static org.openqa.selenium.testing.Ignore.Driver.FIREFOX;
import static org.openqa.selenium.testing.Ignore.Driver.HTMLUNIT;
import static org.openqa.selenium.testing.Ignore.Driver.IE;
import static org.openqa.selenium.testing.Ignore.Driver.IPHONE;
import static org.openqa.selenium.testing.Ignore.Driver.OPERA;
import static org.openqa.selenium.testing.Ignore.Driver.PHANTOMJS;
import static org.openqa.selenium.testing.Ignore.Driver.SAFARI;
import static org.openqa.selenium.testing.Ignore.Driver.OPERA_MOBILE;
import org.openqa.selenium.testing.Ignore;
import org.openqa.selenium.testing.JUnit4TestBase;
import org.openqa.selenium.testing.JavascriptEnabled;
import org.openqa.selenium.testing.NeedsLocalEnvironment;
import org.openqa.selenium.testing.TestUtilities;
import org.junit.Before;
import org.junit.Test;
import java.util.Set;
@Ignore({ANDROID, HTMLUNIT, IPHONE, OPERA, PHANTOMJS, SAFARI, OPERA_MOBILE})
public class AlertsTest extends JUnit4TestBase {
@Before
public void setUp() throws Exception {
driver.get(pages.alertsPage);
}
@JavascriptEnabled
@Test
public void testShouldBeAbleToOverrideTheWindowAlertMethod() {
((JavascriptExecutor) driver).executeScript(
"window.alert = function(msg) { document.getElementById('text').innerHTML = msg; }");
driver.findElement(By.id("alert")).click();
}
@JavascriptEnabled
@Test
public void testShouldAllowUsersToAcceptAnAlertManually() {
driver.findElement(By.id("alert")).click();
Alert alert = waitFor(alertToBePresent(driver));
alert.accept();
// If we can perform any action, we're good to go
assertEquals("Testing Alerts", driver.getTitle());
}
@JavascriptEnabled
@Test
public void testShouldAllowUsersToAcceptAnAlertWithNoTextManually() {
driver.findElement(By.id("empty-alert")).click();
Alert alert = waitFor(alertToBePresent(driver));
alert.accept();
// If we can perform any action, we're good to go
assertEquals("Testing Alerts", driver.getTitle());
}
@Ignore(CHROME)
@JavascriptEnabled
@NeedsLocalEnvironment(reason = "Carefully timing based")
@Test
public void testShouldGetTextOfAlertOpenedInSetTimeout() throws Exception {
driver.findElement(By.id("slow-alert")).click();
// DO NOT WAIT OR SLEEP HERE.
// This is a regression test for a bug where only the first switchTo call would throw,
// and only if it happens before the alert actually loads.
Alert alert = driver.switchTo().alert();
try {
assertEquals("Slow", alert.getText());
} finally {
alert.accept();
}
}
@JavascriptEnabled
@Test
public void testShouldAllowUsersToDismissAnAlertManually() {
driver.findElement(By.id("alert")).click();
Alert alert = waitFor(alertToBePresent(driver));
alert.dismiss();
// If we can perform any action, we're good to go
assertEquals("Testing Alerts", driver.getTitle());
}
@JavascriptEnabled
@Test
public void testShouldAllowAUserToAcceptAPrompt() {
driver.findElement(By.id("prompt")).click();
Alert alert = waitFor(alertToBePresent(driver));
alert.accept();
// If we can perform any action, we're good to go
assertEquals("Testing Alerts", driver.getTitle());
}
@JavascriptEnabled
@Test
public void testShouldAllowAUserToDismissAPrompt() {
driver.findElement(By.id("prompt")).click();
Alert alert = waitFor(alertToBePresent(driver));
alert.dismiss();
// If we can perform any action, we're good to go
assertEquals("Testing Alerts", driver.getTitle());
}
@JavascriptEnabled
@Test
public void testShouldAllowAUserToSetTheValueOfAPrompt() {
driver.findElement(By.id("prompt")).click();
Alert alert = waitFor(alertToBePresent(driver));
alert.sendKeys("cheese");
alert.accept();
waitFor(elementTextToEqual(driver, By.id("text"), "cheese"));
}
@Ignore(CHROME)
@JavascriptEnabled
@Test
public void testSettingTheValueOfAnAlertThrows() {
driver.findElement(By.id("alert")).click();
Alert alert = waitFor(alertToBePresent(driver));
try {
alert.sendKeys("cheese");
fail("Expected exception");
} catch (ElementNotVisibleException expected) {
} finally {
alert.accept();
}
}
@JavascriptEnabled
@Test
public void testShouldAllowTheUserToGetTheTextOfAnAlert() {
driver.findElement(By.id("alert")).click();
Alert alert = waitFor(alertToBePresent(driver));
String value = alert.getText();
alert.accept();
assertEquals("cheese", value);
}
@Test
public void testShouldAllowTheUserToGetTheTextOfAPrompt() {
driver.findElement(By.id("prompt")).click();
Alert alert = waitFor(alertToBePresent(driver));
String value = alert.getText();
alert.accept();
assertEquals("Enter something", value);
}
@JavascriptEnabled
@Test
public void testAlertShouldNotAllowAdditionalCommandsIfDismissed() {
driver.findElement(By.id("alert")).click();
Alert alert = waitFor(alertToBePresent(driver));
alert.dismiss();
try {
alert.getText();
} catch (NoAlertPresentException expected) {
return;
}
fail("Expected NoAlertPresentException");
}
@Ignore(ANDROID)
@JavascriptEnabled
@Test
public void testShouldAllowUsersToAcceptAnAlertInAFrame() {
driver.switchTo().frame("iframeWithAlert");
driver.findElement(By.id("alertInFrame")).click();
Alert alert = waitFor(alertToBePresent(driver));
alert.accept();
// If we can perform any action, we're good to go
assertEquals("Testing Alerts", driver.getTitle());
}
@Ignore(ANDROID)
@JavascriptEnabled
@Test
public void testShouldAllowUsersToAcceptAnAlertInANestedFrame() {
driver.switchTo().frame("iframeWithIframe").switchTo().frame("iframeWithAlert");
driver.findElement(By.id("alertInFrame")).click();
Alert alert = waitFor(alertToBePresent(driver));
alert.accept();
// If we can perform any action, we're good to go
assertEquals("Testing Alerts", driver.getTitle());
}
@JavascriptEnabled
@Test
public void testSwitchingToMissingAlertThrows() throws Exception {
try {
driver.switchTo().alert();
fail("Expected exception");
} catch (NoAlertPresentException expected) {
// Expected
}
}
@JavascriptEnabled
@Ignore(value = {CHROME}, issues = {2764})
@Test
public void testSwitchingToMissingAlertInAClosedWindowThrows() throws Exception {
String mainWindow = driver.getWindowHandle();
try {
driver.findElement(By.id("open-new-window")).click();
waitFor(windowHandleCountToBe(driver, 2));
waitFor(windowToBeSwitchedToWithName(driver, "newwindow"));
driver.close();
try {
alertToBePresent(driver).call();
fail("Expected exception");
} catch (NoSuchWindowException expected) {
// Expected
}
} finally {
driver.switchTo().window(mainWindow);
waitFor(elementTextToEqual(driver, By.id("open-new-window"), "open new window"));
}
}
@JavascriptEnabled
@Test
public void testPromptShouldUseDefaultValueIfNoKeysSent() {
driver.findElement(By.id("prompt-with-default")).click();
Alert alert = waitFor(alertToBePresent(driver));
alert.accept();
waitFor(elementTextToEqual(driver, By.id("text"), "This is a default value"));
}
@JavascriptEnabled
@Ignore(ANDROID)
@Test
public void testPromptShouldHaveNullValueIfDismissed() {
driver.findElement(By.id("prompt-with-default")).click();
Alert alert = waitFor(alertToBePresent(driver));
alert.dismiss();
waitFor(elementTextToEqual(driver, By.id("text"), "null"));
}
@JavascriptEnabled
@Test
public void testHandlesTwoAlertsFromOneInteraction() {
driver.findElement(By.id("double-prompt")).click();
Alert alert1 = waitFor(alertToBePresent(driver));
alert1.sendKeys("brie");
alert1.accept();
Alert alert2 = waitFor(alertToBePresent(driver));
alert2.sendKeys("cheddar");
alert2.accept();
waitFor(elementTextToEqual(driver, By.id("text1"), "brie"));
waitFor(elementTextToEqual(driver, By.id("text2"), "cheddar"));
}
@JavascriptEnabled
@Test
public void testShouldHandleAlertOnPageLoad() {
driver.findElement(By.id("open-page-with-onload-alert")).click();
Alert alert = waitFor(alertToBePresent(driver));
String value = alert.getText();
alert.accept();
assertEquals("onload", value);
waitFor(elementTextToEqual(driver, By.tagName("p"), "Page with onload event handler"));
}
@JavascriptEnabled
@Test
@Ignore(CHROME)
public void testShouldHandleAlertOnPageLoadUsingGet() {
driver.get(appServer.whereIs("pageWithOnLoad.html"));
Alert alert = waitFor(alertToBePresent(driver));
String value = alert.getText();
alert.accept();
assertEquals("onload", value);
waitFor(elementTextToEqual(driver, By.tagName("p"), "Page with onload event handler"));
}
@JavascriptEnabled
@Ignore(value = {CHROME, FIREFOX, IE}, reason = "IE: fails in versions 6 and 7")
@Test
public void testShouldNotHandleAlertInAnotherWindow() {
String mainWindow = driver.getWindowHandle();
Set<String> currentWindowHandles = driver.getWindowHandles();
String onloadWindow = null;
try {
driver.findElement(By.id("open-window-with-onload-alert")).click();
onloadWindow = waitFor(newWindowIsOpened(driver, currentWindowHandles));
boolean gotException = false;
try {
waitFor(alertToBePresent(driver));
} catch (AssertionError expected) {
// Expected
gotException = true;
}
assertTrue(gotException);
} finally {
driver.switchTo().window(onloadWindow);
waitFor(alertToBePresent(driver)).dismiss();
driver.close();
driver.switchTo().window(mainWindow);
waitFor(elementTextToEqual(driver, By.id("open-window-with-onload-alert"), "open new window"));
}
}
@JavascriptEnabled
@Ignore(value = {CHROME})
@Test
public void testShouldHandleAlertOnPageUnload() {
driver.findElement(By.id("open-page-with-onunload-alert")).click();
driver.navigate().back();
Alert alert = waitFor(alertToBePresent(driver));
String value = alert.getText();
alert.accept();
assertEquals("onunload", value);
waitFor(elementTextToEqual(driver, By.id("open-page-with-onunload-alert"), "open new page"));
}
@JavascriptEnabled
@Ignore(value = {ANDROID, CHROME}, reason = "On Android, alerts do not pop up" +
" when a window is closed.")
@Test
public void testShouldHandleAlertOnWindowClose() {
if (TestUtilities.isFirefox(driver) &&
TestUtilities.isNativeEventsEnabled(driver) &&
TestUtilities.getEffectivePlatform().is(Platform.LINUX)) {
System.err.println("x_ignore_nofocus can cause a firefox crash here. Ignoring test. See issue 2987.");
assumeTrue(false);
}
String mainWindow = driver.getWindowHandle();
try {
driver.findElement(By.id("open-window-with-onclose-alert")).click();
waitFor(windowHandleCountToBe(driver, 2));
waitFor(windowToBeSwitchedToWithName(driver, "onclose"));
driver.close();
Alert alert = waitFor(alertToBePresent(driver));
String value = alert.getText();
alert.accept();
assertEquals("onunload", value);
} finally {
driver.switchTo().window(mainWindow);
waitFor(elementTextToEqual(driver, By.id("open-window-with-onclose-alert"), "open new window"));
}
}
@JavascriptEnabled
@Ignore(value = {ANDROID, CHROME, HTMLUNIT, IPHONE, OPERA})
@Test
public void testIncludesAlertTextInUnhandledAlertException() {
driver.findElement(By.id("alert")).click();
waitFor(alertToBePresent(driver));
try {
driver.getTitle();
fail("Expected UnhandledAlertException");
} catch (UnhandledAlertException e) {
assertEquals("cheese", e.getAlertText());
}
}
@NoDriverAfterTest
@Test
public void testCanQuitWhenAnAlertIsPresent() {
driver.get(pages.alertsPage);
driver.findElement(By.id("alert")).click();
waitFor(alertToBePresent(driver));
driver.quit();
}
}
| |
package com.vladmihalcea.hibernate.masterclass.laboratory.concurrency;
import com.vladmihalcea.hibernate.masterclass.laboratory.util.AbstractTest;
import org.hibernate.StaleObjectStateException;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.OptimisticLockType;
import org.hibernate.annotations.OptimisticLocking;
import org.junit.Test;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.math.BigDecimal;
import java.util.concurrent.CountDownLatch;
/**
* OptimisticLockingOneRootDirtyVersioningTest - Test to check optimistic checking on a single entity being updated by many threads
* using the dirty properties instead of a synthetic version column
*
* @author Vlad Mihalcea
*/
public class OptimisticLockingOneRootDirtyVersioningTest extends AbstractTest {
private final CountDownLatch loadProductsLatch = new CountDownLatch(3);
private final CountDownLatch aliceLatch = new CountDownLatch(1);
public class AliceTransaction implements Runnable {
@Override
public void run() {
try {
doInTransaction(session -> {
try {
Product product = (Product) session.get(Product.class, 1L);
loadProductsLatch.countDown();
loadProductsLatch.await();
product.setQuantity(6L);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
});
} catch (StaleObjectStateException expected) {
LOGGER.info("Alice: Optimistic locking failure", expected);
}
aliceLatch.countDown();
}
}
public class BobTransaction implements Runnable {
@Override
public void run() {
try {
doInTransaction(session -> {
try {
Product product = (Product) session.get(Product.class, 1L);
loadProductsLatch.countDown();
loadProductsLatch.await();
aliceLatch.await();
product.incrementLikes();
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
});
} catch (StaleObjectStateException expected) {
LOGGER.info("Bob: Optimistic locking failure", expected);
}
}
}
public class VladTransaction implements Runnable {
@Override
public void run() {
try {
doInTransaction(session -> {
try {
Product product = (Product) session.get(Product.class, 1L);
loadProductsLatch.countDown();
loadProductsLatch.await();
aliceLatch.await();
product.setDescription("Plasma HDTV");
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
});
} catch (StaleObjectStateException expected) {
LOGGER.info("Vlad: Optimistic locking failure", expected);
}
}
}
@Test
public void testOptimisticLocking() throws InterruptedException {
doInTransaction(session -> {
Product product = new Product();
product.setId(1L);
product.setName("TV");
product.setDescription("Plasma TV");
product.setPrice(BigDecimal.valueOf(199.99));
product.setQuantity(7L);
session.persist(product);
});
Thread alice = new Thread(new AliceTransaction());
Thread bob = new Thread(new BobTransaction());
Thread vlad = new Thread(new VladTransaction());
alice.start();
bob.start();
vlad.start();
alice.join();
bob.join();
vlad.join();
}
@Override
protected Class<?>[] entities() {
return new Class<?>[]{
Product.class
};
}
/**
* Product - Product
*
* @author Vlad Mihalcea
*/
@Entity(name = "product")
@Table(name = "product")
@OptimisticLocking(type = OptimisticLockType.DIRTY)
@DynamicUpdate
public static class Product {
@Id
private Long id;
@Column(unique = true, nullable = false)
private String name;
@Column(nullable = false)
private String description;
@Column(nullable = false)
private BigDecimal price;
private long quantity;
private int likes;
public Product() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public long getQuantity() {
return quantity;
}
public void setQuantity(long quantity) {
this.quantity = quantity;
}
public int getLikes() {
return likes;
}
public int incrementLikes() {
return ++likes;
}
}
}
| |
/**
* SIX OVAL - https://nakamura5akihito.github.io/
* Copyright (C) 2010 Akihito Nakamura
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.opensec.six.oval.model.linux;
import io.opensec.six.oval.model.OvalObject;
/**
* The RpmVerifyFileBehaviors defines a set of behaviors
* that for controlling how the individual files in installed rpms are verified.
*
* @author Akihito Nakamura, AIST
* @see <a href="http://oval.mitre.org/language/">OVAL Language</a>
*/
public class RpmVerifyFileBehaviors
implements OvalObject
{
public static final Boolean DEFAULT_NOLINKTO = Boolean.FALSE;
private Boolean nolinkto;
//{optional, default="false"}
public static final Boolean DEFAULT_NOMD5 = Boolean.FALSE;
private Boolean nomd5;
//{optional, default="false"}
public static final Boolean DEFAULT_NOSIZE = Boolean.FALSE;
private Boolean nosize;
//{optional, default="false"}
public static final Boolean DEFAULT_NOUSER = Boolean.FALSE;
private Boolean nouser;
//{optional, default="false"}
public static final Boolean DEFAULT_NOGROUP = Boolean.FALSE;
private Boolean nogroup;
//{optional, default="false"}
public static final Boolean DEFAULT_NOMTIME = Boolean.FALSE;
private Boolean nomtime;
//{optional, default="false"}
public static final Boolean DEFAULT_NOMODE = Boolean.FALSE;
private Boolean nomode;
//{optional, default="false"}
public static final Boolean DEFAULT_NORDEV = Boolean.FALSE;
private Boolean nordev;
//{optional, default="false"}
public static final Boolean DEFAULT_NOCONFIGFILES = Boolean.FALSE;
private Boolean noconfigfiles;
//{optional, default="false"}
public static final Boolean DEFAULT_NOGHOSTFILES = Boolean.FALSE;
private Boolean noghostfiles;
//{optional, default="false"}
/**
* Constructor.
*/
public RpmVerifyFileBehaviors()
{
}
/**
*/
public void setNoLinkto(
final Boolean nolinkto
)
{
this.nolinkto = nolinkto;
}
public Boolean getNoLinkto()
{
return nolinkto;
}
public static final Boolean noLinkto(
final RpmVerifyFileBehaviors obj
)
{
Boolean nolinkto = obj.getNoLinkto();
return (nolinkto == null ? DEFAULT_NOLINKTO : nolinkto);
}
/**
*/
public void setNoMd5(
final Boolean nomd5
)
{
this.nomd5 = nomd5;
}
public Boolean getNoMd5()
{
return nomd5;
}
public static final Boolean noMd5(
final RpmVerifyFileBehaviors obj
)
{
Boolean nomd5 = obj.getNoMd5();
return (nomd5 == null ? DEFAULT_NOMD5 : nomd5);
}
/**
*/
public void setNoSize(
final Boolean nosize
)
{
this.nosize = nosize;
}
public Boolean getNoSize()
{
return nosize;
}
public static final Boolean noSize(
final RpmVerifyFileBehaviors obj
)
{
Boolean nosize = obj.getNoSize();
return (nosize == null ? DEFAULT_NOSIZE : nosize);
}
/**
*/
public void setNoUser(
final Boolean nouser
)
{
this.nouser = nouser;
}
public Boolean getNoUser()
{
return nouser;
}
public static final Boolean noUser(
final RpmVerifyFileBehaviors obj
)
{
Boolean nouser = obj.getNoUser();
return (nouser == null ? DEFAULT_NOUSER : nouser);
}
/**
*/
public void setNoGroup(
final Boolean nogroup
)
{
this.nogroup = nogroup;
}
public Boolean getNoGroup()
{
return nogroup;
}
public static final Boolean noGroup(
final RpmVerifyFileBehaviors obj
)
{
Boolean nogroup = obj.getNoGroup();
return (nogroup == null ? DEFAULT_NOGROUP : nogroup);
}
/**
*/
public void setNoMtime(
final Boolean nomtime
)
{
this.nomtime = nomtime;
}
public Boolean getNoMtime()
{
return nomtime;
}
public static final Boolean noMtime(
final RpmVerifyFileBehaviors obj
)
{
Boolean nomtime = obj.getNoMtime();
return (nomtime == null ? DEFAULT_NOMTIME : nomtime);
}
/**
*/
public void setNoMode(
final Boolean nomode
)
{
this.nomode = nomode;
}
public Boolean getNoMode()
{
return nomode;
}
public static final Boolean noMode(
final RpmVerifyFileBehaviors obj
)
{
Boolean nomode = obj.getNoMode();
return (nomode == null ? DEFAULT_NOMODE : nomode);
}
/**
*/
public void setNoRdev(
final Boolean nordev
)
{
this.nordev = nordev;
}
public Boolean getNoRdev()
{
return nordev;
}
public static final Boolean noRdev(
final RpmVerifyFileBehaviors obj
)
{
Boolean nordev = obj.getNoRdev();
return (nordev == null ? DEFAULT_NORDEV : nordev);
}
/**
*/
public void setNoConfigFiles(
final Boolean noconfigfiles
)
{
this.noconfigfiles = noconfigfiles;
}
public Boolean getNoConfigFiles()
{
return noconfigfiles;
}
public static final Boolean noConfigFiles(
final RpmVerifyFileBehaviors obj
)
{
Boolean noconfigfiles = obj.getNoConfigFiles();
return (noconfigfiles == null ? DEFAULT_NOCONFIGFILES : noconfigfiles);
}
/**
*/
public void setNoGhostFiles(
final Boolean noghostfiles
)
{
this.noghostfiles = noghostfiles;
}
public Boolean getNoGhostFiles()
{
return noghostfiles;
}
public static final Boolean noGhostFiles(
final RpmVerifyFileBehaviors obj
)
{
Boolean noghostfiles = obj.getNoGhostFiles();
return (noghostfiles == null ? DEFAULT_NOGHOSTFILES : noghostfiles);
}
// **************************************************************
// java.lang.Object
// **************************************************************
@Override
public int hashCode()
{
final int prime = 37;
int result = 17;
result = prime * result + noLinkto( this ).hashCode();
result = prime * result + noMd5( this ).hashCode();
result = prime * result + noSize( this ).hashCode();
result = prime * result + noUser( this ).hashCode();
result = prime * result + noGroup( this ).hashCode();
result = prime * result + noMtime( this ).hashCode();
result = prime * result + noMode( this ).hashCode();
result = prime * result + noRdev( this ).hashCode();
result = prime * result + noConfigFiles( this ).hashCode();
result = prime * result + noGhostFiles( this ).hashCode();
return result;
}
@Override
public boolean equals(
final Object obj
)
{
if (this == obj) {
return true;
}
if (!(obj instanceof RpmVerifyFileBehaviors)) {
return false;
}
RpmVerifyFileBehaviors other = (RpmVerifyFileBehaviors)obj;
if (noLinkto( this ) == noLinkto( other )
&& (noMd5( this ) == noMd5( other ))
&& (noSize( this ) == noSize( other ))
&& (noUser( this ) == noUser( other ))
&& (noGroup( this ) == noGroup( other ))
&& (noMtime( this ) == noMtime( other ))
&& (noMode( this ) == noMode( other ))
&& (noRdev( this ) == noRdev( other ))
&& (noConfigFiles( this ) == noConfigFiles( other ))
&& (noGhostFiles( this ) == noGhostFiles( other ))
) {
return true;
}
return false;
}
@Override
public String toString()
{
return "[nolinkto=" + getNoLinkto()
+ ", nomd5=" + getNoMd5()
+ ", nosize=" + getNoSize()
+ ", nouser=" + getNoUser()
+ ", nogroup=" + getNoGroup()
+ ", nomtime=" + getNoMtime()
+ ", nomode=" + getNoMode()
+ ", nordev=" + getNoRdev()
+ ", noconfigfiles=" + getNoConfigFiles()
+ ", noghostfiles=" + getNoGhostFiles()
+ "]";
}
}
//
| |
package com.eternity.socket.server;
/*
The MIT License (MIT)
Copyright (c) 2011 Sonjaya Tandon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. *
*/
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.eternity.socket.common.ChangeRequest;
import com.eternity.socket.common.Constants;
import com.eternity.socket.common.SelectorThread;
public class ServerSelectorThread extends SelectorThread implements Runnable {
private static Logger log = LoggerFactory.getLogger(ServerSelectorThread.class);
private int port;
private Selector selector;
private ServerSocketChannel sChannel;
private ServerSocket socket;
private ByteBuffer buffer;
// holds received data
private BlockingQueue<DataEvent> queue;
// stores requests for changing the selector's interest
private BlockingQueue<ChangeRequest> pendingChanges = new LinkedBlockingQueue<ChangeRequest>();
// stores data waiting to be sent
private Map<SocketChannel, BlockingQueue<ByteBuffer>> pendingData = new ConcurrentHashMap<SocketChannel, BlockingQueue<ByteBuffer>>();
private StringBuffer responseParts = new StringBuffer();
private boolean poll = true;
public ServerSelectorThread(BlockingQueue<DataEvent> queue, int port, int bufferSize) {
this.queue = queue;
this.port = port;
this.buffer = ByteBuffer.allocate(bufferSize);
}
public void run() {
try {
try {
// open a selector
selector = Selector.open();
// open a channel
sChannel = ServerSocketChannel.open();
sChannel.configureBlocking(false);
// open a socket
// TODO : specify an IP or leave it wide open?
socket = sChannel.socket();
socket.bind(new InetSocketAddress(port));
sChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
log.error("", e);
}
while (poll) {
// process channel change requests
synchronized (pendingChanges) {
ChangeRequest changeRequest;
while ((changeRequest = pendingChanges.poll()) != null) {
SelectionKey key = changeRequest.socket.keyFor(selector);
key.interestOps(changeRequest.ops);
}
}
try {
// block until we have something to do
selector.select();
} catch (IOException e) {
log.error("", e);
}
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> it = selectedKeys.iterator();
while (it.hasNext()) {
try {
SelectionKey key = (SelectionKey) it.next();
it.remove();
if (!key.isValid()) {
log.info("invalid key!");
continue;
}
int ready = key.readyOps();
if ((ready & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
read(key);
}
if ((ready & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
write(key);
}
if ((ready & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
accept(key);
}
} catch (IOException e) {
log.error("", e);
}
}
}
} finally {
try {
if (selector != null && selector.isOpen()) {
selector.close();
}
} catch (IOException e) {
}
try {
if (socket != null && !socket.isClosed()) {
socket.close();
}
} catch (IOException ie) {
}
try {
if (sChannel != null && sChannel.isOpen()) {
sChannel.close();
}
} catch (IOException ie) {
}
}
}
private void read(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
int bytesRead = 0;
synchronized (buffer) {
buffer.clear();
try {
bytesRead = socketChannel.read(buffer);
} catch (IOException e) {
// client closed connection, cleanup
log.error("", e);
key.cancel();
socketChannel.close();
return;
}
if (bytesRead == -1) {
key.channel().close();
key.cancel();
return;
}
}
// queue a copy of the data so we can re-use the buffer
byte[] data = new byte[bytesRead];
System.arraycopy(buffer.array(), 0, data, 0, bytesRead);
// break up the data into discrete messages
for (int i = 0; i < data.length; i++) {
if (data[i] == Constants.endOfTransmission) {
// add EOT char
responseParts.append((char) data[i]);
// send out data for processing
queue.add(new DataEvent(socketChannel, responseParts.toString().getBytes()));
// clear StringBuffer
responseParts.delete(0, responseParts.length());
continue;
}
responseParts.append((char) data[i]);
}
}
public void send(SocketChannel socketChannel, byte[] data) {
synchronized (pendingChanges) {
pendingChanges.add(new ChangeRequest(socketChannel, ChangeRequest.CHANGEOPS, SelectionKey.OP_WRITE));
synchronized (pendingData) {
BlockingQueue<ByteBuffer> queue = pendingData.get(socketChannel);
if (queue == null) {
queue = new LinkedBlockingQueue<ByteBuffer>();
pendingData.put(socketChannel, queue);
}
queue.add(ByteBuffer.wrap(data));
}
}
// let the selector know there's data to send
selector.wakeup();
}
private void write(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
synchronized (pendingData) {
BlockingQueue<ByteBuffer> queue = pendingData.get(socketChannel);
// process pendingData
while (queue != null && !queue.isEmpty()) {
ByteBuffer buffer;
try {
buffer = queue.take();
socketChannel.write(buffer);
// socket is full and we still have data
if (buffer.remaining() > 0) {
break;
}
} catch (InterruptedException e) {
log.error("", e);
}
}
// done writing, switch back to read interest
if (queue != null && queue.isEmpty()) {
key.interestOps(SelectionKey.OP_READ);
}
}
}
private void accept(SelectionKey key) throws IOException {
// only server socket channels have pending interest
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
Socket newSocket = socketChannel.socket();
newSocket.setKeepAlive(true);
socketChannel.register(selector, SelectionKey.OP_READ);
}
public void stopPolling() {
this.poll = false;
}
}
| |
/*
* Copyright (c) 2002-2018 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.consistency;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.neo4j.consistency.checking.full.ConsistencyCheckIncompleteException;
import org.neo4j.consistency.checking.full.FullCheck;
import org.neo4j.consistency.report.ConsistencySummaryStatistics;
import org.neo4j.consistency.statistics.AccessStatistics;
import org.neo4j.consistency.statistics.AccessStatsKeepingStoreAccess;
import org.neo4j.consistency.statistics.DefaultCounts;
import org.neo4j.consistency.statistics.Statistics;
import org.neo4j.consistency.statistics.VerboseStatistics;
import org.neo4j.function.Supplier;
import org.neo4j.function.Suppliers;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.helpers.collection.MapUtil;
import org.neo4j.helpers.progress.ProgressMonitorFactory;
import org.neo4j.index.lucene.LuceneLabelScanStoreBuilder;
import org.neo4j.io.fs.DefaultFileSystemAbstraction;
import org.neo4j.io.fs.FileSystemAbstraction;
import org.neo4j.io.pagecache.PageCache;
import org.neo4j.io.pagecache.tracing.PageCacheTracer;
import org.neo4j.kernel.DefaultIdGeneratorFactory;
import org.neo4j.kernel.api.direct.DirectStoreAccess;
import org.neo4j.kernel.api.impl.index.DirectoryFactory;
import org.neo4j.kernel.api.impl.index.LuceneSchemaIndexProvider;
import org.neo4j.kernel.api.index.SchemaIndexProvider;
import org.neo4j.kernel.api.labelscan.LabelScanStore;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.kernel.configuration.Settings;
import org.neo4j.kernel.impl.pagecache.ConfiguringPageCacheFactory;
import org.neo4j.kernel.impl.store.NeoStores;
import org.neo4j.kernel.impl.store.StoreAccess;
import org.neo4j.kernel.impl.store.StoreFactory;
import org.neo4j.logging.DuplicatingLog;
import org.neo4j.logging.Log;
import org.neo4j.logging.LogProvider;
import org.neo4j.udc.UsageDataKeys.OperationalMode;
import static org.neo4j.io.file.Files.createOrOpenAsOuputStream;
public class ConsistencyCheckService
{
private final Date timestamp;
public ConsistencyCheckService()
{
this( new Date() );
}
public ConsistencyCheckService( Date timestamp )
{
this.timestamp = timestamp;
}
public Result runFullConsistencyCheck( File storeDir, Config tuningConfiguration,
ProgressMonitorFactory progressFactory, LogProvider logProvider, boolean verbose )
throws ConsistencyCheckIncompleteException, IOException
{
return runFullConsistencyCheck( storeDir, tuningConfiguration, progressFactory, logProvider,
new DefaultFileSystemAbstraction(), verbose );
}
public Result runFullConsistencyCheck( File storeDir, Config tuningConfiguration,
ProgressMonitorFactory progressFactory, LogProvider logProvider, FileSystemAbstraction fileSystem,
boolean verbose ) throws ConsistencyCheckIncompleteException, IOException
{
Log log = logProvider.getLog( getClass() );
ConfiguringPageCacheFactory pageCacheFactory = new ConfiguringPageCacheFactory(
fileSystem, tuningConfiguration, PageCacheTracer.NULL, logProvider.getLog( PageCache.class ) );
PageCache pageCache = pageCacheFactory.getOrCreatePageCache();
try
{
return runFullConsistencyCheck(
storeDir, tuningConfiguration, progressFactory, logProvider, fileSystem, pageCache, verbose );
}
finally
{
try
{
pageCache.close();
}
catch ( IOException e )
{
log.error( "Failure during shutdown of the page cache", e );
}
}
}
public Result runFullConsistencyCheck( final File storeDir, Config tuningConfiguration,
ProgressMonitorFactory progressFactory, final LogProvider logProvider,
final FileSystemAbstraction fileSystem, final PageCache pageCache, final boolean verbose )
throws ConsistencyCheckIncompleteException
{
Log log = logProvider.getLog( getClass() );
Config consistencyCheckerConfig = tuningConfiguration.with(
MapUtil.stringMap( GraphDatabaseSettings.read_only.name(), Settings.TRUE ) );
StoreFactory factory = new StoreFactory( storeDir, consistencyCheckerConfig,
new DefaultIdGeneratorFactory( fileSystem ), pageCache, fileSystem, logProvider );
ConsistencySummaryStatistics summary;
final File reportFile = chooseReportPath( storeDir, tuningConfiguration );
Log reportLog = new ConsistencyReportLog( Suppliers.lazySingleton( new Supplier<PrintWriter>()
{
@Override
public PrintWriter get()
{
try
{
return new PrintWriter( createOrOpenAsOuputStream( fileSystem, reportFile, true ) );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
} ) );
try ( NeoStores neoStores = factory.openAllNeoStores() )
{
LabelScanStore labelScanStore = null;
try
{
OperationalMode operationalMode = OperationalMode.single;
labelScanStore = new LuceneLabelScanStoreBuilder(
storeDir, neoStores, fileSystem, consistencyCheckerConfig, operationalMode, logProvider )
.build();
SchemaIndexProvider indexes = new LuceneSchemaIndexProvider(
fileSystem,
DirectoryFactory.PERSISTENT,
storeDir, logProvider, consistencyCheckerConfig, operationalMode );
int numberOfThreads = defaultConsistencyCheckThreadsNumber();
Statistics statistics;
StoreAccess storeAccess;
AccessStatistics stats = new AccessStatistics();
if ( verbose )
{
statistics = new VerboseStatistics( stats, new DefaultCounts( numberOfThreads ), log );
storeAccess = new AccessStatsKeepingStoreAccess( neoStores, stats );
}
else
{
statistics = Statistics.NONE;
storeAccess = new StoreAccess( neoStores );
}
storeAccess.initialize();
DirectStoreAccess stores = new DirectStoreAccess( storeAccess, labelScanStore, indexes );
FullCheck check = new FullCheck( tuningConfiguration, progressFactory, statistics, numberOfThreads );
summary = check.execute( stores, new DuplicatingLog( log, reportLog ) );
}
finally
{
try
{
if ( null != labelScanStore )
{
labelScanStore.shutdown();
}
}
catch ( IOException e )
{
log.error( "Failure during shutdown of label scan store", e );
}
}
}
if ( !summary.isConsistent() )
{
log.warn( "See '%s' for a detailed consistency report.", reportFile.getPath() );
return Result.FAILURE;
}
return Result.SUCCESS;
}
private File chooseReportPath( File storeDir, Config tuningConfiguration )
{
final File reportPath = tuningConfiguration.get( ConsistencyCheckSettings.consistency_check_report_file );
if ( reportPath == null )
{
return new File( storeDir, defaultLogFileName( timestamp ) );
}
if ( reportPath.isDirectory() )
{
return new File( reportPath, defaultLogFileName( timestamp ) );
}
return reportPath;
}
public static String defaultLogFileName( Date date )
{
final String formattedDate = new SimpleDateFormat( "yyyy-MM-dd.HH.mm.ss" ).format( date );
return String.format( "inconsistencies-%s.report", formattedDate );
}
public enum Result
{
FAILURE( false ), SUCCESS( true );
private final boolean successful;
Result( boolean successful )
{
this.successful = successful;
}
public boolean isSuccessful()
{
return this.successful;
}
}
public static int defaultConsistencyCheckThreadsNumber()
{
return Math.max( 1, Runtime.getRuntime().availableProcessors() - 1 );
}
}
| |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/automl/v1/operations.proto
package com.google.cloud.automl.v1;
/**
*
*
* <pre>
* Details of DeployModel operation.
* </pre>
*
* Protobuf type {@code google.cloud.automl.v1.DeployModelOperationMetadata}
*/
public final class DeployModelOperationMetadata extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.automl.v1.DeployModelOperationMetadata)
DeployModelOperationMetadataOrBuilder {
private static final long serialVersionUID = 0L;
// Use DeployModelOperationMetadata.newBuilder() to construct.
private DeployModelOperationMetadata(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DeployModelOperationMetadata() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new DeployModelOperationMetadata();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private DeployModelOperationMetadata(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.automl.v1.Operations
.internal_static_google_cloud_automl_v1_DeployModelOperationMetadata_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.automl.v1.Operations
.internal_static_google_cloud_automl_v1_DeployModelOperationMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.automl.v1.DeployModelOperationMetadata.class,
com.google.cloud.automl.v1.DeployModelOperationMetadata.Builder.class);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.automl.v1.DeployModelOperationMetadata)) {
return super.equals(obj);
}
com.google.cloud.automl.v1.DeployModelOperationMetadata other =
(com.google.cloud.automl.v1.DeployModelOperationMetadata) obj;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.automl.v1.DeployModelOperationMetadata parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.automl.v1.DeployModelOperationMetadata parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.automl.v1.DeployModelOperationMetadata parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.automl.v1.DeployModelOperationMetadata parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.automl.v1.DeployModelOperationMetadata parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.automl.v1.DeployModelOperationMetadata parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.automl.v1.DeployModelOperationMetadata parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.automl.v1.DeployModelOperationMetadata parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.automl.v1.DeployModelOperationMetadata parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.automl.v1.DeployModelOperationMetadata parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.automl.v1.DeployModelOperationMetadata parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.automl.v1.DeployModelOperationMetadata parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.automl.v1.DeployModelOperationMetadata prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Details of DeployModel operation.
* </pre>
*
* Protobuf type {@code google.cloud.automl.v1.DeployModelOperationMetadata}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.automl.v1.DeployModelOperationMetadata)
com.google.cloud.automl.v1.DeployModelOperationMetadataOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.automl.v1.Operations
.internal_static_google_cloud_automl_v1_DeployModelOperationMetadata_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.automl.v1.Operations
.internal_static_google_cloud_automl_v1_DeployModelOperationMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.automl.v1.DeployModelOperationMetadata.class,
com.google.cloud.automl.v1.DeployModelOperationMetadata.Builder.class);
}
// Construct using com.google.cloud.automl.v1.DeployModelOperationMetadata.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.automl.v1.Operations
.internal_static_google_cloud_automl_v1_DeployModelOperationMetadata_descriptor;
}
@java.lang.Override
public com.google.cloud.automl.v1.DeployModelOperationMetadata getDefaultInstanceForType() {
return com.google.cloud.automl.v1.DeployModelOperationMetadata.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.automl.v1.DeployModelOperationMetadata build() {
com.google.cloud.automl.v1.DeployModelOperationMetadata result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.automl.v1.DeployModelOperationMetadata buildPartial() {
com.google.cloud.automl.v1.DeployModelOperationMetadata result =
new com.google.cloud.automl.v1.DeployModelOperationMetadata(this);
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.automl.v1.DeployModelOperationMetadata) {
return mergeFrom((com.google.cloud.automl.v1.DeployModelOperationMetadata) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.automl.v1.DeployModelOperationMetadata other) {
if (other == com.google.cloud.automl.v1.DeployModelOperationMetadata.getDefaultInstance())
return this;
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.automl.v1.DeployModelOperationMetadata parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.automl.v1.DeployModelOperationMetadata) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.automl.v1.DeployModelOperationMetadata)
}
// @@protoc_insertion_point(class_scope:google.cloud.automl.v1.DeployModelOperationMetadata)
private static final com.google.cloud.automl.v1.DeployModelOperationMetadata DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.automl.v1.DeployModelOperationMetadata();
}
public static com.google.cloud.automl.v1.DeployModelOperationMetadata getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DeployModelOperationMetadata> PARSER =
new com.google.protobuf.AbstractParser<DeployModelOperationMetadata>() {
@java.lang.Override
public DeployModelOperationMetadata parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new DeployModelOperationMetadata(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<DeployModelOperationMetadata> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DeployModelOperationMetadata> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.automl.v1.DeployModelOperationMetadata getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation 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
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jface.text;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
/**
* Manages the {@link org.eclipse.jface.text.IPainter} object registered with an
* {@link org.eclipse.jface.text.ITextViewer}.
* <p>
* Clients usually instantiate and configure objects of this type.</p>
*
* @since 2.1
*/
public final class PaintManager implements KeyListener, MouseListener, ISelectionChangedListener, ITextListener, ITextInputListener {
/**
* Position updater used by the position manager. This position updater differs from the default position
* updater in that it extends a position when an insertion happens at the position's offset and right behind
* the position.
*/
static class PaintPositionUpdater extends DefaultPositionUpdater {
/**
* Creates the position updater for the given category.
*
* @param category the position category
*/
protected PaintPositionUpdater(String category) {
super(category);
}
/**
* If an insertion happens at a position's offset, the
* position is extended rather than shifted. Also, if something is added
* right behind the end of the position, the position is extended rather
* than kept stable.
*/
protected void adaptToInsert() {
int myStart= fPosition.offset;
int myEnd= fPosition.offset + fPosition.length;
myEnd= Math.max(myStart, myEnd);
int yoursStart= fOffset;
int yoursEnd= fOffset + fReplaceLength;// - 1;
yoursEnd= Math.max(yoursStart, yoursEnd);
if (myEnd < yoursStart)
return;
if (myStart <= yoursStart)
fPosition.length += fReplaceLength;
else
fPosition.offset += fReplaceLength;
}
}
/**
* The paint position manager used by this paint manager. The paint position
* manager is installed on a single document and control the creation/disposed
* and updating of a position category that will be used for managing positions.
*/
static class PositionManager implements IPaintPositionManager {
// /** The document this position manager works on */
private IDocument fDocument;
/** The position updater used for the managing position category */
private IPositionUpdater fPositionUpdater;
/** The managing position category */
private String fCategory;
/**
* Creates a new position manager. Initializes the managing
* position category using its class name and its hash value.
*/
public PositionManager() {
fCategory= getClass().getName() + hashCode();
fPositionUpdater= new PaintPositionUpdater(fCategory);
}
/**
* Installs this position manager in the given document. The position manager stays
* active until <code>uninstall</code> or <code>dispose</code>
* is called.
*
* @param document the document to be installed on
*/
public void install(IDocument document) {
fDocument= document;
fDocument.addPositionCategory(fCategory);
fDocument.addPositionUpdater(fPositionUpdater);
}
/**
* Disposes this position manager. The position manager is automatically
* removed from the document it has previously been installed
* on.
*/
public void dispose() {
uninstall(fDocument);
}
/**
* Uninstalls this position manager form the given document. If the position
* manager has no been installed on this document, this method is without effect.
*
* @param document the document form which to uninstall
*/
public void uninstall(IDocument document) {
if (document == fDocument && document != null) {
try {
fDocument.removePositionUpdater(fPositionUpdater);
fDocument.removePositionCategory(fCategory);
} catch (BadPositionCategoryException x) {
// should not happen
}
fDocument= null;
}
}
/*
* @see IPositionManager#addManagedPosition(Position)
*/
public void managePosition(Position position) {
try {
fDocument.addPosition(fCategory, position);
} catch (BadPositionCategoryException x) {
// should not happen
} catch (BadLocationException x) {
// should not happen
}
}
/*
* @see IPositionManager#removeManagedPosition(Position)
*/
public void unmanagePosition(Position position) {
try {
fDocument.removePosition(fCategory, position);
} catch (BadPositionCategoryException x) {
// should not happen
}
}
}
/** The painters managed by this paint manager. */
private List fPainters= new ArrayList(2);
/** The position manager used by this paint manager */
private PositionManager fManager;
/** The associated text viewer */
private ITextViewer fTextViewer;
/**
* Creates a new paint manager for the given text viewer.
*
* @param textViewer the text viewer associated to this newly created paint manager
*/
public PaintManager(ITextViewer textViewer) {
fTextViewer= textViewer;
}
/**
* Adds the given painter to the list of painters managed by this paint manager.
* If the painter is already registered with this paint manager, this method is
* without effect.
*
* @param painter the painter to be added
*/
public void addPainter(IPainter painter) {
if (!fPainters.contains(painter)) {
fPainters.add(painter);
if (fPainters.size() == 1)
install();
painter.setPositionManager(fManager);
painter.paint(IPainter.INTERNAL);
}
}
/**
* Removes the given painter from the list of painters managed by this
* paint manager. If the painter has not previously been added to this
* paint manager, this method is without effect.
*
* @param painter the painter to be removed
*/
public void removePainter(IPainter painter) {
if (fPainters.remove(painter)) {
painter.deactivate(true);
painter.setPositionManager(null);
}
if (fPainters.size() == 0)
dispose();
}
/**
* Installs/activates this paint manager. Is called as soon as the
* first painter is to be managed by this paint manager.
*/
private void install() {
fManager= new PositionManager();
if (fTextViewer.getDocument() != null)
fManager.install(fTextViewer.getDocument());
fTextViewer.addTextInputListener(this);
addListeners();
}
/**
* Installs our listener set on the text viewer and the text widget,
* respectively.
*/
private void addListeners() {
ISelectionProvider provider= fTextViewer.getSelectionProvider();
provider.addSelectionChangedListener(this);
fTextViewer.addTextListener(this);
StyledText text= fTextViewer.getTextWidget();
text.addKeyListener(this);
text.addMouseListener(this);
}
/**
* Disposes this paint manager. The paint manager uninstalls itself
* and clears all registered painters. This method is also called when the
* last painter is removed from the list of managed painters.
*/
public void dispose() {
if (fManager != null) {
fManager.dispose();
fManager= null;
}
for (Iterator e = fPainters.iterator(); e.hasNext();)
((IPainter) e.next()).dispose();
fPainters.clear();
fTextViewer.removeTextInputListener(this);
removeListeners();
}
/**
* Removes our set of listeners from the text viewer and widget,
* respectively.
*/
private void removeListeners() {
ISelectionProvider provider= fTextViewer.getSelectionProvider();
if (provider != null)
provider.removeSelectionChangedListener(this);
fTextViewer.removeTextListener(this);
StyledText text= fTextViewer.getTextWidget();
if (text != null && !text.isDisposed()) {
text.removeKeyListener(this);
text.removeMouseListener(this);
}
}
/**
* Triggers all registered painters for the given reason.
*
* @param reason the reason
* @see IPainter
*/
private void paint(int reason) {
for (Iterator e = fPainters.iterator(); e.hasNext();)
((IPainter) e.next()).paint(reason);
}
/*
* @see KeyListener#keyPressed(KeyEvent)
*/
public void keyPressed(KeyEvent e) {
paint(IPainter.KEY_STROKE);
}
/*
* @see KeyListener#keyReleased(KeyEvent)
*/
public void keyReleased(KeyEvent e) {
}
/*
* @see MouseListener#mouseDoubleClick(MouseEvent)
*/
public void mouseDoubleClick(MouseEvent e) {
}
/*
* @see MouseListener#mouseDown(MouseEvent)
*/
public void mouseDown(MouseEvent e) {
paint(IPainter.MOUSE_BUTTON);
}
/*
* @see MouseListener#mouseUp(MouseEvent)
*/
public void mouseUp(MouseEvent e) {
}
/*
* @see ISelectionChangedListener#selectionChanged(SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
paint(IPainter.SELECTION);
}
/*
* @see ITextListener#textChanged(TextEvent)
*/
public void textChanged(TextEvent event) {
if (!event.getViewerRedrawState())
return;
Control control= fTextViewer.getTextWidget();
if (control != null) {
control.getDisplay().asyncExec(new Runnable() {
public void run() {
if (fTextViewer != null)
paint(IPainter.TEXT_CHANGE);
}
});
}
}
/*
* @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
if (oldInput != null) {
for (Iterator e = fPainters.iterator(); e.hasNext();)
((IPainter) e.next()).deactivate(false);
fManager.uninstall(oldInput);
removeListeners();
}
}
/*
* @see ITextInputListener#inputDocumentChanged(IDocument, IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
if (newInput != null) {
fManager.install(newInput);
paint(IPainter.TEXT_CHANGE);
addListeners();
}
}
}
| |
/*******************************************************************************
* Copyright 2014 United States Government as represented by the
* Administrator of the National Aeronautics and Space Administration.
* 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 gov.nasa.ensemble.common.ui.ide.navigator;
import gov.nasa.ensemble.common.ui.WidgetUtils;
import java.util.ArrayList;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.IContentProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.accessibility.ACC;
import org.eclipse.swt.accessibility.AccessibleAdapter;
import org.eclipse.swt.accessibility.AccessibleControlAdapter;
import org.eclipse.swt.accessibility.AccessibleControlEvent;
import org.eclipse.swt.accessibility.AccessibleEvent;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPreferenceConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.PatternFilter;
import org.eclipse.ui.internal.WorkbenchMessages;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.ui.progress.WorkbenchJob;
@SuppressWarnings("restriction")
public class EnsembleFilteredTree extends Composite {
/**
* The filter text widget to be used by this tree. This value may be
* <code>null</code> if there is no filter widget, or if the controls have
* not yet been created.
*/
protected Text filterText;
/**
* The control representing the clear button for the filter text entry. This
* value may be <code>null</code> if no such button exists, or if the
* controls have not yet been created.
* <p>
* <strong>Note:</strong> As of 3.5, this is not used if the new look is chosen.
* </p>
*/
protected ToolBarManager filterToolBar;
/**
* The control representing the clear button for the filter text entry. This
* value may be <code>null</code> if no such button exists, or if the
* controls have not yet been created.
* <p>
* <strong>Note:</strong> This is only used if the new look is chosen.
* </p>
*
* @since 3.5
*/
protected Control clearButtonControl;
/**
* The viewer for the filtered tree. This value should never be
* <code>null</code> after the widget creation methods are complete.
*/
protected TreeViewer treeViewer;
/**
* The Composite on which the filter controls are created. This is used to
* set the background color of the filter controls to match the surrounding
* controls.
*/
protected Composite filterComposite;
/**
* The pattern filter for the tree. This value must not be <code>null</code>.
*/
protected EnsemblePatternFilter patternFilter;
/**
* The text to initially show in the filter text control.
*/
protected String initialText = ""; //$NON-NLS-1$
/**
* The job used to refresh the tree.
*/
private Job refreshJob;
/**
* The parent composite of the filtered tree.
*
* @since 3.3
*/
protected Composite parent;
private IViewSite viewSite;
/**
* Whether or not to show the filter controls (text and clear button). The
* default is to show these controls. This can be overridden by providing a
* setting in the product configuration file. The setting to add to not show
* these controls is:
*
* org.eclipse.ui/SHOW_FILTERED_TEXTS=false
*/
protected boolean showFilterControls;
/**
* @since 3.3
*/
protected Composite treeComposite;
/**
* Tells whether to use the pre 3.5 or the new look.
*
* @since 3.5
*/
private boolean useNewLook = false;
/**
* Image descriptor for enabled clear button.
*/
private static final String CLEAR_ICON = "org.eclipse.ui.internal.dialogs.CLEAR_ICON"; //$NON-NLS-1$
/**
* Image descriptor for disabled clear button.
*/
private static final String DISABLED_CLEAR_ICON= "org.eclipse.ui.internal.dialogs.DCLEAR_ICON"; //$NON-NLS-1$
/**
* Maximum time spent expanding the tree after the filter text has been
* updated (this is only used if we were able to at least expand the visible
* nodes)
*/
private static final long SOFT_MAX_EXPAND_TIME = 200;
/**
* Get image descriptors for the clear button.
*/
static {
ImageDescriptor descriptor = AbstractUIPlugin
.imageDescriptorFromPlugin(PlatformUI.PLUGIN_ID,
"$nl$/icons/full/etool16/clear_co.gif"); //$NON-NLS-1$
if (descriptor != null) {
JFaceResources.getImageRegistry().put(CLEAR_ICON, descriptor);
}
descriptor = AbstractUIPlugin.imageDescriptorFromPlugin(
PlatformUI.PLUGIN_ID, "$nl$/icons/full/dtool16/clear_co.gif"); //$NON-NLS-1$
if (descriptor != null) {
JFaceResources.getImageRegistry().put(DISABLED_CLEAR_ICON, descriptor);
}
}
/**
* Create a new instance of the receiver.
*
* @param parent
* the parent <code>Composite</code>
* @param treeStyle
* the style bits for the <code>Tree</code>
* @param filter
* the filter to be used
*
* @deprecated As of 3.5, replaced by
* {@link #FilteredTree(Composite, int, PatternFilter, boolean)} where using the new
* look is encouraged
*/
@Deprecated
public EnsembleFilteredTree(Composite parent, int treeStyle, EnsemblePatternFilter filter) {
super(parent, SWT.NONE);
this.parent = parent;
init(treeStyle, filter);
}
/**
* Create a new instance of the receiver.
*
* @param parent
* the parent <code>Composite</code>
* @param treeStyle
* the style bits for the <code>Tree</code>
* @param filter
* the filter to be used
* @param useNewLook
* <code>true</code> if the new 3.5 look should be used
* @since 3.5
*/
public EnsembleFilteredTree(Composite parent, int treeStyle, EnsemblePatternFilter filter, boolean useNewLook, IViewSite viewSite) {
super(parent, SWT.NONE);
this.viewSite = viewSite;
this.parent = parent;
this.useNewLook= useNewLook;
init(treeStyle, filter);
}
/**
* Create a new instance of the receiver. Subclasses that wish to override
* the default creation behavior may use this constructor, but must ensure
* that the <code>init(composite, int, PatternFilter)</code> method is
* called in the overriding constructor.
*
* @param parent
* the parent <code>Composite</code>
* @see #init(int, PatternFilter)
*
* @since 3.3
* @deprecated As of 3.5, replaced by {@link #FilteredTree(Composite, boolean)} where using the
* look is encouraged
*/
@Deprecated
protected EnsembleFilteredTree(Composite parent) {
super(parent, SWT.NONE);
this.parent = parent;
}
/**
* Create a new instance of the receiver. Subclasses that wish to override
* the default creation behavior may use this constructor, but must ensure
* that the <code>init(composite, int, PatternFilter)</code> method is
* called in the overriding constructor.
*
* @param parent
* the parent <code>Composite</code>
* @param useNewLook
* <code>true</code> if the new 3.5 look should be used
* @see #init(int, PatternFilter)
*
* @since 3.5
*/
protected EnsembleFilteredTree(Composite parent, boolean useNewLook) {
super(parent, SWT.NONE);
this.parent = parent;
this.useNewLook = useNewLook;
}
/**
* Create the filtered tree.
*
* @param treeStyle
* the style bits for the <code>Tree</code>
* @param filter
* the filter to be used
*
* @since 3.3
*/
protected void init(int treeStyle, EnsemblePatternFilter filter) {
patternFilter = filter;
showFilterControls = PlatformUI.getPreferenceStore().getBoolean(
IWorkbenchPreferenceConstants.SHOW_FILTERED_TEXTS);
createControl(parent, treeStyle);
createRefreshJob();
setInitialText(WorkbenchMessages.FilteredTree_FilterMessage);
setFont(parent.getFont());
}
/**
* Create the filtered tree's controls. Subclasses should override.
*
* @param parent
* @param treeStyle
*/
protected void createControl(Composite parent, int treeStyle) {
GridLayout layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
setLayout(layout);
setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
if (showFilterControls) {
if (!useNewLook || useNativeSearchField(parent)) {
filterComposite= new Composite(this, SWT.NONE);
} else {
filterComposite= new Composite(this, SWT.BORDER);
filterComposite.setBackground(getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND));
}
GridLayout filterLayout= new GridLayout(2, false);
filterLayout.marginHeight= 0;
filterLayout.marginWidth= 0;
filterComposite.setLayout(filterLayout);
filterComposite.setFont(parent.getFont());
createFilterControls(filterComposite);
filterComposite.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING,
true, false));
}
treeComposite = new Composite(this, SWT.NONE);
GridLayout treeCompositeLayout = new GridLayout();
treeCompositeLayout.marginHeight = 0;
treeCompositeLayout.marginWidth = 0;
treeComposite.setLayout(treeCompositeLayout);
GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
treeComposite.setLayoutData(data);
createTreeControl(treeComposite, treeStyle);
}
private static Boolean useNativeSearchField;
private static boolean useNativeSearchField(Composite composite) {
if (useNativeSearchField == null) {
useNativeSearchField = Boolean.FALSE;
Text testText = null;
try {
testText = new Text(composite, SWT.SEARCH | SWT.ICON_CANCEL);
useNativeSearchField = new Boolean((testText.getStyle() & SWT.ICON_CANCEL) != 0);
} finally {
if (testText != null) {
testText.dispose();
}
}
}
return useNativeSearchField.booleanValue();
}
/**
* Create the filter controls. By default, a text and corresponding tool bar
* button that clears the contents of the text is created. Subclasses may
* override.
*
* @param parent
* parent <code>Composite</code> of the filter controls
* @return the <code>Composite</code> that contains the filter controls
*/
protected Composite createFilterControls(Composite parent) {
createFilterText(parent);
if (useNewLook)
createClearTextNew(parent);
else
createClearTextOld(parent);
if (clearButtonControl != null) {
// initially there is no text to clear
clearButtonControl.setVisible(false);
}
if (filterToolBar != null) {
filterToolBar.update(false);
// initially there is no text to clear
filterToolBar.getControl().setVisible(false);
}
return parent;
}
/**
* Creates and set up the tree and tree viewer. This method calls
* {@link #doCreateTreeViewer(Composite, int)} to create the tree viewer.
* Subclasses should override {@link #doCreateTreeViewer(Composite, int)}
* instead of overriding this method.
*
* @param parent
* parent <code>Composite</code>
* @param style
* SWT style bits used to create the tree
* @return the tree
*/
protected Control createTreeControl(Composite parent, int style) {
treeViewer = doCreateTreeViewer(parent, style);
GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
treeViewer.getControl().setLayoutData(data);
treeViewer.getControl().addDisposeListener(new DisposeListener() {
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.DisposeListener#widgetDisposed(org.eclipse.swt.events.DisposeEvent)
*/
@Override
public void widgetDisposed(DisposeEvent e) {
refreshJob.cancel();
}
});
if (treeViewer instanceof NotifyingTreeViewer) {
patternFilter.setUseCache(true);
}
treeViewer.addFilter(patternFilter);
return treeViewer.getControl();
}
/**
* Creates the tree viewer. Subclasses may override.
*
* @param parent
* the parent composite
* @param style
* SWT style bits used to create the tree viewer
* @return the tree viewer
*
* @since 3.3
*/
protected TreeViewer doCreateTreeViewer(Composite parent, int style) {
return new NotifyingTreeViewer(parent, style);
}
/**
* Return the first item in the tree that matches the filter pattern.
*
* @param items
* @return the first matching TreeItem
*/
private TreeItem getFirstMatchingItem(TreeItem[] items) {
for (int i = 0; i < items.length; i++) {
if (patternFilter.isLeafMatch(treeViewer, items[i].getData())
&& patternFilter.isElementSelectable(items[i].getData())) {
return items[i];
}
TreeItem treeItem = getFirstMatchingItem(items[i].getItems());
if (treeItem != null) {
return treeItem;
}
}
return null;
}
/**
* Create the refresh job for the receiver.
*
*/
private void createRefreshJob() {
refreshJob = doCreateRefreshJob();
refreshJob.setSystem(true);
}
/**
* Creates a workbench job that will refresh the tree based on the current filter text.
* Subclasses may override.
*
* @return a workbench job that can be scheduled to refresh the tree
*
* @since 3.4
*/
protected WorkbenchJob doCreateRefreshJob() {
return new WorkbenchJob("Refresh Filter") {//$NON-NLS-1$
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
if (treeViewer.getControl().isDisposed()) {
return Status.CANCEL_STATUS;
}
String text = getFilterString();
if (text == null) {
return Status.OK_STATUS;
}
boolean initial = initialText != null
&& initialText.equals(text);
if (initial) {
patternFilter.setPattern(null);
} else if (text != null) {
patternFilter.setPattern(text);
}
Control redrawFalseControl = treeComposite != null ? treeComposite
: treeViewer.getControl();
try {
// don't want the user to see updates that will be made to
// the tree
// we are setting redraw(false) on the composite to avoid
// dancing scrollbar
redrawFalseControl.setRedraw(false);
if (!narrowingDown) {
// collapse all
TreeItem[] is = treeViewer.getTree().getItems();
for (int i = 0; i < is.length; i++) {
TreeItem item = is[i];
if (item.getExpanded()) {
treeViewer.setExpandedState(item.getData(),
false);
}
}
}
treeViewer.refresh(true);
if (text.length() > 0 && !initial) {
/*
* Expand elements one at a time. After each is
* expanded, check to see if the filter text has been
* modified. If it has, then cancel the refresh job so
* the user doesn't have to endure expansion of all the
* nodes.
*/
TreeItem[] items = getViewer().getTree().getItems();
int treeHeight = getViewer().getTree().getBounds().height;
int numVisibleItems = treeHeight
/ getViewer().getTree().getItemHeight();
long stopTime = SOFT_MAX_EXPAND_TIME
+ System.currentTimeMillis();
boolean cancel = false;
if (items.length > 0
&& recursiveExpand(items, monitor, stopTime,
new int[] { numVisibleItems })) {
cancel = true;
}
// enabled toolbar - there is text to clear
// and the list is currently being filtered
updateToolbar(true);
if (cancel) {
return Status.CANCEL_STATUS;
}
} else {
// disabled toolbar - there is no text to clear
// and the list is currently not filtered
updateToolbar(false);
}
} finally {
// done updating the tree - set redraw back to true
TreeItem[] items = getViewer().getTree().getItems();
if (items.length > 0
&& getViewer().getTree().getSelectionCount() == 0) {
treeViewer.getTree().setTopItem(items[0]);
}
redrawFalseControl.setRedraw(true);
}
return Status.OK_STATUS;
}
/**
* Returns true if the job should be canceled (because of timeout or
* actual cancellation).
*
* @param items
* @param monitor
* @param cancelTime
* @param numItemsLeft
* @return true if canceled
*/
private boolean recursiveExpand(TreeItem[] items,
IProgressMonitor monitor, long cancelTime,
int[] numItemsLeft) {
boolean canceled = false;
for (int i = 0; !canceled && i < items.length; i++) {
TreeItem item = items[i];
boolean visible = numItemsLeft[0]-- >= 0;
if (monitor.isCanceled()
|| (!visible && System.currentTimeMillis() > cancelTime)) {
canceled = true;
} else {
Object itemData = item.getData();
if (itemData != null) {
if (!item.getExpanded()) {
// do the expansion through the viewer so that
// it can refresh children appropriately.
treeViewer.setExpandedState(itemData, true);
}
TreeItem[] children = item.getItems();
if (items.length > 0) {
canceled = recursiveExpand(children, monitor,
cancelTime, numItemsLeft);
}
}
}
}
return canceled;
}
};
}
protected void updateToolbar(boolean visible) {
if (clearButtonControl != null) {
clearButtonControl.setVisible(visible);
}
if (filterToolBar != null) {
filterToolBar.getControl().setVisible(visible);
}
}
/**
* Creates the filter text and adds listeners. This method calls
* {@link #doCreateFilterText(Composite)} to create the text control.
* Subclasses should override {@link #doCreateFilterText(Composite)} instead
* of overriding this method.
*
* @param parent
* <code>Composite</code> of the filter text
*/
protected void createFilterText(Composite parent) {
filterText = doCreateFilterText(parent);
filterText.getAccessible().addAccessibleListener(
new AccessibleAdapter() {
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.accessibility.AccessibleListener#getName(org.eclipse.swt.accessibility.AccessibleEvent)
*/
@Override
public void getName(AccessibleEvent e) {
String filterTextString = filterText.getText();
if (filterTextString.length() == 0
|| filterTextString.equals(initialText)) {
e.result = initialText;
} else {
e.result = NLS
.bind(
WorkbenchMessages.FilteredTree_AccessibleListenerFiltered,
new String[] {
filterTextString,
String
.valueOf(getFilteredItemsCount()) });
}
}
/**
* Return the number of filtered items
* @return int
*/
private int getFilteredItemsCount() {
int total = 0;
TreeItem[] items = getViewer().getTree().getItems();
for (int i = 0; i < items.length; i++) {
total += itemCount(items[i]);
}
return total;
}
/**
* Return the count of treeItem and it's children to infinite depth.
* @param treeItem
* @return int
*/
private int itemCount(TreeItem treeItem) {
int count = 1;
TreeItem[] children = treeItem.getItems();
for (int i = 0; i < children.length; i++) {
count += itemCount(children[i]);
}
return count;
}
});
filterText.addFocusListener(new FocusAdapter() {
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
*/
@Override
public void focusGained(FocusEvent e) {
if (!useNewLook) {
/*
* Running in an asyncExec because the selectAll() does not appear to work when
* using mouse to give focus to text.
*/
Display display= filterText.getDisplay();
display.asyncExec(new Runnable() {
@Override
public void run() {
if (!filterText.isDisposed()) {
if (getInitialText().equals(
filterText.getText().trim())) {
filterText.selectAll();
}
}
}
});
return;
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*/
@Override
public void focusLost(FocusEvent e) {
if (!useNewLook) {
return;
}
if (filterText.getText().equals(initialText)) {
setFilterText(""); //$NON-NLS-1$
textChanged();
}
}
});
if (useNewLook) {
filterText.addMouseListener(new MouseAdapter() {
/*
* (non-Javadoc)
*
* @see
* org.eclipse.swt.events.MouseAdapter#mouseDown(org.eclipse.swt.events.MouseEvent)
*/
@Override
public void mouseDown(MouseEvent e) {
if (filterText.getText().equals(initialText)) {
// XXX: We cannot call clearText() due to https://bugs.eclipse.org/bugs/show_bug.cgi?id=260664
setFilterText(""); //$NON-NLS-1$
textChanged();
}
}
});
}
filterText.addKeyListener(new KeyAdapter() {
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.KeyAdapter#keyReleased(org.eclipse.swt.events.KeyEvent)
*/
@Override
public void keyPressed(KeyEvent e) {
// on a CR we want to transfer focus to the list
boolean hasItems = getViewer().getTree().getItemCount() > 0;
if (hasItems && e.keyCode == SWT.ARROW_DOWN) {
treeViewer.getTree().setFocus();
return;
}
}
});
// enter key set focus to tree
filterText.addTraverseListener(new TraverseListener() {
@Override
public void keyTraversed(TraverseEvent e) {
if (e.detail == SWT.TRAVERSE_RETURN) {
e.doit = false;
if (getViewer().getTree().getItemCount() == 0) {
Display.getCurrent().beep();
} else {
// if the initial filter text hasn't changed, do not try
// to match
boolean hasFocus = getViewer().getTree().setFocus();
boolean textChanged = !getInitialText().equals(
filterText.getText().trim());
if (hasFocus && textChanged
&& filterText.getText().trim().length() > 0) {
Tree tree = getViewer().getTree();
TreeItem item;
if (tree.getSelectionCount() > 0)
item = getFirstMatchingItem(tree.getSelection());
else
item = getFirstMatchingItem(tree.getItems());
if (item != null) {
tree.setSelection(new TreeItem[] { item });
ISelection sel = getViewer().getSelection();
getViewer().setSelection(sel, true);
}
}
}
}
}
});
filterText.addModifyListener(new ModifyListener() {
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
*/
@Override
public void modifyText(ModifyEvent e) {
textChanged();
}
});
// if we're using a field with built in cancel we need to listen for
// default selection changes (which tell us the cancel button has been
// pressed)
if ((filterText.getStyle() & SWT.ICON_CANCEL) != 0) {
filterText.addSelectionListener(new SelectionAdapter() {
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.SelectionAdapter#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
*/
@Override
public void widgetDefaultSelected(SelectionEvent e) {
if (e.detail == SWT.ICON_CANCEL)
clearText();
}
});
}
GridData gridData= new GridData(SWT.FILL, SWT.CENTER, true, false);
// if the text widget supported cancel then it will have it's own
// integrated button. We can take all of the space.
if ((filterText.getStyle() & SWT.ICON_CANCEL) != 0)
gridData.horizontalSpan = 2;
filterText.setLayoutData(gridData);
}
/**
* Creates the text control for entering the filter text. Subclasses may
* override.
*
* @param parent
* the parent composite
* @return the text widget
*
* @since 3.3
*/
protected Text doCreateFilterText(Composite parent) {
if (!useNewLook || useNativeSearchField(parent)) {
return new Text(parent, SWT.SINGLE | SWT.BORDER | SWT.SEARCH
| SWT.ICON_CANCEL);
}
return new Text(parent, SWT.SINGLE);
}
private String previousFilterText;
private boolean narrowingDown;
/**
* Update the receiver after the text has changed.
*/
protected void textChanged() {
narrowingDown = previousFilterText == null
|| previousFilterText
.equals(WorkbenchMessages.FilteredTree_FilterMessage)
|| getFilterString().startsWith(previousFilterText);
previousFilterText = getFilterString();
// cancel currently running job first, to prevent unnecessary redraw
refreshJob.cancel();
refreshJob.schedule(getRefreshJobDelay());
}
/**
* Return the time delay that should be used when scheduling the
* filter refresh job. Subclasses may override.
*
* @return a time delay in milliseconds before the job should run
*
* @since 3.5
*/
protected long getRefreshJobDelay() {
return 200;
}
/**
* Set the background for the widgets that support the filter text area.
*
* @param background
* background <code>Color</code> to set
*/
@Override
public void setBackground(Color background) {
super.setBackground(background);
if (filterComposite != null && (!useNewLook || useNativeSearchField(filterComposite))) {
filterComposite.setBackground(background);
}
if (filterToolBar != null && filterToolBar.getControl() != null) {
filterToolBar.getControl().setBackground(background);
}
}
/**
* Create the button that clears the text.
*
* @param parent
* parent <code>Composite</code> of toolbar button
*/
private void createClearTextOld(Composite parent) {
// only create the button if the text widget doesn't support one
// natively
if ((filterText.getStyle() & SWT.ICON_CANCEL) == 0) {
filterToolBar= new ToolBarManager(SWT.FLAT | SWT.HORIZONTAL);
filterToolBar.createControl(parent);
IAction clearTextAction= new Action("", IAction.AS_PUSH_BUTTON) {//$NON-NLS-1$
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.Action#run()
*/
@Override
public void run() {
clearText();
}
};
clearTextAction
.setToolTipText(WorkbenchMessages.FilteredTree_ClearToolTip);
clearTextAction.setImageDescriptor(JFaceResources
.getImageRegistry().getDescriptor(CLEAR_ICON));
clearTextAction.setDisabledImageDescriptor(JFaceResources
.getImageRegistry().getDescriptor(DISABLED_CLEAR_ICON));
filterToolBar.add(clearTextAction);
}
}
/**
* Create the button that clears the text.
*
* @param parent parent <code>Composite</code> of toolbar button
*/
private void createClearTextNew(Composite parent) {
// only create the button if the text widget doesn't support one
// natively
if ((filterText.getStyle() & SWT.ICON_CANCEL) == 0) {
final Image inactiveImage= JFaceResources.getImageRegistry().getDescriptor(DISABLED_CLEAR_ICON).createImage();
final Image activeImage= JFaceResources.getImageRegistry().getDescriptor(CLEAR_ICON).createImage();
final Image pressedImage= new Image(getDisplay(), activeImage, SWT.IMAGE_GRAY);
final Label clearButton= new Label(parent, SWT.NONE);
clearButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
clearButton.setImage(inactiveImage);
clearButton.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND));
clearButton.setToolTipText(WorkbenchMessages.FilteredTree_ClearToolTip);
clearButton.addMouseListener(new MouseAdapter() {
private MouseMoveListener fMoveListener;
@Override
public void mouseDown(MouseEvent e) {
clearButton.setImage(pressedImage);
fMoveListener= new MouseMoveListener() {
private boolean fMouseInButton= true;
@Override
public void mouseMove(MouseEvent e) {
boolean mouseInButton= isMouseInButton(e);
if (mouseInButton != fMouseInButton) {
fMouseInButton= mouseInButton;
clearButton.setImage(mouseInButton ? pressedImage : inactiveImage);
}
}
};
clearButton.addMouseMoveListener(fMoveListener);
}
@Override
public void mouseUp(MouseEvent e) {
if (fMoveListener != null) {
clearButton.removeMouseMoveListener(fMoveListener);
fMoveListener= null;
boolean mouseInButton= isMouseInButton(e);
clearButton.setImage(mouseInButton ? activeImage : inactiveImage);
if (mouseInButton) {
clearText();
filterText.setFocus();
}
}
}
private boolean isMouseInButton(MouseEvent e) {
Point buttonSize = clearButton.getSize();
return 0 <= e.x && e.x < buttonSize.x && 0 <= e.y && e.y < buttonSize.y;
}
});
clearButton.addMouseTrackListener(new MouseTrackListener() {
@Override
public void mouseEnter(MouseEvent e) {
clearButton.setImage(activeImage);
}
@Override
public void mouseExit(MouseEvent e) {
clearButton.setImage(inactiveImage);
}
@Override
public void mouseHover(MouseEvent e) {
// do nothing
}
});
clearButton.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
inactiveImage.dispose();
activeImage.dispose();
pressedImage.dispose();
}
});
clearButton.getAccessible().addAccessibleListener(
new AccessibleAdapter() {
@Override
public void getName(AccessibleEvent e) {
e.result= WorkbenchMessages.FilteredTree_AccessibleListenerClearButton;
}
});
clearButton.getAccessible().addAccessibleControlListener(
new AccessibleControlAdapter() {
@Override
public void getRole(AccessibleControlEvent e) {
e.detail= ACC.ROLE_PUSHBUTTON;
}
});
this.clearButtonControl= clearButton;
}
}
/**
* Clears the text in the filter text widget.
*/
protected void clearText() {
setFilterText(""); //$NON-NLS-1$
textChanged();
}
/**
* Set the text in the filter control.
*
* @param string
*/
protected void setFilterText(String string) {
if (filterText != null) {
filterText.setText(string);
selectAll();
}
}
/**
* Returns the pattern filter used by this tree.
*
* @return The pattern filter; never <code>null</code>.
*/
public final EnsemblePatternFilter getPatternFilter() {
return patternFilter;
}
/**
* Get the tree viewer of the receiver.
*
* @return the tree viewer
*/
public TreeViewer getViewer() {
return treeViewer;
}
/**
* Get the filter text for the receiver, if it was created. Otherwise return
* <code>null</code>.
*
* @return the filter Text, or null if it was not created
*/
public Text getFilterControl() {
return filterText;
}
/**
* Convenience method to return the text of the filter control. If the text
* widget is not created, then null is returned.
*
* @return String in the text, or null if the text does not exist
*/
protected String getFilterString() {
return filterText != null ? filterText.getText() : null;
}
/**
* Set the text that will be shown until the first focus. A default value is
* provided, so this method only need be called if overriding the default
* initial text is desired.
*
* @param text
* initial text to appear in text field
*/
public void setInitialText(String text) {
initialText = text;
if (useNewLook && filterText != null) {
filterText.setMessage(text);
if (filterText.isFocusControl()) {
setFilterText(initialText);
textChanged();
} else {
getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
if (!filterText.isDisposed() && filterText.isFocusControl()) {
setFilterText(initialText);
textChanged();
}
}
});
}
} else {
setFilterText(initialText);
textChanged();
}
}
/**
* Select all text in the filter text field.
*
*/
protected void selectAll() {
if (filterText != null) {
filterText.selectAll();
}
}
/**
* Get the initial text for the receiver.
*
* @return String
*/
protected String getInitialText() {
return initialText;
}
/**
* Return a bold font if the given element matches the given pattern.
* Clients can opt to call this method from a Viewer's label provider to get
* a bold font for which to highlight the given element in the tree.
*
* @param element
* element for which a match should be determined
* @param tree
* FilteredTree in which the element resides
* @param filter
* PatternFilter which determines a match
*
* @return bold font
*/
public static Font getBoldFont(Object element, EnsembleFilteredTree tree,
EnsemblePatternFilter filter) {
String filterText = tree.getFilterString();
if (filterText == null) {
return null;
}
// Do nothing if it's empty string
String initialText = tree.getInitialText();
if (!filterText.equals("") && !filterText.equals(initialText)) {//$NON-NLS-1$
if (tree.getPatternFilter() != filter) {
boolean initial= initialText != null
&& initialText.equals(filterText);
if (initial) {
filter.setPattern(null);
} else if (filterText != null) {
filter.setPattern(filterText);
}
}
if (filter.isElementVisible(tree.getViewer(), element)
&& filter.isLeafMatch(tree.getViewer(), element)) {
return JFaceResources.getFontRegistry().getBold(
JFaceResources.DIALOG_FONT);
}
}
return null;
}
/**
* Custom tree viewer subclass that clears the caches in patternFilter on
* any change to the tree. See bug 187200.
*
* @since 3.3
*
*/
class NotifyingTreeViewer extends EnsembleNavigatorViewer {
/**
* @param parent
* @param style
*/
public NotifyingTreeViewer(Composite parent, int style) {
super(viewSite.getId(),parent, style);
addFilter(patternFilter);
}
@Override
public void add(Object parentElementOrTreePath, Object childElement) {
getPatternFilter().clearCaches();
super.add(parentElementOrTreePath, childElement);
}
@Override
public void add(Object parentElementOrTreePath, Object[] childElements) {
getPatternFilter().clearCaches();
super.add(parentElementOrTreePath, childElements);
}
@Override
protected void inputChanged(Object input, Object oldInput) {
getPatternFilter().clearCaches();
super.inputChanged(input, oldInput);
}
@Override
public void insert(Object parentElementOrTreePath, Object element,
int position) {
getPatternFilter().clearCaches();
super.insert(parentElementOrTreePath, element, position);
}
@Override
public void refresh() {
getPatternFilter().clearCaches();
super.refresh();
}
@Override
public void refresh(boolean updateLabels) {
getPatternFilter().clearCaches();
super.refresh(updateLabels);
}
@Override
public void refresh(Object element) {
getPatternFilter().clearCaches();
super.refresh(element);
}
@Override
public void refresh(Object element, boolean updateLabels) {
getPatternFilter().clearCaches();
super.refresh(element, updateLabels);
}
@Override
public void remove(Object elementsOrTreePaths) {
getPatternFilter().clearCaches();
super.remove(elementsOrTreePaths);
}
@Override
public void remove(Object parent, Object[] elements) {
getPatternFilter().clearCaches();
super.remove(parent, elements);
}
@Override
public void remove(Object[] elementsOrTreePaths) {
getPatternFilter().clearCaches();
super.remove(elementsOrTreePaths);
}
@Override
public void replace(Object parentElementOrTreePath, int index,
Object element) {
getPatternFilter().clearCaches();
super.replace(parentElementOrTreePath, index, element);
}
@Override
public void setChildCount(Object elementOrTreePath, int count) {
getPatternFilter().clearCaches();
super.setChildCount(elementOrTreePath, count);
}
@Override
public void setContentProvider(IContentProvider provider) {
getPatternFilter().clearCaches();
super.setContentProvider(provider);
}
@Override
public void setHasChildren(Object elementOrTreePath, boolean hasChildren) {
getPatternFilter().clearCaches();
super.setHasChildren(elementOrTreePath, hasChildren);
}
@Override
protected Object[] getFilteredChildren(Object parent) {
Object[] filteredChildren = super.getFilteredChildren(parent);
ArrayList reFilteredChildren = new ArrayList();
for(Object object: filteredChildren) {
TreeViewer viewer = EnsembleFilteredTree.this.getViewer();
if(patternFilter.isLeafMatch(viewer, object) || patternFilter.isParentMatch(viewer, object)) {
reFilteredChildren.add(object);
}
}
return reFilteredChildren.toArray();
}
@Override
protected void labelProviderChanged() {
WidgetUtils.runInDisplayThread(getControl(), new Runnable() {
@Override
public void run() {
// we have to walk the (visible) tree and update every item
Control tree = getControl();
tree.setRedraw(false);
// don't pick up structure changes, but do force label updates
internalRefresh(tree, getRoot(), false, true);
tree.setRedraw(true);
}
});
}
}
}
| |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.androsz.electricsleepbeta.alarmclock;
import java.util.Calendar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.actionbarsherlock.view.Menu;
import com.androsz.electricsleepbeta.R;
import com.androsz.electricsleepbeta.app.SettingsActivity;
/**
* AlarmClock application.
*/
public class AlarmClock extends com.androsz.electricsleepbeta.app.HostActivity
implements OnItemClickListener {
private class AlarmTimeAdapter extends CursorAdapter {
public AlarmTimeAdapter(final Context context, final Cursor cursor) {
super(context, cursor);
}
@Override
public void bindView(final View view, final Context context,
final Cursor cursor) {
final Alarm alarm = new Alarm(cursor);
final View indicator = view.findViewById(R.id.indicator);
indicator.setBackgroundColor(android.R.color.transparent);
// Set the initial state of the clock "checkbox"
final CheckBox clockOnOff = (CheckBox) indicator
.findViewById(R.id.clock_onoff);
clockOnOff.setChecked(alarm.enabled);
// Clicking outside the "checkbox" should also change the state.
indicator.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
clockOnOff.toggle();
boolean enabled = clockOnOff.isChecked();
Alarms.enableAlarm(AlarmClock.this, alarm.id, enabled);
if (enabled) {
SetAlarm.popAlarmSetToast(AlarmClock.this, alarm.hour,
alarm.minutes, alarm.daysOfWeek);
}
}
});
final DigitalClock digitalClock = (DigitalClock) view
.findViewById(R.id.digitalClock);
// set the alarm text
final Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, alarm.hour);
c.set(Calendar.MINUTE, alarm.minutes);
digitalClock.updateTime(c);
digitalClock.setTypeface(Typeface.DEFAULT);
// Set the repeat text or leave it blank if it does not repeat.
final TextView daysOfWeekView = (TextView) digitalClock
.findViewById(R.id.daysOfWeek);
final String daysOfWeekStr = alarm.daysOfWeek.toString(
AlarmClock.this, false);
if (daysOfWeekStr != null && daysOfWeekStr.length() != 0) {
daysOfWeekView.setText(daysOfWeekStr);
daysOfWeekView.setVisibility(View.VISIBLE);
} else {
daysOfWeekView.setVisibility(View.GONE);
}
// Display the label
final TextView labelView = (TextView) view.findViewById(R.id.label);
if (alarm.label != null && alarm.label.length() != 0) {
labelView.setText(alarm.label);
labelView.setVisibility(View.VISIBLE);
} else {
labelView.setVisibility(View.GONE);
}
}
@Override
public View newView(final Context context, final Cursor cursor,
final ViewGroup parent) {
final View ret = mFactory.inflate(R.layout.alarm_time, parent,
false);
final DigitalClock digitalClock = (DigitalClock) ret
.findViewById(R.id.digitalClock);
digitalClock.setLive(false);
return ret;
}
}
/**
* This must be false for production. If true, turns on logging, test code,
* etc.
*/
static final boolean DEBUG = false;
private ListView mAlarmsList;
private Cursor mCursor;
private LayoutInflater mFactory;
private SharedPreferences mPrefs;
private void addNewAlarm() {
startActivity(new Intent(this, SetAlarm.class));
}
@Override
protected int getContentAreaLayoutId() {
return R.layout.alarm_clock;
}
@Override
public boolean onContextItemSelected(final MenuItem item) {
final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
final int id = (int) info.id;
switch (item.getItemId()) {
case R.id.delete_alarm:
// Confirm that the alarm will be deleted.
new AlertDialog.Builder(this)
.setTitle(getString(R.string.delete_alarm))
.setMessage(getString(R.string.delete_alarm_confirm))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface d,
final int w) {
Alarms.deleteAlarm(AlarmClock.this, id);
}
}).setNegativeButton(android.R.string.cancel, null)
.show();
return true;
case R.id.enable_alarm:
final Cursor c = (Cursor) mAlarmsList.getAdapter().getItem(
info.position);
final Alarm alarm = new Alarm(c);
Alarms.enableAlarm(this, alarm.id, !alarm.enabled);
if (!alarm.enabled) {
SetAlarm.popAlarmSetToast(this, alarm.hour, alarm.minutes,
alarm.daysOfWeek);
}
return true;
case R.id.edit_alarm:
final Intent intent = new Intent(this, SetAlarm.class);
intent.putExtra(Alarms.ALARM_ID, id);
startActivity(intent);
return true;
default:
break;
}
return super.onContextItemSelected(item);
};
@Override
protected void onCreate(final Bundle icicle) {
super.onCreate(icicle);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
mPrefs = getSharedPreferences(SettingsActivity.PREFERENCES, 0);
mCursor = Alarms.getAlarmsCursor(getContentResolver());
mCursor.deactivate();
return null;
}
@Override
protected void onPostExecute(Void result) {
updateLayout();
super.onPostExecute(result);
}
@Override
protected void onPreExecute() {
mFactory = LayoutInflater.from(AlarmClock.this);
super.onPreExecute();
}
}.execute();
}
@Override
public void onCreateContextMenu(final ContextMenu menu, final View view,
final ContextMenuInfo menuInfo) {
// Inflate the menu from xml.
// super.getMenuInflater().inflate(R.menu.context_menu, (Menu)menu);
menu.add(android.view.Menu.NONE, R.id.enable_alarm,
android.view.Menu.NONE, R.string.enable_alarm);
menu.add(android.view.Menu.NONE, R.id.edit_alarm,
android.view.Menu.NONE, R.string.menu_edit_alarm);
menu.add(android.view.Menu.NONE, R.id.delete_alarm,
android.view.Menu.NONE, R.string.delete_alarm);
// Use the current item to create a custom view for the header.
final AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
final Cursor c = (Cursor) mAlarmsList.getAdapter().getItem(
info.position);
final Alarm alarm = new Alarm(c);
// Construct the Calendar to compute the time.
final Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, alarm.hour);
cal.set(Calendar.MINUTE, alarm.minutes);
final String time = Alarms.formatTime(this, cal);
// Inflate the custom view and set each TextView's text.
final View v = mFactory.inflate(R.layout.context_menu_header, null);
TextView textView = (TextView) v.findViewById(R.id.header_time);
textView.setText(time);
textView = (TextView) v.findViewById(R.id.header_label);
textView.setText(alarm.label);
// Set the custom view on the menu.
menu.setHeaderView(v);
// Change the text based on the state of the alarm.
if (alarm.enabled) {
menu.findItem(R.id.enable_alarm).setTitle(R.string.disable_alarm);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.menu_alarm_clock, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
protected void onDestroy() {
super.onDestroy();
ToastMaster.cancelToast();
if (mCursor != null && !mCursor.isClosed()) {
mCursor.close();
}
}
@Override
public void onItemClick(final AdapterView parent, final View v,
final int pos, final long id) {
final Intent intent = new Intent(this, SetAlarm.class);
intent.putExtra(Alarms.ALARM_ID, (int) id);
startActivity(intent);
}
@Override
public boolean onOptionsItemSelected(
com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_add_alarm:
addNewAlarm();
break;
}
return super.onOptionsItemSelected(item);
}
private void updateLayout() {
mAlarmsList = (ListView) findViewById(R.id.alarms_list);
mCursor.requery();
final AlarmTimeAdapter adapter = new AlarmTimeAdapter(this, mCursor);
mAlarmsList.setAdapter(adapter);
mAlarmsList.setVerticalScrollBarEnabled(true);
mAlarmsList.setOnItemClickListener(this);
mAlarmsList.setOnCreateContextMenuListener(this);
mAlarmsList.setBackgroundColor(getResources().getColor(
R.color.background_dark));
}
}
| |
/*
* @(#)CodePointInputMethod.java 1.6 05/11/17
*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution 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 Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
/*
* @(#)CodePointInputMethod.java 1.6 05/11/17
*/
package com.sun.inputmethods.internal.codepointim;
import java.text.AttributedCharacterIterator;
import java.util.Map;
import java.awt.AWTEvent;
import java.awt.Toolkit;
import java.awt.Rectangle;
import java.awt.event.InputMethodEvent;
import java.awt.event.KeyEvent;
import java.awt.font.TextAttribute;
import java.awt.font.TextHitInfo;
import java.awt.im.InputMethodHighlight;
import java.awt.im.spi.InputMethod;
import java.awt.im.spi.InputMethodContext;
import java.io.IOException;
import java.text.AttributedString;
import java.util.Locale;
/**
* The Code Point Input Method is a simple input method that allows Unicode
* characters to be entered using their code point or code unit values. See the
* accompanying file README.txt for more information.
*
* @author Brian Beck
*/
public class CodePointInputMethod implements InputMethod {
private static final int UNSET = 0;
private static final int ESCAPE = 1; // \u0000 - \uFFFF
private static final int SPECIAL_ESCAPE = 2; // \U000000 - \U10FFFF
private static final int SURROGATE_PAIR = 3; // \uD800\uDC00 - \uDBFF\uDFFF
private InputMethodContext context;
private Locale locale;
private StringBuffer buffer;
private int insertionPoint;
private int format = UNSET;
public CodePointInputMethod() throws IOException {
}
/**
* This is the input method's main routine. The composed text is stored
* in buffer.
*/
public void dispatchEvent(AWTEvent event) {
// This input method handles KeyEvent only.
if (!(event instanceof KeyEvent)) {
return;
}
KeyEvent e = (KeyEvent) event;
int eventID = event.getID();
boolean notInCompositionMode = buffer.length() == 0;
if (eventID == KeyEvent.KEY_PRESSED) {
// If we are not in composition mode, pass through
if (notInCompositionMode) {
return;
}
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
moveCaretLeft();
break;
case KeyEvent.VK_RIGHT:
moveCaretRight();
break;
}
} else if (eventID == KeyEvent.KEY_TYPED) {
char c = e.getKeyChar();
// If we are not in composition mode, wait a back slash
if (notInCompositionMode) {
// If the type character is not a back slash, pass through
if (c != '\\') {
return;
}
startComposition(); // Enter to composition mode
} else {
switch (c) {
case ' ': // Exit from composition mode
finishComposition();
break;
case '\u007f': // Delete
deleteCharacter();
break;
case '\b': // BackSpace
deletePreviousCharacter();
break;
case '\u001b': // Escape
cancelComposition();
break;
case '\n': // Return
case '\t': // Tab
sendCommittedText();
break;
default:
composeUnicodeEscape(c);
break;
}
}
} else { // KeyEvent.KEY_RELEASED
// If we are not in composition mode, pass through
if (notInCompositionMode) {
return;
}
}
e.consume();
}
private void composeUnicodeEscape(char c) {
switch (buffer.length()) {
case 1: // \\
waitEscapeCharacter(c);
break;
case 2: // \\u or \\U
case 3: // \\ux or \\Ux
case 4: // \\uxx or \\Uxx
waitDigit(c);
break;
case 5: // \\uxxx or \\Uxxx
if (format == SPECIAL_ESCAPE) {
waitDigit(c);
} else {
waitDigit2(c);
}
break;
case 6: // \\uxxxx or \\Uxxxx
if (format == SPECIAL_ESCAPE) {
waitDigit(c);
} else if (format == SURROGATE_PAIR) {
waitBackSlashOrLowSurrogate(c);
} else {
beep();
}
break;
case 7: // \\Uxxxxx
// Only SPECIAL_ESCAPE format uses this state.
// Since the second "\\u" of SURROGATE_PAIR format is inserted
// automatically, users don't have to type these keys.
waitDigit(c);
break;
case 8: // \\uxxxx\\u
case 9: // \\uxxxx\\ux
case 10: // \\uxxxx\\uxx
case 11: // \\uxxxx\\uxxx
if (format == SURROGATE_PAIR) {
waitDigit(c);
} else {
beep();
}
break;
default:
beep();
break;
}
}
private void waitEscapeCharacter(char c) {
if (c == 'u' || c == 'U') {
buffer.append(c);
insertionPoint++;
sendComposedText();
format = (c == 'u') ? ESCAPE : SPECIAL_ESCAPE;
} else {
if (c != '\\') {
buffer.append(c);
insertionPoint++;
}
sendCommittedText();
}
}
private void waitDigit(char c) {
if (Character.digit(c, 16) != -1) {
buffer.insert(insertionPoint++, c);
sendComposedText();
} else {
beep();
}
}
private void waitDigit2(char c) {
if (Character.digit(c, 16) != -1) {
buffer.insert(insertionPoint++, c);
char codePoint = (char)getCodePoint(buffer, 2, 5);
if (Character.isHighSurrogate(codePoint)) {
format = SURROGATE_PAIR;
buffer.append("\\u");
insertionPoint = 8;
} else {
format = ESCAPE;
}
sendComposedText();
} else {
beep();
}
}
private void waitBackSlashOrLowSurrogate(char c) {
if (insertionPoint == 6) {
if (c == '\\') {
buffer.append(c);
buffer.append('u');
insertionPoint = 8;
sendComposedText();
} else if (Character.digit(c, 16) != -1) {
buffer.append("\\u");
buffer.append(c);
insertionPoint = 9;
sendComposedText();
} else {
beep();
}
} else {
beep();
}
}
/**
* Send the composed text to the client.
*/
private void sendComposedText() {
AttributedString as = new AttributedString(buffer.toString());
as.addAttribute(TextAttribute.INPUT_METHOD_HIGHLIGHT,
InputMethodHighlight.SELECTED_RAW_TEXT_HIGHLIGHT);
context.dispatchInputMethodEvent(
InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
as.getIterator(), 0,
TextHitInfo.leading(insertionPoint), null);
}
/**
* Send the committed text to the client.
*/
private void sendCommittedText() {
AttributedString as = new AttributedString(buffer.toString());
context.dispatchInputMethodEvent(
InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
as.getIterator(), buffer.length(),
TextHitInfo.leading(insertionPoint), null);
buffer.setLength(0);
insertionPoint = 0;
format = UNSET;
}
/**
* Move the insertion point one position to the left in the composed text.
* Do not let the caret move to the left of the "\\u" or "\\U".
*/
private void moveCaretLeft() {
int len = buffer.length();
if (--insertionPoint < 2) {
insertionPoint++;
beep();
} else if (format == SURROGATE_PAIR && insertionPoint == 7) {
insertionPoint = 8;
beep();
}
context.dispatchInputMethodEvent(
InputMethodEvent.CARET_POSITION_CHANGED,
null, 0,
TextHitInfo.leading(insertionPoint), null);
}
/**
* Move the insertion point one position to the right in the composed text.
*/
private void moveCaretRight() {
int len = buffer.length();
if (++insertionPoint > len) {
insertionPoint = len;
beep();
}
context.dispatchInputMethodEvent(
InputMethodEvent.CARET_POSITION_CHANGED,
null, 0,
TextHitInfo.leading(insertionPoint), null);
}
/**
* Delete the character preceding the insertion point in the composed text.
* If the insertion point is not at the end of the composed text and the
* preceding text is "\\u" or "\\U", ring the bell.
*/
private void deletePreviousCharacter() {
if (insertionPoint == 2) {
if (buffer.length() == 2) {
cancelComposition();
} else {
// Do not allow deletion of the leading "\\u" or "\\U" if there
// are other digits in the composed text.
beep();
}
} else if (insertionPoint == 8) {
if (buffer.length() == 8) {
if (format == SURROGATE_PAIR) {
buffer.deleteCharAt(--insertionPoint);
}
buffer.deleteCharAt(--insertionPoint);
sendComposedText();
} else {
// Do not allow deletion of the second "\\u" if there are other
// digits in the composed text.
beep();
}
} else {
buffer.deleteCharAt(--insertionPoint);
if (buffer.length() == 0) {
sendCommittedText();
} else {
sendComposedText();
}
}
}
/**
* Delete the character following the insertion point in the composed text.
* If the insertion point is at the end of the composed text, ring the bell.
*/
private void deleteCharacter() {
if (insertionPoint < buffer.length()) {
buffer.deleteCharAt(insertionPoint);
sendComposedText();
} else {
beep();
}
}
private void startComposition() {
buffer.append('\\');
insertionPoint = 1;
sendComposedText();
}
private void cancelComposition() {
buffer.setLength(0);
insertionPoint = 0;
sendCommittedText();
}
private void finishComposition() {
int len = buffer.length();
if (len == 6 && format != SPECIAL_ESCAPE) {
char codePoint = (char)getCodePoint(buffer, 2, 5);
if (Character.isValidCodePoint(codePoint) && codePoint != 0xFFFF) {
buffer.setLength(0);
buffer.append(codePoint);
sendCommittedText();
return;
}
} else if (len == 8 && format == SPECIAL_ESCAPE) {
int codePoint = getCodePoint(buffer, 2, 7);
if (Character.isValidCodePoint(codePoint) && codePoint != 0xFFFF) {
buffer.setLength(0);
buffer.appendCodePoint(codePoint);
sendCommittedText();
return;
}
} else if (len == 12 && format == SURROGATE_PAIR) {
char[] codePoint = {
(char)getCodePoint(buffer, 2, 5),
(char)getCodePoint(buffer, 8, 11)
};
if (Character.isHighSurrogate(codePoint[0]) &&
Character.isLowSurrogate(codePoint[1])) {
buffer.setLength(0);
buffer.append(codePoint);
sendCommittedText();
return;
}
}
beep();
}
private int getCodePoint(StringBuffer sb, int from, int to) {
int value = 0;
for (int i = from; i <= to; i++) {
value = (value<<4) + Character.digit(sb.charAt(i), 16);
}
return value;
}
private static void beep() {
Toolkit.getDefaultToolkit().beep();
}
public void activate() {
if (buffer == null) {
buffer = new StringBuffer(12);
insertionPoint = 0;
}
}
public void deactivate(boolean isTemporary) {
if (!isTemporary) {
buffer = null;
}
}
public void dispose() {
}
public Object getControlObject() {
return null;
}
public void endComposition() {
sendCommittedText();
}
public Locale getLocale() {
return locale;
}
public void hideWindows() {
}
public boolean isCompositionEnabled() {
// always enabled
return true;
}
public void notifyClientWindowChange(Rectangle location) {
}
public void reconvert() {
// not supported yet
throw new UnsupportedOperationException();
}
public void removeNotify() {
}
public void setCharacterSubsets(Character.Subset[] subsets) {
}
public void setCompositionEnabled(boolean enable) {
// not supported yet
throw new UnsupportedOperationException();
}
public void setInputMethodContext(InputMethodContext context) {
this.context = context;
}
/*
* The Code Point Input Method supports all locales.
*/
public boolean setLocale(Locale locale) {
this.locale = locale;
return true;
}
}
| |
package cz.vhromada.export.gui;
import java.awt.EventQueue;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.event.DocumentListener;
import cz.vhromada.export.api.Export;
import cz.vhromada.export.api.entities.Database;
import cz.vhromada.export.commons.SwingUtils;
import cz.vhromada.export.gui.data.InputValidator;
import cz.vhromada.export.gui.data.Pictures;
import cz.vhromada.export.sql.SqlExporter;
import cz.vhromada.export.xml.XmlExporter;
import cz.vhromada.validators.Validators;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A class represents choosing exportation type.
*
* @author Vladimir Hromada
*/
public class ExportChoose extends JFrame {
/**
* Logger
*/
private static final Logger logger = LoggerFactory.getLogger(ExportChoose.class);
/**
* Serial version UID
*/
private static final long serialVersionUID = 1L;
/**
* Combo box for exportation types
*/
private JComboBox<String> exportType = new JComboBox<>(new String[]{ "SQL", "XML" });
/**
* Label for directory
*/
private JLabel directoryLabel = new JLabel("Directory");
/**
* Text field for directory
*/
private JTextField directoryData = new JTextField();
/**
* Label for file
*/
private JLabel fileLabel = new JLabel("File");
/**
* Text field for file
*/
private JTextField fileData = new JTextField();
/**
* Button Back
*/
private JButton backButton = new JButton("Back", Pictures.getPicture("back"));
/**
* Button ExportChoose
*/
private JButton exportButton = new JButton("ExportChoose", Pictures.getPicture("export"));
/**
* Button Exit
*/
private JButton exitButton = new JButton("Exit", Pictures.getPicture("exit"));
/**
* Database description
*/
private Database database;
/**
* Charset
*/
private Charset charset;
/**
* Creates a new instance of ExportChoose.
*
* @param database database description
* @param charset charset
* @throws IllegalArgumentException if database description is null
* or charset is null
*/
public ExportChoose(final Database database, final Charset charset) {
Validators.validateArgumentNotNull(database, "Database");
Validators.validateArgumentNotNull(charset, "Charset");
this.database = database;
this.charset = charset;
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setTitle("Database export");
setIconImage(Pictures.getPicture("export").getImage());
exportType.setSelectedItem(null);
exportType.addActionListener(e -> exportTypeAction());
directoryLabel.setLabelFor(directoryData);
directoryLabel.setFocusable(false);
fileLabel.setLabelFor(fileData);
fileLabel.setFocusable(false);
SwingUtils.initLabelComponent(directoryLabel, directoryData);
SwingUtils.initLabelComponent(fileLabel, fileData);
final DocumentListener inputValidator = new InputValidator(exportButton) {
@Override
public boolean isInputValid() {
return ExportChoose.this.isInputValid();
}
};
SwingUtils.addInputValidator(inputValidator, directoryData, fileData);
backButton.addActionListener(e -> backAction());
exportButton.addActionListener(e -> exportAction());
exitButton.addActionListener(e -> System.exit(0));
final GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(createHorizontalLayout(layout));
layout.setVerticalGroup(createVerticalLayout(layout));
pack();
setLocationRelativeTo(getRootPane());
}
/**
* Performs action for combo box for exportation types.
*/
private void exportTypeAction() {
exportButton.setEnabled(isInputValid());
}
/**
* Performs action for button Back.
*/
private void backAction() {
EventQueue.invokeLater(() -> {
setVisible(false);
new DbChoose(charset).setVisible(true);
});
}
/**
* Performs action for button ExportChoose.
*/
private void exportAction() {
logger.info("Type: {}", exportType.getSelectedItem());
logger.info("Directory: {}", directoryData.getText());
logger.info("File: {}", fileData.getText());
EventQueue.invokeLater(() -> new ExportDialog(getExport(), database, charset).setVisible(true));
}
/**
* Returns export.
*
* @return export
*/
private Export getExport() {
final Path directory = Paths.get(directoryData.getText());
final String file = fileData.getText();
switch (exportType.getSelectedIndex()) {
case 0:
return new SqlExporter(directory, file);
case 1:
return new XmlExporter(directory, file);
default:
throw new IllegalArgumentException("Bad selected export type.");
}
}
/**
* Returns true if input is valid: exportation type is selected and directory isn't empty string and file isn't empty string.
*
* @return true if input is valid: exportation type is selected and directory isn't empty string and file isn't empty string
*/
private boolean isInputValid() {
return exportType.getSelectedIndex() >= 0 && !directoryData.getText().isEmpty() && !fileData.getText().isEmpty();
}
/**
* Returns horizontal layout.
*
* @param layout layout
* @return horizontal layout
*/
private GroupLayout.Group createHorizontalLayout(final GroupLayout layout) {
final Map<JLabel, JTextField> components = new LinkedHashMap<>(4);
components.put(directoryLabel, directoryData);
components.put(fileLabel, fileData);
return SwingUtils.createHorizontalLayout(layout, exportType, components, backButton, exportButton, exitButton);
}
/**
* Returns vertical layout.
*
* @param layout layout
* @return vertical layout
*/
private GroupLayout.Group createVerticalLayout(final GroupLayout layout) {
final Map<JLabel, JTextField> components = new LinkedHashMap<>(4);
components.put(directoryLabel, directoryData);
components.put(fileLabel, fileData);
return SwingUtils.createVerticalLayout(layout, exportType, components, backButton, exportButton, exitButton);
}
}
| |
/*
* Copyright 2007 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.collect.Lists;
import com.google.javascript.jscomp.NodeTraversal.Callback;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;
/**
* Inlines methods that take no arguments and have only a return statement
* returning a property. Because it works on method names rather than type
* inference, a method with multiple definitions will be inlined if each
* definition is identical.
*
* <pre>
* A.prototype.foo = function() { return this.b; }
* B.prototype.foo = function() { return this.b; }
* </pre>
*
* will inline foo, but
*
* <pre>
* A.prototype.foo = function() { return this.b; }
* B.prototype.foo = function() { return this.c; }
* </pre>
*
* will not.
*
* Declarations are not removed because we do not find all possible
* call sites. For examples, calls of the form foo["bar"] are not
* detected.
*
*/
class InlineSimpleMethods extends MethodCompilerPass {
private static final Logger logger =
Logger.getLogger(InlineSimpleMethods.class.getName());
InlineSimpleMethods(AbstractCompiler compiler) {
super(compiler);
}
/**
* For each method call, see if it is a candidate for inlining.
* TODO(kushal): Cache the results of the checks
*/
private class InlineTrivialAccessors extends InvocationsCallback {
@Override
void visit(NodeTraversal t, Node callNode, Node parent, String callName) {
if (externMethods.contains(callName) ||
nonMethodProperties.contains(callName)) {
return;
}
Collection<Node> definitions = methodDefinitions.get(callName);
if (definitions == null || definitions.size() == 0) {
return;
}
// Do check of arity, complexity, and consistency in what we think is
// the order from least to most complex
Node firstDefinition = definitions.iterator().next();
// Check any multiple definitions
if (definitions.size() == 1 || allDefinitionsEquivalent(definitions)) {
if (!argsMayHaveSideEffects(callNode)) {
// Verify this is a trivial return
Node returned = returnedExpression(firstDefinition);
if (returned != null) {
if (isPropertyTree(returned)) {
logger.fine("Inlining property accessor: " + callName);
inlinePropertyReturn(parent, callNode, returned);
} else if (NodeUtil.isLiteralValue(returned, false) &&
!NodeUtil.mayHaveSideEffects(
callNode.getFirstChild(), compiler)) {
logger.fine("Inlining constant accessor: " + callName);
inlineConstReturn(parent, callNode, returned);
}
} else if (isEmptyMethod(firstDefinition) &&
!NodeUtil.mayHaveSideEffects(
callNode.getFirstChild(), compiler)) {
logger.fine("Inlining empty method: " + callName);
inlineEmptyMethod(parent, callNode);
}
}
} else {
logger.fine("Method '" + callName + "' has conflicting definitions.");
}
}
}
@Override
Callback getActingCallback() {
return new InlineTrivialAccessors();
}
/**
* Returns true if the provided node is a getprop for
* which the left child is this or a valid property tree
* and for which the right side is a string.
*/
private static boolean isPropertyTree(Node expectedGetprop) {
if (!expectedGetprop.isGetProp()) {
return false;
}
Node leftChild = expectedGetprop.getFirstChild();
if (!leftChild.isThis() &&
!isPropertyTree(leftChild)) {
return false;
}
Node retVal = leftChild.getNext();
if (NodeUtil.getStringValue(retVal) == null) {
return false;
}
return true;
}
/**
* Finds the occurrence of "this" in the provided property tree and replaces
* it with replacement
*/
private static void replaceThis(Node expectedGetprop, Node replacement) {
Node leftChild = expectedGetprop.getFirstChild();
if (leftChild.isThis()) {
expectedGetprop.replaceChild(leftChild, replacement);
} else {
replaceThis(leftChild, replacement);
}
}
/**
* Return the node that represents the expression returned
* by the method, given a FUNCTION node.
*/
private static Node returnedExpression(Node fn) {
Node expectedBlock = getMethodBlock(fn);
if (!expectedBlock.hasOneChild()) {
return null;
}
Node expectedReturn = expectedBlock.getFirstChild();
if (!expectedReturn.isReturn()) {
return null;
}
if (!expectedReturn.hasOneChild()) {
return null;
}
return expectedReturn.getLastChild();
}
/**
* Return whether the given FUNCTION node is an empty method definition.
*
* Must be private, or moved to NodeUtil.
*/
private static boolean isEmptyMethod(Node fn) {
Node expectedBlock = getMethodBlock(fn);
return expectedBlock == null ?
false : NodeUtil.isEmptyBlock(expectedBlock);
}
/**
* Return a BLOCK node if the given FUNCTION node is a valid method
* definition, null otherwise.
*
* Must be private, or moved to NodeUtil.
*/
private static Node getMethodBlock(Node fn) {
if (fn.getChildCount() != 3) {
return null;
}
Node expectedBlock = fn.getLastChild();
return expectedBlock.isBlock() ?
expectedBlock : null;
}
/**
* Given a set of method definitions, verify they are the same.
*/
private boolean allDefinitionsEquivalent(
Collection<Node> definitions) {
List<Node> list = Lists.newArrayList();
list.addAll(definitions);
Node node0 = list.get(0);
for (int i = 1; i < list.size(); i++) {
if (!compiler.areNodesEqualForInlining(list.get(i), node0)) {
return false;
}
}
return true;
}
/**
* Replace the provided method call with the tree specified in returnedValue
*
* Parse tree of a call is
* name
* call
* getprop
* obj
* string
*/
private void inlinePropertyReturn(Node parent, Node call,
Node returnedValue) {
Node getProp = returnedValue.cloneTree();
replaceThis(getProp, call.getFirstChild().removeFirstChild());
parent.replaceChild(call, getProp);
compiler.reportCodeChange();
}
/**
* Replace the provided object and its method call with the tree specified
* in returnedValue. Should be called only if the object reference has
* no side effects.
*/
private void inlineConstReturn(Node parent, Node call,
Node returnedValue) {
Node retValue = returnedValue.cloneTree();
parent.replaceChild(call, retValue);
compiler.reportCodeChange();
}
/**
* Remove the provided object and its method call.
*/
private void inlineEmptyMethod(Node parent, Node call) {
// If the return value of the method call is read,
// replace it with "void 0". Otherwise, remove the call entirely.
if (NodeUtil.isExprCall(parent)) {
parent.getParent().replaceChild(parent, IR.empty());
} else {
Node srcLocation = call;
parent.replaceChild(call, NodeUtil.newUndefinedNode(srcLocation));
}
compiler.reportCodeChange();
}
/**
* Check whether the given method call's arguments have side effects.
* @param call The call node of a method invocation.
*/
private boolean argsMayHaveSideEffects(Node call) {
for (Node currentChild = call.getFirstChild().getNext();
currentChild != null;
currentChild = currentChild.getNext()) {
if (NodeUtil.mayHaveSideEffects(currentChild, compiler)) {
return true;
}
}
return false;
}
/**
* A do-nothing signature store.
*/
static final MethodCompilerPass.SignatureStore DUMMY_SIGNATURE_STORE =
new MethodCompilerPass.SignatureStore() {
@Override
public void addSignature(
String functionName, Node functionNode, String sourceFile) {
}
@Override
public void removeSignature(String functionName) {
}
@Override
public void reset() {
}
};
@Override
SignatureStore getSignatureStore() {
return DUMMY_SIGNATURE_STORE;
}
}
| |
/*
* Copyright 2013 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 info.ipeanut.googletrainingcoursedemos.basicsyncadapter;
import android.accounts.Account;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SyncStatusObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import info.ipeanut.googletrainingcoursedemos.R;
import info.ipeanut.googletrainingcoursedemos.basicsyncadapter.accounts.GenericAccountService;
import info.ipeanut.googletrainingcoursedemos.basicsyncadapter.provider.FeedContract;
/**
* List fragment containing a list of Atom entry objects (articles) stored in the local database.
*
* <p>Database access is mediated by a content provider, specified in
* {@link com.example.android.network.sync.basicsyncadapter.provider.FeedProvider}. This content
* provider is
* automatically populated by {@link SyncService}.
*
* <p>Selecting an item from the displayed list displays the article in the default browser.
*
* <p>If the content provider doesn't return any data, then the first sync hasn't run yet. This sync
* adapter assumes data exists in the provider once a sync has run. If your app doesn't work like
* this, you should add a flag that notes if a sync has run, so you can differentiate between "no
* available data" and "no initial sync", and display this in the UI.
*
* <p>The ActionBar displays a "Refresh" button. When the user clicks "Refresh", the sync adapter
* runs immediately. An indeterminate ProgressBar element is displayed, showing that the sync is
* occurring.
*/
public class EntryListFragment extends ListFragment
implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = "EntryListFragment";
/**
* Cursor adapter for controlling ListView results.
*/
private SimpleCursorAdapter mAdapter;
/**
* Handle to a SyncObserver. The ProgressBar element is visible until the SyncObserver reports
* that the sync is complete.
*
* <p>This allows us to delete our SyncObserver once the application is no longer in the
* foreground.
*/
private Object mSyncObserverHandle;
/**
* Options menu used to populate ActionBar.
*/
private Menu mOptionsMenu;
/**
* Projection for querying the content provider.
*/
private static final String[] PROJECTION = new String[]{
FeedContract.Entry._ID,
FeedContract.Entry.COLUMN_NAME_TITLE,
FeedContract.Entry.COLUMN_NAME_LINK,
FeedContract.Entry.COLUMN_NAME_PUBLISHED
};
// Column indexes. The index of a column in the Cursor is the same as its relative position in
// the projection.
/** Column index for _ID */
private static final int COLUMN_ID = 0;
/** Column index for title */
private static final int COLUMN_TITLE = 1;
/** Column index for link */
private static final int COLUMN_URL_STRING = 2;
/** Column index for published */
private static final int COLUMN_PUBLISHED = 3;
/**
* List of Cursor columns to read from when preparing an adapter to populate the ListView.
*/
private static final String[] FROM_COLUMNS = new String[]{
FeedContract.Entry.COLUMN_NAME_TITLE,
FeedContract.Entry.COLUMN_NAME_PUBLISHED
};
/**
* List of Views which will be populated by Cursor data.
*/
private static final int[] TO_FIELDS = new int[]{
android.R.id.text1,
android.R.id.text2};
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public EntryListFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
/**
* Create SyncAccount at launch, if needed.
*
* <p>This will create a new account with the system for our application, register our
* {@link SyncService} with it, and establish a sync schedule.
*/
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Create account, if needed
SyncUtils.CreateSyncAccount(activity);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mAdapter = new SimpleCursorAdapter(
getActivity(), // Current context
android.R.layout.simple_list_item_activated_2, // Layout for individual rows
null, // Cursor
FROM_COLUMNS, // Cursor columns to use
TO_FIELDS, // Layout fields to use
0 // No flags
);
mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int i) {
if (i == COLUMN_PUBLISHED) {
// Convert timestamp to human-readable date
Time t = new Time();
t.set(cursor.getLong(i));
((TextView) view).setText(t.format("%Y-%m-%d %H:%M"));
return true;
} else {
// Let SimpleCursorAdapter handle other fields automatically
return false;
}
}
});
setListAdapter(mAdapter);
setEmptyText(getText(R.string.loading));
getLoaderManager().initLoader(0, null, this);
}
@Override
public void onResume() {
super.onResume();
mSyncStatusObserver.onStatusChanged(0);
// Watch for sync state changes
final int mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING |
ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE;
mSyncObserverHandle = ContentResolver.addStatusChangeListener(mask, mSyncStatusObserver);
}
@Override
public void onPause() {
super.onPause();
if (mSyncObserverHandle != null) {
ContentResolver.removeStatusChangeListener(mSyncObserverHandle);
mSyncObserverHandle = null;
}
}
/**
* Query the content provider for data.
*
* <p>Loaders do queries in a background thread. They also provide a ContentObserver that is
* triggered when data in the content provider changes. When the sync adapter updates the
* content provider, the ContentObserver responds by resetting the loader and then reloading
* it.
*/
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
// We only have one loader, so we can ignore the value of i.
// (It'll be '0', as set in onCreate().)
return new CursorLoader(getActivity(), // Context
FeedContract.Entry.CONTENT_URI, // URI
PROJECTION, // Projection
null, // Selection
null, // Selection args
FeedContract.Entry.COLUMN_NAME_PUBLISHED + " desc"); // Sort
}
/**
* Move the Cursor returned by the query into the ListView adapter. This refreshes the existing
* UI with the data in the Cursor.
*/
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
mAdapter.changeCursor(cursor);
}
/**
* Called when the ContentObserver defined for the content provider detects that data has
* changed. The ContentObserver resets the loader, and then re-runs the loader. In the adapter,
* set the Cursor value to null. This removes the reference to the Cursor, allowing it to be
* garbage-collected.
*/
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
mAdapter.changeCursor(null);
}
/**
* Create the ActionBar.
*/
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
mOptionsMenu = menu;
inflater.inflate(R.menu.menu_entry_list, menu);
}
/**
* Respond to user gestures on the ActionBar.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// If the user clicks the "Refresh" button.
case R.id.menu_refresh:
SyncUtils.TriggerRefresh();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Load an article in the default browser when selected by the user.
*/
@Override
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
// Get a URI for the selected item, then start an Activity that displays the URI. Any
// Activity that filters for ACTION_VIEW and a URI can accept this. In most cases, this will
// be a browser.
// Get the item at the selected position, in the form of a Cursor.
Cursor c = (Cursor) mAdapter.getItem(position);
// Get the link to the article represented by the item.
String articleUrlString = c.getString(COLUMN_URL_STRING);
if (articleUrlString == null) {
Log.e(TAG, "Attempt to launch entry with null link");
return;
}
Log.i(TAG, "Opening URL: " + articleUrlString);
// Get a Uri object for the URL string
Uri articleURL = Uri.parse(articleUrlString);
Intent i = new Intent(Intent.ACTION_VIEW, articleURL);
startActivity(i);
}
/**
* Set the state of the Refresh button. If a sync is active, turn on the ProgressBar widget.
* Otherwise, turn it off.
*
* @param refreshing True if an active sync is occuring, false otherwise
*/
public void setRefreshActionButtonState(boolean refreshing) {
if (mOptionsMenu == null) {
return;
}
final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_refresh);
if (refreshItem != null) {
if (refreshing) {
refreshItem.setActionView(R.layout.actionbar_indeterminate_progress);
} else {
refreshItem.setActionView(null);
}
}
}
/**
* Crfate a new anonymous SyncStatusObserver. It's attached to the app's ContentResolver in
* onResume(), and removed in onPause(). If status changes, it sets the state of the Refresh
* button. If a sync is active or pending, the Refresh button is replaced by an indeterminate
* ProgressBar; otherwise, the button itself is displayed.
*/
private SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() {
/** Callback invoked with the sync adapter status changes. */
@Override
public void onStatusChanged(int which) {
getActivity().runOnUiThread(new Runnable() {
/**
* The SyncAdapter runs on a background thread. To update the UI, onStatusChanged()
* runs on the UI thread.
*/
@Override
public void run() {
// Create a handle to the account that was created by
// SyncService.CreateSyncAccount(). This will be used to query the system to
// see how the sync status has changed.
Account account = GenericAccountService.GetAccount();
if (account == null) {
// GetAccount() returned an invalid value. This shouldn't happen, but
// we'll set the status to "not refreshing".
setRefreshActionButtonState(false);
return;
}
// Test the ContentResolver to see if the sync adapter is active or pending.
// Set the state of the refresh button accordingly.
boolean syncActive = ContentResolver.isSyncActive(
account, FeedContract.CONTENT_AUTHORITY);
boolean syncPending = ContentResolver.isSyncPending(
account, FeedContract.CONTENT_AUTHORITY);
setRefreshActionButtonState(syncActive || syncPending);
}
});
}
};
}
| |
package im.tny.segvault.disturbances.ui.fragment.top;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.sufficientlysecure.htmltextview.HtmlTextView;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import im.tny.segvault.disturbances.API;
import im.tny.segvault.disturbances.Connectivity;
import im.tny.segvault.disturbances.Coordinator;
import im.tny.segvault.disturbances.MapManager;
import im.tny.segvault.disturbances.ui.adapter.DisturbanceRecyclerViewAdapter;
import im.tny.segvault.disturbances.R;
import im.tny.segvault.disturbances.exception.APIException;
import im.tny.segvault.disturbances.ui.activity.MainActivity;
import im.tny.segvault.disturbances.ui.fragment.TopFragment;
import im.tny.segvault.subway.Network;
/**
* A fragment representing a list of Items.
* <p/>
* Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
* interface.
*/
public class DisturbanceFragment extends TopFragment {
private static final String ARG_COLUMN_COUNT = "column-count";
private int mColumnCount = 1;
private OnListFragmentInteractionListener mListener;
private LinearLayout listContainer;
private RecyclerView recyclerView;
private TextView emptyView;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public DisturbanceFragment() {
}
@Override
public boolean needsTopology() {
return true;
}
@Override
public int getNavDrawerId() {
return R.id.nav_disturbances;
}
@Override
public String getNavDrawerIdAsString() {
return "nav_disturbances";
}
@SuppressWarnings("unused")
public static DisturbanceFragment newInstance(int columnCount) {
DisturbanceFragment fragment = new DisturbanceFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setUpActivity(getString(R.string.frag_disturbances_title), false, true);
setHasOptionsMenu(true);
View view = inflater.inflate(R.layout.fragment_disturbance_list, container, false);
// Set the adapter
Context context = view.getContext();
emptyView = view.findViewById(R.id.no_disturbances_view);
recyclerView = view.findViewById(R.id.list);
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
listContainer = view.findViewById(R.id.list_container);
// fix scroll fling. less than ideal, but apparently there's still no other solution
recyclerView.setNestedScrollingEnabled(false);
HtmlTextView htmltv = view.findViewById(R.id.html_view);
htmltv.setHtml(getString(R.string.frag_disturbances_bottom));
getSwipeRefreshLayout().setRefreshing(true);
IntentFilter filter = new IntentFilter();
filter.addAction(MainActivity.ACTION_MAIN_SERVICE_BOUND);
filter.addAction(MapManager.ACTION_UPDATE_TOPOLOGY_FINISHED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(context);
bm.registerReceiver(mBroadcastReceiver, filter);
new DisturbanceFragment.UpdateDataTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
getSwipeRefreshLayout().setOnRefreshListener(() -> new UpdateDataTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR));
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.disturbance_list, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_refresh) {
new DisturbanceFragment.UpdateDataTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private boolean initialRefresh = true;
private class UpdateDataTask extends AsyncTask<Void, Integer, Boolean> {
private List<DisturbanceRecyclerViewAdapter.DisturbanceItem> items = new ArrayList<>();
@Override
protected void onPreExecute() {
super.onPreExecute();
getSwipeRefreshLayout().setRefreshing(true);
}
protected Boolean doInBackground(Void... v) {
Context context = getContext();
if (getActivity() == null || context == null) {
return false;
}
if (!Connectivity.isConnected(context)) {
return false;
}
if (mListener == null || mListener.getMainService() == null) {
return false;
}
Collection<Network> networks = Coordinator.get(getContext()).getMapManager().getNetworks();
try {
List<API.Disturbance> disturbances = API.getInstance().getDisturbancesSince(new Date(new Date().getTime() - TimeUnit.DAYS.toMillis(14)));
for (API.Disturbance d : disturbances) {
items.add(new DisturbanceRecyclerViewAdapter.DisturbanceItem(d, networks, getContext()));
}
} catch (APIException e) {
return false;
}
Collections.sort(items, Collections.<DisturbanceRecyclerViewAdapter.DisturbanceItem>reverseOrder((disturbanceItem, t1) -> Long.compare(disturbanceItem.startTime.getTime(), t1.startTime.getTime())));
return true;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Boolean result) {
if (!isAdded()) {
// prevent onPostExecute from doing anything if no longer attached to an activity
return;
}
if (result && recyclerView != null && mListener != null) {
recyclerView.setAdapter(new DisturbanceRecyclerViewAdapter(items, mListener));
recyclerView.invalidate();
emptyView.setVisibility(View.GONE);
listContainer.setVisibility(View.VISIBLE);
} else {
if(listContainer != null) {
listContainer.setVisibility(View.GONE);
}
emptyView.setVisibility(View.VISIBLE);
}
getSwipeRefreshLayout().setRefreshing(false);
if (!initialRefresh) {
if (result) {
Snackbar.make(getFloatingActionButton(), R.string.frag_disturbance_updated, Snackbar.LENGTH_SHORT).show();
} else {
Snackbar.make(getFloatingActionButton(), R.string.error_no_connection, Snackbar.LENGTH_SHORT)
.setAction(getString(R.string.error_no_connection_action_retry), view -> new UpdateDataTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)).show();
}
} else {
initialRefresh = false;
}
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnListFragmentInteractionListener extends TopFragment.OnInteractionListener {
void onListFragmentInteraction(DisturbanceRecyclerViewAdapter.DisturbanceItem item);
}
private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (getActivity() == null || intent.getAction() == null) {
return;
}
switch (intent.getAction()) {
case MainActivity.ACTION_MAIN_SERVICE_BOUND:
case MapManager.ACTION_UPDATE_TOPOLOGY_FINISHED:
new DisturbanceFragment.UpdateDataTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
break;
}
}
};
}
| |
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.autoconfigure.web.servlet;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.Filter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.web.servlet.DelegatingFilterProxyRegistrationBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.ServletContextInitializerBeans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultHandler;
import org.springframework.test.web.servlet.result.PrintingResultHandler;
import org.springframework.test.web.servlet.setup.ConfigurableMockMvcBuilder;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.WebApplicationContext;
/**
* {@link MockMvcBuilderCustomizer} for a typical Spring Boot application. Usually applied
* automatically via {@link AutoConfigureMockMvc @AutoConfigureMockMvc}, but may also be
* used directly.
*
* @author Phillip Webb
* @author Andy Wilkinson
* @since 1.4.0
*/
public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomizer {
private final WebApplicationContext context;
private boolean addFilters = true;
private MockMvcPrint print = MockMvcPrint.DEFAULT;
private boolean printOnlyOnFailure = true;
/**
* Create a new {@link SpringBootMockMvcBuilderCustomizer} instance.
* @param context the source application context
*/
public SpringBootMockMvcBuilderCustomizer(WebApplicationContext context) {
Assert.notNull(context, "Context must not be null");
this.context = context;
}
@Override
public void customize(ConfigurableMockMvcBuilder<?> builder) {
if (this.addFilters) {
addFilters(builder);
}
ResultHandler printHandler = getPrintHandler();
if (printHandler != null) {
builder.alwaysDo(printHandler);
}
}
private ResultHandler getPrintHandler() {
LinesWriter writer = getLinesWriter();
if (writer == null) {
return null;
}
if (this.printOnlyOnFailure) {
writer = new DeferredLinesWriter(this.context, writer);
}
return new LinesWritingResultHandler(writer);
}
private LinesWriter getLinesWriter() {
if (this.print == MockMvcPrint.NONE) {
return null;
}
if (this.print == MockMvcPrint.LOG_DEBUG) {
return new LoggingLinesWriter();
}
return new SystemLinesWriter(this.print);
}
private void addFilters(ConfigurableMockMvcBuilder<?> builder) {
ServletContextInitializerBeans Initializers = new ServletContextInitializerBeans(
this.context);
for (ServletContextInitializer initializer : Initializers) {
if (initializer instanceof FilterRegistrationBean) {
addFilter(builder, (FilterRegistrationBean) initializer);
}
if (initializer instanceof DelegatingFilterProxyRegistrationBean) {
addFilter(builder, (DelegatingFilterProxyRegistrationBean) initializer);
}
}
}
private void addFilter(ConfigurableMockMvcBuilder<?> builder,
FilterRegistrationBean registration) {
addFilter(builder, registration.getFilter(), registration.getUrlPatterns());
}
private void addFilter(ConfigurableMockMvcBuilder<?> builder,
DelegatingFilterProxyRegistrationBean registration) {
addFilter(builder, registration.getFilter(), registration.getUrlPatterns());
}
private void addFilter(ConfigurableMockMvcBuilder<?> builder, Filter filter,
Collection<String> urls) {
if (urls.isEmpty()) {
builder.addFilters(filter);
}
else {
builder.addFilter(filter, urls.toArray(new String[urls.size()]));
}
}
public void setAddFilters(boolean addFilters) {
this.addFilters = addFilters;
}
public boolean isAddFilters() {
return this.addFilters;
}
public void setPrint(MockMvcPrint print) {
this.print = print;
}
public MockMvcPrint getPrint() {
return this.print;
}
public void setPrintOnlyOnFailure(boolean printOnlyOnFailure) {
this.printOnlyOnFailure = printOnlyOnFailure;
}
public boolean isPrintOnlyOnFailure() {
return this.printOnlyOnFailure;
}
/**
* {@link ResultHandler} that prints {@link MvcResult} details to a given
* {@link LinesWriter}.
*/
private static class LinesWritingResultHandler implements ResultHandler {
private final LinesWriter writer;
LinesWritingResultHandler(LinesWriter writer) {
this.writer = writer;
}
@Override
public void handle(MvcResult result) throws Exception {
LinesPrintingResultHandler delegate = new LinesPrintingResultHandler();
delegate.handle(result);
delegate.write(this.writer);
}
private static class LinesPrintingResultHandler extends PrintingResultHandler {
protected LinesPrintingResultHandler() {
super(new Printer());
}
public void write(LinesWriter writer) {
writer.write(((Printer) getPrinter()).getLines());
}
private static class Printer implements ResultValuePrinter {
private final List<String> lines = new ArrayList<String>();
@Override
public void printHeading(String heading) {
this.lines.add("");
this.lines.add(String.format("%s:", heading));
}
@Override
public void printValue(String label, Object value) {
if (value != null && value.getClass().isArray()) {
value = CollectionUtils.arrayToList(value);
}
this.lines.add(String.format("%17s = %s", label, value));
}
public List<String> getLines() {
return this.lines;
}
}
}
}
/**
* Strategy interface to write MVC result lines.
*/
interface LinesWriter {
void write(List<String> lines);
}
/**
* {@link LinesWriter} used to defer writing until errors are detected.
* @see MockMvcPrintOnlyOnFailureTestExecutionListener
*/
static class DeferredLinesWriter implements LinesWriter {
private static final String BEAN_NAME = DeferredLinesWriter.class.getName();
private final LinesWriter delegate;
private final List<String> lines = new ArrayList<String>();
DeferredLinesWriter(WebApplicationContext context, LinesWriter delegate) {
Assert.state(context instanceof ConfigurableApplicationContext,
"A ConfigurableApplicationContext is required for printOnlyOnFailure");
((ConfigurableApplicationContext) context).getBeanFactory()
.registerSingleton(BEAN_NAME, this);
this.delegate = delegate;
}
@Override
public void write(List<String> lines) {
this.lines.addAll(lines);
}
public void writeDeferredResult() {
this.delegate.write(this.lines);
}
public static DeferredLinesWriter get(ApplicationContext applicationContext) {
try {
return applicationContext.getBean(BEAN_NAME, DeferredLinesWriter.class);
}
catch (NoSuchBeanDefinitionException ex) {
return null;
}
}
}
/**
* {@link LinesWriter} to output results to the log.
*/
private static class LoggingLinesWriter implements LinesWriter {
private static final Log logger = LogFactory
.getLog("org.springframework.test.web.servlet.result");
@Override
public void write(List<String> lines) {
if (logger.isDebugEnabled()) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
for (String line : lines) {
printWriter.println(line);
}
logger.debug("MvcResult details:\n" + stringWriter);
}
}
}
/**
* {@link LinesWriter} to output results to {@code System.out} or {@code System.err}.
*/
private static class SystemLinesWriter implements LinesWriter {
private final MockMvcPrint print;
SystemLinesWriter(MockMvcPrint print) {
this.print = print;
}
@Override
public void write(List<String> lines) {
PrintStream printStream = getPrintStream();
for (String line : lines) {
printStream.println(line);
}
}
private PrintStream getPrintStream() {
if (this.print == MockMvcPrint.SYSTEM_ERR) {
return System.err;
}
return System.out;
}
}
}
| |
/*
* Copyright 2016 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.blaze.android.run.binary;
import com.android.tools.idea.run.ValidationError;
import com.android.tools.idea.run.util.LaunchUtils;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.google.idea.blaze.android.run.BlazeAndroidRunConfigurationCommonState;
import com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryLaunchMethodsProvider.AndroidBinaryLaunchMethod;
import com.google.idea.blaze.base.run.state.RunConfigurationState;
import com.google.idea.blaze.base.run.state.RunConfigurationStateEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.jdom.Element;
import org.jetbrains.android.facet.AndroidFacet;
/** State specific to the android binary run configuration. */
public final class BlazeAndroidBinaryRunConfigurationState implements RunConfigurationState {
public static final String LAUNCH_DEFAULT_ACTIVITY = "default_activity";
public static final String LAUNCH_SPECIFIC_ACTIVITY = "specific_activity";
public static final String DO_NOTHING = "do_nothing";
public static final String LAUNCH_DEEP_LINK = "launch_deep_link";
private static final String LAUNCH_METHOD_ATTR = "launch-method";
// Remove once v2 becomes default.
private static final String USE_SPLIT_APKS_IF_POSSIBLE = "use-split-apks-if-possible";
private static final String WORK_PROFILE_ATTR = "use-work-profile-if-present";
private static final String USER_ID_ATTR = "user-id";
private AndroidBinaryLaunchMethod launchMethod = AndroidBinaryLaunchMethod.MOBILE_INSTALL;
private boolean useSplitApksIfPossible = false;
private boolean useWorkProfileIfPresent = false;
private Integer userId;
private static final String DEEP_LINK = "DEEP_LINK";
private static final String ACTIVITY_CLASS = "ACTIVITY_CLASS";
private static final String MODE = "MODE";
private static final String ACTIVITY_EXTRA_FLAGS = "ACTIVITY_EXTRA_FLAGS";
private String deepLink = "";
private String activityClass = "";
private String mode = LAUNCH_DEFAULT_ACTIVITY;
private final BlazeAndroidRunConfigurationCommonState commonState;
BlazeAndroidBinaryRunConfigurationState(String buildSystemName) {
commonState = new BlazeAndroidRunConfigurationCommonState(buildSystemName, false);
}
public BlazeAndroidRunConfigurationCommonState getCommonState() {
return commonState;
}
public AndroidBinaryLaunchMethod getLaunchMethod() {
return launchMethod;
}
void setLaunchMethod(AndroidBinaryLaunchMethod launchMethod) {
this.launchMethod = launchMethod;
}
public boolean useSplitApksIfPossible() {
return useSplitApksIfPossible;
}
void setUseSplitApksIfPossible(boolean useSplitApksIfPossible) {
this.useSplitApksIfPossible = useSplitApksIfPossible;
}
public boolean useWorkProfileIfPresent() {
return useWorkProfileIfPresent;
}
void setUseWorkProfileIfPresent(boolean useWorkProfileIfPresent) {
this.useWorkProfileIfPresent = useWorkProfileIfPresent;
}
Integer getUserId() {
return userId;
}
void setUserId(Integer userId) {
this.userId = userId;
}
public String getDeepLink() {
return deepLink;
}
public void setDeepLink(String deepLink) {
this.deepLink = deepLink;
}
public String getActivityClass() {
return activityClass;
}
public void setActivityClass(String activityClass) {
this.activityClass = activityClass;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
/**
* We collect errors rather than throwing to avoid missing fatal errors by exiting early for a
* warning.
*/
public List<ValidationError> validate(@Nullable AndroidFacet facet) {
return commonState.validate(facet);
}
@Override
public void readExternal(Element element) throws InvalidDataException {
commonState.readExternal(element);
setDeepLink(Strings.nullToEmpty(element.getAttributeValue(DEEP_LINK)));
setActivityClass(Strings.nullToEmpty(element.getAttributeValue(ACTIVITY_CLASS)));
String modeValue = element.getAttributeValue(MODE);
setMode(Strings.isNullOrEmpty(modeValue) ? LAUNCH_DEFAULT_ACTIVITY : modeValue);
String launchMethodAttribute = element.getAttributeValue(LAUNCH_METHOD_ATTR);
if (launchMethodAttribute != null) {
launchMethod = AndroidBinaryLaunchMethod.valueOf(launchMethodAttribute);
} else {
launchMethod = AndroidBinaryLaunchMethod.MOBILE_INSTALL;
}
setUseSplitApksIfPossible(
Boolean.parseBoolean(element.getAttributeValue(USE_SPLIT_APKS_IF_POSSIBLE)));
setUseWorkProfileIfPresent(Boolean.parseBoolean(element.getAttributeValue(WORK_PROFILE_ATTR)));
String userIdString = element.getAttributeValue(USER_ID_ATTR);
if (userIdString != null) {
setUserId(Integer.parseInt(userIdString));
}
for (Map.Entry<String, String> entry : getLegacyValues(element).entrySet()) {
String value = entry.getValue();
switch (entry.getKey()) {
case DEEP_LINK:
deepLink = Strings.nullToEmpty(value);
break;
case ACTIVITY_CLASS:
activityClass = Strings.nullToEmpty(value);
break;
case MODE:
mode = Strings.isNullOrEmpty(value) ? LAUNCH_DEFAULT_ACTIVITY : value;
break;
case ACTIVITY_EXTRA_FLAGS:
if (userId == null) {
userId = LaunchUtils.getUserIdFromFlags(value);
}
break;
default:
break;
}
}
}
@Override
public void writeExternal(Element element) throws WriteExternalException {
commonState.writeExternal(element);
element.setAttribute(DEEP_LINK, deepLink);
element.setAttribute(ACTIVITY_CLASS, activityClass);
element.setAttribute(MODE, mode);
element.setAttribute(LAUNCH_METHOD_ATTR, launchMethod.name());
element.setAttribute(USE_SPLIT_APKS_IF_POSSIBLE, Boolean.toString(useSplitApksIfPossible));
element.setAttribute(WORK_PROFILE_ATTR, Boolean.toString(useWorkProfileIfPresent));
if (userId != null) {
element.setAttribute(USER_ID_ATTR, Integer.toString(userId));
} else {
element.removeAttribute(USER_ID_ATTR);
}
}
/** Imports legacy values in the old reflective JDOM externalizer manner. Can be removed ~2.0+. */
private static Map<String, String> getLegacyValues(Element element) {
Map<String, String> result = Maps.newHashMap();
for (Element option : element.getChildren("option")) {
String name = option.getAttributeValue("name");
String value = option.getAttributeValue("value");
result.put(name, value);
}
return result;
}
@Override
public RunConfigurationStateEditor getEditor(Project project) {
return new BlazeAndroidBinaryRunConfigurationStateEditor(
commonState.getEditor(project), project);
}
}
| |
package io.tracee.contextlogger.contextprovider.api;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Unit test for {@link TraceeContextProviderProcessor}
*/
public class TraceeContextProviderProcessorTest {
private TraceeContextProviderProcessor unit = new TraceeContextProviderProcessor();
private RoundEnvironment roundEnvironment;
private ProcessingEnvironment processingEnvironment;
private Messager messager;
private Set<? extends TypeElement> annotationSet;
@Before
public void init() {
roundEnvironment = mock(RoundEnvironment.class);
processingEnvironment = mock(ProcessingEnvironment.class);
messager = mock(Messager.class);
when(processingEnvironment.getMessager()).thenReturn(messager);
unit.init(processingEnvironment);
}
@Test
public void checkIfClassHasNoargsConstructor_WithNoConstructor() {
TypeElement typeElement = mock(TypeElement.class);
List<Element> childElements = new ArrayList<Element>();
TypeElement child1 = mock(TypeElement.class);
when(child1.getKind()).thenReturn(ElementKind.METHOD);
childElements.add(child1);
when(typeElement.getEnclosedElements()).thenReturn((List) childElements);
assertThat(unit.checkIfClassHasNoargsConstructor(typeElement), is(true));
}
@Test
public void checkIfClassHasNoargsConstructor_WithNoArgConstructor() {
TypeElement typeElement = mock(TypeElement.class);
List<Element> childElements = new ArrayList<Element>();
ExecutableElement child1 = mock(ExecutableElement.class);
when(child1.getKind()).thenReturn(ElementKind.CONSTRUCTOR);
when(child1.getParameters()).thenReturn(new ArrayList());
childElements.add(child1);
when(typeElement.getEnclosedElements()).thenReturn((List) childElements);
assertThat(unit.checkIfClassHasNoargsConstructor(typeElement), is(true));
}
@Test
public void checkIfClassHasNoargsConstructor_WithMultipleConstructors() {
TypeElement typeElement = mock(TypeElement.class);
List<Element> childElements = new ArrayList<Element>();
ExecutableElement child1 = mock(ExecutableElement.class);
when(child1.getKind()).thenReturn(ElementKind.CONSTRUCTOR);
when(child1.getParameters()).thenReturn(new ArrayList());
childElements.add(child1);
ExecutableElement child2 = mock(ExecutableElement.class);
when(child2.getKind()).thenReturn(ElementKind.CONSTRUCTOR);
List parameters = new ArrayList();
parameters.add(mock(VariableElement.class));
when(child2.getParameters()).thenReturn(parameters);
childElements.add(child2);
when(typeElement.getEnclosedElements()).thenReturn((List) childElements);
assertThat(unit.checkIfClassHasNoargsConstructor(typeElement), is(true));
}
@Test
public void checkIfClassHasNoargsConstructor_withNoNoargConstructor() {
TypeElement typeElement = mock(TypeElement.class);
List<Element> childElements = new ArrayList<Element>();
ExecutableElement child2 = mock(ExecutableElement.class);
when(child2.getKind()).thenReturn(ElementKind.CONSTRUCTOR);
List parameters = new ArrayList();
parameters.add(mock(VariableElement.class));
when(child2.getParameters()).thenReturn(parameters);
childElements.add(child2);
when(typeElement.getEnclosedElements()).thenReturn((List) childElements);
}
@Test
public void process_validClass() throws IOException {
TraceeContextProviderProcessor spy = Mockito.spy(unit);
ProfileConfig profileConfig = mock(ProfileConfig.class);
when(profileConfig.basic()).thenReturn(true);
when(profileConfig.enhanced()).thenReturn(true);
when(profileConfig.full()).thenReturn(true);
TypeElement typeElement = mock(TypeElement.class);
when(typeElement.getAnnotation(ProfileConfig.class)).thenReturn(profileConfig);
Set<Element> set = new HashSet<Element>();
set.add(typeElement);
when(roundEnvironment.getElementsAnnotatedWith(TraceeContextProvider.class)).thenReturn((Set) set);
doReturn(true).when(spy).isValidClass(typeElement);
doReturn(true).when(spy).checkIfTypeElementIsAssignableToType(typeElement, ImplicitContextData.class);
doReturn(false).when(spy).checkIfTypeElementIsAssignableToType(typeElement, WrappedContextData.class);
doReturn(true).when(spy).checkIfClassHasNoargsConstructor(typeElement);
Mockito.doNothing().when(spy).writeToPropertyFile(Mockito.any(Profile.class), Mockito.any(TypeElement.class), Mockito.any(Boolean.class));
assertThat(spy.process(annotationSet, roundEnvironment), Matchers.is(false));
verify(spy).writeToPropertyFile(Profile.BASIC, typeElement, true);
verify(spy).writeToPropertyFile(Profile.ENHANCED, typeElement, true);
verify(spy).writeToPropertyFile(Profile.FULL, typeElement, true);
verify(spy, never()).error(eq(typeElement), anyString(), anyString(), anyString(), anyString());
}
@Test
public void process_validClassWithMissingProfileSettingsAnnotation() throws IOException {
TraceeContextProviderProcessor spy = Mockito.spy(unit);
ProfileConfig profileConfig = null;
TypeElement typeElement = mock(TypeElement.class);
when(typeElement.getAnnotation(ProfileConfig.class)).thenReturn(profileConfig);
Set<Element> set = new HashSet<Element>();
set.add(typeElement);
when(roundEnvironment.getElementsAnnotatedWith(TraceeContextProvider.class)).thenReturn((Set) set);
doReturn(true).when(spy).isValidClass(typeElement);
doReturn(true).when(spy).checkIfTypeElementIsAssignableToType(typeElement, ImplicitContextData.class);
doReturn(false).when(spy).checkIfTypeElementIsAssignableToType(typeElement, WrappedContextData.class);
doReturn(true).when(spy).checkIfClassHasNoargsConstructor(typeElement);
Mockito.doNothing().when(spy).writeToPropertyFile(Mockito.any(Profile.class), Mockito.any(TypeElement.class), Mockito.any(Boolean.class));
assertThat(spy.process(annotationSet, roundEnvironment), Matchers.is(false));
verify(spy).writeToPropertyFile(Profile.BASIC, typeElement, false);
verify(spy).writeToPropertyFile(Profile.ENHANCED, typeElement, false);
verify(spy).writeToPropertyFile(Profile.FULL, typeElement, true);
verify(spy, never()).error(eq(typeElement), anyString(), anyString(), anyString(), anyString());
}
@Test
public void process_classWithMissingNoargsConstructor() throws IOException {
TraceeContextProviderProcessor spy = Mockito.spy(unit);
ProfileConfig profileConfig = mock(ProfileConfig.class);
when(profileConfig.basic()).thenReturn(true);
when(profileConfig.enhanced()).thenReturn(true);
when(profileConfig.full()).thenReturn(true);
TypeElement typeElement = mock(TypeElement.class);
when(typeElement.getAnnotation(ProfileConfig.class)).thenReturn(profileConfig);
Set<Element> set = new HashSet<Element>();
set.add(typeElement);
when(roundEnvironment.getElementsAnnotatedWith(TraceeContextProvider.class)).thenReturn((Set) set);
doReturn(true).when(spy).isValidClass(typeElement);
doReturn(true).when(spy).checkIfTypeElementIsAssignableToType(typeElement, ImplicitContextData.class);
doReturn(false).when(spy).checkIfTypeElementIsAssignableToType(typeElement, WrappedContextData.class);
doReturn(false).when(spy).checkIfClassHasNoargsConstructor(typeElement);
Mockito.doNothing().when(spy).writeToPropertyFile(Mockito.any(Profile.class), Mockito.any(TypeElement.class), Mockito.any(Boolean.class));
assertThat(spy.process(annotationSet, roundEnvironment), Matchers.is(false));
verify(spy, never()).writeToPropertyFile(Profile.BASIC, typeElement, true);
verify(spy, never()).writeToPropertyFile(Profile.ENHANCED, typeElement, true);
verify(spy, never()).writeToPropertyFile(Profile.FULL, typeElement, true);
verify(spy, times(1)).error(eq(typeElement), anyString(), anyString(), anyString());
}
@Test
public void process_classWithMissingNoargsConstructor2() throws IOException {
TraceeContextProviderProcessor spy = Mockito.spy(unit);
ProfileConfig profileConfig = mock(ProfileConfig.class);
when(profileConfig.basic()).thenReturn(true);
when(profileConfig.enhanced()).thenReturn(true);
when(profileConfig.full()).thenReturn(true);
TypeElement typeElement = mock(TypeElement.class);
when(typeElement.getAnnotation(ProfileConfig.class)).thenReturn(profileConfig);
Set<Element> set = new HashSet<Element>();
set.add(typeElement);
when(roundEnvironment.getElementsAnnotatedWith(TraceeContextProvider.class)).thenReturn((Set) set);
doReturn(true).when(spy).isValidClass(typeElement);
doReturn(false).when(spy).checkIfTypeElementIsAssignableToType(typeElement, ImplicitContextData.class);
doReturn(true).when(spy).checkIfTypeElementIsAssignableToType(typeElement, WrappedContextData.class);
doReturn(false).when(spy).checkIfClassHasNoargsConstructor(typeElement);
Mockito.doNothing().when(spy).writeToPropertyFile(Mockito.any(Profile.class), Mockito.any(TypeElement.class), Mockito.any(Boolean.class));
assertThat(spy.process(annotationSet, roundEnvironment), Matchers.is(false));
verify(spy, never()).writeToPropertyFile(Profile.BASIC, typeElement, true);
verify(spy, never()).writeToPropertyFile(Profile.ENHANCED, typeElement, true);
verify(spy, never()).writeToPropertyFile(Profile.FULL, typeElement, true);
verify(spy, times(1)).error(eq(typeElement), anyString(), anyString(), anyString());
}
@Test
public void process_invalidClass() throws IOException {
TraceeContextProviderProcessor spy = Mockito.spy(unit);
ProfileConfig profileConfig = mock(ProfileConfig.class);
when(profileConfig.basic()).thenReturn(true);
when(profileConfig.enhanced()).thenReturn(true);
when(profileConfig.full()).thenReturn(true);
TypeElement typeElement = mock(TypeElement.class);
when(typeElement.getAnnotation(ProfileConfig.class)).thenReturn(profileConfig);
Set<Element> set = new HashSet<Element>();
set.add(typeElement);
when(roundEnvironment.getElementsAnnotatedWith(TraceeContextProvider.class)).thenReturn((Set) set);
doReturn(false).when(spy).isValidClass(typeElement);
doReturn(true).when(spy).checkIfTypeElementIsAssignableToType(typeElement, ImplicitContextData.class);
doReturn(false).when(spy).checkIfTypeElementIsAssignableToType(typeElement, WrappedContextData.class);
doReturn(true).when(spy).checkIfClassHasNoargsConstructor(typeElement);
Mockito.doNothing().when(spy).writeToPropertyFile(Mockito.any(Profile.class), Mockito.any(TypeElement.class), Mockito.any(Boolean.class));
assertThat(spy.process(annotationSet, roundEnvironment), Matchers.is(false));
verify(spy, never()).writeToPropertyFile(Profile.BASIC, typeElement, true);
verify(spy, never()).writeToPropertyFile(Profile.ENHANCED, typeElement, true);
verify(spy, never()).writeToPropertyFile(Profile.FULL, typeElement, true);
verify(spy, never()).error(eq(typeElement), anyString(), anyString(), anyString(), anyString());
}
}
| |
/**
* Copyright 2014 yangming.liu<liuyangming@gmail.com>.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, see <http://www.gnu.org/licenses/>.
*/
package org.bytesoft.openjtcc.recovery;
import java.rmi.RemoteException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.RollbackException;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.TransactionManager;
import org.bytesoft.openjtcc.TransactionImpl;
import org.bytesoft.openjtcc.TransactionManagerImpl;
import org.bytesoft.openjtcc.archive.CompensableArchive;
import org.bytesoft.openjtcc.archive.TerminatorArchive;
import org.bytesoft.openjtcc.archive.TransactionArchive;
import org.bytesoft.openjtcc.common.TransactionContext;
import org.bytesoft.openjtcc.common.TransactionStatus;
import org.bytesoft.openjtcc.supports.TransactionLogger;
import org.bytesoft.openjtcc.supports.TransactionRepository;
import org.bytesoft.openjtcc.supports.TransactionStatistic;
import org.bytesoft.openjtcc.xa.XidImpl;
public class RecoveryManager {
private TransactionManager transactionManager;
private TransactionStatistic transactionStatistic;
public void reconstruct() {
TransactionRepository repository = this.getTransactionRepository();
TransactionLogger transactionLogger = repository.getTransactionLogger();
Set<TransactionArchive> transactions = transactionLogger.getLoggedTransactionSet();
Iterator<TransactionArchive> itr = transactions.iterator();
while (itr.hasNext()) {
TransactionArchive archive = itr.next();
RecoveredTransactionImpl transaction = this.reconstructTransaction(archive);
TransactionContext transactionContext = transaction.getTransactionContext();
XidImpl globalXid = transactionContext.getGlobalXid();
repository.putTransaction(globalXid, transaction);
repository.putErrorTransaction(globalXid, transaction);
this.transactionStatistic.fireRecoverTransaction(transaction);
}
}
public RecoveredTransactionImpl reconstructTransaction(TransactionArchive archive) {
TransactionRepository repository = this.getTransactionRepository();
TransactionManagerImpl txManager = (TransactionManagerImpl) this.transactionManager;
RecoveredTransactionImpl transaction = new RecoveredTransactionImpl();
transaction.setTransactionStatistic(txManager.getTransactionStatistic());
TransactionContext transactionContext = archive.getTransactionContext();
// transaction.setTransactionRecovery(true);
TransactionStatus transactionStatus = archive.getTransactionStatus();
transaction.setTransactionContext(transactionContext);
transaction.setTransactionStatus(transactionStatus);
transaction.setTransactionManager(txManager);
transaction.setTransactionLogger(repository.getTransactionLogger());
transaction.getXidToNativeSvrMap().putAll(archive.getXidToNativeSvrMap());
transaction.getAppToTerminatorMap().putAll(archive.getAppToTerminatorMap());
if (transactionStatus.isActive()) {
transaction.setRecoveryRollbackOnly(true);
} else if (transactionStatus.isMarkedRollbackOnly()) {
transaction.setRecoveryRollbackOnly(true);
} else if (transactionStatus.isPreparing()) {
this.confirmPreparedTerminator(transaction);
if (transaction.isRecoveryRollbackOnly()) {
// ignore
} else {
this.confirmPreparedLaunchService(transaction);
}
} else if (transactionStatus.isPrepared()) {
this.confirmPreparedLaunchService(transaction);
} else if (transactionStatus.isRollingBack()) {
transaction.setRecoveryRollbackOnly(true);
} else if (transactionStatus.isRolledBack()) {
transaction.setRecoveryRollbackOnly(true);
}
return transaction;
}
private void confirmPreparedLaunchService(RecoveredTransactionImpl transaction) {
Map<XidImpl, CompensableArchive> xidToSvcMap = transaction.getXidToNativeSvrMap();
Iterator<Map.Entry<XidImpl, CompensableArchive>> itr = xidToSvcMap.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry<XidImpl, CompensableArchive> entry = itr.next();
CompensableArchive holder = entry.getValue();
if (holder.launchSvc) {
TransactionStatus transactionStatus = transaction.getTransactionStatus();
int statusTrace = transactionStatus.getInnerStatusTrace();
int xorStatus = TransactionStatus.STATUS_MARKED_ROLLBACK & statusTrace;
boolean rollbackRequired = (xorStatus == TransactionStatus.STATUS_MARKED_ROLLBACK);
if (rollbackRequired) {
transaction.setRecoveryRollbackOnly(true);
} else if (holder.tryCommitted) {
transaction.setRecoveryRollbackOnly(false);
} else {
transaction.setRecoveryRollbackOnly(true);
}
}
}
}
private void confirmPreparedTerminator(RecoveredTransactionImpl transaction) {
Map<String, TerminatorArchive> appToTerminatorMap = transaction.getAppToTerminatorMap();
Iterator<Map.Entry<String, TerminatorArchive>> itr = appToTerminatorMap.entrySet().iterator();
boolean errorExists = false;
while (itr.hasNext()) {
Map.Entry<String, TerminatorArchive> entry = itr.next();
TerminatorArchive holder = entry.getValue();
if (holder.prepared) {
// ignore
} else {
errorExists = true;
break;
}
}
if (errorExists) {
transaction.setRecoveryRollbackOnly(true);
}
}
/**
* commit/rollback the uncompleted transactions.
*/
public void recover() {
TransactionRepository repository = this.getTransactionRepository();
Iterator<TransactionImpl> itr = repository.getErrorTransactionSet().iterator();
while (itr.hasNext()) {
TransactionImpl transaction = itr.next();
try {
this.recoverTransaction(transaction);
} catch (HeuristicMixedException ex) {
ex.printStackTrace();
} catch (SystemException ex) {
ex.printStackTrace();
} catch (RuntimeException ex) {
ex.printStackTrace();
}
}
}
/**
* commit/rollback the specific transaction.
*
* @param globalXid
* @throws HeuristicMixedException
* @throws SystemException
*/
public void recoverTransaction(XidImpl globalXid) throws HeuristicMixedException, SystemException {
TransactionRepository repository = this.getTransactionRepository();
TransactionImpl transaction = repository.getErrorTransaction(globalXid);
this.recoverTransaction(transaction);
}
public void recoverTransaction(TransactionImpl transaction) throws HeuristicMixedException, SystemException {
TransactionManagerImpl txManager = this.getTransactionManagerImpl();
try {
txManager.associateTransaction(transaction);
if (RecoveredTransactionImpl.class.isInstance(transaction)) {
RecoveredTransactionImpl recoveredTransaction = (RecoveredTransactionImpl) transaction;
this.recoveredTransactionRecovery(recoveredTransaction);
} else {
this.activeTransactionRecovery(transaction);
}
} finally {
txManager.unassociateTransaction();
}
}
private void recoveredTransactionRecovery(RecoveredTransactionImpl transaction) throws HeuristicMixedException,
SystemException {
TransactionContext transactionContext = transaction.getTransactionContext();
TransactionStatus transactionStatus = transaction.getTransactionStatus();
if (transactionContext.isCoordinator()) {
if (transaction.isRecoveryRollbackOnly()) {
transaction.rollback();
} else {
try {
transaction.commit();
} catch (SecurityException ex) {
// ignore
} catch (HeuristicRollbackException ex) {
// ignore
} catch (RollbackException ex) {
// ignore
}
}
} else if (transactionStatus.isActive() || transactionStatus.isMarkedRollbackOnly()) {
transaction.rollback();
try {
transaction.cleanup();
} catch (Exception rex) {
SystemException exception = new SystemException();
exception.initCause(rex);
throw exception;
}
}
}
private void activeTransactionRecovery(TransactionImpl transaction) throws HeuristicMixedException, SystemException {
TransactionContext transactionContext = transaction.getTransactionContext();
if (transactionContext.isCoordinator()) {
this.coordinateTransactionRecovery(transaction);
}
}
private void coordinateTransactionRecovery(TransactionImpl transaction) throws HeuristicMixedException,
SystemException {
TransactionStatus status = transaction.getTransactionStatus();
switch (status.getTransactionStatus()) {
case Status.STATUS_ACTIVE:
case Status.STATUS_MARKED_ROLLBACK:
transaction.rollback();
break;
case Status.STATUS_PREPARING:
transaction.rollback();
break;
case Status.STATUS_PREPARED:
case Status.STATUS_COMMITTING:
try {
transaction.commit();
} catch (SecurityException ex) {
// ignore
} catch (HeuristicRollbackException ex) {
// ignore
} catch (RollbackException ex) {
// ignore
}
break;
case Status.STATUS_ROLLING_BACK:
transaction.rollback();
break;
case Status.STATUS_COMMITTED:
case Status.STATUS_ROLLEDBACK:
try {
transaction.cleanup();
} catch (RemoteException rex) {
SystemException exception = new SystemException();
exception.initCause(rex);
throw exception;
} catch (RuntimeException rex) {
SystemException exception = new SystemException();
exception.initCause(rex);
throw exception;
}
break;
case Status.STATUS_UNKNOWN:
// should be processed manually.
throw new SystemException();
default:
throw new SystemException();
}
}
public TransactionRepository getTransactionRepository() {
TransactionManagerImpl txm = (TransactionManagerImpl) this.transactionManager;
return txm.getTransactionRepository();
}
public TransactionManagerImpl getTransactionManagerImpl() {
return (TransactionManagerImpl) transactionManager;
}
public TransactionManager getTransactionManager() {
return transactionManager;
}
public void setTransactionManager(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public void setTransactionStatistic(TransactionStatistic transactionStatistic) {
this.transactionStatistic = transactionStatistic;
}
}
| |
/*
* 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.psi.impl.source.tree;
import com.intellij.lang.ASTNode;
import com.intellij.lang.FileASTNode;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.*;
import com.intellij.psi.impl.CheckUtil;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.psi.impl.source.codeStyle.CodeEditUtil;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.CharTable;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
//TODO: rename/regroup?
public class SharedImplUtil {
private static final Logger LOG = Logger.getInstance(SharedImplUtil.class);
private static final boolean CHECK_FOR_READ_ACTION = DebugUtil.DO_EXPENSIVE_CHECKS || ApplicationManager.getApplication().isInternal();
private SharedImplUtil() {
}
public static PsiElement getParent(ASTNode thisElement) {
if (CHECK_FOR_READ_ACTION && thisElement instanceof TreeElement) {
((TreeElement)thisElement).assertReadAccessAllowed();
}
return SourceTreeToPsiMap.treeElementToPsi(thisElement.getTreeParent());
}
public static PsiElement getFirstChild(@NotNull ASTNode element) {
return SourceTreeToPsiMap.treeElementToPsi(element.getFirstChildNode());
}
@Nullable
public static PsiElement getLastChild(@NotNull ASTNode element) {
return SourceTreeToPsiMap.treeElementToPsi(element.getLastChildNode());
}
public static PsiElement getNextSibling(@NotNull ASTNode thisElement) {
return SourceTreeToPsiMap.treeElementToPsi(thisElement.getTreeNext());
}
public static PsiElement getPrevSibling(@NotNull ASTNode thisElement) {
return SourceTreeToPsiMap.treeElementToPsi(thisElement.getTreePrev());
}
public static PsiFile getContainingFile(@NotNull ASTNode thisElement) {
FileASTNode node = findFileElement(thisElement);
PsiElement psi = node == null ? null : node.getPsi();
if (psi == null || psi instanceof PsiFile) return (PsiFile)psi;
throw new AssertionError("Invalid PSI " + psi + " of " + psi.getClass() + " for AST " + node + " of " + node.getClass());
}
public static boolean isValid(ASTNode thisElement) {
LOG.assertTrue(thisElement instanceof PsiElement);
PsiFile file = getContainingFile(thisElement);
return file != null && file.isValid();
}
public static boolean isWritable(ASTNode thisElement) {
PsiFile file = getContainingFile(thisElement);
return file == null || file.isWritable();
}
public static FileASTNode findFileElement(@NotNull ASTNode element) {
ASTNode parent = element.getTreeParent();
while (parent != null) {
element = parent;
parent = parent.getTreeParent();
}
if (CHECK_FOR_READ_ACTION && element instanceof TreeElement) {
((TreeElement)element).assertReadAccessAllowed();
}
if (element instanceof FileASTNode) {
return (FileASTNode)element;
}
return null;
}
@NotNull
public static CharTable findCharTableByTree(ASTNode tree) {
for (ASTNode o = tree; o != null; o = o.getTreeParent()) {
CharTable charTable = o.getUserData(CharTable.CHAR_TABLE_KEY);
if (charTable != null) {
return charTable;
}
if (o instanceof FileASTNode) {
return ((FileASTNode)o).getCharTable();
}
}
throw new AssertionError("CharTable not found in: " + tree);
}
public static PsiElement addRange(PsiElement thisElement,
PsiElement first,
PsiElement last,
ASTNode anchor,
Boolean before) throws IncorrectOperationException {
CheckUtil.checkWritable(thisElement);
final CharTable table = findCharTableByTree(SourceTreeToPsiMap.psiElementToTree(thisElement));
TreeElement copyFirst = null;
ASTNode copyLast = null;
ASTNode next = SourceTreeToPsiMap.psiElementToTree(last).getTreeNext();
ASTNode parent = null;
for (ASTNode element = SourceTreeToPsiMap.psiElementToTree(first); element != next; element = element.getTreeNext()) {
TreeElement elementCopy = ChangeUtil.copyElement((TreeElement)element, table);
if (element == first.getNode()) {
copyFirst = elementCopy;
}
if (element == last.getNode()) {
copyLast = elementCopy;
}
if (parent == null) {
parent = elementCopy.getTreeParent();
}
else {
if(elementCopy.getElementType() == TokenType.WHITE_SPACE)
CodeEditUtil.setNodeGenerated(elementCopy, true);
parent.addChild(elementCopy, null);
}
}
if (copyFirst == null) return null;
copyFirst = ((CompositeElement)SourceTreeToPsiMap.psiElementToTree(thisElement)).addInternal(copyFirst, copyLast, anchor, before);
for (TreeElement element = copyFirst; element != null; element = element.getTreeNext()) {
element = ChangeUtil.decodeInformation(element);
if (element.getTreePrev() == null) {
copyFirst = element;
}
}
return SourceTreeToPsiMap.treeElementToPsi(copyFirst);
}
public static PsiManager getManagerByTree(final ASTNode node) {
if(node instanceof FileElement) return node.getPsi().getManager();
return node.getTreeParent().getPsi().getManager();
}
public static ASTNode @NotNull [] getChildrenOfType(@NotNull ASTNode node, @NotNull IElementType elementType) {
int count = countChildrenOfType(node, elementType);
if (count == 0) {
return ASTNode.EMPTY_ARRAY;
}
final ASTNode[] result = new ASTNode[count];
count = 0;
for (ASTNode child = node.getFirstChildNode(); child != null; child = child.getTreeNext()) {
if (child.getElementType() == elementType) {
result[count++] = child;
}
}
return result;
}
private static int countChildrenOfType(@NotNull ASTNode node, @NotNull IElementType elementType) {
// no lock is needed because all chameleons are expanded already
int count = 0;
for (ASTNode child = node.getFirstChildNode(); child != null; child = child.getTreeNext()) {
if (child.getElementType() == elementType) {
count++;
}
}
return count;
}
public static void acceptChildren(@NotNull PsiElementVisitor visitor, @NotNull ASTNode root) {
ASTNode childNode = root.getFirstChildNode();
while (childNode != null) {
final PsiElement psi;
if (childNode instanceof PsiElement) {
psi = (PsiElement)childNode;
}
else {
psi = childNode.getPsi();
}
psi.accept(visitor);
childNode = childNode.getTreeNext();
}
}
public static PsiElement doReplace(@NotNull PsiElement psiElement, @NotNull TreeElement treeElement, @NotNull PsiElement newElement) {
CompositeElement treeParent = treeElement.getTreeParent();
LOG.assertTrue(treeParent != null);
CheckUtil.checkWritable(psiElement);
TreeElement elementCopy = ChangeUtil.copyToElement(newElement);
treeParent.replaceChildInternal(treeElement, elementCopy);
elementCopy = ChangeUtil.decodeInformation(elementCopy);
final PsiElement result = SourceTreeToPsiMap.treeElementToPsi(elementCopy);
treeElement.invalidate();
return result;
}
}
| |
package com.compositesw.services.system.admin;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Holder;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
import com.compositesw.services.system.admin.archive.ArchiveContents;
import com.compositesw.services.system.admin.archive.ExportSettings;
import com.compositesw.services.system.admin.archive.ImportSettings;
import com.compositesw.services.system.util.common.MessageEntryList;
import com.compositesw.services.system.util.common.OperationStatus;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.1-b01-
* Generated source version: 2.2
*
*/
@WebService(name = "archivePortType", targetNamespace = "http://www.compositesw.com/services/system/admin")
@XmlSeeAlso({
com.compositesw.services.system.admin.user.ObjectFactory.class,
com.compositesw.services.system.admin.archive.ObjectFactory.class,
com.compositesw.services.system.util.common.ObjectFactory.class,
com.compositesw.services.system.util.security.ObjectFactory.class,
com.compositesw.services.system.admin.resource.ObjectFactory.class,
com.compositesw.services.system.admin.execute.ObjectFactory.class,
com.compositesw.services.system.admin.server.ObjectFactory.class
})
public interface ArchivePortType {
/**
*
* @param status
* @param archiveId
* @param archiveReport
* @throws CancelArchiveSoapFault
*/
@WebMethod(action = "cancelArchive")
@RequestWrapper(localName = "cancelArchive", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.CancelArchiveRequest")
@ResponseWrapper(localName = "cancelArchiveResponse", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.CancelArchiveResponse")
public void cancelArchive(
@WebParam(name = "archiveId", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
String archiveId,
@WebParam(name = "status", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", mode = WebParam.Mode.OUT)
Holder<OperationStatus> status,
@WebParam(name = "archiveReport", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", mode = WebParam.Mode.OUT)
Holder<MessageEntryList> archiveReport)
throws CancelArchiveSoapFault
;
/**
*
* @param settings
* @return
* returns java.lang.String
* @throws CreateExportArchiveSoapFault
*/
@WebMethod(action = "createExportArchive")
@WebResult(name = "archiveId", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
@RequestWrapper(localName = "createExportArchive", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.CreateExportArchiveRequest")
@ResponseWrapper(localName = "createExportArchiveResponse", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.CreateExportArchiveResponse")
public String createExportArchive(
@WebParam(name = "settings", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
ExportSettings settings)
throws CreateExportArchiveSoapFault
;
/**
*
* @param data
* @return
* returns java.lang.String
* @throws CreateImportArchiveSoapFault
*/
@WebMethod(action = "createImportArchive")
@WebResult(name = "archiveId", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
@RequestWrapper(localName = "createImportArchive", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.CreateImportArchiveRequest")
@ResponseWrapper(localName = "createImportArchiveResponse", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.CreateImportArchiveResponse")
public String createImportArchive(
@WebParam(name = "data", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
byte[] data)
throws CreateImportArchiveSoapFault
;
/**
*
* @param archiveId
* @return
* returns com.compositesw.services.system.admin.archive.ArchiveContents
* @throws GetArchiveContentsSoapFault
*/
@WebMethod(action = "getArchiveContents")
@WebResult(name = "contents", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
@RequestWrapper(localName = "getArchiveContents", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.GetArchiveContentsRequest")
@ResponseWrapper(localName = "getArchiveContentsResponse", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.GetArchiveContentsResponse")
public ArchiveContents getArchiveContents(
@WebParam(name = "archiveId", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
String archiveId)
throws GetArchiveContentsSoapFault
;
/**
*
* @param status
* @param archiveId
* @param archiveReport
* @param data
* @param maxBytes
* @throws GetArchiveExportDataSoapFault
*/
@WebMethod(action = "getArchiveExportData")
@RequestWrapper(localName = "getArchiveExportData", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.GetArchiveExportDataRequest")
@ResponseWrapper(localName = "getArchiveExportDataResponse", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.GetArchiveExportDataResponse")
public void getArchiveExportData(
@WebParam(name = "archiveId", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
String archiveId,
@WebParam(name = "maxBytes", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
Integer maxBytes,
@WebParam(name = "status", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", mode = WebParam.Mode.OUT)
Holder<OperationStatus> status,
@WebParam(name = "archiveReport", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", mode = WebParam.Mode.OUT)
Holder<MessageEntryList> archiveReport,
@WebParam(name = "data", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", mode = WebParam.Mode.OUT)
Holder<byte[]> data)
throws GetArchiveExportDataSoapFault
;
/**
*
* @param archiveId
* @return
* returns com.compositesw.services.system.admin.archive.ExportSettings
* @throws GetArchiveExportSettingsSoapFault
*/
@WebMethod(action = "getArchiveExportSettings")
@WebResult(name = "settings", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
@RequestWrapper(localName = "getArchiveExportSettings", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.GetArchiveExportSettingsRequest")
@ResponseWrapper(localName = "getArchiveExportSettingsResponse", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.GetArchiveExportSettingsResponse")
public ExportSettings getArchiveExportSettings(
@WebParam(name = "archiveId", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
String archiveId)
throws GetArchiveExportSettingsSoapFault
;
/**
*
* @param status
* @param archiveId
* @param archiveReport
* @param isBlocking
* @throws GetArchiveImportReportSoapFault
*/
@WebMethod(action = "getArchiveImportReport")
@RequestWrapper(localName = "getArchiveImportReport", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.GetArchiveImportReportRequest")
@ResponseWrapper(localName = "getArchiveImportReportResponse", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.GetArchiveImportReportResponse")
public void getArchiveImportReport(
@WebParam(name = "archiveId", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
String archiveId,
@WebParam(name = "isBlocking", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
boolean isBlocking,
@WebParam(name = "status", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", mode = WebParam.Mode.OUT)
Holder<OperationStatus> status,
@WebParam(name = "archiveReport", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", mode = WebParam.Mode.OUT)
Holder<MessageEntryList> archiveReport)
throws GetArchiveImportReportSoapFault
;
/**
*
* @param archiveId
* @return
* returns com.compositesw.services.system.admin.archive.ImportSettings
* @throws GetArchiveImportSettingsSoapFault
*/
@WebMethod(action = "getArchiveImportSettings")
@WebResult(name = "settings", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
@RequestWrapper(localName = "getArchiveImportSettings", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.GetArchiveImportSettingsRequest")
@ResponseWrapper(localName = "getArchiveImportSettingsResponse", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.GetArchiveImportSettingsResponse")
public ImportSettings getArchiveImportSettings(
@WebParam(name = "archiveId", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
String archiveId)
throws GetArchiveImportSettingsSoapFault
;
/**
*
* @param status
* @param archiveId
* @param archiveReport
* @param isBlocking
* @throws PerformArchiveImportSoapFault
*/
@WebMethod(action = "performArchiveImport")
@RequestWrapper(localName = "performArchiveImport", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.PerformArchiveImportRequest")
@ResponseWrapper(localName = "performArchiveImportResponse", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.PerformArchiveImportResponse")
public void performArchiveImport(
@WebParam(name = "archiveId", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
String archiveId,
@WebParam(name = "isBlocking", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
boolean isBlocking,
@WebParam(name = "status", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", mode = WebParam.Mode.OUT)
Holder<OperationStatus> status,
@WebParam(name = "archiveReport", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", mode = WebParam.Mode.OUT)
Holder<MessageEntryList> archiveReport)
throws PerformArchiveImportSoapFault
;
/**
*
* @param archiveId
* @param settings
* @throws UpdateArchiveExportSettingsSoapFault
*/
@WebMethod(action = "updateArchiveExportSettings")
@RequestWrapper(localName = "updateArchiveExportSettings", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.UpdateArchiveExportSettingsRequest")
@ResponseWrapper(localName = "updateArchiveExportSettingsResponse", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.UpdateArchiveExportSettingsResponse")
public void updateArchiveExportSettings(
@WebParam(name = "archiveId", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
String archiveId,
@WebParam(name = "settings", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
ExportSettings settings)
throws UpdateArchiveExportSettingsSoapFault
;
/**
*
* @param archiveId
* @param settings
* @throws UpdateArchiveImportSettingsSoapFault
*/
@WebMethod(action = "updateArchiveImportSettings")
@RequestWrapper(localName = "updateArchiveImportSettings", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.UpdateArchiveImportSettingsRequest")
@ResponseWrapper(localName = "updateArchiveImportSettingsResponse", targetNamespace = "http://www.compositesw.com/services/system/admin/archive", className = "com.compositesw.services.system.admin.archive.UpdateArchiveImportSettingsResponse")
public void updateArchiveImportSettings(
@WebParam(name = "archiveId", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
String archiveId,
@WebParam(name = "settings", targetNamespace = "http://www.compositesw.com/services/system/admin/archive")
ImportSettings settings)
throws UpdateArchiveImportSettingsSoapFault
;
}
| |
/**
* Generated with Acceleo
*/
package com.github.lbroudoux.dsl.eip.parts.forms;
// Start of user code for imports
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent;
import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart;
import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.part.impl.SectionPropertiesEditingPart;
import org.eclipse.emf.eef.runtime.ui.parts.PartComposer;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.BindingCompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionStep;
import org.eclipse.emf.eef.runtime.ui.utils.EditingUtils;
import org.eclipse.emf.eef.runtime.ui.widgets.ButtonsModeEnum;
import org.eclipse.emf.eef.runtime.ui.widgets.EObjectFlatComboViewer;
import org.eclipse.emf.eef.runtime.ui.widgets.FormUtils;
import org.eclipse.emf.eef.runtime.ui.widgets.eobjflatcombo.EObjectFlatComboSettings;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.views.properties.tabbed.ISection;
import com.github.lbroudoux.dsl.eip.parts.EipViewsRepository;
import com.github.lbroudoux.dsl.eip.parts.ServiceInvocationPropertiesEditionPart;
import com.github.lbroudoux.dsl.eip.providers.EipMessages;
// End of user code
/**
* @author yanngv29
*
*/
public class ServiceInvocationPropertiesEditionPartForm extends SectionPropertiesEditingPart implements IFormPropertiesEditionPart, ServiceInvocationPropertiesEditionPart {
protected Text context;
protected Text operationName;
protected EObjectFlatComboViewer serviceRef;
/**
* For {@link ISection} use only.
*/
public ServiceInvocationPropertiesEditionPartForm() { super(); }
/**
* Default constructor
* @param editionComponent the {@link IPropertiesEditionComponent} that manage this part
*
*/
public ServiceInvocationPropertiesEditionPartForm(IPropertiesEditionComponent editionComponent) {
super(editionComponent);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
* createFigure(org.eclipse.swt.widgets.Composite, org.eclipse.ui.forms.widgets.FormToolkit)
*
*/
public Composite createFigure(final Composite parent, final FormToolkit widgetFactory) {
ScrolledForm scrolledForm = widgetFactory.createScrolledForm(parent);
Form form = scrolledForm.getForm();
view = form.getBody();
GridLayout layout = new GridLayout();
layout.numColumns = 3;
view.setLayout(layout);
createControls(widgetFactory, view);
return scrolledForm;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
* createControls(org.eclipse.ui.forms.widgets.FormToolkit, org.eclipse.swt.widgets.Composite)
*
*/
public void createControls(final FormToolkit widgetFactory, Composite view) {
CompositionSequence serviceInvocationStep = new BindingCompositionSequence(propertiesEditionComponent);
CompositionStep propertiesStep = serviceInvocationStep.addStep(EipViewsRepository.ServiceInvocation.Properties.class);
propertiesStep.addStep(EipViewsRepository.ServiceInvocation.Properties.context);
propertiesStep.addStep(EipViewsRepository.ServiceInvocation.Properties.operationName);
propertiesStep.addStep(EipViewsRepository.ServiceInvocation.Properties.serviceRef);
composer = new PartComposer(serviceInvocationStep) {
@Override
public Composite addToPart(Composite parent, Object key) {
if (key == EipViewsRepository.ServiceInvocation.Properties.class) {
return createPropertiesGroup(widgetFactory, parent);
}
if (key == EipViewsRepository.ServiceInvocation.Properties.context) {
return createContextText(widgetFactory, parent);
}
if (key == EipViewsRepository.ServiceInvocation.Properties.operationName) {
return createOperationNameText(widgetFactory, parent);
}
if (key == EipViewsRepository.ServiceInvocation.Properties.serviceRef) {
return createServiceRefFlatComboViewer(parent, widgetFactory);
}
return parent;
}
};
composer.compose(view);
}
/**
*
*/
protected Composite createPropertiesGroup(FormToolkit widgetFactory, final Composite parent) {
Section propertiesSection = widgetFactory.createSection(parent, Section.TITLE_BAR | Section.TWISTIE | Section.EXPANDED);
propertiesSection.setText(EipMessages.ServiceInvocationPropertiesEditionPart_PropertiesGroupLabel);
GridData propertiesSectionData = new GridData(GridData.FILL_HORIZONTAL);
propertiesSectionData.horizontalSpan = 3;
propertiesSection.setLayoutData(propertiesSectionData);
Composite propertiesGroup = widgetFactory.createComposite(propertiesSection);
GridLayout propertiesGroupLayout = new GridLayout();
propertiesGroupLayout.numColumns = 3;
propertiesGroup.setLayout(propertiesGroupLayout);
propertiesSection.setClient(propertiesGroup);
return propertiesGroup;
}
protected Composite createContextText(FormToolkit widgetFactory, Composite parent) {
createDescription(parent, EipViewsRepository.ServiceInvocation.Properties.context, EipMessages.ServiceInvocationPropertiesEditionPart_ContextLabel);
context = widgetFactory.createText(parent, ""); //$NON-NLS-1$
context.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
widgetFactory.paintBordersFor(parent);
GridData contextData = new GridData(GridData.FILL_HORIZONTAL);
context.setLayoutData(contextData);
context.addFocusListener(new FocusAdapter() {
/**
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(
ServiceInvocationPropertiesEditionPartForm.this,
EipViewsRepository.ServiceInvocation.Properties.context,
PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, context.getText()));
propertiesEditionComponent
.firePropertiesChanged(new PropertiesEditionEvent(
ServiceInvocationPropertiesEditionPartForm.this,
EipViewsRepository.ServiceInvocation.Properties.context,
PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_LOST,
null, context.getText()));
}
}
/**
* @see org.eclipse.swt.events.FocusAdapter#focusGained(org.eclipse.swt.events.FocusEvent)
*/
@Override
public void focusGained(FocusEvent e) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent
.firePropertiesChanged(new PropertiesEditionEvent(
ServiceInvocationPropertiesEditionPartForm.this,
null,
PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_GAINED,
null, null));
}
}
});
context.addKeyListener(new KeyAdapter() {
/**
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(ServiceInvocationPropertiesEditionPartForm.this, EipViewsRepository.ServiceInvocation.Properties.context, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, context.getText()));
}
}
});
EditingUtils.setID(context, EipViewsRepository.ServiceInvocation.Properties.context);
EditingUtils.setEEFtype(context, "eef::Text"); //$NON-NLS-1$
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EipViewsRepository.ServiceInvocation.Properties.context, EipViewsRepository.FORM_KIND), null); //$NON-NLS-1$
// Start of user code for createContextText
// End of user code
return parent;
}
protected Composite createOperationNameText(FormToolkit widgetFactory, Composite parent) {
createDescription(parent, EipViewsRepository.ServiceInvocation.Properties.operationName, EipMessages.ServiceInvocationPropertiesEditionPart_OperationNameLabel);
operationName = widgetFactory.createText(parent, ""); //$NON-NLS-1$
operationName.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
widgetFactory.paintBordersFor(parent);
GridData operationNameData = new GridData(GridData.FILL_HORIZONTAL);
operationName.setLayoutData(operationNameData);
operationName.addFocusListener(new FocusAdapter() {
/**
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(
ServiceInvocationPropertiesEditionPartForm.this,
EipViewsRepository.ServiceInvocation.Properties.operationName,
PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, operationName.getText()));
propertiesEditionComponent
.firePropertiesChanged(new PropertiesEditionEvent(
ServiceInvocationPropertiesEditionPartForm.this,
EipViewsRepository.ServiceInvocation.Properties.operationName,
PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_LOST,
null, operationName.getText()));
}
}
/**
* @see org.eclipse.swt.events.FocusAdapter#focusGained(org.eclipse.swt.events.FocusEvent)
*/
@Override
public void focusGained(FocusEvent e) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent
.firePropertiesChanged(new PropertiesEditionEvent(
ServiceInvocationPropertiesEditionPartForm.this,
null,
PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_GAINED,
null, null));
}
}
});
operationName.addKeyListener(new KeyAdapter() {
/**
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(ServiceInvocationPropertiesEditionPartForm.this, EipViewsRepository.ServiceInvocation.Properties.operationName, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, operationName.getText()));
}
}
});
EditingUtils.setID(operationName, EipViewsRepository.ServiceInvocation.Properties.operationName);
EditingUtils.setEEFtype(operationName, "eef::Text"); //$NON-NLS-1$
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EipViewsRepository.ServiceInvocation.Properties.operationName, EipViewsRepository.FORM_KIND), null); //$NON-NLS-1$
// Start of user code for createOperationNameText
// End of user code
return parent;
}
/**
* @param parent the parent composite
* @param widgetFactory factory to use to instanciante widget of the form
*
*/
protected Composite createServiceRefFlatComboViewer(Composite parent, FormToolkit widgetFactory) {
createDescription(parent, EipViewsRepository.ServiceInvocation.Properties.serviceRef, EipMessages.ServiceInvocationPropertiesEditionPart_ServiceRefLabel);
serviceRef = new EObjectFlatComboViewer(parent, !propertiesEditionComponent.isRequired(EipViewsRepository.ServiceInvocation.Properties.serviceRef, EipViewsRepository.FORM_KIND));
widgetFactory.adapt(serviceRef);
serviceRef.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
GridData serviceRefData = new GridData(GridData.FILL_HORIZONTAL);
serviceRef.setLayoutData(serviceRefData);
serviceRef.addSelectionChangedListener(new ISelectionChangedListener() {
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(ServiceInvocationPropertiesEditionPartForm.this, EipViewsRepository.ServiceInvocation.Properties.serviceRef, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, getServiceRef()));
}
});
serviceRef.setID(EipViewsRepository.ServiceInvocation.Properties.serviceRef);
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EipViewsRepository.ServiceInvocation.Properties.serviceRef, EipViewsRepository.FORM_KIND), null); //$NON-NLS-1$
// Start of user code for createServiceRefFlatComboViewer
// End of user code
return parent;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
*
*/
public void firePropertiesChanged(IPropertiesEditionEvent event) {
// Start of user code for tab synchronization
// End of user code
}
/**
* {@inheritDoc}
*
* @see com.github.lbroudoux.dsl.eip.parts.ServiceInvocationPropertiesEditionPart#getContext()
*
*/
public String getContext() {
return context.getText();
}
/**
* {@inheritDoc}
*
* @see com.github.lbroudoux.dsl.eip.parts.ServiceInvocationPropertiesEditionPart#setContext(String newValue)
*
*/
public void setContext(String newValue) {
if (newValue != null) {
context.setText(newValue);
} else {
context.setText(""); //$NON-NLS-1$
}
boolean eefElementEditorReadOnlyState = isReadOnly(EipViewsRepository.ServiceInvocation.Properties.context);
if (eefElementEditorReadOnlyState && context.isEnabled()) {
context.setEnabled(false);
context.setToolTipText(EipMessages.ServiceInvocation_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !context.isEnabled()) {
context.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see com.github.lbroudoux.dsl.eip.parts.ServiceInvocationPropertiesEditionPart#getOperationName()
*
*/
public String getOperationName() {
return operationName.getText();
}
/**
* {@inheritDoc}
*
* @see com.github.lbroudoux.dsl.eip.parts.ServiceInvocationPropertiesEditionPart#setOperationName(String newValue)
*
*/
public void setOperationName(String newValue) {
if (newValue != null) {
operationName.setText(newValue);
} else {
operationName.setText(""); //$NON-NLS-1$
}
boolean eefElementEditorReadOnlyState = isReadOnly(EipViewsRepository.ServiceInvocation.Properties.operationName);
if (eefElementEditorReadOnlyState && operationName.isEnabled()) {
operationName.setEnabled(false);
operationName.setToolTipText(EipMessages.ServiceInvocation_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !operationName.isEnabled()) {
operationName.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see com.github.lbroudoux.dsl.eip.parts.ServiceInvocationPropertiesEditionPart#getServiceRef()
*
*/
public EObject getServiceRef() {
if (serviceRef.getSelection() instanceof StructuredSelection) {
Object firstElement = ((StructuredSelection) serviceRef.getSelection()).getFirstElement();
if (firstElement instanceof EObject)
return (EObject) firstElement;
}
return null;
}
/**
* {@inheritDoc}
*
* @see com.github.lbroudoux.dsl.eip.parts.ServiceInvocationPropertiesEditionPart#initServiceRef(EObjectFlatComboSettings)
*/
public void initServiceRef(EObjectFlatComboSettings settings) {
serviceRef.setInput(settings);
if (current != null) {
serviceRef.setSelection(new StructuredSelection(settings.getValue()));
}
boolean eefElementEditorReadOnlyState = isReadOnly(EipViewsRepository.ServiceInvocation.Properties.serviceRef);
if (eefElementEditorReadOnlyState && serviceRef.isEnabled()) {
serviceRef.setEnabled(false);
serviceRef.setToolTipText(EipMessages.ServiceInvocation_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !serviceRef.isEnabled()) {
serviceRef.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see com.github.lbroudoux.dsl.eip.parts.ServiceInvocationPropertiesEditionPart#setServiceRef(EObject newValue)
*
*/
public void setServiceRef(EObject newValue) {
if (newValue != null) {
serviceRef.setSelection(new StructuredSelection(newValue));
} else {
serviceRef.setSelection(new StructuredSelection()); //$NON-NLS-1$
}
boolean eefElementEditorReadOnlyState = isReadOnly(EipViewsRepository.ServiceInvocation.Properties.serviceRef);
if (eefElementEditorReadOnlyState && serviceRef.isEnabled()) {
serviceRef.setEnabled(false);
serviceRef.setToolTipText(EipMessages.ServiceInvocation_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !serviceRef.isEnabled()) {
serviceRef.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see com.github.lbroudoux.dsl.eip.parts.ServiceInvocationPropertiesEditionPart#setServiceRefButtonMode(ButtonsModeEnum newValue)
*/
public void setServiceRefButtonMode(ButtonsModeEnum newValue) {
serviceRef.setButtonMode(newValue);
}
/**
* {@inheritDoc}
*
* @see com.github.lbroudoux.dsl.eip.parts.ServiceInvocationPropertiesEditionPart#addFilterServiceRef(ViewerFilter filter)
*
*/
public void addFilterToServiceRef(ViewerFilter filter) {
serviceRef.addFilter(filter);
}
/**
* {@inheritDoc}
*
* @see com.github.lbroudoux.dsl.eip.parts.ServiceInvocationPropertiesEditionPart#addBusinessFilterServiceRef(ViewerFilter filter)
*
*/
public void addBusinessFilterToServiceRef(ViewerFilter filter) {
serviceRef.addBusinessRuleFilter(filter);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart#getTitle()
*
*/
public String getTitle() {
return EipMessages.ServiceInvocation_Part_Title;
}
// Start of user code additional methods
// End of user code
}
| |
package ch.hevs.aislab.paams.ui;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import ch.hevs.aislab.paams.connector.DoubleValueAdapter;
import ch.hevs.aislab.paams.connector.SingleValueAdapter;
import ch.hevs.aislab.paams.connector.ValueAdapter;
import ch.hevs.aislab.paams.connector.ValueDAO;
import ch.hevs.aislab.paams.model.Type;
import ch.hevs.aislab.paams.model.Value;
import ch.hevs.aislab.paams.ui.utils.RevealAnimationSetting;
import ch.hevs.aislab.paamsdemo.R;
public class ListValuesFragment extends ListFragment implements MainActivity.OnChangeDummyDataDisplayListener {
private static final String TAG = "ListValuesFragment";
private static final String ARG_TYPE = "TYPE_OF_PHYSIOLOGICAL_VALUE";
private static final String BUNDLE_KEY = "items";
private Type type;
private static ValueAdapter valueAdapter;
private ValueDAO valueDAO;
private FloatingActionButton addValueButton;
private Boolean displayDummyData;
public ListValuesFragment() {
}
public static ListValuesFragment newInstance(Type type) {
ListValuesFragment fragment = new ListValuesFragment();
Bundle args = new Bundle();
args.putString(ARG_TYPE, type.name());
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(Context context) {
Log.i(TAG, "onAttach()");
displayDummyData = ((MainActivity) getActivity()).setOnChangeDummyDataDisplayListener(this);
super.onAttach(context);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
type = Type.valueOf(getArguments().getString(ARG_TYPE));
}
Log.i(TAG, "onCreate() from " + type);
if (savedInstanceState == null) {
switch (type) {
case GLUCOSE:
case WEIGHT:
valueAdapter = new SingleValueAdapter();
break;
case BLOOD_PRESSURE:
valueAdapter = new DoubleValueAdapter();
break;
}
} else {
if (savedInstanceState.getParcelableArray(BUNDLE_KEY) != null) {
Value[] values = (Value[]) savedInstanceState.getParcelableArray(BUNDLE_KEY);
List<Value> valuesList = new ArrayList<>();
for (int i = 0; i < values.length; i++) {
valuesList.add(values[i]);
}
switch (type) {
case GLUCOSE:
case WEIGHT:
valueAdapter = new SingleValueAdapter(valuesList);
break;
case BLOOD_PRESSURE:
valueAdapter = new DoubleValueAdapter(valuesList);
break;
}
}
}
valueDAO = new ValueDAO(getActivity());
valueDAO.open();
if (valueAdapter.getCount() == 0) {
valueAdapter.addAllItems(valueDAO.getAllValues(type));
}
setListAdapter(valueAdapter);
valueAdapter.displayDummyData(displayDummyData);
setHasOptionsMenu(true);
}
@Override
public void onStart() {
Log.i(TAG, "onStart() from " + type);
super.onStart();
}
@Override
public void onResume() {
Log.i(TAG, "onResume() from " + type);
super.onResume();
}
@Override
public void onPause() {
Log.i(TAG, "onPause() from " + type);
super.onPause();
}
@Override
public void onStop() {
Log.i(TAG, "onStop() from " + type);
super.onStop();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list_values, container, false);
addValueButton = (FloatingActionButton) view.findViewById(R.id.fab_addValue);
setAddAction(addValueButton);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(TAG, "onActivityCreated() from " + type);
getListView().setHeaderDividersEnabled(true);
LinearLayout headerLayout = null;
switch (type) {
case GLUCOSE:
case WEIGHT:
headerLayout = (LinearLayout) LayoutInflater
.from(getActivity()).inflate(R.layout.single_value_row_header, getListView(), false);
TextView valueHeaderTextView = (TextView) headerLayout.findViewById(R.id.valueHeaderTextView);
if (type.equals(Type.GLUCOSE)) {
valueHeaderTextView.setText("mmol/L");
} else if (type.equals(Type.WEIGHT)) {
valueHeaderTextView.setText("kg");
}
break;
case BLOOD_PRESSURE:
headerLayout = (LinearLayout) LayoutInflater
.from(getActivity()).inflate(R.layout.double_value_row_header, getListView(), false);
TextView firstValueHeaderTextView = (TextView) headerLayout.findViewById(R.id.firstValueHeaderTextView);
firstValueHeaderTextView.setText("Systolic");
TextView secondValueHeaderTextView = (TextView) headerLayout.findViewById(R.id.secondValueHeaderTextView);
secondValueHeaderTextView.setText("Diastolic");
break;
}
getListView().addHeaderView(headerLayout, null, false);
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Value value = (Value) valueAdapter.getItem(--position);
ImageView checkImageView = (ImageView) view.findViewById(R.id.checkImageView);
if (value.isMarked()) {
checkImageView.setImageResource(R.mipmap.btn_check_buttonless_off);
value.setMarked(false);
} else {
checkImageView.setImageResource(R.mipmap.btn_check_buttonless_on);
value.setMarked(true);
}
}
});
}
@Override
public void onDestroy() {
//TODO: Save the marked state
Log.i(TAG, "onDestroy() from " + type);
valueDAO.close();
super.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
Value[] items = valueAdapter.getItems();
Log.i(TAG, "onSaveInstanceState() from " + type);
Log.i(TAG, "Number of items: " + items.length);
if (items.length > 0) {
outState.putParcelableArray(BUNDLE_KEY, items);
}
super.onSaveInstanceState(outState);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
Log.i(TAG, "Fragment type in onCreateOptionsMenu(): " + type.name());
menu.clear();
menuInflater.inflate(R.menu.menu_delete_value_toolbar, menu);
super.onCreateOptionsMenu(menu, menuInflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.i(TAG, "Fragment type: " + type.name());
switch (item.getItemId()) {
case R.id.deleteValueButton:
List<Value> values = valueAdapter.getSelectedItems();
if (values.isEmpty()) {
Toast.makeText(getContext(), "Select the items to delete", Toast.LENGTH_LONG).show();
return true;
} else {
int size = 0;
String dummy = "";
for (Value value : values) {
if (!value.isDummy()) {
size++;
valueAdapter.removeItem(value);
valueDAO.deleteValue(value);
} else {
dummy = " Dummy data cannot be deleted.";
}
}
Toast.makeText(getContext(), "Deleted " + size + " entries." + dummy, Toast.LENGTH_LONG).show();
return true;
}
default:
return false;
}
}
public ValueAdapter getValueAdapter() {
return valueAdapter;
}
private void setAddAction(FloatingActionButton button) {
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().beginTransaction()
.replace(R.id.main_container, AddValueFragment.newInstance(type, constructRevealSettings()), "Add")
.commit();
}
});
}
private RevealAnimationSetting constructRevealSettings() {
// Coordinates of FAB's parent
int offsetX = (int) ((ViewGroup) addValueButton.getParent()).getX();
int offsetY = (int) ((ViewGroup) addValueButton.getParent()).getY();
return RevealAnimationSetting.with(
(int) (offsetX + addValueButton.getX() + addValueButton.getWidth() / 2),
(int) (offsetY + addValueButton.getY() + addValueButton.getHeight() / 2),
((ViewGroup) getView().getParent()).getWidth(),
((ViewGroup) getView().getParent()).getHeight());
}
@Override
public void displayDummyData(Boolean display) {
Log.i(TAG, "displayDummyData() for type " + type + " with " + display);
valueAdapter.displayDummyData(display);
}
}
| |
/*
* Copyright (c) 2009-2020 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.asset;
import com.jme3.asset.cache.AssetCache;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <code>ImplHandler</code> manages the asset loader and asset locator
* implementations in a thread safe way. This allows implementations
* which store local persistent data to operate with a multi-threaded system.
* This is done by keeping an instance of each asset loader and asset
* locator object in a thread local.
*/
final class ImplHandler {
private static final Logger logger = Logger.getLogger(ImplHandler.class.getName());
private final AssetManager assetManager;
private final ThreadLocal<AssetKey> parentAssetKey
= new ThreadLocal<AssetKey>();
private final CopyOnWriteArrayList<ImplThreadLocal<AssetLocator>> locatorsList =
new CopyOnWriteArrayList<ImplThreadLocal<AssetLocator>>();
private final HashMap<Class<?>, ImplThreadLocal<AssetLoader>> classToLoaderMap =
new HashMap<Class<?>, ImplThreadLocal<AssetLoader>>();
private final ConcurrentHashMap<String, ImplThreadLocal<AssetLoader>> extensionToLoaderMap =
new ConcurrentHashMap<String, ImplThreadLocal<AssetLoader>>();
private final ConcurrentHashMap<Class<? extends AssetProcessor>, AssetProcessor> classToProcMap =
new ConcurrentHashMap<Class<? extends AssetProcessor>, AssetProcessor>();
private final ConcurrentHashMap<Class<? extends AssetCache>, AssetCache> classToCacheMap =
new ConcurrentHashMap<Class<? extends AssetCache>, AssetCache>();
public ImplHandler(AssetManager assetManager){
this.assetManager = assetManager;
}
protected static class ImplThreadLocal<T> extends ThreadLocal<T> {
private final Class<T> type;
private final String path;
private final String[] extensions;
public ImplThreadLocal(Class<T> type, String[] extensions){
this.type = type;
this.extensions = extensions.clone();
this.path = null;
}
public ImplThreadLocal(Class<T> type, String path){
this.type = type;
this.path = path;
this.extensions = null;
}
public ImplThreadLocal(Class<T> type){
this.type = type;
this.path = null;
this.extensions = null;
}
public String getPath() {
return path;
}
public String[] getExtensions(){
return extensions;
}
public Class<?> getTypeClass(){
return type;
}
@Override
protected T initialValue(){
try {
T obj = type.newInstance();
if (path != null) {
((AssetLocator)obj).setRootPath(path);
}
return obj;
} catch (InstantiationException | IllegalAccessException ex) {
logger.log(Level.SEVERE,"Cannot create locator of type {0}, does"
+ " the class have an empty and publicly accessible"+
" constructor?", type.getName());
logger.throwing(type.getName(), "<init>", ex);
}
return null;
}
}
/**
* Establishes the asset key that is used for tracking dependent assets
* that have failed to load. When set, the {@link DesktopAssetManager}
* gets a hint that it should suppress {@link AssetNotFoundException}s
* and instead call the listener callback (if set).
*
* @param parentKey The parent key
*/
public void establishParentKey(AssetKey parentKey){
if (parentAssetKey.get() == null){
parentAssetKey.set(parentKey);
}
}
public void releaseParentKey(AssetKey parentKey){
if (parentAssetKey.get() == parentKey){
parentAssetKey.set(null);
}
}
public AssetKey getParentKey(){
return parentAssetKey.get();
}
/**
* Attempts to locate the given resource name.
* @param key The full name of the resource.
* @return The AssetInfo containing resource information required for
* access, or null if not found.
*/
public AssetInfo tryLocate(AssetKey key){
if (locatorsList.isEmpty()){
logger.warning("There are no locators currently"+
" registered. Use AssetManager."+
"registerLocator() to register a"+
" locator.");
return null;
}
for (ImplThreadLocal<AssetLocator> local : locatorsList){
AssetInfo info = local.get().locate(assetManager, key);
if (info != null) {
return info;
}
}
return null;
}
public int getLocatorCount(){
return locatorsList.size();
}
/**
* Returns the AssetLoader registered for the given extension
* of the current thread.
* @return AssetLoader registered with addLoader.
*/
public AssetLoader aquireLoader(AssetKey key){
// No need to synchronize() against map, its concurrent
ImplThreadLocal local = extensionToLoaderMap.get(key.getExtension());
if (local == null){
throw new AssetLoadException("No loader registered for type \"" +
key.getExtension() + "\"");
}
return (AssetLoader) local.get();
}
public void clearCache(){
// The iterator of the values collection is thread safe
synchronized (classToCacheMap) {
for (AssetCache cache : classToCacheMap.values()){
cache.clearCache();
}
}
}
@SuppressWarnings("unchecked")
public <T extends AssetCache> T getCache(Class<T> cacheClass) {
if (cacheClass == null) {
return null;
}
T cache = (T) classToCacheMap.get(cacheClass);
if (cache == null) {
synchronized (classToCacheMap) {
cache = (T) classToCacheMap.get(cacheClass);
if (cache == null) {
try {
cache = cacheClass.newInstance();
classToCacheMap.put(cacheClass, cache);
} catch (InstantiationException ex) {
throw new IllegalArgumentException("The cache class cannot"
+ " be created, ensure it has empty constructor", ex);
} catch (IllegalAccessException ex) {
throw new IllegalArgumentException("The cache class cannot "
+ "be accessed", ex);
}
}
}
}
return cache;
}
@SuppressWarnings("unchecked")
public <T extends AssetProcessor> T getProcessor(Class<T> procClass){
if (procClass == null)
return null;
T proc = (T) classToProcMap.get(procClass);
if (proc == null){
synchronized(classToProcMap){
proc = (T) classToProcMap.get(procClass);
if (proc == null) {
try {
proc = procClass.newInstance();
classToProcMap.put(procClass, proc);
} catch (InstantiationException ex) {
throw new IllegalArgumentException("The processor class cannot"
+ " be created, ensure it has empty constructor", ex);
} catch (IllegalAccessException ex) {
throw new IllegalArgumentException("The processor class cannot "
+ "be accessed", ex);
}
}
}
}
return proc;
}
@SuppressWarnings("unchecked")
public void addLoader(final Class<? extends AssetLoader> loaderType, String ... extensions){
// Synchronized access must be used for any ops on classToLoaderMap
ImplThreadLocal local = new ImplThreadLocal(loaderType, extensions);
for (String extension : extensions){
extension = extension.toLowerCase();
synchronized (classToLoaderMap){
classToLoaderMap.put(loaderType, local);
extensionToLoaderMap.put(extension, local);
}
}
}
public void removeLoader(final Class<? extends AssetLoader> loaderType){
// Synchronized access must be used for any ops on classToLoaderMap
// Find the loader ImplThreadLocal for this class
synchronized (classToLoaderMap){
// Remove it from the class->loader map
ImplThreadLocal local = classToLoaderMap.remove(loaderType);
if (local == null) return;
// Remove it from the extension->loader map
for (String extension : local.getExtensions()){
extensionToLoaderMap.remove(extension);
}
}
}
@SuppressWarnings("unchecked")
public void addLocator(final Class<? extends AssetLocator> locatorType, String rootPath){
locatorsList.add(new ImplThreadLocal(locatorType, rootPath));
}
public void removeLocator(final Class<? extends AssetLocator> locatorType, String rootPath){
ArrayList<ImplThreadLocal<AssetLocator>> locatorsToRemove = new ArrayList<ImplThreadLocal<AssetLocator>>();
Iterator<ImplThreadLocal<AssetLocator>> it = locatorsList.iterator();
while (it.hasNext()){
ImplThreadLocal<AssetLocator> locator = it.next();
if (locator.getPath().equals(rootPath) &&
locator.getTypeClass().equals(locatorType)){
//it.remove();
// copy on write list doesn't support iterator remove,
// must use temporary list
locatorsToRemove.add(locator);
}
}
locatorsList.removeAll(locatorsToRemove);
}
}
| |
/*
* Copyright (C) 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.cloud.dataflow.sdk.options;
import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory.JsonIgnorePredicate;
import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory.Registration;
import com.google.cloud.dataflow.sdk.util.InstanceBuilder;
import com.google.cloud.dataflow.sdk.util.common.ReflectHelpers;
import com.google.common.base.Defaults;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ClassToInstanceMap;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.MutableClassToInstanceMap;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.annotation.concurrent.ThreadSafe;
/**
* Represents and {@link InvocationHandler} for a {@link Proxy}. The invocation handler uses bean
* introspection of the proxy class to store and retrieve values based off of the property name.
*
* <p>Unset properties use the {@code @Default} metadata on the getter to return values. If there
* is no {@code @Default} annotation on the getter, then a <a
* href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html">default</a> as
* per the Java Language Specification for the expected return type is returned.
*
* <p>In addition to the getter/setter pairs, this proxy invocation handler supports
* {@link Object#equals(Object)}, {@link Object#hashCode()}, {@link Object#toString()} and
* {@link PipelineOptions#as(Class)}.
*/
@ThreadSafe
class ProxyInvocationHandler implements InvocationHandler {
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* No two instances of this class are considered equivalent hence we generate a random hash code
* between 0 and {@link Integer#MAX_VALUE}.
*/
private final int hashCode = (int) (Math.random() * Integer.MAX_VALUE);
private final Set<Class<? extends PipelineOptions>> knownInterfaces;
private final ClassToInstanceMap<PipelineOptions> interfaceToProxyCache;
private final Map<String, Object> options;
private final Map<String, JsonNode> jsonOptions;
private final Map<String, String> gettersToPropertyNames;
private final Map<String, String> settersToPropertyNames;
ProxyInvocationHandler(Map<String, Object> options) {
this(options, Maps.<String, JsonNode>newHashMap());
}
private ProxyInvocationHandler(Map<String, Object> options, Map<String, JsonNode> jsonOptions) {
this.options = options;
this.jsonOptions = jsonOptions;
this.knownInterfaces = new HashSet<>(PipelineOptionsFactory.getRegisteredOptions());
gettersToPropertyNames = Maps.newHashMap();
settersToPropertyNames = Maps.newHashMap();
interfaceToProxyCache = MutableClassToInstanceMap.create();
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
if (args == null && "toString".equals(method.getName())) {
return toString();
} else if (args != null && args.length == 1 && "equals".equals(method.getName())) {
return equals(args[0]);
} else if (args == null && "hashCode".equals(method.getName())) {
return hashCode();
} else if (args != null && "as".equals(method.getName()) && args[0] instanceof Class) {
@SuppressWarnings("unchecked")
Class<? extends PipelineOptions> clazz = (Class<? extends PipelineOptions>) args[0];
return as(clazz);
} else if (args != null && "cloneAs".equals(method.getName()) && args[0] instanceof Class) {
@SuppressWarnings("unchecked")
Class<? extends PipelineOptions> clazz = (Class<? extends PipelineOptions>) args[0];
return cloneAs(proxy, clazz);
}
String methodName = method.getName();
synchronized (this) {
if (gettersToPropertyNames.keySet().contains(methodName)) {
String propertyName = gettersToPropertyNames.get(methodName);
if (!options.containsKey(propertyName)) {
// Lazy bind the default to the method.
Object value = jsonOptions.containsKey(propertyName)
? getValueFromJson(propertyName, method)
: getDefault((PipelineOptions) proxy, method);
options.put(propertyName, value);
}
return options.get(propertyName);
} else if (settersToPropertyNames.containsKey(methodName)) {
options.put(settersToPropertyNames.get(methodName), args[0]);
return Void.TYPE;
}
}
throw new RuntimeException("Unknown method [" + method + "] invoked with args ["
+ Arrays.toString(args) + "].");
}
/**
* Backing implementation for {@link PipelineOptions#as(Class)}.
*
* @param iface The interface that the returned object needs to implement.
* @return An object that implements the interface <T>.
*/
synchronized <T extends PipelineOptions> T as(Class<T> iface) {
Preconditions.checkNotNull(iface);
Preconditions.checkArgument(iface.isInterface());
if (!interfaceToProxyCache.containsKey(iface)) {
Registration<T> registration =
PipelineOptionsFactory.validateWellFormed(iface, knownInterfaces);
List<PropertyDescriptor> propertyDescriptors = registration.getPropertyDescriptors();
Class<T> proxyClass = registration.getProxyClass();
gettersToPropertyNames.putAll(generateGettersToPropertyNames(propertyDescriptors));
settersToPropertyNames.putAll(generateSettersToPropertyNames(propertyDescriptors));
knownInterfaces.add(iface);
interfaceToProxyCache.putInstance(iface,
InstanceBuilder.ofType(proxyClass)
.fromClass(proxyClass)
.withArg(InvocationHandler.class, this)
.build());
}
return interfaceToProxyCache.getInstance(iface);
}
/**
* Backing implementation for {@link PipelineOptions#cloneAs(Class)}.
*
* @return A copy of the PipelineOptions.
*/
synchronized <T extends PipelineOptions> T cloneAs(Object proxy, Class<T> iface) {
PipelineOptions clonedOptions;
try {
clonedOptions = MAPPER.readValue(MAPPER.writeValueAsBytes(proxy), PipelineOptions.class);
} catch (IOException e) {
throw new IllegalStateException("Failed to serialize the pipeline options to JSON.", e);
}
for (Class<? extends PipelineOptions> knownIface : knownInterfaces) {
clonedOptions.as(knownIface);
}
return clonedOptions.as(iface);
}
/**
* Returns true if the other object is a ProxyInvocationHandler or is a Proxy object and has the
* same ProxyInvocationHandler as this.
*
* @param obj The object to compare against this.
* @return true iff the other object is a ProxyInvocationHandler or is a Proxy object and has the
* same ProxyInvocationHandler as this.
*/
@Override
public boolean equals(Object obj) {
return obj != null && ((obj instanceof ProxyInvocationHandler && this == obj)
|| (Proxy.isProxyClass(obj.getClass()) && this == Proxy.getInvocationHandler(obj)));
}
/**
* Each instance of this ProxyInvocationHandler is unique and has a random hash code.
*
* @return A hash code that was generated randomly.
*/
@Override
public int hashCode() {
return hashCode;
}
/**
* This will output all the currently set values. This is a relatively costly function
* as it will call {@code toString()} on each object that has been set and format
* the results in a readable format.
*
* @return A pretty printed string representation of this.
*/
@Override
public synchronized String toString() {
SortedMap<String, Object> sortedOptions = new TreeMap<>();
// Add the options that we received from deserialization
sortedOptions.putAll(jsonOptions);
// Override with any programmatically set options.
sortedOptions.putAll(options);
StringBuilder b = new StringBuilder();
b.append("Current Settings:\n");
for (Map.Entry<String, Object> entry : sortedOptions.entrySet()) {
b.append(" " + entry.getKey() + ": " + entry.getValue() + "\n");
}
return b.toString();
}
/**
* Uses a Jackson {@link ObjectMapper} to attempt type conversion.
*
* @param method The method whose return type you would like to return.
* @param propertyName The name of the property that is being returned.
* @return An object matching the return type of the method passed in.
*/
private Object getValueFromJson(String propertyName, Method method) {
try {
JavaType type = MAPPER.getTypeFactory().constructType(method.getGenericReturnType());
JsonNode jsonNode = jsonOptions.get(propertyName);
return MAPPER.readValue(jsonNode.toString(), type);
} catch (IOException e) {
throw new RuntimeException("Unable to parse representation", e);
}
}
/**
* Returns a default value for the method based upon {@code @Default} metadata on the getter
* to return values. If there is no {@code @Default} annotation on the getter, then a <a
* href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html">default</a> as
* per the Java Language Specification for the expected return type is returned.
*
* @param proxy The proxy object for which we are attempting to get the default.
* @param method The getter method that was invoked.
* @return The default value from an {@link Default} annotation if present, otherwise a default
* value as per the Java Language Specification.
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private Object getDefault(PipelineOptions proxy, Method method) {
for (Annotation annotation : method.getAnnotations()) {
if (annotation instanceof Default.Class) {
return ((Default.Class) annotation).value();
} else if (annotation instanceof Default.String) {
return ((Default.String) annotation).value();
} else if (annotation instanceof Default.Boolean) {
return ((Default.Boolean) annotation).value();
} else if (annotation instanceof Default.Character) {
return ((Default.Character) annotation).value();
} else if (annotation instanceof Default.Byte) {
return ((Default.Byte) annotation).value();
} else if (annotation instanceof Default.Short) {
return ((Default.Short) annotation).value();
} else if (annotation instanceof Default.Integer) {
return ((Default.Integer) annotation).value();
} else if (annotation instanceof Default.Long) {
return ((Default.Long) annotation).value();
} else if (annotation instanceof Default.Float) {
return ((Default.Float) annotation).value();
} else if (annotation instanceof Default.Double) {
return ((Default.Double) annotation).value();
} else if (annotation instanceof Default.Enum) {
return Enum.valueOf((Class<Enum>) method.getReturnType(),
((Default.Enum) annotation).value());
} else if (annotation instanceof Default.InstanceFactory) {
return InstanceBuilder.ofType(((Default.InstanceFactory) annotation).value())
.build()
.create(proxy);
}
}
/*
* We need to make sure that we return something appropriate for the return type. Thus we return
* a default value as defined by the JLS.
*/
return Defaults.defaultValue(method.getReturnType());
}
/**
* Returns a map from the getters method name to the name of the property based upon the passed in
* {@link PropertyDescriptor}s property descriptors.
*
* @param propertyDescriptors A list of {@link PropertyDescriptor}s to use when generating the
* map.
* @return A map of getter method name to property name.
*/
private static Map<String, String> generateGettersToPropertyNames(
List<PropertyDescriptor> propertyDescriptors) {
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
for (PropertyDescriptor descriptor : propertyDescriptors) {
if (descriptor.getReadMethod() != null) {
builder.put(descriptor.getReadMethod().getName(), descriptor.getName());
}
}
return builder.build();
}
/**
* Returns a map from the setters method name to its matching getters method name based upon the
* passed in {@link PropertyDescriptor}s property descriptors.
*
* @param propertyDescriptors A list of {@link PropertyDescriptor}s to use when generating the
* map.
* @return A map of setter method name to getter method name.
*/
private static Map<String, String> generateSettersToPropertyNames(
List<PropertyDescriptor> propertyDescriptors) {
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
for (PropertyDescriptor descriptor : propertyDescriptors) {
if (descriptor.getWriteMethod() != null) {
builder.put(descriptor.getWriteMethod().getName(), descriptor.getName());
}
}
return builder.build();
}
static class Serializer extends JsonSerializer<PipelineOptions> {
@Override
public void serialize(PipelineOptions value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
ProxyInvocationHandler handler = (ProxyInvocationHandler) Proxy.getInvocationHandler(value);
synchronized (handler) {
// We first filter out any properties that have been modified since
// the last serialization of this PipelineOptions and then verify that
// they are all serializable.
Map<String, Object> filteredOptions = Maps.newHashMap(handler.options);
removeIgnoredOptions(handler.knownInterfaces, filteredOptions);
ensureSerializable(handler.knownInterfaces, filteredOptions);
// Now we create the map of serializable options by taking the original
// set of serialized options (if any) and updating them with any properties
// instances that have been modified since the previous serialization.
Map<String, Object> serializableOptions =
Maps.<String, Object>newHashMap(handler.jsonOptions);
serializableOptions.putAll(filteredOptions);
jgen.writeStartObject();
jgen.writeFieldName("options");
jgen.writeObject(serializableOptions);
jgen.writeEndObject();
}
}
/**
* We remove all properties within the passed in options where there getter is annotated with
* {@link JsonIgnore @JsonIgnore} from the passed in options using the passed in interfaces.
*/
private void removeIgnoredOptions(
Set<Class<? extends PipelineOptions>> interfaces, Map<String, Object> options) {
// Find all the method names that are annotated with JSON ignore.
Set<String> jsonIgnoreMethodNames = FluentIterable.from(
ReflectHelpers.getClosureOfMethodsOnInterfaces(interfaces))
.filter(JsonIgnorePredicate.INSTANCE).transform(new Function<Method, String>() {
@Override
public String apply(Method input) {
return input.getName();
}
}).toSet();
// Remove all options that have the same method name as the descriptor.
for (PropertyDescriptor descriptor
: PipelineOptionsFactory.getPropertyDescriptors(interfaces)) {
if (jsonIgnoreMethodNames.contains(descriptor.getReadMethod().getName())) {
options.remove(descriptor.getName());
}
}
}
/**
* We use an {@link ObjectMapper} to verify that the passed in options are serializable
* and deserializable.
*/
private void ensureSerializable(Set<Class<? extends PipelineOptions>> interfaces,
Map<String, Object> options) throws IOException {
// Construct a map from property name to the return type of the getter.
Map<String, Type> propertyToReturnType = Maps.newHashMap();
for (PropertyDescriptor descriptor
: PipelineOptionsFactory.getPropertyDescriptors(interfaces)) {
if (descriptor.getReadMethod() != null) {
propertyToReturnType.put(descriptor.getName(),
descriptor.getReadMethod().getGenericReturnType());
}
}
// Attempt to serialize and deserialize each property.
for (Map.Entry<String, Object> entry : options.entrySet()) {
try {
String serializedValue = MAPPER.writeValueAsString(entry.getValue());
JavaType type = MAPPER.getTypeFactory()
.constructType(propertyToReturnType.get(entry.getKey()));
MAPPER.readValue(serializedValue, type);
} catch (Exception e) {
throw new IOException(String.format(
"Failed to serialize and deserialize property '%s' with value '%s'",
entry.getKey(), entry.getValue()), e);
}
}
}
}
static class Deserializer extends JsonDeserializer<PipelineOptions> {
@Override
public PipelineOptions deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
ObjectNode objectNode = (ObjectNode) jp.readValueAsTree();
ObjectNode optionsNode = (ObjectNode) objectNode.get("options");
Map<String, JsonNode> fields = Maps.newHashMap();
for (Iterator<Map.Entry<String, JsonNode>> iterator = optionsNode.fields();
iterator.hasNext(); ) {
Map.Entry<String, JsonNode> field = iterator.next();
fields.put(field.getKey(), field.getValue());
}
PipelineOptions options =
new ProxyInvocationHandler(Maps.<String, Object>newHashMap(), fields)
.as(PipelineOptions.class);
return options;
}
}
}
| |
/*
Copyright 2013 Nationale-Nederlanden
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 nl.nn.adapterframework.extensions.sap.jco3;
import java.util.ArrayList;
import java.util.List;
import nl.nn.adapterframework.util.LogUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import com.sap.conn.idoc.IDocConversionException;
import com.sap.conn.idoc.IDocDocument;
import com.sap.conn.idoc.IDocFieldNotFoundException;
import com.sap.conn.idoc.IDocIllegalTypeException;
import com.sap.conn.idoc.IDocMetaDataUnavailableException;
import com.sap.conn.idoc.IDocSegment;
import com.sap.conn.idoc.IDocSyntaxException;
import com.sap.conn.idoc.jco.JCoIDoc;
import com.sap.conn.jco.JCoException;
/**
* DefaultHandler extension to parse SAP Idocs in XML format into JCoIDoc format.
*
* @author Gerrit van Brakel
* @author Jaco de Groot
* @since 5.0
* @version $Id$
*/
public class IdocXmlHandler extends DefaultHandler {
protected Logger log = LogUtil.getLogger(this.getClass());
private SapSystem sapSystem;
private IDocDocument doc=null;
private List segmentStack=new ArrayList();
private String currentField;
private StringBuffer currentFieldValue=new StringBuffer();
private boolean parsingEdiDcHeader=false;
private Locator locator;
public IdocXmlHandler(SapSystem sapSystem) {
super();
this.sapSystem=sapSystem;
}
public IDocDocument getIdoc() {
return doc;
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
//log.debug("startElement("+localName+")");
if (doc==null) {
log.debug("creating Idoc ["+localName+"]");
try {
doc = JCoIDoc.getIDocFactory().createIDocDocument(sapSystem.getIDocRepository(), localName);
} catch (IDocMetaDataUnavailableException e) {
throw new SAXException("could not create idoc document, idoc meta data unavailable", e);
} catch (JCoException e) {
throw new SAXException("could not create idoc document", e);
}
IDocSegment segment = doc.getRootSegment();
segmentStack.add(segment);
} else {
if (attributes.getIndex("SEGMENT")>=0) {
if (localName.startsWith("EDI_DC")) {
parsingEdiDcHeader=true;
} else {
log.debug("creating segment ["+localName+"]");
IDocSegment parentSegment = (IDocSegment)segmentStack.get(segmentStack.size()-1);
IDocSegment segment;
try {
segment = parentSegment.addChild(localName);
} catch (IDocIllegalTypeException e) {
throw new SAXException("could not parse segment, idoc illegal type", e);
} catch (IDocMetaDataUnavailableException e) {
throw new SAXException("could not parse segment, idoc meta data unavailable", e);
}
segmentStack.add(segment);
}
} else {
currentField=localName;
}
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
//log.debug("endElement("+localName+")");
if (currentField!=null) {
String value=currentFieldValue.toString().trim();
if (StringUtils.isNotEmpty(value)) {
if (parsingEdiDcHeader) {
if (log.isDebugEnabled()) log.debug("parsed header field ["+currentField+"] value ["+value+"]");
try {
if (currentField.equals("ARCKEY")) { doc.setArchiveKey(value); }
else if (currentField.equals("MANDT")) { doc.setClient(value); }
else if (currentField.equals("CREDAT")) { doc.setCreationDate(value); }
else if (currentField.equals("CRETIM")) { doc.setCreationTime(value); }
else if (currentField.equals("DIRECT")) { doc.setDirection(value); }
else if (currentField.equals("REFMES")) { doc.setEDIMessage(value); }
else if (currentField.equals("REFGRP")) { doc.setEDIMessageGroup(value); }
else if (currentField.equals("STDMES")) { doc.setEDIMessageType(value); }
else if (currentField.equals("STD")) { doc.setEDIStandardFlag(value); }
else if (currentField.equals("STDVRS")) { doc.setEDIStandardVersion(value); }
else if (currentField.equals("REFINT")) { doc.setEDITransmissionFile(value); }
// Not available anymore in JCo 3.0
// else if (currentField.equals("EXPRSS")) { doc.setExpressFlag(value); }
else if (currentField.equals("DOCTYP")) { doc.setIDocCompoundType(value); }
else if (currentField.equals("DOCNUM")) { doc.setIDocNumber(value); }
else if (currentField.equals("DOCREL")) { doc.setIDocSAPRelease(value); }
else if (currentField.equals("IDOCTYP")){ doc.setIDocType(value); }
else if (currentField.equals("CIMTYP")) { doc.setIDocTypeExtension(value); }
else if (currentField.equals("MESCOD")) { doc.setMessageCode(value); }
else if (currentField.equals("MESFCT")) { doc.setMessageFunction(value); }
else if (currentField.equals("MESTYP")) { doc.setMessageType(value); }
else if (currentField.equals("OUTMOD")) { doc.setOutputMode(value); }
else if (currentField.equals("RCVSAD")) { doc.setRecipientAddress(value); }
else if (currentField.equals("RCVLAD")) { doc.setRecipientLogicalAddress(value); }
else if (currentField.equals("RCVPFC")) { doc.setRecipientPartnerFunction(value); }
else if (currentField.equals("RCVPRN")) { doc.setRecipientPartnerNumber(value); }
else if (currentField.equals("RCVPRT")) { doc.setRecipientPartnerType(value); }
else if (currentField.equals("RCVPOR")) { doc.setRecipientPort(value); }
else if (currentField.equals("SNDSAD")) { doc.setSenderAddress(value); }
else if (currentField.equals("SNDLAD")) { doc.setSenderLogicalAddress(value); }
else if (currentField.equals("SNDPFC")) { doc.setSenderPartnerFunction(value); }
else if (currentField.equals("SNDPRN")) { doc.setSenderPartnerNumber(value); }
else if (currentField.equals("SNDPRT")) { doc.setSenderPartnerType(value); }
else if (currentField.equals("SNDPOR")) { doc.setSenderPort(value); }
else if (currentField.equals("SERIAL")) { doc.setSerialization(value); }
else if (currentField.equals("STATUS")) { doc.setStatus(value); }
else if (currentField.equals("TEST")) { doc.setTestFlag(value); }
else {
log.warn("header field ["+currentField+"] value ["+value+"] discarded");
}
} catch (IDocConversionException e) {
throw new SAXException("could not parse header field, idoc conversion exception", e);
} catch (IDocSyntaxException e) {
throw new SAXException("could not parse header field, idoc syntax exception", e);
}
} else {
IDocSegment segment = (IDocSegment)segmentStack.get(segmentStack.size()-1);
if (log.isDebugEnabled()) log.debug("setting field ["+currentField+"] to ["+value+"]");
try {
segment.setValue(currentField,value);
} catch (IDocFieldNotFoundException e) {
throw new SAXException("could not set field ["+currentField+"] to ["+value+"], idoc field not found", e);
} catch (IDocConversionException e) {
throw new SAXException("could not set field ["+currentField+"] to ["+value+"], idoc conversion exception", e);
} catch (IDocSyntaxException e) {
throw new SAXException("could not set field ["+currentField+"] to ["+value+"], idoc syntax exception", e);
}
}
}
currentField = null;
currentFieldValue.setLength(0);
} else {
if (parsingEdiDcHeader) {
parsingEdiDcHeader=false;
} else {
if (segmentStack.size()>0) {
segmentStack.remove(segmentStack.size()-1);
}
}
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentField==null) {
String part=new String(ch,start,length).trim();
if (StringUtils.isNotEmpty(part)) {
throw new SAXParseException("found character content ["+part+"] outside a field", locator);
}
return;
}
currentFieldValue.append(ch,start,length);
}
public void error(SAXParseException e) throws SAXException {
log.warn("Parser Error",e);
super.error(e);
}
public void fatalError(SAXParseException e) throws SAXException {
log.warn("Parser FatalError",e);
super.fatalError(e);
}
public void warning(SAXParseException e) throws SAXException {
log.warn("Parser Warning",e);
super.warning(e);
}
public void setDocumentLocator(Locator locator) {
super.setDocumentLocator(locator);
this.locator=locator;
}
}
| |
/*
* 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.
*/
/**
* Date.java
*
* This file was auto-generated from WSDL
* by the Apache Axis2 version: SNAPSHOT Built on : Dec 21, 2007 (04:03:30 LKT)
*/
package org.apache.axis2.databinding.types.soapencoding;
import javax.xml.stream.XMLStreamWriter;
/**
* Date bean class
*/
public class Date
implements org.apache.axis2.databinding.ADBBean{
/* This type was generated from the piece of schema that had
name = date
Namespace URI = http://schemas.xmlsoap.org/soap/encoding/
Namespace Prefix = ns1
*/
private static java.lang.String generatePrefix(java.lang.String namespace) {
if(namespace.equals("http://schemas.xmlsoap.org/soap/encoding/")){
return "SOAP-ENC";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
/**
* field for Date
*/
protected java.util.Date localDate ;
/**
* Auto generated getter method
* @return java.util.Date
*/
public java.util.Date getDate(){
return localDate;
}
/**
* Auto generated setter method
* @param param Date
*/
public void setDate(java.util.Date param){
this.localDate=param;
}
public java.lang.String toString(){
return localDate.toString();
}
/**
* isReaderMTOMAware
* @return true if the reader supports MTOM
*/
public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) {
boolean isReaderMTOMAware = false;
try{
isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE));
}catch(java.lang.IllegalArgumentException e){
isReaderMTOMAware = false;
}
return isReaderMTOMAware;
}
/**
*
* @param parentQName
* @param factory
* @return org.apache.axiom.om.OMElement
*/
public org.apache.axiom.om.OMElement getOMElement (
final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{
org.apache.axiom.om.OMDataSource dataSource =
new org.apache.axis2.databinding.ADBDataSource(this,parentQName);
return factory.createOMElement(dataSource,parentQName);
}
public void serialize(final javax.xml.namespace.QName parentQName,
XMLStreamWriter xmlWriter)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
serialize(parentQName,xmlWriter,false);
}
public void serialize(final javax.xml.namespace.QName parentQName,
XMLStreamWriter xmlWriter,
boolean serializeType)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
java.lang.String prefix = null;
java.lang.String namespace = null;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
if ((namespace != null) && (namespace.trim().length() > 0)) {
java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(namespace, parentQName.getLocalPart());
} else {
if (prefix == null) {
prefix = generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
} else {
xmlWriter.writeStartElement(parentQName.getLocalPart());
}
if (serializeType){
java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://schemas.xmlsoap.org/soap/encoding/");
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
namespacePrefix+":date",
xmlWriter);
} else {
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
"date",
xmlWriter);
}
}
if (localDate==null){
// write the nil attribute
throw new org.apache.axis2.databinding.ADBException("date cannot be null!!");
}else{
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localDate));
}
xmlWriter.writeEndElement();
}
/**
* Util method to write an attribute with the ns prefix
*/
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace,attName,attValue);
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeAttribute(java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (namespace.equals(""))
{
xmlWriter.writeAttribute(attName,attValue);
}
else
{
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace,attName,attValue);
}
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName,
javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String attributeNamespace = qname.getNamespaceURI();
java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace);
if (attributePrefix == null) {
attributePrefix = registerPrefix(xmlWriter, attributeNamespace);
}
java.lang.String attributeValue;
if (attributePrefix.trim().length() > 0) {
attributeValue = attributePrefix + ":" + qname.getLocalPart();
} else {
attributeValue = qname.getLocalPart();
}
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName, attributeValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace, attName, attributeValue);
}
}
/**
* method to handle Qnames
*/
private void writeQName(javax.xml.namespace.QName qname,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String namespaceURI = qname.getNamespaceURI();
if (namespaceURI != null) {
java.lang.String prefix = xmlWriter.getPrefix(namespaceURI);
if (prefix == null) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
} else {
// i.e this is the default namespace
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
} else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
private void writeQNames(javax.xml.namespace.QName[] qnames,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (qnames != null) {
// we have to store this data until last moment since it is not possible to write any
// namespace data after writing the charactor data
java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer();
java.lang.String namespaceURI = null;
java.lang.String prefix = null;
for (int i = 0; i < qnames.length; i++) {
if (i > 0) {
stringToWrite.append(" ");
}
namespaceURI = qnames[i].getNamespaceURI();
if (namespaceURI != null) {
prefix = xmlWriter.getPrefix(namespaceURI);
if ((prefix == null) || (prefix.length() == 0)) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
}
xmlWriter.writeCharacters(stringToWrite.toString());
}
}
/**
* Register a namespace prefix
*/
private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = generatePrefix(namespace);
while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) {
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
/**
* databinding method to get an XML representation of this object
*
*/
public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName)
throws org.apache.axis2.databinding.ADBException{
java.util.ArrayList elementList = new java.util.ArrayList();
java.util.ArrayList attribList = new java.util.ArrayList();
elementList.add(org.apache.axis2.databinding.utils.reader.ADBXMLStreamReader.ELEMENT_TEXT);
if (localDate != null){
elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localDate));
} else {
throw new org.apache.axis2.databinding.ADBException("date cannot be null!!");
}
return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray());
}
/**
* Factory class that keeps the parse method
*/
public static class Factory{
public static Date fromString(java.lang.String value,
java.lang.String namespaceURI){
Date returnValue = new Date();
returnValue.setDate(
org.apache.axis2.databinding.utils.ConverterUtil.convertToDate(value));
return returnValue;
}
public static Date fromString(javax.xml.stream.XMLStreamReader xmlStreamReader,
java.lang.String content) {
if (content.indexOf(":") > -1){
java.lang.String prefix = content.substring(0,content.indexOf(":"));
java.lang.String namespaceUri = xmlStreamReader.getNamespaceContext().getNamespaceURI(prefix);
return Date.Factory.fromString(content,namespaceUri);
} else {
return Date.Factory.fromString(content,"");
}
}
/**
* static method to create the object
* Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable
* If this object is not an element, it is a complex type and the reader is at the event just after the outer start element
* Postcondition: If this object is an element, the reader is positioned at its end element
* If this object is a complex type, the reader is positioned at the end element of its outer element
*/
public static Date parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{
Date object =
new Date();
int event;
java.lang.String nillableValue = null;
java.lang.String prefix ="";
java.lang.String namespaceuri ="";
try {
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){
java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
"type");
if (fullTypeName!=null){
java.lang.String nsPrefix = null;
if (fullTypeName.indexOf(":") > -1){
nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix==null?"":nsPrefix;
java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1);
if (!"date".equals(type)){
//find namespace for the prefix
java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (Date)org.apache.axis2.databinding.types.soapencoding.ExtensionMapper.getTypeObject(
nsUri,type,reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
java.util.Vector handledAttributes = new java.util.Vector();
while(!reader.isEndElement()) {
if (reader.isStartElement() || reader.hasText()){
if (reader.isStartElement() || reader.hasText()){
java.lang.String content = reader.getElementText();
object.setDate(
org.apache.axis2.databinding.utils.ConverterUtil.convertToDate(content));
} // End of if for expected property start element
else{
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName());
}
} else {
reader.next();
}
} // end of while loop
} catch (javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}//end of factory class
}
| |
package models.field_visit;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import helpers.DB;
import models.farmer.Farmer;
import models.field_visit.PlantStageEnd;
import models.field_visit.PlantStageStart;
import models.field_visit.WeeklyVisitReport;
import org.sql2o.Connection;
import play.Logger;
import play.libs.F;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Date;
/**
* Created by lenovo on 11/9/2015.
*/
public class FarmerFieldVisit {
public class FieldVisit {
@JsonProperty("season_id")
public int seasonId;
@JsonProperty("season_code")
public String seasonCode;
@JsonProperty("farmer_field_visit_id")
public int farmerFieldVisitId;
@JsonProperty("farmer_id")
public int farmerId;
@JsonProperty("farmer_name")
public String farmerName;
@JsonProperty("cluster_group_id")
public int clusterGroupId;
@JsonProperty("cluster_group_name")
public String clusterGroupName;
@JsonProperty("kkv_group_id")
public int kkvGroupId;
@JsonProperty("kkv_group_name")
public String kkvGroupName;
@JsonProperty("desa_id")
public int desaId;
@JsonProperty("desa_name")
public String desaName;
@JsonProperty("polygon")
public ArrayList<HashMap<String, Double>> polygon;
}
public class FieldVisitDetail {
@JsonProperty("farmer_field_visit_id")
public int farmerFieldVisitId;
@JsonIgnore
public int seasonId;
@JsonProperty("farmer_id")
public int farmerId;
@JsonProperty("farmer_name")
public String farmerName;
@JsonProperty("cluster_group_id")
public int clusterGroupId;
@JsonProperty("cluster_group_name")
public String clusterGroupName;
@JsonProperty("kkv_group_id")
public int kkvGroupId;
@JsonProperty("kkv_group_name")
public String kkvGroupName;
@JsonProperty("desa_id")
public int desaId;
@JsonProperty("desa_name")
public String desaName;
@JsonProperty("plant_stage_start")
public HashMap<String, Object> plantStageStart;
@JsonProperty("plant_stage_end")
public HashMap<String, Object> plantStageEnd;
@JsonProperty("weekly_visit_list")
public List<WeeklyVisitReport> listWeeklyVisit;
@JsonProperty("polygon")
public ArrayList<HashMap<String, Double>> polygon;
}
public class FarmerSimple {
@JsonProperty("farmer_id")
public int farmer_id;
@JsonProperty("farmer_name")
public String farmer_name;
}
public static List<FieldVisit> select (int seasonId) {
try (Connection con = DB.sql2o.open()) {
String sql =
"SELECT season.season_id as seasonId, season.season_code AS seasonCode, " +
"v.farmer_field_visit_id AS farmerFieldVisitId, v.farmer_id AS farmerId, f.name AS farmerName, " +
"ds.id AS desaId, ds.name AS desaName, c.id AS clusterGroupId, c.name AS clusterGroupName, " +
"kkv.id AS kkvGroupId, kkv.name AS kkvGroupName " +
"FROM farmer_field_visit v, farmer f, master_desa ds, master_season season, cluster_group c, farmer_kkv_group kkv " +
"WHERE (:seasonId = -1 OR v.season_id = :seasonId) AND " +
"v.farmer_id = f.id AND " +
"v.season_id = season.season_id AND " +
"f.desa_id = ds.id AND " +
"f.cluster_group_id = c.id AND " +
"f.kkv_group_id = kkv.id";
List<FieldVisit> fieldVisits = con.createQuery(sql)
.addParameter("seasonId", seasonId)
.executeAndFetch(FieldVisit.class);
for (FieldVisit fieldVisit : fieldVisits) {
fieldVisit.polygon = selectFieldPolygon(fieldVisit.farmerFieldVisitId, fieldVisit.seasonId);
}
return fieldVisits;
}
}
public static List<FarmerSimple> selectUnassignedFarmer (int seasonId) {
try (Connection con = DB.sql2o.open()) {
String sql =
"SELECT f.id AS farmer_id, f.name AS farmer_name FROM farmer f " +
"WHERE NOT EXISTS " +
"(SELECT * FROM farmer_field_visit v WHERE v.farmer_id = f.id AND v.season_id = :seasonId) " +
"ORDER BY farmer_name";
return con.createQuery(sql)
.addParameter("seasonId", seasonId)
.executeAndFetch(FarmerSimple.class);
}
}
public static FieldVisitDetail selectDetail (int farmerFieldVisitId) {
try (Connection con = DB.sql2o.open()) {
String sql =
"SELECT v.farmer_field_visit_id AS farmerFieldVisitId, v.farmer_id AS farmerId, f.name AS farmerName, " +
"ds.id AS desaId, ds.name AS desaName, c.id AS clusterGroupId, c.name AS clusterGroupName, " +
"kkv.id AS kkvGroupId, kkv.name AS kkvGroupName, v.season_id AS seasonId " +
"FROM farmer_field_visit v, farmer f, master_desa ds, cluster_group c, farmer_kkv_group kkv " +
"WHERE v.farmer_field_visit_id = :farmerFieldVisitId AND v.farmer_id = f.id AND " +
"f.desa_id = ds.id AND " +
"f.cluster_group_id = c.id AND " +
"f.kkv_group_id = kkv.id";
FieldVisitDetail detail = con.createQuery(sql)
.addParameter("farmerFieldVisitId", farmerFieldVisitId)
.executeAndFetchFirst(FieldVisitDetail.class);
if (detail == null) return detail;
detail.polygon = selectFieldPolygon(farmerFieldVisitId, detail.seasonId);
detail.plantStageStart = new HashMap<String, Object>();
detail.plantStageEnd = new HashMap<String, Object>();
for (PlantStageStart plantStageStart : PlantStageStart.select(null, detail.farmerFieldVisitId)) {
detail.plantStageStart.put(plantStageStart.plantStageType, plantStageStart.startDate);
}
for (PlantStageEnd plantStageEnd : PlantStageEnd.select(null, detail.farmerFieldVisitId)) {
detail.plantStageEnd.put(plantStageEnd.plantStageType, plantStageEnd.endDate);
}
detail.listWeeklyVisit = WeeklyVisitReport.select(-1, detail.farmerFieldVisitId);
return detail;
}
}
public static ArrayList<HashMap<String, Double>> selectFieldPolygon (int fieldVisitId, int seasonId) {
try (Connection con = DB.sql2o.open()) {
String sql = "SELECT ST_AsText(polygon) FROM farmer_field_visit " +
"WHERE farmer_field_visit_id = :fieldVisitId AND season_id = :seasonId";
String polygon = con.createQuery(sql)
.addParameter("fieldVisitId", fieldVisitId)
.addParameter("seasonId", seasonId)
.executeScalar(String.class);
if (polygon == null) return null;
polygon = polygon.replace("(","").replace(")","").replace("POLYGON","");
ArrayList<HashMap<String, Double>> longLatList = new ArrayList();
for (String point : polygon.split(",")) {
String longitude = (point.split(" "))[0];
String latitude = (point.split(" "))[1];
HashMap<String, Double> map = new HashMap<>();
map.put("longitude", Double.parseDouble(longitude));
map.put("latitude", Double.parseDouble(latitude));
longLatList.add(map);
}
return longLatList;
}
}
public static int insert (int seasonId, int farmerId) {
try (Connection con = DB.sql2o.open()) {
String sql = "INSERT INTO farmer_field_visit (season_id, farmer_id) VALUES (:seasonId, :farmerId)";
return con.createQuery(sql, true)
.addParameter("seasonId", seasonId)
.addParameter("farmerId", farmerId)
.executeUpdate()
.getKey(Integer.class);
}
}
public static int insertPolygon (int seasonId, int farmerId, List<F.Tuple<Double, Double>> longLatList) {
try (Connection con = DB.sql2o.open()) {
String sql = "UPDATE farmer_field_visit SET polygon = ST_GeographyFromText('POLYGON((";
int counter = 0;
for (F.Tuple<Double, Double> longLat : longLatList) {
if (counter == 0) {
sql = sql + longLat._1 + " " + longLat._2;
} else {
sql = sql + ", " + longLat._1 + " " + longLat._2;
}
counter++;
}
sql = sql + "))') WHERE season_id = :seasonId AND farmer_id = :farmerId";
return con.createQuery(sql)
.addParameter("seasonId", seasonId)
.addParameter("farmerId", farmerId)
.executeUpdate()
.getResult();
}
}
public static int delete (int seasonId, int farmerId) throws Exception {
try (Connection con = DB.sql2o.open()) {
// delete files
try {
String sqlGetFarmerId = "SELECT farmer_field_visit_id FROM farmer_field_visit WHERE season_id = :seasonId AND farmer_id = :farmerId";
int farmerFieldVisitId = con.createQuery(sqlGetFarmerId)
.addParameter("seasonId", seasonId)
.addParameter("farmerId", farmerId).executeScalar(Integer.class);
for (WeeklyVisitReport weeklyVisitReport : WeeklyVisitReport.select(-1, farmerFieldVisitId)) {
FarmerFieldVisitFile.delete(weeklyVisitReport.weeklyVisitId, null);
}
} catch (Exception e) {
// do nothing
}
String sql = "DELETE FROM farmer_field_visit WHERE season_id = :seasonId AND farmer_id = :farmerId";
return con.createQuery(sql)
.addParameter("seasonId", seasonId)
.addParameter("farmerId", farmerId).executeUpdate().getResult();
}
}
}
| |
/**
* 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.yarn.client.api.impl;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.AbstractMap.SimpleEntry;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.net.Node;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.yarn.api.ApplicationMasterProtocol;
import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest;
import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse;
import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterRequest;
import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterResponse;
import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterRequest;
import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterResponse;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerStatus;
import org.apache.hadoop.yarn.api.records.ContainerUpdateType;
import org.apache.hadoop.yarn.api.records.ExecutionType;
import org.apache.hadoop.yarn.api.records.ExecutionTypeRequest;
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
import org.apache.hadoop.yarn.api.records.NMToken;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.ResourceBlacklistRequest;
import org.apache.hadoop.yarn.api.records.ResourceInformation;
import org.apache.hadoop.yarn.api.records.ResourceRequest;
import org.apache.hadoop.yarn.api.records.SchedulingRequest;
import org.apache.hadoop.yarn.api.records.Token;
import org.apache.hadoop.yarn.api.records.UpdateContainerRequest;
import org.apache.hadoop.yarn.api.records.UpdatedContainer;
import org.apache.hadoop.yarn.api.resource.PlacementConstraint;
import org.apache.hadoop.yarn.client.AMRMClientUtils;
import org.apache.hadoop.yarn.client.ClientRMProxy;
import org.apache.hadoop.yarn.client.api.AMRMClient;
import org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest;
import org.apache.hadoop.yarn.client.api.InvalidContainerRequestException;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.ApplicationMasterNotRegisteredException;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.security.AMRMTokenIdentifier;
import org.apache.hadoop.yarn.util.RackResolver;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import org.apache.hadoop.yarn.util.resource.Resources;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Private
@Unstable
public class AMRMClientImpl<T extends ContainerRequest> extends AMRMClient<T> {
private static final Logger LOG =
LoggerFactory.getLogger(AMRMClientImpl.class);
private static final List<String> ANY_LIST =
Collections.singletonList(ResourceRequest.ANY);
private int lastResponseId = 0;
protected String appHostName;
protected int appHostPort;
protected String appTrackingUrl;
protected String newTrackingUrl;
protected ApplicationMasterProtocol rmClient;
protected Resource clusterAvailableResources;
protected int clusterNodeCount;
// blacklistedNodes is required for keeping history of blacklisted nodes that
// are sent to RM. On RESYNC command from RM, blacklistedNodes are used to get
// current blacklisted nodes and send back to RM.
protected final Set<String> blacklistedNodes = new HashSet<String>();
protected final Set<String> blacklistAdditions = new HashSet<String>();
protected final Set<String> blacklistRemovals = new HashSet<String>();
private Map<Set<String>, PlacementConstraint> placementConstraints =
new HashMap<>();
protected Map<String, Resource> resourceProfilesMap;
static class ResourceRequestInfo<T> {
ResourceRequest remoteRequest;
LinkedHashSet<T> containerRequests;
ResourceRequestInfo(Long allocationRequestId, Priority priority,
String resourceName, Resource capability, boolean relaxLocality) {
remoteRequest = ResourceRequest.newBuilder().priority(priority)
.resourceName(resourceName).capability(capability).numContainers(0)
.allocationRequestId(allocationRequestId).relaxLocality(relaxLocality)
.build();
containerRequests = new LinkedHashSet<T>();
}
}
/**
* Class compares Resource by memory, then cpu and then the remaining resource
* types in reverse order.
*/
static class ResourceReverseComparator<T extends Resource>
implements Comparator<T>, Serializable {
public int compare(Resource res0, Resource res1) {
return res1.compareTo(res0);
}
}
private final Map<Long, RemoteRequestsTable<T>> remoteRequests =
new HashMap<>();
protected final Set<ResourceRequest> ask = new TreeSet<ResourceRequest>(
new org.apache.hadoop.yarn.api.records.ResourceRequest.ResourceRequestComparator());
protected final Set<ContainerId> release = new TreeSet<ContainerId>();
// pendingRelease holds history of release requests.
// request is removed only if RM sends completedContainer.
// How it different from release? --> release is for per allocate() request.
protected Set<ContainerId> pendingRelease = new TreeSet<ContainerId>();
// change map holds container resource change requests between two allocate()
// calls, and are cleared after each successful allocate() call.
protected final Map<ContainerId,
SimpleEntry<Container, UpdateContainerRequest>> change = new HashMap<>();
// pendingChange map holds history of container resource change requests in
// case AM needs to reregister with the ResourceManager.
// Change requests are removed from this map if RM confirms the change
// through allocate response, or if RM confirms that the container has been
// completed.
protected final Map<ContainerId,
SimpleEntry<Container, UpdateContainerRequest>> pendingChange =
new HashMap<>();
private List<SchedulingRequest> schedulingRequests = new ArrayList<>();
private Map<Set<String>, List<SchedulingRequest>> outstandingSchedRequests =
new HashMap<>();
public AMRMClientImpl() {
super(AMRMClientImpl.class.getName());
}
@VisibleForTesting
AMRMClientImpl(ApplicationMasterProtocol protocol) {
super(AMRMClientImpl.class.getName());
this.rmClient = protocol;
}
@Override
protected void serviceInit(Configuration conf) throws Exception {
RackResolver.init(conf);
super.serviceInit(conf);
}
@Override
protected void serviceStart() throws Exception {
final YarnConfiguration conf = new YarnConfiguration(getConfig());
try {
if (rmClient == null) {
rmClient = ClientRMProxy.createRMProxy(
conf, ApplicationMasterProtocol.class);
}
} catch (IOException e) {
throw new YarnRuntimeException(e);
}
super.serviceStart();
}
@Override
protected void serviceStop() throws Exception {
if (this.rmClient != null) {
RPC.stopProxy(this.rmClient);
}
super.serviceStop();
}
@Override
public RegisterApplicationMasterResponse registerApplicationMaster(
String appHostName, int appHostPort, String appTrackingUrl)
throws YarnException, IOException {
return registerApplicationMaster(appHostName, appHostPort, appTrackingUrl,
null);
}
@Override
public RegisterApplicationMasterResponse registerApplicationMaster(
String appHostName, int appHostPort, String appTrackingUrl,
Map<Set<String>, PlacementConstraint> placementConstraintsMap)
throws YarnException, IOException {
this.appHostName = appHostName;
this.appHostPort = appHostPort;
this.appTrackingUrl = appTrackingUrl;
if (placementConstraintsMap != null && !placementConstraintsMap.isEmpty()) {
this.placementConstraints.putAll(placementConstraintsMap);
}
Preconditions.checkArgument(appHostName != null,
"The host name should not be null");
Preconditions.checkArgument(appHostPort >= -1, "Port number of the host"
+ " should be any integers larger than or equal to -1");
return registerApplicationMaster();
}
@SuppressWarnings("unchecked")
private RegisterApplicationMasterResponse registerApplicationMaster()
throws YarnException, IOException {
RegisterApplicationMasterRequest request =
RegisterApplicationMasterRequest.newInstance(this.appHostName,
this.appHostPort, this.appTrackingUrl);
if (!this.placementConstraints.isEmpty()) {
request.setPlacementConstraints(this.placementConstraints);
}
RegisterApplicationMasterResponse response =
rmClient.registerApplicationMaster(request);
synchronized (this) {
lastResponseId = 0;
if (!response.getNMTokensFromPreviousAttempts().isEmpty()) {
populateNMTokens(response.getNMTokensFromPreviousAttempts());
}
this.resourceProfilesMap = response.getResourceProfiles();
List<Container> prevContainers =
response.getContainersFromPreviousAttempts();
AMRMClientUtils.removeFromOutstandingSchedulingRequests(prevContainers,
this.outstandingSchedRequests);
}
return response;
}
@Override
public synchronized void addSchedulingRequests(
Collection<SchedulingRequest> newSchedulingRequests) {
this.schedulingRequests.addAll(newSchedulingRequests);
AMRMClientUtils.addToOutstandingSchedulingRequests(newSchedulingRequests,
this.outstandingSchedRequests);
}
@Override
public AllocateResponse allocate(float progressIndicator)
throws YarnException, IOException {
Preconditions.checkArgument(progressIndicator >= 0,
"Progress indicator should not be negative");
AllocateResponse allocateResponse = null;
List<ResourceRequest> askList = null;
List<ContainerId> releaseList = null;
AllocateRequest allocateRequest = null;
List<String> blacklistToAdd = new ArrayList<String>();
List<String> blacklistToRemove = new ArrayList<String>();
Map<ContainerId, SimpleEntry<Container, UpdateContainerRequest>> oldChange =
new HashMap<>();
List<SchedulingRequest> schedulingRequestList = new LinkedList<>();
try {
synchronized (this) {
askList = cloneAsks();
// Save the current change for recovery
oldChange.putAll(change);
List<UpdateContainerRequest> updateList = createUpdateList();
releaseList = new ArrayList<ContainerId>(release);
schedulingRequestList = new ArrayList<>(schedulingRequests);
// optimistically clear this collection assuming no RPC failure
ask.clear();
release.clear();
change.clear();
schedulingRequests.clear();
blacklistToAdd.addAll(blacklistAdditions);
blacklistToRemove.addAll(blacklistRemovals);
ResourceBlacklistRequest blacklistRequest =
ResourceBlacklistRequest.newInstance(blacklistToAdd,
blacklistToRemove);
allocateRequest = AllocateRequest.newBuilder()
.responseId(lastResponseId).progress(progressIndicator)
.askList(askList).resourceBlacklistRequest(blacklistRequest)
.releaseList(releaseList).updateRequests(updateList)
.schedulingRequests(schedulingRequestList).build();
if (this.newTrackingUrl != null) {
allocateRequest.setTrackingUrl(this.newTrackingUrl);
this.appTrackingUrl = this.newTrackingUrl;
this.newTrackingUrl = null;
}
// clear blacklistAdditions and blacklistRemovals before
// unsynchronized part
blacklistAdditions.clear();
blacklistRemovals.clear();
}
try {
allocateResponse = rmClient.allocate(allocateRequest);
} catch (ApplicationMasterNotRegisteredException e) {
LOG.warn("ApplicationMaster is out of sync with ResourceManager,"
+ " hence resyncing.");
synchronized (this) {
release.addAll(this.pendingRelease);
blacklistAdditions.addAll(this.blacklistedNodes);
for (RemoteRequestsTable remoteRequestsTable :
remoteRequests.values()) {
@SuppressWarnings("unchecked")
Iterator<ResourceRequestInfo<T>> reqIter =
remoteRequestsTable.iterator();
while (reqIter.hasNext()) {
addResourceRequestToAsk(reqIter.next().remoteRequest);
}
}
change.putAll(this.pendingChange);
for (List<SchedulingRequest> schedReqs :
this.outstandingSchedRequests.values()) {
this.schedulingRequests.addAll(schedReqs);
}
}
// re register with RM
registerApplicationMaster();
allocateResponse = allocate(progressIndicator);
return allocateResponse;
}
synchronized (this) {
// update these on successful RPC
clusterNodeCount = allocateResponse.getNumClusterNodes();
lastResponseId = allocateResponse.getResponseId();
clusterAvailableResources = allocateResponse.getAvailableResources();
if (!allocateResponse.getNMTokens().isEmpty()) {
populateNMTokens(allocateResponse.getNMTokens());
}
if (allocateResponse.getAMRMToken() != null) {
updateAMRMToken(allocateResponse.getAMRMToken());
}
if (!pendingRelease.isEmpty()
&& !allocateResponse.getCompletedContainersStatuses().isEmpty()) {
removePendingReleaseRequests(allocateResponse
.getCompletedContainersStatuses());
}
if (!pendingChange.isEmpty()) {
List<ContainerStatus> completed =
allocateResponse.getCompletedContainersStatuses();
List<UpdatedContainer> changed = new ArrayList<>();
changed.addAll(allocateResponse.getUpdatedContainers());
// remove all pending change requests that belong to the completed
// containers
for (ContainerStatus status : completed) {
ContainerId containerId = status.getContainerId();
pendingChange.remove(containerId);
}
// remove all pending change requests that have been satisfied
if (!changed.isEmpty()) {
removePendingChangeRequests(changed);
}
}
AMRMClientUtils.removeFromOutstandingSchedulingRequests(
allocateResponse.getAllocatedContainers(),
this.outstandingSchedRequests);
AMRMClientUtils.removeFromOutstandingSchedulingRequests(
allocateResponse.getContainersFromPreviousAttempts(),
this.outstandingSchedRequests);
}
} finally {
// TODO how to differentiate remote yarn exception vs error in rpc
if(allocateResponse == null) {
// we hit an exception in allocate()
// preserve ask and release for next call to allocate()
synchronized (this) {
release.addAll(releaseList);
// requests could have been added or deleted during call to allocate
// If requests were added/removed then there is nothing to do since
// the ResourceRequest object in ask would have the actual new value.
// If ask does not have this ResourceRequest then it was unchanged and
// so we can add the value back safely.
// This assumes that there will no concurrent calls to allocate() and
// so we dont have to worry about ask being changed in the
// synchronized block at the beginning of this method.
for(ResourceRequest oldAsk : askList) {
if(!ask.contains(oldAsk)) {
ask.add(oldAsk);
}
}
// change requests could have been added during the allocate call.
// Those are the newest requests which take precedence
// over requests cached in the oldChange map.
//
// Only insert entries from the cached oldChange map
// that do not exist in the current change map:
for (Map.Entry<ContainerId,
SimpleEntry<Container, UpdateContainerRequest>> entry :
oldChange.entrySet()) {
ContainerId oldContainerId = entry.getKey();
Container oldContainer = entry.getValue().getKey();
UpdateContainerRequest oldupdate = entry.getValue().getValue();
if (change.get(oldContainerId) == null) {
change.put(
oldContainerId, new SimpleEntry<>(oldContainer, oldupdate));
}
}
blacklistAdditions.addAll(blacklistToAdd);
blacklistRemovals.addAll(blacklistToRemove);
schedulingRequests.addAll(schedulingRequestList);
}
}
}
return allocateResponse;
}
private List<UpdateContainerRequest> createUpdateList() {
List<UpdateContainerRequest> updateList = new ArrayList<>();
for (Map.Entry<ContainerId, SimpleEntry<Container,
UpdateContainerRequest>> entry : change.entrySet()) {
Resource targetCapability = entry.getValue().getValue().getCapability();
ExecutionType targetExecType =
entry.getValue().getValue().getExecutionType();
ContainerUpdateType updateType =
entry.getValue().getValue().getContainerUpdateType();
int version = entry.getValue().getKey().getVersion();
updateList.add(
UpdateContainerRequest.newInstance(version, entry.getKey(),
updateType, targetCapability, targetExecType));
}
return updateList;
}
private List<ResourceRequest> cloneAsks() {
List<ResourceRequest> askList = new ArrayList<ResourceRequest>(ask.size());
for(ResourceRequest r : ask) {
// create a copy of ResourceRequest as we might change it while the
// RPC layer is using it to send info across
askList.add(ResourceRequest.clone(r));
}
return askList;
}
protected void removePendingReleaseRequests(
List<ContainerStatus> completedContainersStatuses) {
for (ContainerStatus containerStatus : completedContainersStatuses) {
pendingRelease.remove(containerStatus.getContainerId());
}
}
protected void removePendingChangeRequests(
List<UpdatedContainer> changedContainers) {
for (UpdatedContainer changedContainer : changedContainers) {
ContainerId containerId = changedContainer.getContainer().getId();
if (pendingChange.get(containerId) == null) {
continue;
}
if (LOG.isDebugEnabled()) {
LOG.debug("RM has confirmed changed resource allocation for "
+ "container " + containerId + ". Current resource allocation:"
+ changedContainer.getContainer().getResource()
+ ". Remove pending change request:"
+ pendingChange.get(containerId).getValue());
}
pendingChange.remove(containerId);
}
}
@Private
@VisibleForTesting
protected void populateNMTokens(List<NMToken> nmTokens) {
for (NMToken token : nmTokens) {
String nodeId = token.getNodeId().toString();
if (LOG.isDebugEnabled()) {
if (getNMTokenCache().containsToken(nodeId)) {
LOG.debug("Replacing token for : " + nodeId);
} else {
LOG.debug("Received new token for : " + nodeId);
}
}
getNMTokenCache().setToken(nodeId, token.getToken());
}
}
@Override
public void unregisterApplicationMaster(FinalApplicationStatus appStatus,
String appMessage, String appTrackingUrl) throws YarnException,
IOException {
Preconditions.checkArgument(appStatus != null,
"AppStatus should not be null.");
FinishApplicationMasterRequest request =
FinishApplicationMasterRequest.newInstance(appStatus, appMessage,
appTrackingUrl);
try {
while (true) {
FinishApplicationMasterResponse response =
rmClient.finishApplicationMaster(request);
if (response.getIsUnregistered()) {
break;
}
LOG.info("Waiting for application to be successfully unregistered.");
Thread.sleep(100);
}
} catch (InterruptedException e) {
LOG.info("Interrupted while waiting for application"
+ " to be removed from RMStateStore");
} catch (ApplicationMasterNotRegisteredException e) {
LOG.warn("ApplicationMaster is out of sync with ResourceManager,"
+ " hence resyncing.");
// re register with RM
registerApplicationMaster();
unregisterApplicationMaster(appStatus, appMessage, appTrackingUrl);
}
}
@Override
public synchronized void addContainerRequest(T req) {
Preconditions.checkArgument(req != null,
"Resource request can not be null.");
Set<String> dedupedRacks = new HashSet<String>();
if (req.getRacks() != null) {
dedupedRacks.addAll(req.getRacks());
if(req.getRacks().size() != dedupedRacks.size()) {
Joiner joiner = Joiner.on(',');
LOG.warn("ContainerRequest has duplicate racks: "
+ joiner.join(req.getRacks()));
}
}
Set<String> inferredRacks = resolveRacks(req.getNodes());
inferredRacks.removeAll(dedupedRacks);
Resource resource = checkAndGetResourceProfile(req.getResourceProfile(),
req.getCapability());
// check that specific and non-specific requests cannot be mixed within a
// priority
checkLocalityRelaxationConflict(req.getAllocationRequestId(),
req.getPriority(), ANY_LIST, req.getRelaxLocality());
// check that specific rack cannot be mixed with specific node within a
// priority. If node and its rack are both specified then they must be
// in the same request.
// For explicitly requested racks, we set locality relaxation to true
checkLocalityRelaxationConflict(req.getAllocationRequestId(),
req.getPriority(), dedupedRacks, true);
checkLocalityRelaxationConflict(req.getAllocationRequestId(),
req.getPriority(), inferredRacks, req.getRelaxLocality());
// check if the node label expression specified is valid
checkNodeLabelExpression(req);
if (req.getNodes() != null) {
HashSet<String> dedupedNodes = new HashSet<String>(req.getNodes());
if(dedupedNodes.size() != req.getNodes().size()) {
Joiner joiner = Joiner.on(',');
LOG.warn("ContainerRequest has duplicate nodes: "
+ joiner.join(req.getNodes()));
}
for (String node : dedupedNodes) {
addResourceRequest(req.getPriority(), node,
req.getExecutionTypeRequest(), resource, req, true,
req.getNodeLabelExpression());
}
}
for (String rack : dedupedRacks) {
addResourceRequest(req.getPriority(), rack, req.getExecutionTypeRequest(),
resource, req, true, req.getNodeLabelExpression());
}
// Ensure node requests are accompanied by requests for
// corresponding rack
for (String rack : inferredRacks) {
addResourceRequest(req.getPriority(), rack, req.getExecutionTypeRequest(),
resource, req, req.getRelaxLocality(),
req.getNodeLabelExpression());
}
// Off-switch
addResourceRequest(req.getPriority(), ResourceRequest.ANY,
req.getExecutionTypeRequest(), resource, req,
req.getRelaxLocality(), req.getNodeLabelExpression());
}
@Override
public synchronized void removeContainerRequest(T req) {
Preconditions.checkArgument(req != null,
"Resource request can not be null.");
Resource resource = checkAndGetResourceProfile(req.getResourceProfile(),
req.getCapability());
Set<String> allRacks = new HashSet<String>();
if (req.getRacks() != null) {
allRacks.addAll(req.getRacks());
}
allRacks.addAll(resolveRacks(req.getNodes()));
// Update resource requests
if (req.getNodes() != null) {
for (String node : new HashSet<String>(req.getNodes())) {
decResourceRequest(req.getPriority(), node,
req.getExecutionTypeRequest(), resource, req);
}
}
for (String rack : allRacks) {
decResourceRequest(req.getPriority(), rack,
req.getExecutionTypeRequest(), resource, req);
}
decResourceRequest(req.getPriority(), ResourceRequest.ANY,
req.getExecutionTypeRequest(), resource, req);
}
@Override
public synchronized void requestContainerUpdate(
Container container, UpdateContainerRequest updateContainerRequest) {
Preconditions.checkNotNull(container, "Container cannot be null!!");
Preconditions.checkNotNull(updateContainerRequest,
"UpdateContainerRequest cannot be null!!");
LOG.info("Requesting Container update : " +
"container=" + container + ", " +
"updateType=" + updateContainerRequest.getContainerUpdateType() + ", " +
"targetCapability=" + updateContainerRequest.getCapability() + ", " +
"targetExecType=" + updateContainerRequest.getExecutionType());
if (updateContainerRequest.getCapability() != null &&
updateContainerRequest.getExecutionType() == null) {
validateContainerResourceChangeRequest(
updateContainerRequest.getContainerUpdateType(),
container.getId(), container.getResource(),
updateContainerRequest.getCapability());
} else if (updateContainerRequest.getExecutionType() != null &&
updateContainerRequest.getCapability() == null) {
validateContainerExecTypeChangeRequest(
updateContainerRequest.getContainerUpdateType(),
container.getId(), container.getExecutionType(),
updateContainerRequest.getExecutionType());
} else if (updateContainerRequest.getExecutionType() == null &&
updateContainerRequest.getCapability() == null) {
throw new IllegalArgumentException("Both target Capability and" +
"target Execution Type are null");
} else {
throw new IllegalArgumentException("Support currently exists only for" +
" EITHER update of Capability OR update of Execution Type NOT both");
}
if (change.get(container.getId()) == null) {
change.put(container.getId(),
new SimpleEntry<>(container, updateContainerRequest));
} else {
change.get(container.getId()).setValue(updateContainerRequest);
}
if (pendingChange.get(container.getId()) == null) {
pendingChange.put(container.getId(),
new SimpleEntry<>(container, updateContainerRequest));
} else {
pendingChange.get(container.getId()).setValue(updateContainerRequest);
}
}
@Override
public synchronized void releaseAssignedContainer(ContainerId containerId) {
Preconditions.checkArgument(containerId != null,
"ContainerId can not be null.");
pendingRelease.add(containerId);
release.add(containerId);
pendingChange.remove(containerId);
}
@Override
public synchronized Resource getAvailableResources() {
return clusterAvailableResources;
}
@Override
public synchronized int getClusterNodeCount() {
return clusterNodeCount;
}
@Override
@SuppressWarnings("unchecked")
public Collection<T> getMatchingRequests(long allocationRequestId) {
RemoteRequestsTable remoteRequestsTable = getTable(allocationRequestId);
LinkedHashSet<T> list = new LinkedHashSet<>();
if (remoteRequestsTable != null) {
Iterator<ResourceRequestInfo<T>> reqIter =
remoteRequestsTable.iterator();
while (reqIter.hasNext()) {
ResourceRequestInfo<T> resReqInfo = reqIter.next();
list.addAll(resReqInfo.containerRequests);
}
}
return list;
}
@Override
public synchronized List<? extends Collection<T>> getMatchingRequests(
Priority priority,
String resourceName,
Resource capability) {
return getMatchingRequests(priority, resourceName,
ExecutionType.GUARANTEED, capability);
}
@Override
public List<? extends Collection<T>> getMatchingRequests(Priority priority,
String resourceName, ExecutionType executionType,
Resource capability, String profile) {
capability = checkAndGetResourceProfile(profile, capability);
return getMatchingRequests(priority, resourceName, executionType, capability);
}
@Override
@SuppressWarnings("unchecked")
public synchronized List<? extends Collection<T>> getMatchingRequests(
Priority priority, String resourceName, ExecutionType executionType,
Resource capability) {
Preconditions.checkArgument(capability != null,
"The Resource to be requested should not be null ");
Preconditions.checkArgument(priority != null,
"The priority at which to request containers should not be null ");
List<LinkedHashSet<T>> list = new LinkedList<>();
RemoteRequestsTable remoteRequestsTable = getTable(0);
if (null != remoteRequestsTable) {
List<ResourceRequestInfo<T>> matchingRequests = remoteRequestsTable
.getMatchingRequests(priority, resourceName, executionType,
capability);
if (null != matchingRequests) {
// If no exact match. Container may be larger than what was requested.
// get all resources <= capability. map is reverse sorted.
for (ResourceRequestInfo<T> resReqInfo : matchingRequests) {
if (Resources.fitsIn(resReqInfo.remoteRequest.getCapability(),
capability) && !resReqInfo.containerRequests.isEmpty()) {
list.add(resReqInfo.containerRequests);
}
}
}
}
// no match found
return list;
}
private Set<String> resolveRacks(List<String> nodes) {
Set<String> racks = new HashSet<String>();
if (nodes != null) {
List<Node> tmpList = RackResolver.resolve(nodes);
for (Node node : tmpList) {
String rack = node.getNetworkLocation();
// Ensure node requests are accompanied by requests for
// corresponding rack
if (rack == null) {
LOG.warn("Failed to resolve rack for node " + node + ".");
} else {
racks.add(rack);
}
}
}
return racks;
}
/**
* ContainerRequests with locality relaxation cannot be made at the same
* priority as ContainerRequests without locality relaxation.
*/
private void checkLocalityRelaxationConflict(Long allocationReqId,
Priority priority, Collection<String> locations, boolean relaxLocality) {
// Locality relaxation will be set to relaxLocality for all implicitly
// requested racks. Make sure that existing rack requests match this.
RemoteRequestsTable<T> remoteRequestsTable = getTable(allocationReqId);
if (remoteRequestsTable != null) {
@SuppressWarnings("unchecked")
List<ResourceRequestInfo> allCapabilityMaps =
remoteRequestsTable.getAllResourceRequestInfos(priority, locations);
for (ResourceRequestInfo reqs : allCapabilityMaps) {
ResourceRequest remoteRequest = reqs.remoteRequest;
boolean existingRelaxLocality = remoteRequest.getRelaxLocality();
if (relaxLocality != existingRelaxLocality) {
throw new InvalidContainerRequestException("Cannot submit a "
+ "ContainerRequest asking for location "
+ remoteRequest.getResourceName() + " with locality relaxation "
+ relaxLocality + " when it has already been requested"
+ "with locality relaxation " + existingRelaxLocality);
}
}
}
}
// When profile and override resource are specified at the same time, override
// predefined resource value in profile if any resource type has a positive
// value.
private Resource checkAndGetResourceProfile(String profile,
Resource overrideResource) {
Resource returnResource = overrideResource;
// if application requested a non-empty/null profile, and the
if (profile != null && !profile.isEmpty()) {
if (resourceProfilesMap == null || (!resourceProfilesMap.containsKey(
profile))) {
throw new InvalidContainerRequestException(
"Invalid profile name specified=" + profile + (
resourceProfilesMap == null ?
"" :
(", valid profile names are " + resourceProfilesMap
.keySet())));
}
returnResource = Resources.clone(resourceProfilesMap.get(profile));
for (ResourceInformation info : overrideResource
.getAllResourcesListCopy()) {
if (info.getValue() > 0) {
returnResource.setResourceInformation(info.getName(), info);
}
}
}
return returnResource;
}
/**
* Valid if a node label expression specified on container request is valid or
* not
*
* @param containerRequest
*/
private void checkNodeLabelExpression(T containerRequest) {
String exp = containerRequest.getNodeLabelExpression();
if (null == exp || exp.isEmpty()) {
return;
}
// Don't support specifying > 1 node labels in a node label expression now
if (exp.contains("&&") || exp.contains("||")) {
throw new InvalidContainerRequestException(
"Cannot specify more than one node label"
+ " in a single node label expression");
}
}
private void validateContainerResourceChangeRequest(
ContainerUpdateType updateType, ContainerId containerId,
Resource original, Resource target) {
Preconditions.checkArgument(containerId != null,
"ContainerId cannot be null");
Preconditions.checkArgument(original != null,
"Original resource capability cannot be null");
Preconditions.checkArgument(!Resources.equals(Resources.none(), original)
&& Resources.fitsIn(Resources.none(), original),
"Original resource capability must be greater than 0");
Preconditions.checkArgument(target != null,
"Target resource capability cannot be null");
Preconditions.checkArgument(!Resources.equals(Resources.none(), target)
&& Resources.fitsIn(Resources.none(), target),
"Target resource capability must be greater than 0");
if (ContainerUpdateType.DECREASE_RESOURCE == updateType) {
Preconditions.checkArgument(Resources.fitsIn(target, original),
"Target resource capability must fit in Original capability");
} else {
Preconditions.checkArgument(Resources.fitsIn(original, target),
"Target resource capability must be more than Original capability");
}
}
private void validateContainerExecTypeChangeRequest(
ContainerUpdateType updateType, ContainerId containerId,
ExecutionType original, ExecutionType target) {
Preconditions.checkArgument(containerId != null,
"ContainerId cannot be null");
Preconditions.checkArgument(original != null,
"Original Execution Type cannot be null");
Preconditions.checkArgument(target != null,
"Target Execution Type cannot be null");
if (ContainerUpdateType.DEMOTE_EXECUTION_TYPE == updateType) {
Preconditions.checkArgument(target == ExecutionType.OPPORTUNISTIC
&& original == ExecutionType.GUARANTEED,
"Incorrect Container update request, target should be" +
" OPPORTUNISTIC and original should be GUARANTEED");
} else {
Preconditions.checkArgument(target == ExecutionType.GUARANTEED
&& original == ExecutionType.OPPORTUNISTIC,
"Incorrect Container update request, target should be" +
" GUARANTEED and original should be OPPORTUNISTIC");
}
}
private void addResourceRequestToAsk(ResourceRequest remoteRequest) {
// This code looks weird but is needed because of the following scenario.
// A ResourceRequest is removed from the remoteRequestTable. A 0 container
// request is added to 'ask' to notify the RM about not needing it any more.
// Before the call to allocate, the user now requests more containers. If
// the locations of the 0 size request and the new request are the same
// (with the difference being only container count), then the set comparator
// will consider both to be the same and not add the new request to ask. So
// we need to check for the "same" request being present and remove it and
// then add it back. The comparator is container count agnostic.
// This should happen only rarely but we do need to guard against it.
if(ask.contains(remoteRequest)) {
ask.remove(remoteRequest);
}
ask.add(remoteRequest);
}
private void addResourceRequest(Priority priority, String resourceName,
ExecutionTypeRequest execTypeReq, Resource capability, T req,
boolean relaxLocality, String labelExpression) {
RemoteRequestsTable<T> remoteRequestsTable =
getTable(req.getAllocationRequestId());
if (remoteRequestsTable == null) {
remoteRequestsTable = new RemoteRequestsTable<>();
putTable(req.getAllocationRequestId(), remoteRequestsTable);
}
@SuppressWarnings("unchecked")
ResourceRequestInfo resourceRequestInfo = remoteRequestsTable
.addResourceRequest(req.getAllocationRequestId(), priority,
resourceName, execTypeReq, capability, req, relaxLocality,
labelExpression);
// Note this down for next interaction with ResourceManager
addResourceRequestToAsk(resourceRequestInfo.remoteRequest);
if (LOG.isDebugEnabled()) {
LOG.debug("Adding request to ask " + resourceRequestInfo.remoteRequest);
LOG.debug("addResourceRequest:" + " applicationId="
+ " priority=" + priority.getPriority()
+ " resourceName=" + resourceName + " numContainers="
+ resourceRequestInfo.remoteRequest.getNumContainers()
+ " #asks=" + ask.size());
}
}
private void decResourceRequest(Priority priority, String resourceName,
ExecutionTypeRequest execTypeReq, Resource capability, T req) {
RemoteRequestsTable<T> remoteRequestsTable =
getTable(req.getAllocationRequestId());
if (remoteRequestsTable != null) {
@SuppressWarnings("unchecked")
ResourceRequestInfo resourceRequestInfo =
remoteRequestsTable.decResourceRequest(priority, resourceName,
execTypeReq, capability, req);
// send the ResourceRequest to RM even if is 0 because it needs to
// override a previously sent value. If ResourceRequest was not sent
// previously then sending 0 aught to be a no-op on RM
if (resourceRequestInfo != null) {
addResourceRequestToAsk(resourceRequestInfo.remoteRequest);
// delete entry from map if no longer needed
if (resourceRequestInfo.remoteRequest.getNumContainers() == 0) {
remoteRequestsTable.remove(priority, resourceName,
execTypeReq.getExecutionType(), capability);
}
if (LOG.isDebugEnabled()) {
LOG.debug("AFTER decResourceRequest:"
+ " allocationRequestId=" + req.getAllocationRequestId()
+ " priority=" + priority.getPriority()
+ " resourceName=" + resourceName + " numContainers="
+ resourceRequestInfo.remoteRequest.getNumContainers()
+ " #asks=" + ask.size());
}
}
} else {
LOG.info("No remoteRequestTable found with allocationRequestId="
+ req.getAllocationRequestId());
}
}
@Override
public synchronized void updateBlacklist(List<String> blacklistAdditions,
List<String> blacklistRemovals) {
if (blacklistAdditions != null) {
this.blacklistAdditions.addAll(blacklistAdditions);
this.blacklistedNodes.addAll(blacklistAdditions);
// if some resources are also in blacklistRemovals updated before, we
// should remove them here.
this.blacklistRemovals.removeAll(blacklistAdditions);
}
if (blacklistRemovals != null) {
this.blacklistRemovals.addAll(blacklistRemovals);
this.blacklistedNodes.removeAll(blacklistRemovals);
// if some resources are in blacklistAdditions before, we should remove
// them here.
this.blacklistAdditions.removeAll(blacklistRemovals);
}
if (blacklistAdditions != null && blacklistRemovals != null
&& blacklistAdditions.removeAll(blacklistRemovals)) {
// we allow resources to appear in addition list and removal list in the
// same invocation of updateBlacklist(), but should get a warn here.
LOG.warn("The same resources appear in both blacklistAdditions and " +
"blacklistRemovals in updateBlacklist.");
}
}
@Override
public synchronized void updateTrackingUrl(String trackingUrl) {
this.newTrackingUrl = trackingUrl;
}
private void updateAMRMToken(Token token) throws IOException {
org.apache.hadoop.security.token.Token<AMRMTokenIdentifier> amrmToken =
new org.apache.hadoop.security.token.Token<AMRMTokenIdentifier>(token
.getIdentifier().array(), token.getPassword().array(), new Text(
token.getKind()), new Text(token.getService()));
// Preserve the token service sent by the RM when adding the token
// to ensure we replace the previous token setup by the RM.
// Afterwards we can update the service address for the RPC layer.
UserGroupInformation currentUGI = UserGroupInformation.getCurrentUser();
currentUGI.addToken(amrmToken);
amrmToken.setService(ClientRMProxy.getAMRMTokenService(getConfig()));
}
@VisibleForTesting
RemoteRequestsTable<T> getTable(long allocationRequestId) {
return remoteRequests.get(Long.valueOf(allocationRequestId));
}
@VisibleForTesting
Map<Set<String>, List<SchedulingRequest>> getOutstandingSchedRequests() {
return outstandingSchedRequests;
}
RemoteRequestsTable<T> putTable(long allocationRequestId,
RemoteRequestsTable<T> table) {
return remoteRequests.put(Long.valueOf(allocationRequestId), table);
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.engine;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.BinaryDocValues;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.Fields;
import org.apache.lucene.index.IndexCommit;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.LeafMetaData;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.PointValues;
import org.apache.lucene.index.SortedDocValues;
import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.index.StoredFieldVisitor;
import org.apache.lucene.index.Terms;
import org.apache.lucene.store.ByteBuffersDirectory;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Bits;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.internal.io.IOUtils;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.mapper.SourceToParse;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.translog.Translog;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;
/**
* A {@link DirectoryReader} contains a single leaf reader delegating to an in-memory Lucene segment that is lazily created from
* a single document.
*/
final class SingleDocDirectoryReader extends DirectoryReader {
private final SingleDocLeafReader leafReader;
SingleDocDirectoryReader(ShardId shardId, Translog.Index operation, DocumentMapper mapper, Analyzer analyzer) throws IOException {
this(new SingleDocLeafReader(shardId, operation, mapper, analyzer));
}
private SingleDocDirectoryReader(SingleDocLeafReader leafReader) throws IOException {
super(leafReader.directory, new LeafReader[]{leafReader});
this.leafReader = leafReader;
}
boolean assertMemorySegmentStatus(boolean loaded) {
return leafReader.assertMemorySegmentStatus(loaded);
}
private static UnsupportedOperationException unsupported() {
assert false : "unsupported operation";
return new UnsupportedOperationException();
}
@Override
protected DirectoryReader doOpenIfChanged() {
throw unsupported();
}
@Override
protected DirectoryReader doOpenIfChanged(IndexCommit commit) {
throw unsupported();
}
@Override
protected DirectoryReader doOpenIfChanged(IndexWriter writer, boolean applyAllDeletes) {
throw unsupported();
}
@Override
public long getVersion() {
throw unsupported();
}
@Override
public boolean isCurrent() {
throw unsupported();
}
@Override
public IndexCommit getIndexCommit() {
throw unsupported();
}
@Override
protected void doClose() throws IOException {
leafReader.close();
}
@Override
public CacheHelper getReaderCacheHelper() {
return leafReader.getReaderCacheHelper();
}
private static class SingleDocLeafReader extends LeafReader {
private final ShardId shardId;
private final Translog.Index operation;
private final DocumentMapper mapper;
private final Analyzer analyzer;
private final Directory directory;
private final AtomicReference<LeafReader> delegate = new AtomicReference<>();
SingleDocLeafReader(ShardId shardId, Translog.Index operation, DocumentMapper mapper, Analyzer analyzer) {
this.shardId = shardId;
this.operation = operation;
this.mapper = mapper;
this.analyzer = analyzer;
this.directory = new ByteBuffersDirectory();
}
private LeafReader getDelegate() {
ensureOpen();
LeafReader reader = delegate.get();
if (reader == null) {
synchronized (this) {
reader = delegate.get();
if (reader == null) {
reader = createInMemoryLeafReader();
final LeafReader existing = delegate.getAndSet(reader);
assert existing == null;
}
}
}
return reader;
}
private LeafReader createInMemoryLeafReader() {
assert Thread.holdsLock(this);
final ParsedDocument parsedDocs = mapper.parse(new SourceToParse(shardId.getIndexName(), operation.id(),
operation.source(), XContentHelper.xContentType(operation.source()), operation.routing()));
parsedDocs.updateSeqID(operation.seqNo(), operation.primaryTerm());
parsedDocs.version().setLongValue(operation.version());
final IndexWriterConfig writeConfig = new IndexWriterConfig(analyzer).setOpenMode(IndexWriterConfig.OpenMode.CREATE);
try (IndexWriter writer = new IndexWriter(directory, writeConfig)) {
writer.addDocument(parsedDocs.rootDoc());
final DirectoryReader reader = open(writer);
if (reader.leaves().size() != 1 || reader.leaves().get(0).reader().numDocs() != 1) {
reader.close();
throw new IllegalStateException("Expected a single document segment; " +
"but [" + reader.leaves().size() + " segments with " + reader.leaves().get(0).reader().numDocs() + " documents");
}
return reader.leaves().get(0).reader();
} catch (IOException e) {
throw new EngineException(shardId, "failed to create an in-memory segment for get [" + operation.id() + "]", e);
}
}
@Override
public CacheHelper getCoreCacheHelper() {
return getDelegate().getCoreCacheHelper();
}
@Override
public CacheHelper getReaderCacheHelper() {
return getDelegate().getReaderCacheHelper();
}
@Override
public Terms terms(String field) throws IOException {
return getDelegate().terms(field);
}
@Override
public NumericDocValues getNumericDocValues(String field) throws IOException {
return getDelegate().getNumericDocValues(field);
}
@Override
public BinaryDocValues getBinaryDocValues(String field) throws IOException {
return getDelegate().getBinaryDocValues(field);
}
@Override
public SortedDocValues getSortedDocValues(String field) throws IOException {
return getDelegate().getSortedDocValues(field);
}
@Override
public SortedNumericDocValues getSortedNumericDocValues(String field) throws IOException {
return getDelegate().getSortedNumericDocValues(field);
}
@Override
public SortedSetDocValues getSortedSetDocValues(String field) throws IOException {
return getDelegate().getSortedSetDocValues(field);
}
@Override
public NumericDocValues getNormValues(String field) throws IOException {
return getDelegate().getNormValues(field);
}
@Override
public FieldInfos getFieldInfos() {
return getDelegate().getFieldInfos();
}
@Override
public Bits getLiveDocs() {
return getDelegate().getLiveDocs();
}
@Override
public PointValues getPointValues(String field) throws IOException {
return getDelegate().getPointValues(field);
}
@Override
public void checkIntegrity() throws IOException {
}
@Override
public LeafMetaData getMetaData() {
return getDelegate().getMetaData();
}
@Override
public Fields getTermVectors(int docID) throws IOException {
return getDelegate().getTermVectors(docID);
}
@Override
public int numDocs() {
return 1;
}
@Override
public int maxDoc() {
return 1;
}
synchronized boolean assertMemorySegmentStatus(boolean loaded) {
if (loaded) {
assert delegate.get() != null :
"Expected an in memory segment was loaded; but it wasn't. Please check the reader wrapper implementation";
} else {
assert delegate.get() == null :
"Expected an in memory segment wasn't loaded; but it was. Please check the reader wrapper implementation";
}
return true;
}
@Override
public void document(int docID, StoredFieldVisitor visitor) throws IOException {
assert assertMemorySegmentStatus(true);
getDelegate().document(docID, visitor);
}
@Override
protected void doClose() throws IOException {
IOUtils.close(delegate.get(), directory);
}
}
}
| |
/**
* Copyright 2014 Netflix, 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 rx.internal.operators;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import java.util.NoSuchElementException;
import org.junit.Test;
import org.mockito.InOrder;
import rx.Observable;
import rx.Observer;
import rx.functions.Func1;
public class OperatorLastTest {
@Test
public void testLastWithElements() {
Observable<Integer> last = Observable.just(1, 2, 3).last();
assertEquals(3, last.toBlocking().single().intValue());
}
@Test(expected = NoSuchElementException.class)
public void testLastWithNoElements() {
Observable<?> last = Observable.empty().last();
last.toBlocking().single();
}
@Test
public void testLastMultiSubscribe() {
Observable<Integer> last = Observable.just(1, 2, 3).last();
assertEquals(3, last.toBlocking().single().intValue());
assertEquals(3, last.toBlocking().single().intValue());
}
@Test
public void testLastViaObservable() {
Observable.just(1, 2, 3).last();
}
@Test
public void testLast() {
Observable<Integer> observable = Observable.just(1, 2, 3).last();
@SuppressWarnings("unchecked")
Observer<Integer> observer = mock(Observer.class);
observable.subscribe(observer);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, times(1)).onNext(3);
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testLastWithOneElement() {
Observable<Integer> observable = Observable.just(1).last();
@SuppressWarnings("unchecked")
Observer<Integer> observer = mock(Observer.class);
observable.subscribe(observer);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, times(1)).onNext(1);
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testLastWithEmpty() {
Observable<Integer> observable = Observable.<Integer> empty().last();
@SuppressWarnings("unchecked")
Observer<Integer> observer = mock(Observer.class);
observable.subscribe(observer);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, times(1)).onError(
isA(NoSuchElementException.class));
inOrder.verifyNoMoreInteractions();
}
@Test
public void testLastWithPredicate() {
Observable<Integer> observable = Observable.just(1, 2, 3, 4, 5, 6)
.last(new Func1<Integer, Boolean>() {
@Override
public Boolean call(Integer t1) {
return t1 % 2 == 0;
}
});
@SuppressWarnings("unchecked")
Observer<Integer> observer = mock(Observer.class);
observable.subscribe(observer);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, times(1)).onNext(6);
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testLastWithPredicateAndOneElement() {
Observable<Integer> observable = Observable.just(1, 2).last(
new Func1<Integer, Boolean>() {
@Override
public Boolean call(Integer t1) {
return t1 % 2 == 0;
}
});
@SuppressWarnings("unchecked")
Observer<Integer> observer = mock(Observer.class);
observable.subscribe(observer);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, times(1)).onNext(2);
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testLastWithPredicateAndEmpty() {
Observable<Integer> observable = Observable.just(1).last(
new Func1<Integer, Boolean>() {
@Override
public Boolean call(Integer t1) {
return t1 % 2 == 0;
}
});
@SuppressWarnings("unchecked")
Observer<Integer> observer = mock(Observer.class);
observable.subscribe(observer);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, times(1)).onError(
isA(NoSuchElementException.class));
inOrder.verifyNoMoreInteractions();
}
@Test
public void testLastOrDefault() {
Observable<Integer> observable = Observable.just(1, 2, 3)
.lastOrDefault(4);
@SuppressWarnings("unchecked")
Observer<Integer> observer = mock(Observer.class);
observable.subscribe(observer);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, times(1)).onNext(3);
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testLastOrDefaultWithOneElement() {
Observable<Integer> observable = Observable.just(1).lastOrDefault(2);
@SuppressWarnings("unchecked")
Observer<Integer> observer = mock(Observer.class);
observable.subscribe(observer);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, times(1)).onNext(1);
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testLastOrDefaultWithEmpty() {
Observable<Integer> observable = Observable.<Integer> empty()
.lastOrDefault(1);
@SuppressWarnings("unchecked")
Observer<Integer> observer = mock(Observer.class);
observable.subscribe(observer);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, times(1)).onNext(1);
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testLastOrDefaultWithPredicate() {
Observable<Integer> observable = Observable.just(1, 2, 3, 4, 5, 6)
.lastOrDefault(8, new Func1<Integer, Boolean>() {
@Override
public Boolean call(Integer t1) {
return t1 % 2 == 0;
}
});
@SuppressWarnings("unchecked")
Observer<Integer> observer = mock(Observer.class);
observable.subscribe(observer);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, times(1)).onNext(6);
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testLastOrDefaultWithPredicateAndOneElement() {
Observable<Integer> observable = Observable.just(1, 2).lastOrDefault(4,
new Func1<Integer, Boolean>() {
@Override
public Boolean call(Integer t1) {
return t1 % 2 == 0;
}
});
@SuppressWarnings("unchecked")
Observer<Integer> observer = mock(Observer.class);
observable.subscribe(observer);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, times(1)).onNext(2);
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testLastOrDefaultWithPredicateAndEmpty() {
Observable<Integer> observable = Observable.just(1).lastOrDefault(2,
new Func1<Integer, Boolean>() {
@Override
public Boolean call(Integer t1) {
return t1 % 2 == 0;
}
});
@SuppressWarnings("unchecked")
Observer<Integer> observer = mock(Observer.class);
observable.subscribe(observer);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, times(1)).onNext(2);
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
}
| |
package me.aksalj.usiuboard.activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.util.Log;
import com.squareup.picasso.Picasso;
import me.aksalj.usiuboard.R;
import me.aksalj.utils.DeviceHelper;
/**
* Copyright (c) 2015 Salama AB
* All rights reserved
* Contact: aksalj@aksalj.me
* Website: http://www.aksalj.me
* <p/>
* Project : USIU Board
* File : me.aksalj.usiuboard.activity.SettingsActivity
* Date : Feb, 20 2015 10:36 AM
* Description :
*/
public class SettingsActivity extends PreferenceActivity {
public static String APP_PREF = "app_prefs";
public static String PREF_FIRST_LAUNCH = "fl";
public static String PREF_EULA_AGREED = "eula";
public static String PREF_GCM_NOTIFICATIONS = "gcm_notifs";
public static String PREF_PHONE_NOTIFICATIONS = "phone_notifs";
public static String PREF_LIMITED_DATA_CONSUMPTION = "wifi_only";
Handler mHandler;
/**
*
* @param cxt
* @return
*/
public static boolean isFirstLaunch(Context cxt) {
SharedPreferences pref = cxt.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE);
return pref.getBoolean(PREF_FIRST_LAUNCH, true);
}
/**
*
* @param cxt
*/
public static void hasFirstLaunched(Context cxt) {
SharedPreferences pref = cxt.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE);
pref.edit().putBoolean(PREF_FIRST_LAUNCH, false).apply();
}
/**
*
* @param cxt
* @return
*/
public static boolean hasAgreedToEULA(Context cxt) {
SharedPreferences pref = cxt.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE);
return pref.getBoolean(PREF_EULA_AGREED, false);
}
/**
*
* @param cxt
*/
public static void agreeToEULA(Context cxt) {
SharedPreferences pref = cxt.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE);
pref.edit().putBoolean(PREF_EULA_AGREED, true).apply();
}
/**
*
* @param cxt
* @return
*/
public static boolean notificationsAllowed(Context cxt) {
SharedPreferences pref = cxt.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE);
return pref.getBoolean(PREF_GCM_NOTIFICATIONS, false) || pref.getBoolean(PREF_PHONE_NOTIFICATIONS, false);
}
/**
*
* @param cxt
* @return
*/
public static boolean phoneNotificationsAllowed(Context cxt) {
SharedPreferences pref = cxt.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE);
return pref.getBoolean(PREF_PHONE_NOTIFICATIONS, false);
}
/**
*
* @param cxt
* @return
*/
public static boolean gcmNotificationsAllowed(Context cxt) {
SharedPreferences pref = cxt.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE);
return pref.getBoolean(PREF_GCM_NOTIFICATIONS, false);
}
/**
*
* @param cxt
* @return
*/
public static boolean dataConsumptionLimited(Context cxt) {
SharedPreferences pref = cxt.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE);
return pref.getBoolean(PREF_LIMITED_DATA_CONSUMPTION, false);
}
/**
*
* @param cxt
*/
public static void toggleDataConsumption(Context cxt) {
SharedPreferences pref = cxt.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE);
pref.edit().putBoolean(PREF_LIMITED_DATA_CONSUMPTION, !dataConsumptionLimited(cxt)).apply();
}
/**
* Save notification preferences. Must register if allowed and not registered ;)
* @param cxt
* @param phone
* @param gcm
*/
public static void allowNotifications(Context cxt, boolean phone, boolean gcm) {
SharedPreferences pref = cxt.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE);
pref
.edit()
.putBoolean(PREF_GCM_NOTIFICATIONS, gcm)
.putBoolean(PREF_PHONE_NOTIFICATIONS, phone)
.apply();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
addPreferencesFromResource(R.xml.settings);
// notifications
final CheckBoxPreference notifs = (CheckBoxPreference) findPreference("notifs");
notifs.setChecked(notificationsAllowed(this));
notifs.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean allow = (boolean) newValue;
if(!allow) {
allowNotifications(SettingsActivity.this, false, false);
// TODO: Unregister device from server
fakeWork(notifs, "Unsubscribing from server...", getString(R.string.notifs_statement_));
} else {
allowNotifications(SettingsActivity.this, true, true);
// TODO: Register device to server
fakeWork(notifs, "Subscribing to notifications from server...", getString(R.string.notifs_statement_));
}
return true;
}
});
CheckBoxPreference push = (CheckBoxPreference) findPreference("gcm_notifs");
push.setChecked(gcmNotificationsAllowed(this));
CheckBoxPreference phone = (CheckBoxPreference) findPreference("phone_notifs");
phone.setChecked(phoneNotificationsAllowed(this));
//phone.setSummary(DeviceHelper.getPhoneNumber(this));
// Wifi Only
CheckBoxPreference data = (CheckBoxPreference) findPreference("img_dld");
data.setChecked(dataConsumptionLimited(this));
data.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
toggleDataConsumption(SettingsActivity.this);
return true;
}
});
// cache
final Preference clearCache = findPreference("cache_clear");
clearCache.setSummary(DeviceHelper.cacheSizeInMB(this));
clearCache.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
clearCache.setSummary("Clearing...");
DeviceHelper.clearCache(SettingsActivity.this, new Runnable() {
@Override
public void run() {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
clearCache.setSummary(DeviceHelper.cacheSizeInMB(SettingsActivity.this));
}
}, 1030);
}
});
return true;
}
});
// bug report
// TODO: crashlytics.com
}
// FIXME: DELETE ME OHHH
void fakeWork(final Preference pref, String before, final String after) {
pref.setSummary(before);
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
pref.setSummary(after);
}
}, 3000);
}
}
| |
/**
* Logback: the reliable, generic, fast and flexible logging framework.
* Copyright (C) 1999-2015, QOS.ch. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
*/
package ch.qos.logback.classic.db;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.db.DriverManagerConnectionSource;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.status.StatusChecker;
import ch.qos.logback.core.testUtil.RandomUtil;
import ch.qos.logback.core.util.EnvUtil;
import ch.qos.logback.core.util.StatusPrinter;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.MDC;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
public class DBAppenderIntegrationTest {
static String LOCAL_HOST_NAME;
static String[] CONFORMING_HOST_LIST = new String[] { "Orion" };
static String[] POSTGRES_CONFORMING_HOST_LIST = new String[] { "haro" };
static String[] MYSQL_CONFORMING_HOST_LIST = new String[] { "xharo" };
static String[] ORACLE_CONFORMING_HOST_LIST = new String[] { "xharo" };
int diff = RandomUtil.getPositiveInt();
LoggerContext lc = new LoggerContext();
@BeforeClass
public static void setUpBeforeClass() throws Exception {
InetAddress localhostIA = InetAddress.getLocalHost();
LOCAL_HOST_NAME = localhostIA.getHostName();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
lc.setName("lc" + diff);
}
@After
public void tearDown() throws Exception {
// lc will never be used again
lc.stop();
}
DriverManagerConnectionSource getConnectionSource() {
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) lc
.getLogger(Logger.ROOT_LOGGER_NAME);
DBAppender dbAppender = (DBAppender) root.getAppender("DB");
assertNotNull(dbAppender);
return (DriverManagerConnectionSource) dbAppender.getConnectionSource();
}
public void doTest(String configFile) throws JoranException, SQLException {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
configurator.doConfigure(configFile);
Logger logger = lc.getLogger(DBAppenderIntegrationTest.class);
// the key userid is used in SiftingAppender test
// suffix with diff to avoid collision
MDC.put("userid"+diff, "user" + diff);
int runLength = 5;
for (int i = 1; i <= runLength; i++) {
logger.debug("This is a debug message. Message number: " + (diff + i));
}
Exception e = new Exception("Just testing", getCause());
logger.error("At last an error.", e);
StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
long lastEventId = getLastEventId();
verify(lastEventId);
// check that there were no errors
StatusChecker checker = new StatusChecker(lc);
checker.assertIsErrorFree();
}
long getLastEventId() throws SQLException {
DriverManagerConnectionSource cs = getConnectionSource();
Connection con = cs.getConnection();
Statement statement = con.createStatement();
statement.setMaxRows(1);
ResultSet rs = statement
.executeQuery("select event_id from logging_event order by event_id desc");
rs.next();
long eventId = rs.getLong(1);
rs.close();
statement.close();
return eventId;
}
void verify(long lastEventId) throws SQLException {
verifyDebugMsg(lastEventId);
verifyException(lastEventId);
verifyProperty(lastEventId);
}
void verifyDebugMsg(long lastEventId) throws SQLException {
DriverManagerConnectionSource cs = getConnectionSource();
Connection con = cs.getConnection();
Statement statement = con.createStatement();
ResultSet rs = statement
.executeQuery("select formatted_message from logging_event where event_id='"
+ (lastEventId - 1) + "'");
rs.next();
String msg = rs.getString(1);
assertEquals("This is a debug message. Message number: " + (diff + 5), msg);
}
@SuppressWarnings("unchecked")
void verifyProperty(long lastEventId) throws SQLException {
DriverManagerConnectionSource cs = getConnectionSource();
Connection con = cs.getConnection();
Statement statement = con.createStatement();
ResultSet rs = statement
.executeQuery("select mapped_key, mapped_value from logging_event_property where event_id='"
+ (lastEventId - 1) + "'");
Map<String, String> witness = lc.getCopyOfPropertyMap();
witness.putAll(MDC.getCopyOfContextMap());
Map<String, String> map = new HashMap<String, String>();
while (rs.next()) {
String key = rs.getString(1);
String val = rs.getString(2);
map.put(key, val);
}
assertEquals(witness, map);
}
void verifyException(long lastEventId) throws SQLException {
DriverManagerConnectionSource cs = getConnectionSource();
Connection con = cs.getConnection();
Statement statement = con.createStatement();
ResultSet rs = statement
.executeQuery("select trace_line from logging_event_exception where event_id='"
+ (lastEventId) + "' AND I='0'");
rs.next();
String traceLine = rs.getString(1);
assertEquals("java.lang.Exception: Just testing", traceLine);
}
Throwable getCause() {
return new IllegalStateException("test cause");
}
static boolean isConformingHostAndJDK16OrHigher(String[] conformingHostList) {
if (!EnvUtil.isJDK6OrHigher()) {
return false;
}
for (String conformingHost : conformingHostList) {
if (conformingHost.equalsIgnoreCase(LOCAL_HOST_NAME)) {
return true;
}
}
return false;
}
static boolean isConformingHostAndJDK16OrHigher() {
return isConformingHostAndJDK16OrHigher(CONFORMING_HOST_LIST);
}
@Test
public void sqlserver() throws Exception {
// perform test only on conforming hosts
if (!isConformingHostAndJDK16OrHigher()) {
return;
}
doTest("src/test/input/integration/db/sqlserver-with-driver.xml");
}
@Test
public void oracle10g() throws Exception {
// perform test only on conforming hosts
if (!isConformingHostAndJDK16OrHigher(ORACLE_CONFORMING_HOST_LIST)) {
return;
}
doTest("src/test/input/integration/db/oracle10g-with-driver.xml");
}
@Test
@Ignore
public void oracle11g() throws Exception {
// perform test only on conforming hosts
if (!isConformingHostAndJDK16OrHigher()) {
return;
}
doTest("src/test/input/integration/db/oracle11g-with-driver.xml");
}
@Test
public void mysql() throws Exception {
// perform test only on conforming hosts
if (!isConformingHostAndJDK16OrHigher(MYSQL_CONFORMING_HOST_LIST)) {
return;
}
doTest("src/test/input/integration/db/mysql-with-driver.xml");
}
@Test
public void postgres() throws Exception {
// perform test only on conforming hosts
if (!isConformingHostAndJDK16OrHigher(POSTGRES_CONFORMING_HOST_LIST)) {
return;
}
System.out.println("running postgres() test");
doTest("src/test/input/integration/db/postgresql-with-driver.xml");
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.plugin;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
import javax.management.JMException;
import javax.management.ObjectName;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.BrokerContext;
import org.apache.activemq.broker.jmx.ManagementContext;
import org.apache.activemq.plugin.jmx.RuntimeConfigurationView;
import org.apache.activemq.schema.core.DtoBroker;
import org.apache.activemq.spring.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class RuntimeConfigurationBroker extends AbstractRuntimeConfigurationBroker {
public static final Logger LOG = LoggerFactory.getLogger(RuntimeConfigurationBroker.class);
public static final String objectNamePropsAppendage = ",service=RuntimeConfiguration,name=Plugin";
PropertiesPlaceHolderUtil placeHolderUtil = null;
private long checkPeriod;
private long lastModified = -1;
private Resource configToMonitor;
private DtoBroker currentConfiguration;
private Schema schema;
public RuntimeConfigurationBroker(Broker next) {
super(next);
}
@Override
public void start() throws Exception {
super.start();
try {
BrokerContext brokerContext = next.getBrokerService().getBrokerContext();
if (brokerContext != null) {
configToMonitor = Utils.resourceFromString(brokerContext.getConfigurationUrl());
info("Configuration " + configToMonitor);
} else {
LOG.error("Null BrokerContext; impossible to determine configuration url resource from broker, updates cannot be tracked");
}
} catch (Exception error) {
LOG.error("failed to determine configuration url resource from broker, updates cannot be tracked", error);
}
currentConfiguration = loadConfiguration(configToMonitor);
monitorModification(configToMonitor);
registerMbean();
}
@Override
protected void registerMbean() {
if (getBrokerService().isUseJmx()) {
ManagementContext managementContext = getBrokerService().getManagementContext();
try {
objectName = new ObjectName(getBrokerService().getBrokerObjectName().toString() + objectNamePropsAppendage);
managementContext.registerMBean(new RuntimeConfigurationView(this), objectName);
} catch (Exception ignored) {
LOG.debug("failed to register RuntimeConfigurationMBean", ignored);
}
}
}
@Override
protected void unregisterMbean() {
if (objectName != null) {
try {
getBrokerService().getManagementContext().unregisterMBean(objectName);
} catch (JMException ignored) {
}
}
}
public String updateNow() {
LOG.info("Manual configuration update triggered");
infoString = "";
applyModifications(configToMonitor);
String result = infoString;
infoString = null;
return result;
}
private void monitorModification(final Resource configToMonitor) {
monitorTask = new Runnable() {
@Override
public void run() {
try {
if (configToMonitor.lastModified() > lastModified) {
applyModifications(configToMonitor);
}
} catch (Throwable e) {
LOG.error("Failed to determine lastModified time on configuration: " + configToMonitor, e);
}
}
};
if (lastModified > 0 && checkPeriod > 0) {
this.getBrokerService().getScheduler().executePeriodically(monitorTask, checkPeriod);
info("Monitoring for updates (every " + checkPeriod + "millis) : " + configToMonitor + ", lastUpdate: " + new Date(lastModified));
}
}
private void applyModifications(Resource configToMonitor) {
DtoBroker changed = loadConfiguration(configToMonitor);
if (changed != null && !currentConfiguration.equals(changed)) {
LOG.info("change in " + configToMonitor + " at: " + new Date(lastModified));
LOG.debug("current:" + filterPasswords(currentConfiguration));
LOG.debug("new :" + filterPasswords(changed));
processSelectiveChanges(currentConfiguration, changed);
currentConfiguration = changed;
} else {
info("No material change to configuration in " + configToMonitor + " at: " + new Date(lastModified));
}
}
private void processSelectiveChanges(DtoBroker currentConfiguration, DtoBroker modifiedConfiguration) {
for (Class upDatable : new Class[]{
DtoBroker.DestinationPolicy.class,
DtoBroker.NetworkConnectors.class,
DtoBroker.DestinationInterceptors.class,
DtoBroker.Plugins.class,
DtoBroker.Destinations.class}) {
processChanges(currentConfiguration, modifiedConfiguration, upDatable);
}
}
private void processChanges(DtoBroker currentConfiguration, DtoBroker modifiedConfiguration, Class upDatable) {
ConfigurationProcessor processor = ProcessorFactory.createProcessor(this, upDatable);
processor.processChanges(currentConfiguration, modifiedConfiguration);
}
private DtoBroker loadConfiguration(Resource configToMonitor) {
DtoBroker jaxbConfig = null;
if (configToMonitor != null) {
try {
JAXBContext context = JAXBContext.newInstance(DtoBroker.class);
Unmarshaller unMarshaller = context.createUnmarshaller();
unMarshaller.setSchema(getSchema());
// skip beans and pull out the broker node to validate
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(configToMonitor.getInputStream());
Node brokerRootNode = doc.getElementsByTagNameNS("*","broker").item(0);
if (brokerRootNode != null) {
JAXBElement<DtoBroker> brokerJAXBElement =
unMarshaller.unmarshal(brokerRootNode, DtoBroker.class);
jaxbConfig = brokerJAXBElement.getValue();
// if we can parse we can track mods
lastModified = configToMonitor.lastModified();
loadPropertiesPlaceHolderSupport(doc);
} else {
info("Failed to find 'broker' element by tag in: " + configToMonitor);
}
} catch (IOException e) {
info("Failed to access: " + configToMonitor, e);
} catch (JAXBException e) {
info("Failed to parse: " + configToMonitor, e);
} catch (ParserConfigurationException e) {
info("Failed to document parse: " + configToMonitor, e);
} catch (SAXException e) {
info("Failed to find broker element in: " + configToMonitor, e);
} catch (Exception e) {
info("Unexpected exception during load of: " + configToMonitor, e);
}
}
return jaxbConfig;
}
private void loadPropertiesPlaceHolderSupport(Document doc) {
BrokerContext brokerContext = getBrokerService().getBrokerContext();
if (brokerContext != null) {
Properties initialProperties = new Properties(System.getProperties());
placeHolderUtil = new PropertiesPlaceHolderUtil(initialProperties);
placeHolderUtil.mergeProperties(doc, initialProperties, brokerContext);
}
}
private Schema getSchema() throws SAXException, IOException {
if (schema == null) {
SchemaFactory schemaFactory = SchemaFactory.newInstance(
XMLConstants.W3C_XML_SCHEMA_NS_URI);
ArrayList<StreamSource> schemas = new ArrayList<StreamSource>();
schemas.add(new StreamSource(getClass().getResource("/activemq.xsd").toExternalForm()));
schemas.add(new StreamSource(getClass().getResource("/org/springframework/beans/factory/xml/spring-beans-3.0.xsd").toExternalForm()));
schema = schemaFactory.newSchema(schemas.toArray(new Source[]{}));
}
return schema;
}
public long getLastModified() {
return lastModified;
}
public Resource getConfigToMonitor() {
return configToMonitor;
}
public long getCheckPeriod() {
return checkPeriod;
}
public void setCheckPeriod(long checkPeriod) {
this.checkPeriod = checkPeriod;
}
}
| |
/**
*
*/
package org.commcare.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Hashtable;
import org.commcare.cases.model.Case;
import org.commcare.cases.util.CaseDBUtils;
import org.commcare.core.properties.CommCareProperties;
import org.commcare.data.xml.DataModelPullParser;
import org.commcare.model.PeriodicEvent;
import org.commcare.resources.model.CommCareOTARestoreListener;
import org.commcare.restore.CommCareOTARestoreTransitions;
import org.commcare.util.time.PermissionsEvent;
import org.commcare.xml.util.InvalidStructureException;
import org.commcare.xml.util.UnfullfilledRequirementsException;
import org.javarosa.core.io.StreamsUtil;
import org.javarosa.core.io.StreamsUtil.InputIOException;
import org.javarosa.core.io.StreamsUtil.OutputIOException;
import org.javarosa.core.log.WrappedException;
import org.javarosa.core.model.instance.ExternalDataInstance;
import org.javarosa.core.model.utils.DateUtils;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.Reference;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.PropertyManager;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.services.storage.IStorageUtility;
import org.javarosa.core.services.storage.StorageManager;
import org.javarosa.j2me.log.HandledThread;
import org.javarosa.j2me.reference.HttpReference.SecurityFailureListener;
import org.javarosa.j2me.storage.rms.RMSTransaction;
import org.javarosa.model.xform.DataModelSerializer;
import org.javarosa.service.transport.securehttp.AuthenticatedHttpTransportMessage;
import org.javarosa.service.transport.securehttp.HttpAuthenticator;
import org.javarosa.services.transport.TransportMessage;
import org.javarosa.services.transport.TransportService;
import org.javarosa.services.transport.impl.TransportException;
import org.javarosa.services.transport.impl.simplehttp.StreamingHTTPMessage;
import org.xmlpull.v1.XmlPullParserException;
/**
* @author ctsims
*
*/
public class CommCareRestorer implements Runnable {
protected static final int RESPONSE_NONE = 0;
protected static final int RESPONSE_YES = 1;
protected static final int RESPONSE_NO = 2;
int response = RESPONSE_NONE;
CommCareOTARestoreTransitions transitions;
CommCareOTARestoreListener listener;
String restoreURI;
boolean noPartial;
boolean isSync;
int[] caseTallies;
HttpAuthenticator authenticator;
boolean errorsOccurred;
String syncToken;
private boolean recoveryMode = false;
String originalRestoreURI;
String logSubmitURI;
String stateHash;
public void initialize(CommCareOTARestoreListener rListener, CommCareOTARestoreTransitions transitions,
String restoreURI, HttpAuthenticator authenticator, boolean isSync, boolean noPartial, String syncToken, String logSubmitURI){
if (isSync && !noPartial) {
System.err.println("WARNING: no-partial mode is strongly recommended when syncing");
}
this.syncToken = syncToken;
this.originalRestoreURI = restoreURI;
this.authenticator = authenticator;
this.logSubmitURI = logSubmitURI;
this.isSync = isSync;
if (isSync) {
this.stateHash = CaseDBUtils.computeHash((IStorageUtility<Case>)StorageManager.getStorage(Case.STORAGE_KEY));
initURI(syncToken, stateHash);
} else {
initURI(null,null);
}
this.noPartial = noPartial;
this.listener = rListener;
this.transitions = transitions;
HandledThread t = new HandledThread(this);
t.start();
}
private AuthenticatedHttpTransportMessage getClientMessage(HttpAuthenticator authenticator) {
AuthenticatedHttpTransportMessage message = AuthenticatedHttpTransportMessage.AuthenticatedHttpRequest(restoreURI, authenticator,
new SecurityFailureListener() {
public void onSecurityException(SecurityException e) {
PeriodicEvent.schedule(new PermissionsEvent());
}
});
return message;
}
public void run() {
if(authenticator != null) {
AuthenticatedHttpTransportMessage message = getClientMessage(authenticator);
tryDownload(message);
} else{
start();
}
}
public void start() {
Reference bypassRef = getBypassRef();
if(bypassRef != null) {
listener.refreshView();
tryBypass(bypassRef);
} else{
listener.statusUpdate(CommCareOTARestoreListener.REGULAR_START);
startOtaProcess();
}
}
private void startOtaProcess() {
if(authenticator == null) {
getCredentials();
} else {
listener.refreshView();
tryDownload(getClientMessage(authenticator));
}
}
private void getCredentials() {
listener.getCredentials();
}
private void tryDownload(AuthenticatedHttpTransportMessage message) {
tryDownload(message, true);
}
private void tryDownload(AuthenticatedHttpTransportMessage message, boolean tryCache) {
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_DOWNLOAD);
Logger.log("restore", "start");
try {
if(message.getUrl() == null) {
//TODO Figure out what's up with this failure
listener.onFailure(Localization.get("restore.noserveruri"));
listener.refreshView();
listener.onFailure(null);
return;
}
AuthenticatedHttpTransportMessage sent = (AuthenticatedHttpTransportMessage)TransportService.sendBlocking(message);
if(sent.isSuccess()) {
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_CONNECTION_MADE);
try {
if(tryCache) {
downloadRemoteData(sent.getResponse());
} else {
startRestore(sent.getResponse());
}
return;
} catch(IOException e) {
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_BAD_DOWNLOAD);
listener.promptRetry(Localization.get("restore.fail.transport", new String[] {WrappedException.printException(e)}));
return;
}
} else {
if(sent.getResponseCode() == 401) {
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_BAD_CREDENTIALS);
Logger.log("restore",Localization.get("restore.badcredentials"));
getCredentials();
return;
} else if(sent.getResponseCode() == 404) {
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_BAD_SERVER);
listener.promptRetry(Localization.get("restore.badserver"));
return;
} else if(sent.getResponseCode() == 412) {
//Our local copy of the case database has gotten out of sync. We need to start a recovery
//process.
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_BAD_DB);
startRecovery();
return;
} else if(sent.getResponseCode() == 503) {
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_DB_BUSY);
listener.promptRetry(Localization.get("restore.db.busy"));
return;
} else if(sent.getResponseCode() == 0){
listener.promptRetry(Localization.get("restore.fail.nointernet"));
} else {
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_FAIL_OTHER);
listener.promptRetry(Localization.get("restore.fail.other", new String[] {sent.getFailureReason()}));
return;
}
}
} catch (TransportException e) {
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_CONNECTION_FAIL_ENTRY);
listener.promptRetry(Localization.get("restore.fail.transport", new String[] {WrappedException.printException(e)}));
}
}
/**
* The recovery process comes in three phases. First, reporting to the server all of the cases that
* currently live on the phone (so the server can compare to its current state).
*
* Next, the full restore data is retrieved from the server and stored locally to ensure that the db
* can be recovered. Then local storage is cleared of data, and
*/
private void startRecovery() {
//Make a streaming message (the db is likely be too big to store in memory)
TransportMessage message = new StreamingHTTPMessage(this.getSubmitUrl()) {
public void _writeBody(OutputStream os) throws IOException {
//TODO: This is just the casedb, we actually want
DataModelSerializer s = new DataModelSerializer(os, new CommCareInstanceInitializer(CommCareStatic.appStringCache));
s.serialize(new ExternalDataInstance("jr://instance/casedb/report" + "/" + syncToken + "/" + stateHash,"casedb"), null);
}
};
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_RECOVER_SEND);
try {
message = TransportService.sendBlocking(message);
} catch (TransportException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(message.isSuccess()) {
//The server is now informed of our current state, time for the tricky part,
this.recoveryMode = true;
initURI(null, null);
//TODO: Set a flag somewhere (sync token perhaps) that we're in recovery mode
this.startOtaProcess();
} else {
listener.promptRetry("restore.recover.fail");
}
}
public boolean startRestore(InputStream input) {
listener.refreshView();
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_START);
final InputStream fInput = input;
if(recoveryMode) {
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_RECOVERY_WIPE);
//We've downloaded our file and can now recovery state fully for this user, so we need to wipe
//out existing cases. Ideally we'd do this by renaming the RMS (so we could recover if needed),
//but for now, just go for it.
StorageManager.getStorage(Case.STORAGE_KEY).removeAll();
}
errorsOccurred = false;
boolean success = false;
String[] parseErrors = new String[0];
String restoreID = null;
try {
beginTransaction();
CommCareTransactionParserFactory factory = new CommCareTransactionParserFactory(!noPartial);
DataModelPullParser parser = new DataModelPullParser(fInput,factory,listener);
parser.requireRootEnvelopeType("OpenRosaResponse");
success = parser.parse();
restoreID = factory.getRestoreId();
caseTallies = factory.getCaseTallies();
//TODO: Is success here too strict?
if (success) {
transitions.commitSyncToken(restoreID);
PropertyManager._().setProperty(CommCareProperties.LAST_SYNC_AT, DateUtils.formatDateTime(new Date(), DateUtils.FORMAT_ISO8601));
}
parseErrors = parser.getParseErrors();
} catch (IOException e) {
listener.promptRetry(Localization.get("restore.fail.retry"));
return false;
} catch (InvalidStructureException e) {
listener.promptRetry(Localization.get("restore.fail.technical"));
Logger.exception(e);
return false;
} catch (XmlPullParserException e) {
listener.promptRetry(Localization.get("restore.fail.technical"));
Logger.exception(e);
return false;
} catch (UnfullfilledRequirementsException e) {
listener.promptRetry(Localization.get("restore.fail.technical"));
Logger.exception(e);
return false;
} catch (RuntimeException e) {
Logger.exception(e);
listener.promptRetry(Localization.get("restore.fail.technical"));
return false;
} finally {
if (success) {
commitTransaction();
} else {
rollbackTransaction();
}
}
if (success) {
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_SUCCESS);
Logger.log("restore", "successful: " + (restoreID != null ? restoreID : "???"));
}
else {
if (noPartial) {
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_FAIL);
}
else {
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_FAIL_PARTIAL);
}
Logger.log("restore", (noPartial ? "restore errors; rolled-back" : "unsuccessful or partially successful") +
": " + (restoreID != null ? restoreID : "???"));
for(String s : parseErrors) {
Logger.log("restore", "err: " + s);
}
errorsOccurred = true;
}
listener.onSuccess();
return success || !noPartial;
}
public void tryBypass(final Reference bypass) {
listener.statusUpdate(CommCareOTARestoreListener.BYPASS_START);
try {
Logger.log("restore", "starting bypass restore attempt with file: " + bypass.getLocalURI());
InputStream restoreStream = bypass.getStream();
if(startRestore(restoreStream)) {
try {
//Success! Try to wipe the local file and then let the UI handle the rest.
restoreStream.close();
listener.statusUpdate(CommCareOTARestoreListener.BYPASS_CLEAN);
bypass.remove();
listener.statusUpdate(CommCareOTARestoreListener.BYPASS_CLEAN_SUCCESS);
} catch (IOException e) {
//Even if we fail to delete the local file, it's mostly fine. Jut let the user know
e.printStackTrace();
listener.statusUpdate(CommCareOTARestoreListener.BYPASS_CLEANFAIL);
}
Logger.log("restore", "bypass restore succeeded");
return;
}
} catch(IOException e) {
//Couldn't open a stream to the restore file, we'll need to dump out to
//OTA
e.printStackTrace();
}
//Something bad about the restore file.
//Skip it and dump back to OTA Restore
Logger.log("restore", "bypass restore failed, falling back to OTA");
listener.statusUpdate(CommCareOTARestoreListener.BYPASS_FAIL);
startOtaProcess();
}
/**
*
* @param stream
* @throws IOException If there was a problem which resulted in the cached
* file being corrupted or unavailable _and_ the input stream becoming invalidated
* such that a retry is necessary.
*/
private void downloadRemoteData(InputStream stream) throws IOException {
listener.refreshView();
Reference ref;
try {
ref = ReferenceManager._().DeriveReference(getCacheRef());
boolean badCache = false;
try {
//Wipe out the file if it exists (and we can)
if(ref.doesBinaryExist()) {
ref.remove();
}
} catch(IOException e) {
badCache = true;
}
if(badCache || ref.isReadOnly()) {
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_NO_CACHE);
noCache(stream);
} else {
OutputStream output;
//We want to treat any problems dealing with the inability to
//download as separate from a _failed_ download, which is
//what this try-catch is all about.
try {
output = ref.getOutputStream();
}
catch (Exception e) {
if(recoveryMode) {
//In recovery mode we can't really afford to not cache this, so report that, and try again.
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_NEED_CACHE);
return;
} else {
e.printStackTrace();
noCache(stream);
return;
}
}
try {
StreamsUtil.writeFromInputToOutputSpecific(stream, output);
} catch (OutputIOException e) {
//So for some reason it's entirely possible to fail on some Nokia phones only while _writing_
//to the SD card, not while opening the Stream for writing. This exception should be handled the
//same way
if(recoveryMode) {
//In recovery mode we can't really afford to not cache this, so report that, and try again.
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_NEED_CACHE);
return;
} else {
//otherwise we need to start again from the top and not attempt to cache.
//first, close out the input stream
try { stream.close(); } catch(IOException ioe) { }
//Now start over with no local caching
this.tryDownload(this.getClientMessage(this.getAuthenticator()), false);
return;
}
} catch(InputIOException e) {
//Now any further IOExceptions will get handled as "download failed",
//rather than "couldn't attempt to download"
throw e.getWrapped();
} finally {
try {
//need to close file's write stream before we read from it (S60 is not happy otherwise)
output.close();
} catch(IOException e) {
//Stupid Java
}
}
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_DOWNLOADED);
startRestore(ref.getStream());
}
} catch (InvalidReferenceException e) {
noCache(stream);
}
}
protected String getCacheRef() {
return "jr://file/commcare_ota_backup.xml";
}
private void initURI (String lastSync, String stateHash) {//TODO add character here
String baseURI = this.originalRestoreURI;
if(baseURI.indexOf("verson=2.0") == -1) {
baseURI = baseURI + (baseURI.indexOf("?") == -1 ? "?" : "&") + "version=2.0";
}
//get property
if (lastSync != null) {
this.restoreURI = baseURI + (baseURI.indexOf("?") == -1 ? "?" : "&" ) + "since=" + lastSync + "&state=ccsh:" + stateHash;
} else {
this.restoreURI = baseURI;
}
//add arg to request the count of items in the envelope
this.restoreURI = restoreURI + (restoreURI.indexOf("?") == -1 ? "?" : "&") + "items=true";
}
private void noCache(InputStream input) throws IOException {
if (this.noPartial) {
Logger.log("ota-restore", "attempted to restore OTA in 'no partial' mode, but could not cache payload locally");
throw new IOException();
} else {
listener.statusUpdate(CommCareOTARestoreListener.RESTORE_NO_CACHE);
startRestore(input);
}
}
public Reference getBypassRef() {
try {
String bypassRef = PropertyManager._().getSingularProperty(CommCareProperties.OTA_RESTORE_OFFLINE);
if(bypassRef == null || bypassRef == "") {
return null;
}
Reference bypass = ReferenceManager._().DeriveReference(bypassRef);
if(bypass == null || !bypass.doesBinaryExist()) {
return null;
}
return bypass;
} catch(Exception e){
e.printStackTrace();
//It would be absurdly stupid if we couldn't OTA restore because of an error here
return null;
}
}
public Hashtable<String, Integer> getCaseTallies() {
Hashtable<String, Integer> tall = new Hashtable<String, Integer>();
tall.put("create", new Integer(this.caseTallies[0]));
tall.put("update", new Integer(this.caseTallies[1]));
tall.put("close", new Integer(this.caseTallies[2]));
return tall;
}
private void beginTransaction () {
if (this.noPartial)
RMSTransaction.beginTransaction();
}
private void commitTransaction () {
if (this.noPartial)
RMSTransaction.commitTransaction();
}
private void rollbackTransaction () {
if (this.noPartial)
RMSTransaction.rollbackTransaction();
}
protected void fail(Exception e) {
listener.onFailure("Fail with: " + e.getMessage());
}
private String getSubmitUrl() {
return logSubmitURI;
}
public HttpAuthenticator getAuthenticator(){
return authenticator;
}
}
| |
/*
* GuiSettings.java
*
* This file is part of SQL Workbench/J, http://www.sql-workbench.net
*
* Copyright 2002-2015, Thomas Kellerer
*
* 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.
*
* To contact the author please send an email to: support@sql-workbench.net
*
*/
package workbench.resource;
import java.util.List;
import java.util.Set;
import workbench.db.DbSettings;
import workbench.db.DropType;
import workbench.db.WbConnection;
import workbench.util.CollectionUtil;
import static workbench.resource.Settings.*;
/**
*
* @author Thomas Kellerer
*/
public class DbExplorerSettings
{
public static final String PROP_USE_FILTER_RETRIEVE = "workbench.dbexplorer.tablelist.filter.retrieve";
public static final String PROP_USE_SQLSORT = "workbench.dbexplorer.datapanel.applysqlorder";
public static final String PROP_TABLE_HISTORY = "workbench.dbexplorer.tablelist.history";
public static final String PROP_ALLOW_ALTER_TABLE = "workbench.dbexplorer.allow.alter";
public static final String PROP_ALLOW_SOURCE_EDITING = "workbench.dbexplorer.allow.source.edit";
public static final String PROP_INSTANT_FILTER = "workbench.dbexplorer.instantfilter";
public static final String PROP_ASSUME_WILDCARDS = "workbench.dbexplorer.assumewildcards";
public static boolean showApplyDDLHint()
{
return Settings.getInstance().getBoolProperty("workbench.gui.apply.ddl.hint", true);
}
public static boolean showSynonymTargetInDbExplorer()
{
return Settings.getInstance().getBoolProperty("workbench.dbexplorer.synonyms.showtarget", true);
}
public static void setShowSynonymTargetInDbExplorer(boolean flag)
{
Settings.getInstance().setProperty("workbench.dbexplorer.synonyms.showtarget", flag);
}
public static boolean allowSourceEditing()
{
return Settings.getInstance().getBoolProperty(PROP_ALLOW_SOURCE_EDITING, false);
}
public static void setAllowSourceEditing(boolean flag)
{
Settings.getInstance().setProperty(PROP_ALLOW_SOURCE_EDITING, flag);
}
/**
* Return a list of object types for which the DbExplorer should not confirm the execution from within the "Source" panel.
*
*/
public static Set<String> objectTypesToRunWithoutConfirmation()
{
List<String> types = Settings.getInstance().getListProperty("workbench.dbexplorer.exec.noconfirm.types", false);
Set<String> result = CollectionUtil.caseInsensitiveSet();
result.addAll(types);
return result;
}
public static boolean allowAlterInDbExplorer()
{
return Settings.getInstance().getBoolProperty(PROP_ALLOW_ALTER_TABLE, false);
}
public static void setAllowAlterInDbExplorer(boolean flag)
{
Settings.getInstance().setProperty(PROP_ALLOW_ALTER_TABLE, flag);
}
public static boolean getUseFilterForRetrieve()
{
return Settings.getInstance().getBoolProperty(PROP_USE_FILTER_RETRIEVE, false);
}
public static void setUseFilterForRetrieve(boolean flag)
{
Settings.getInstance().setProperty(PROP_USE_FILTER_RETRIEVE, flag);
}
public static boolean getApplySQLSortInDbExplorer()
{
return Settings.getInstance().getBoolProperty(PROP_USE_SQLSORT, false);
}
public static void setApplySQLSortInDbExplorer(boolean flag)
{
Settings.getInstance().setProperty(PROP_USE_SQLSORT, flag);
}
public static boolean getDbExplorerTableDetailFullyQualified()
{
return Settings.getInstance().getBoolProperty("workbench.dbexplorer.tabledetails.fullname", true);
}
public static int getDbExplorerTableHistorySize()
{
return Settings.getInstance().getIntProperty("workbench.dbexplorer.tablelist.history.size", 25);
}
public static boolean getDbExplorerShowTableHistory()
{
return Settings.getInstance().getBoolProperty(PROP_TABLE_HISTORY, true);
}
public static void setDbExplorerShowTableHistory(boolean flag)
{
Settings.getInstance().setProperty(PROP_TABLE_HISTORY, flag);
}
public static boolean getDbExplorerMultiSelectTypes()
{
return Settings.getInstance().getBoolProperty("workbench.dbexplorer.tablelist.types.multiselect", true);
}
public static boolean getDbExplorerMultiSelectTypesAutoClose()
{
return Settings.getInstance().getBoolProperty("workbench.dbexplorer.tablelist.types.multiselect.autoclose", false);
}
public static boolean getDbExplorerIncludeTrgInTableSource()
{
return Settings.getInstance().getBoolProperty("workbench.dbexplorer.tablesource.include.trigger", false);
}
public static void setDbExplorerIncludeTrgInTableSource(boolean flag)
{
Settings.getInstance().setProperty("workbench.dbexplorer.tablesource.include.trigger", flag);
}
public static boolean getGenerateTableGrants()
{
return Settings.getInstance().getBoolProperty("workbench.db.generate.tablesource.include.grants", true);
}
public static void setGenerateTableGrants(boolean flag)
{
Settings.getInstance().setProperty("workbench.db.generate.tablesource.include.grants", flag);
}
public static DropType getDropTypeToGenerate()
{
return getDropTypeToGenerate(null);
}
public static DropType getDropTypeToGenerate(String objectType)
{
String baseKey = "workbench.dbexplorer.generate.drop";
String type = Settings.getInstance().getProperty(baseKey, DropType.cascaded.name());
if (objectType != null && !"default".equalsIgnoreCase(objectType))
{
type = Settings.getInstance().getProperty(baseKey + "." + DbSettings.getKeyValue(objectType), type);
}
// migrate from the old setting (true/false)
if ("true".equalsIgnoreCase(type))
{
return DropType.cascaded;
}
if ("false".equalsIgnoreCase(type))
{
return DropType.none;
}
try
{
return DropType.valueOf(type);
}
catch (Exception ex)
{
return DropType.cascaded;
}
}
public static void setDropTypeToGenerate(DropType type)
{
Settings.getInstance().setProperty("workbench.dbexplorer.generate.drop", type.name());
}
public static void setDropTypeToGenerate(DropType type, String objectType)
{
Settings.getInstance().setProperty("workbench.dbexplorer.generate.drop." + DbSettings.getKeyValue(objectType), type.name());
}
public static boolean getUsePartialMatch()
{
return Settings.getInstance().getBoolProperty(PROP_ASSUME_WILDCARDS, true);
}
public static void setUsePartialMatch(boolean flag)
{
Settings.getInstance().setProperty(PROP_ASSUME_WILDCARDS, flag);
}
public static boolean getFilterDuringTyping()
{
return Settings.getInstance().getBoolProperty(PROP_INSTANT_FILTER, false);
}
public static void setFilterDuringTyping(boolean flag)
{
Settings.getInstance().setProperty(PROP_INSTANT_FILTER, flag);
}
public static boolean isOwnTransaction(WbConnection dbConnection)
{
if (dbConnection == null) return false;
if (dbConnection.getAutoCommit()) return false;
return (dbConnection.getProfile().getUseSeparateConnectionPerTab() || getAlwaysUseSeparateConnForDbExpWindow());
}
public static boolean getAlwaysUseSeparateConnForDbExpWindow()
{
return Settings.getInstance().getBoolProperty("workbench.dbexplorer.connection.always.separate", false);
}
public static String getDefaultExplorerObjectType()
{
return Settings.getInstance().getProperty("workbench.gui.dbobjects.TableListPanel.objecttype", null);
}
public static void setDefaultExplorerObjectType(String type)
{
Settings.getInstance().setProperty("workbench.gui.dbobjects.TableListPanel.objecttype", type);
}
public static boolean getRetrieveDbExplorer()
{
return Settings.getInstance().getBoolProperty("workbench.dbexplorer.retrieveonopen", true);
}
public static void setRetrieveDbExplorer(boolean aFlag)
{
Settings.getInstance().setProperty("workbench.dbexplorer.retrieveonopen", aFlag);
}
public static void setShowDbExplorerInMainWindow(boolean showWindow)
{
Settings.getInstance().setProperty("workbench.dbexplorer.mainwindow", showWindow);
}
public static boolean getShowDbExplorerInMainWindow()
{
return Settings.getInstance().getBoolProperty("workbench.dbexplorer.mainwindow", true);
}
public static boolean getAutoGeneratePKName()
{
return Settings.getInstance().getBoolProperty("workbench.db.createpkname", false);
}
public static void setGenerateColumnListInViews(boolean flag)
{
Settings.getInstance().setProperty("workbench.sql.create.view.columnlist", flag);
}
public static boolean getGenerateColumnListInViews()
{
return Settings.getInstance().getBoolProperty("workbench.sql.create.view.columnlist", true);
}
public static void setAutoGeneratePKName(boolean flag)
{
Settings.getInstance().setProperty("workbench.db.createpkname", flag);
}
/**
* Returns true if the DbExplorer should show an additional
* panel with all triggers
*/
public static boolean getShowTriggerPanel()
{
return Settings.getInstance().getBoolProperty("workbench.dbexplorer.triggerpanel.show", true);
}
public static void setShowTriggerPanel(boolean flag)
{
Settings.getInstance().setProperty("workbench.dbexplorer.triggerpanel.show", flag);
}
public static void setShowFocusInDbExplorer(boolean flag)
{
Settings.getInstance().setProperty("workbench.gui.dbobjects.showfocus", flag);
}
/**
* Indicate if the column order of tables displaying meta data (table list, procedures)
* should be saved in the workspace
*
* @param tableType the table for which the column order should be checked (e.g. tablelist)
*/
public static boolean getRememberMetaColumnOrder(String tableType)
{
return Settings.getInstance().getBoolProperty("workbench.dbexplorer." + tableType + ".remember.columnorder", true);
}
/**
* Control if the column order of tables displaying meta data (table list, procedures)
* should be saved in the workspace
*
* @param tableType the table for which the column order should be checked (e.g. tablelist)
* @param flag
*/
public static void setRememberMetaColumnOrder(String tableType, boolean flag)
{
Settings.getInstance().setProperty("workbench.dbexplorer." + tableType + ".remember.columnorder", flag);
}
public static boolean showFocusInDbExplorer()
{
return Settings.getInstance().getBoolProperty("workbench.gui.dbobjects.showfocus", false);
}
public static void setRememberSortInDbExplorer(boolean flag)
{
Settings.getInstance().setProperty(PROPERTY_DBEXP_REMEMBER_SORT, flag);
}
public static boolean getRememberSortInDbExplorer()
{
return Settings.getInstance().getBoolProperty(PROPERTY_DBEXP_REMEMBER_SORT, false);
}
/**
* Set if the column order in the DbExplorer's Data tab should be remembered across restarts
*/
public static void setRememberColumnOrder(boolean flag)
{
Settings.getInstance().setProperty("workbench.dbexplorer.remember.columnorder", flag);
}
/**
* Indicate if the column order in the DbExplorer's Data tab should be remembered across restarts
*/
public static boolean getRememberColumnOrder()
{
return Settings.getInstance().getBoolProperty("workbench.dbexplorer.remember.columnorder", false);
}
public static void setStoreExplorerObjectType(boolean flag)
{
Settings.getInstance().setProperty("workbench.dbexplorer.rememberObjectType", flag);
}
public static boolean getStoreExplorerObjectType()
{
return Settings.getInstance().getBoolProperty("workbench.dbexplorer.rememberObjectType", false);
}
public static boolean getSwitchCatalogInExplorer()
{
return Settings.getInstance().getBoolProperty("workbench.dbexplorer.switchcatalog", true);
}
public static boolean getSelectDataPanelAfterRetrieve()
{
return Settings.getInstance().getBoolProperty("workbench.gui.dbobjects.autoselectdatapanel", true);
}
public static void setSelectDataPanelAfterRetrieve(boolean flag)
{
Settings.getInstance().setProperty("workbench.gui.dbobjects.autoselectdatapanel", flag);
}
public static boolean getSelectSourcePanelAfterRetrieve()
{
return Settings.getInstance().getBoolProperty("workbench.gui.dbobjects.autoselectsrcpanel", true);
}
public static void setSelectSourcePanelAfterRetrieve(boolean flag)
{
Settings.getInstance().setProperty("workbench.gui.dbobjects.autoselectsrcpanel", flag);
}
public static boolean getAutoRetrieveFKTree()
{
return Settings.getInstance().getBoolProperty("workbench.dbexplorer.fktree.autoload", true);
}
public static void setAutoRetrieveFKTree(boolean flag)
{
Settings.getInstance().setProperty("workbench.dbexplorer.fktree.autoload", flag);
}
public static boolean getGenerateScriptSeparator()
{
return Settings.getInstance().getBoolProperty("workbench.dbexplorer.sqlscript.separator", false);
}
public static void setGenerateScriptSeparator(boolean flag)
{
Settings.getInstance().setProperty("workbench.dbexplorer.sqlscript.separator", flag);
}
}
| |
/*
* Copyright 2018 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.jbpm.workbench.pr.client.editors.instance.list;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import org.dashbuilder.dataset.DataSet;
import org.dashbuilder.dataset.DataSetOp;
import org.dashbuilder.dataset.DataSetOpType;
import org.dashbuilder.dataset.client.DataSetReadyCallback;
import org.dashbuilder.dataset.filter.ColumnFilter;
import org.dashbuilder.dataset.filter.CoreFunctionFilter;
import org.dashbuilder.dataset.filter.CoreFunctionType;
import org.dashbuilder.dataset.filter.DataSetFilter;
import org.dashbuilder.dataset.sort.SortOrder;
import org.jboss.errai.common.client.api.Caller;
import org.jbpm.workbench.common.client.list.AbstractMultiGridPresenter;
import org.jbpm.workbench.common.client.list.ExtendedPagedTable;
import org.jbpm.workbench.common.client.list.MultiGridView;
import org.jbpm.workbench.common.client.menu.PrimaryActionMenuBuilder;
import org.jbpm.workbench.common.client.menu.RefreshMenuBuilder;
import org.jbpm.workbench.df.client.filter.FilterSettings;
import org.jbpm.workbench.df.client.list.DataSetQueryHelper;
import org.jbpm.workbench.forms.client.display.process.QuickNewProcessInstancePopup;
import org.jbpm.workbench.pr.client.editors.instance.signal.ProcessInstanceSignalPresenter;
import org.jbpm.workbench.pr.client.resources.i18n.Constants;
import org.jbpm.workbench.pr.events.NewProcessInstanceEvent;
import org.jbpm.workbench.pr.events.ProcessInstanceSelectionEvent;
import org.jbpm.workbench.pr.events.ProcessInstancesUpdateEvent;
import org.jbpm.workbench.pr.model.ProcessInstanceKey;
import org.jbpm.workbench.pr.model.ProcessInstanceSummary;
import org.jbpm.workbench.pr.service.ProcessService;
import org.kie.api.runtime.process.ProcessInstance;
import org.uberfire.client.annotations.WorkbenchMenu;
import org.uberfire.client.annotations.WorkbenchScreen;
import org.uberfire.client.workbench.events.BeforeClosePlaceEvent;
import org.uberfire.mvp.PlaceRequest;
import org.uberfire.mvp.impl.DefaultPlaceRequest;
import org.uberfire.workbench.model.menu.MenuFactory;
import org.uberfire.workbench.model.menu.Menus;
import static org.dashbuilder.dataset.filter.FilterFactory.equalsTo;
import static org.jbpm.workbench.common.client.PerspectiveIds.*;
import static org.jbpm.workbench.common.client.util.DataSetUtils.*;
import static org.jbpm.workbench.pr.model.ProcessInstanceDataSetConstants.*;
@Dependent
@WorkbenchScreen(identifier = PROCESS_INSTANCE_LIST_SCREEN)
public class ProcessInstanceListPresenter extends AbstractMultiGridPresenter<ProcessInstanceSummary, ProcessInstanceListPresenter.ProcessInstanceListView> {
protected final List<ProcessInstanceSummary> myProcessInstancesFromDataSet = new ArrayList<ProcessInstanceSummary>();
private final Constants constants = Constants.INSTANCE;
private final org.jbpm.workbench.common.client.resources.i18n.Constants commonConstants = org.jbpm.workbench.common.client.resources.i18n.Constants.INSTANCE;
@Inject
private DataSetQueryHelper dataSetQueryHelperDomainSpecific;
@Inject
private QuickNewProcessInstancePopup newProcessInstancePopup;
private Caller<ProcessService> processService;
protected Event<ProcessInstanceSelectionEvent> processInstanceSelectionEvent;
@Inject
public void setProcessInstanceSelectedEvent(final Event<ProcessInstanceSelectionEvent> processInstanceSelectionEvent) {
this.processInstanceSelectionEvent = processInstanceSelectionEvent;
}
@Override
public void createListBreadcrumb() {
setupListBreadcrumb(placeManager,
commonConstants.Manage_Process_Instances());
}
public void setupDetailBreadcrumb(String detailLabel) {
setupDetailBreadcrumb(placeManager,
commonConstants.Manage_Process_Instances(),
detailLabel,
PROCESS_INSTANCE_DETAILS_SCREEN);
}
protected DataSetReadyCallback createDataSetDomainSpecificCallback(final int startRange,
final FilterSettings tableSettings,
boolean lastPage) {
return errorHandlerBuilder.get().withUUID(tableSettings.getUUID()).withDataSetCallback(
dataSet -> {
Set<String> columns = new HashSet<String>();
for (int i = 0; i < dataSet.getRowCount(); i++) {
Long processInstanceId = getColumnLongValue(dataSet,
PROCESS_INSTANCE_ID,
i);
String variableName = getColumnStringValue(dataSet,
VARIABLE_NAME,
i);
String variableValue = getColumnStringValue(dataSet,
VARIABLE_VALUE,
i);
for (ProcessInstanceSummary pis : myProcessInstancesFromDataSet) {
String initiator = pis.getInitiator();
if (pis.getProcessInstanceId().equals(processInstanceId) && !filterInitiator(variableName,
variableValue,
initiator)) {
pis.addDomainData(variableName,
variableValue);
columns.add(variableName);
}
}
}
view.addDomainSpecifColumns(view.getListGrid(),
columns);
updateDataOnCallback(myProcessInstancesFromDataSet,
startRange,
startRange + myProcessInstancesFromDataSet.size(),
lastPage);
})
.withEmptyResultsCallback(() -> setEmptyResults());
}
protected boolean filterInitiator(String variableName,
String variableValue,
String initiator) {
return variableName.equals("initiator") && variableValue.equals(initiator);
}
@Override
protected DataSetReadyCallback getDataSetReadyCallback(final Integer startRange,
final FilterSettings tableSettings) {
return errorHandlerBuilder.get().withUUID(tableSettings.getUUID()).withDataSetCallback(
dataSet -> {
if (dataSet != null && dataSetQueryHelper.getCurrentTableSettings().getKey().equals(tableSettings.getKey())) {
myProcessInstancesFromDataSet.clear();
for (int i = 0; i < dataSet.getRowCount(); i++) {
myProcessInstancesFromDataSet.add(createProcessInstanceSummaryFromDataSet(dataSet,
i));
}
boolean lastPage = false;
if (dataSet.getRowCount() < view.getListGrid().getPageSize()) {
lastPage = true;
}
final String filterValue = isFilteredByProcessId(tableSettings.getDataSetLookup().getOperationList());
if (filterValue != null) {
getDomainSpecifDataForProcessInstances(startRange,
myProcessInstancesFromDataSet,
lastPage);
} else {
updateDataOnCallback(myProcessInstancesFromDataSet,
startRange,
startRange + myProcessInstancesFromDataSet.size(),
lastPage);
}
}
view.hideBusyIndicator();
})
.withEmptyResultsCallback(() -> setEmptyResults());
}
protected String isFilteredByProcessId(List<DataSetOp> ops) {
for (DataSetOp dataSetOp : ops) {
if (dataSetOp.getType().equals(DataSetOpType.FILTER)) {
List<ColumnFilter> filters = ((DataSetFilter) dataSetOp).getColumnFilterList();
for (ColumnFilter filter : filters) {
if (filter instanceof CoreFunctionFilter) {
CoreFunctionFilter coreFilter = ((CoreFunctionFilter) filter);
if (filter.getColumnId().toUpperCase().equals(COLUMN_PROCESS_ID.toUpperCase()) &&
((CoreFunctionFilter) filter).getType() == CoreFunctionType.EQUALS_TO) {
List parameters = coreFilter.getParameters();
if (parameters.size() > 0) {
return parameters.get(0).toString();
}
}
}
}
}
}
return null;
}
public void getDomainSpecifDataForProcessInstances(final Integer startRange,
final List<ProcessInstanceSummary> instancesFromDataSet,
final Boolean lastPage) {
List<Long> processIds = instancesFromDataSet.stream().map(t -> t.getId()).collect(Collectors.toList());
FilterSettings variablesTableSettings = filterSettingsManager.getVariablesFilterSettings(processIds);
variablesTableSettings.setServerTemplateId(getSelectedServerTemplate());
variablesTableSettings.setTablePageSize(-1);
dataSetQueryHelperDomainSpecific.setDataSetHandler(variablesTableSettings);
dataSetQueryHelperDomainSpecific.setCurrentTableSettings(variablesTableSettings);
dataSetQueryHelperDomainSpecific.setLastOrderedColumn(PROCESS_INSTANCE_ID);
dataSetQueryHelperDomainSpecific.setLastSortOrder(SortOrder.ASCENDING);
dataSetQueryHelperDomainSpecific.lookupDataSet(0,
createDataSetDomainSpecificCallback(startRange,
variablesTableSettings,
lastPage));
}
protected ProcessInstanceSummary createProcessInstanceSummaryFromDataSet(DataSet dataSet,
int i) {
return new ProcessInstanceSummary(
getSelectedServerTemplate(),
getColumnLongValue(dataSet,
COLUMN_PROCESS_INSTANCE_ID,
i),
getColumnStringValue(dataSet,
COLUMN_PROCESS_ID,
i),
getColumnStringValue(dataSet,
COLUMN_EXTERNAL_ID,
i),
getColumnStringValue(dataSet,
COLUMN_PROCESS_NAME,
i),
getColumnStringValue(dataSet,
COLUMN_PROCESS_VERSION,
i),
getColumnIntValue(dataSet,
COLUMN_STATUS,
i),
getColumnDateValue(dataSet,
COLUMN_START,
i),
getColumnDateValue(dataSet,
COLUMN_END,
i),
getColumnStringValue(dataSet,
COLUMN_IDENTITY,
i),
getColumnStringValue(dataSet,
COLUMN_PROCESS_INSTANCE_DESCRIPTION,
i),
getColumnStringValue(dataSet,
COLUMN_CORRELATION_KEY,
i),
getColumnLongValue(dataSet,
COLUMN_PARENT_PROCESS_INSTANCE_ID,
i),
getColumnDateValue(dataSet,
COLUMN_LAST_MODIFICATION_DATE,
i),
getColumnIntValue(dataSet,
COLUMN_SLA_COMPLIANCE,
i),
getColumnDateValue(dataSet,
COLUMN_SLA_DUE_DATE,
i),
getColumnIntValue(dataSet,
COLUMN_ERROR_COUNT,
i)
);
}
public void newInstanceCreated(@Observes final NewProcessInstanceEvent pi) {
refreshGrid();
}
public void newInstanceCreated(@Observes final ProcessInstancesUpdateEvent pis) {
refreshGrid();
}
public void abortProcessInstance(String containerId,
long processInstanceId) {
view.displayNotification(constants.Aborting_Process_Instance(processInstanceId));
processService.call((Void v) -> refreshGrid()).abortProcessInstance(new ProcessInstanceKey(getSelectedServerTemplate(),
containerId,
processInstanceId));
}
public void abortProcessInstances(Map<String, List<Long>> containerInstances) {
processService.call((Void v) -> refreshGrid()).abortProcessInstances(getSelectedServerTemplate(),
containerInstances);
}
public void bulkSignal(List<ProcessInstanceSummary> processInstances) {
if (processInstances == null || processInstances.isEmpty()) {
return;
}
final StringBuilder processIdsParam = new StringBuilder();
final StringBuilder deploymentIdsParam = new StringBuilder();
for (ProcessInstanceSummary selected : processInstances) {
if (selected.getState() != ProcessInstance.STATE_ACTIVE) {
view.displayNotification(constants.Signaling_Process_Instance_Not_Allowed(selected.getId()));
continue;
}
processIdsParam.append(selected.getId() + ",");
deploymentIdsParam.append(selected.getDeploymentId() + ",");
}
if (processIdsParam.length() == 0) {
return;
} else {
// remove last ,
processIdsParam.deleteCharAt(processIdsParam.length() - 1);
deploymentIdsParam.deleteCharAt(deploymentIdsParam.length() - 1);
}
PlaceRequest placeRequestImpl = new DefaultPlaceRequest(ProcessInstanceSignalPresenter.SIGNAL_PROCESS_POPUP);
placeRequestImpl.addParameter("processInstanceId",
processIdsParam.toString());
placeRequestImpl.addParameter("deploymentId",
deploymentIdsParam.toString());
placeRequestImpl.addParameter("serverTemplateId",
getSelectedServerTemplate());
placeManager.goTo(placeRequestImpl);
}
public void bulkAbort(List<ProcessInstanceSummary> processInstances) {
if (processInstances == null || processInstances.isEmpty()) {
return;
}
final Map<String, List<Long>> containerInstances = new HashMap<>();
for (ProcessInstanceSummary selected : processInstances) {
if (selected.getState() != ProcessInstance.STATE_ACTIVE) {
view.displayNotification(constants.Aborting_Process_Instance_Not_Allowed(selected.getId()));
continue;
}
containerInstances.computeIfAbsent(selected.getDeploymentId(), key -> new ArrayList<>()).add(selected.getProcessInstanceId());
view.displayNotification(constants.Aborting_Process_Instance(selected.getId()));
}
if (containerInstances.size() > 0) {
abortProcessInstances(containerInstances);
}
}
@WorkbenchMenu
public Menus getMenus() {
return MenuFactory
.newTopLevelCustomMenu(new RefreshMenuBuilder(this)).endMenu()
.newTopLevelCustomMenu(new PrimaryActionMenuBuilder(constants.New_Process_Instance(),
() -> {
final String selectedServerTemplate = getSelectedServerTemplate();
if (selectedServerTemplate != null && !selectedServerTemplate.isEmpty()) {
newProcessInstancePopup.show(selectedServerTemplate);
} else {
view.displayNotification(constants.SelectServerTemplate());
}
}
))
.endMenu()
.build();
}
public void signalProcessInstance(final ProcessInstanceSummary processInstance) {
PlaceRequest placeRequestImpl = new DefaultPlaceRequest(ProcessInstanceSignalPresenter.SIGNAL_PROCESS_POPUP);
placeRequestImpl.addParameter("processInstanceId",
Long.toString(processInstance.getProcessInstanceId()));
placeRequestImpl.addParameter("deploymentId",
processInstance.getDeploymentId());
placeRequestImpl.addParameter("serverTemplateId",
getSelectedServerTemplate());
placeManager.goTo(placeRequestImpl);
}
@Override
public void selectSummaryItem(final ProcessInstanceSummary summary) {
setupDetailBreadcrumb(constants.ProcessInstanceBreadcrumb(summary.getProcessInstanceId()));
placeManager.goTo(PROCESS_INSTANCE_DETAILS_SCREEN);
processInstanceSelectionEvent.fire(new ProcessInstanceSelectionEvent(summary.getProcessInstanceKey(),
false));
}
public void formClosed(@Observes BeforeClosePlaceEvent closed) {
if (ProcessInstanceSignalPresenter.SIGNAL_PROCESS_POPUP.equals(closed.getPlace().getIdentifier())) {
refreshGrid();
}
}
@Inject
public void setFilterSettingsManager(final ProcessInstanceListFilterSettingsManager filterSettingsManager) {
super.setFilterSettingsManager(filterSettingsManager);
}
@Inject
public void setProcessService(final Caller<ProcessService> processService) {
this.processService = processService;
}
@Override
public void setupActiveSearchFilters() {
boolean hasSearchParam = false;
final Optional<String> processDefinitionSearch = getSearchParameter(SEARCH_PARAMETER_PROCESS_DEFINITION_ID);
if (processDefinitionSearch.isPresent()) {
final String processDefinitionId = processDefinitionSearch.get();
addActiveFilter(equalsTo(COLUMN_PROCESS_ID,
processDefinitionId),
constants.Process_Definition_Id(),
processDefinitionId,
processDefinitionId,
v -> removeActiveFilter(equalsTo(COLUMN_PROCESS_ID,
v))
);
hasSearchParam = true;
}
final Optional<String> processInstanceSearch = getSearchParameter(SEARCH_PARAMETER_PROCESS_INSTANCE_ID);
if (processInstanceSearch.isPresent()) {
final String processInstanceId = processInstanceSearch.get();
addActiveFilter(equalsTo(COLUMN_PROCESS_INSTANCE_ID,
Integer.valueOf(processInstanceId)),
constants.Id(),
processInstanceId,
Integer.valueOf(processInstanceId),
v -> removeActiveFilter(equalsTo(COLUMN_PROCESS_INSTANCE_ID,
v))
);
hasSearchParam = true;
}
if (!hasSearchParam) {
setupDefaultActiveSearchFilters();
}
}
@Override
public void setupDefaultActiveSearchFilters() {
addActiveFilter(equalsTo(COLUMN_STATUS,
ProcessInstance.STATE_ACTIVE),
constants.State(),
constants.Active(),
ProcessInstance.STATE_ACTIVE,
v -> removeActiveFilter(equalsTo(COLUMN_STATUS,
v))
);
}
public void openJobsView(final String pid) {
navigateToPerspective(JOBS,
SEARCH_PARAMETER_PROCESS_INSTANCE_ID,
pid);
}
public void openTaskView(final String pid) {
navigateToPerspective(isUserAuthorizedForPerspective(TASKS_ADMIN) ? TASKS_ADMIN : TASKS,
SEARCH_PARAMETER_PROCESS_INSTANCE_ID,
pid);
}
@Override
public void openErrorView(final String pid) {
final PlaceRequest request = new DefaultPlaceRequest(EXECUTION_ERRORS);
request.addParameter(SEARCH_PARAMETER_PROCESS_INSTANCE_ID,
pid);
request.addParameter(SEARCH_PARAMETER_IS_ERROR_ACK,
Boolean.toString(false));
placeManager.goTo(request);
}
public Predicate<ProcessInstanceSummary> getSignalActionCondition() {
return pis -> pis.getState() == ProcessInstance.STATE_ACTIVE;
}
public Predicate<ProcessInstanceSummary> getAbortActionCondition() {
return pis -> pis.getState() == ProcessInstance.STATE_ACTIVE;
}
public Predicate<ProcessInstanceSummary> getViewJobsActionCondition() {
return pis -> isUserAuthorizedForPerspective(JOBS);
}
public Predicate<ProcessInstanceSummary> getViewTasksActionCondition() {
return pis -> isUserAuthorizedForPerspective(TASKS_ADMIN) || isUserAuthorizedForPerspective(TASKS);
}
@Override
public Predicate<ProcessInstanceSummary> getViewErrorsActionCondition() {
return pis -> isUserAuthorizedForPerspective(EXECUTION_ERRORS) && pis.getErrorCount() != null && pis.getErrorCount() > 0;
}
public interface ProcessInstanceListView extends MultiGridView<ProcessInstanceSummary, ProcessInstanceListPresenter> {
void addDomainSpecifColumns(ExtendedPagedTable<ProcessInstanceSummary> extendedPagedTable,
Set<String> columns);
}
}
| |
package ua.com.fielden.platform.test;
import static java.lang.String.format;
import static ua.com.fielden.platform.dao.HibernateMappingsGenerator.ID_SEQUENCE_NAME;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Session;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.After;
import org.junit.Before;
import ua.com.fielden.platform.dao.IEntityDao;
import ua.com.fielden.platform.dao.ISessionEnabled;
import ua.com.fielden.platform.dao.annotations.SessionRequired;
import ua.com.fielden.platform.dao.exceptions.EntityCompanionException;
import ua.com.fielden.platform.data.IDomainDrivenData;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.DynamicEntityKey;
import ua.com.fielden.platform.entity.factory.EntityFactory;
import ua.com.fielden.platform.entity.factory.ICompanionObjectFinder;
import ua.com.fielden.platform.reflection.Finder;
import ua.com.fielden.platform.utils.DbUtils;
/**
* This is a base class for all test cases in TG based applications. Each application module should provide file <b>src/test/resources/test.properties</b> with property
* <code>config-domain</code> assigned an application specific class implementing contract {@link IDomainDrivenTestCaseConfiguration}.
*
* @author TG Team
*
*/
public abstract class AbstractDomainDrivenTestCase implements IDomainDrivenData, ISessionEnabled {
private DbCreator dbCreator;
private static ICompanionObjectFinder coFinder;
private static EntityFactory factory;
private static Function<Class<?>, Object> instantiator;
private static final DateTimeFormatter jodaFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
private static final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private Session session;
private String transactionGuid;
/**
* Should be implemented in order to provide domain driven data population.
*/
protected abstract void populateDomain();
/**
* Should return a complete list of domain entity types.
*
* @return
*/
protected abstract List<Class<? extends AbstractEntity<?>>> domainEntityTypes();
@Before
public final void beforeTest() throws Exception {
dbCreator.populateOrRestoreData(this);
}
@SessionRequired
protected void resetIdGenerator() {
DbUtils.resetSequenceGenerator(ID_SEQUENCE_NAME, 1000000, this.getSession());
}
@After
public final void afterTest() {
dbCreator.clearData();
}
public AbstractDomainDrivenTestCase setDbCreator(final DbCreator dbCreator) {
this.dbCreator = dbCreator;
return this;
}
public DbCreator getDbCreator() {
return dbCreator;
}
@Override
public final <T> T getInstance(final Class<T> type) {
return (T) instantiator.apply(type);
}
@Override
public <T extends AbstractEntity<?>> T save(final T instance) {
@SuppressWarnings("unchecked")
final IEntityDao<T> pp = coFinder.find((Class<T>) instance.getType());
return pp.save(instance);
}
private final Map<Class<? extends AbstractEntity<?>>, IEntityDao<?>> co$Cache = new HashMap<>();
private final Map<Class<? extends AbstractEntity<?>>, IEntityDao<?>> coCache = new HashMap<>();
@Override
@SuppressWarnings("unchecked")
public <C extends IEntityDao<E>, E extends AbstractEntity<?>> C co$(final Class<E> type) {
IEntityDao<?> co = co$Cache.get(type);
if (co == null) {
co = coFinder.find(type, false);
co$Cache.put(type, co);
}
return (C) co;
}
@Override
@SuppressWarnings("unchecked")
public <C extends IEntityDao<E>, E extends AbstractEntity<?>> C co(final Class<E> type) {
return (C) coCache.computeIfAbsent(type, k -> coFinder.find(k, true));
}
@Override
public final Date date(final String dateTime) {
try {
return formatter.parse(dateTime);
} catch (ParseException e) {
throw new IllegalArgumentException(format("Could not parse value [%s].", dateTime));
}
}
@Override
public final DateTime dateTime(final String dateTime) {
return jodaFormatter.parseDateTime(dateTime);
}
/**
* Instantiates a new entity with a non-composite key, the value for which is provided as the second argument, and description -- provided as the value for the third argument.
*
* @param entityClass
* @param key
* @param desc
* @return
*/
@Override
public <T extends AbstractEntity<K>, K extends Comparable<?>> T new_(final Class<T> entityClass, final K key, final String desc) {
final T entity = new_(entityClass);
entity.setKey(key);
entity.setDesc(desc);
return entity;
}
/**
* Instantiates a new entity with a non-composite key, the value for which is provided as the second argument.
*
* @param entityClass
* @param key
* @return
*/
@Override
public <T extends AbstractEntity<K>, K extends Comparable<?>> T new_(final Class<T> entityClass, final K key) {
final T entity = new_(entityClass);
entity.setKey(key);
return entity;
}
/**
* Instantiates a new entity with composite key, where composite key members are assigned based on the provide value. The order of values must match the order specified in key
* member definitions. An empty list of key values is permitted.
*
* @param entityClass
* @param keys
* @return
*/
@Override
public <T extends AbstractEntity<DynamicEntityKey>> T new_composite(final Class<T> entityClass, final Object... keys) {
final T entity = new_(entityClass);
if (keys.length > 0) {
// setting composite key fields
final List<Field> fieldList = Finder.getKeyMembers(entityClass);
if (fieldList.size() != keys.length) {
throw new IllegalArgumentException(format("Number of key values is %s but should be %s", keys.length, fieldList.size()));
}
for (int index = 0; index < fieldList.size(); index++) {
final Field keyField = fieldList.get(index);
final Object keyValue = keys[index];
entity.set(keyField.getName(), keyValue);
}
}
return entity;
}
/**
* Instantiates a new entity based on the provided type only, which leads to creation of a completely empty instance without any of entity properties assigned.
*
* @param entityClass
* @return
*/
@Override
public <T extends AbstractEntity<K>, K extends Comparable<?>> T new_(final Class<T> entityClass) {
final IEntityDao<T> co = co$(entityClass);
return co != null ? co.new_() : factory.newEntity(entityClass);
}
/////////////// @SessionRequired support ///////////////
@Override
public Session getSession() {
if (session == null) {
throw new EntityCompanionException("Session is missing, most likely, due to missing @SessionRequired annotation.");
}
return session;
}
@Override
public void setSession(final Session session) {
this.session = session;
}
@Override
public String getTransactionGuid() {
if (StringUtils.isEmpty(transactionGuid)) {
throw new EntityCompanionException("Transaction GUID is missing.");
}
return transactionGuid;
}
@Override
public void setTransactionGuid(final String guid) {
this.transactionGuid = guid;
}
}
| |
/*
* 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.hdds.scm.client;
import com.google.common.base.Preconditions;
import org.apache.hadoop.hdds.scm.XceiverClientManager;
import org.apache.hadoop.hdds.scm.XceiverClientSpi;
import org.apache.hadoop.hdds.scm.container.common.helpers.ContainerWithPipeline;
import org.apache.hadoop.hdds.scm.container.common.helpers.ContainerInfo;
import org.apache.hadoop.hdds.scm.container.common.helpers.Pipeline;
import org.apache.hadoop.hdds.scm.protocolPB
.StorageContainerLocationProtocolClientSideTranslatorPB;
import org.apache.hadoop.hdds.scm.storage.ContainerProtocolCalls;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
.ContainerData;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
.ReadContainerResponseProto;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
import org.apache.hadoop.hdds.protocol.proto
.StorageContainerLocationProtocolProtos.ObjectStageChangeRequestProto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import static org.apache.hadoop.hdds.protocol.proto.HddsProtos.LifeCycleState
.ALLOCATED;
import static org.apache.hadoop.hdds.protocol.proto.HddsProtos.LifeCycleState
.OPEN;
/**
* This class provides the client-facing APIs of container operations.
*/
public class ContainerOperationClient implements ScmClient {
private static final Logger LOG =
LoggerFactory.getLogger(ContainerOperationClient.class);
private static long containerSizeB = -1;
private final StorageContainerLocationProtocolClientSideTranslatorPB
storageContainerLocationClient;
private final XceiverClientManager xceiverClientManager;
public ContainerOperationClient(
StorageContainerLocationProtocolClientSideTranslatorPB
storageContainerLocationClient,
XceiverClientManager xceiverClientManager) {
this.storageContainerLocationClient = storageContainerLocationClient;
this.xceiverClientManager = xceiverClientManager;
}
/**
* Return the capacity of containers. The current assumption is that all
* containers have the same capacity. Therefore one static is sufficient for
* any container.
* @return The capacity of one container in number of bytes.
*/
public static long getContainerSizeB() {
return containerSizeB;
}
/**
* Set the capacity of container. Should be exactly once on system start.
* @param size Capacity of one container in number of bytes.
*/
public static void setContainerSizeB(long size) {
containerSizeB = size;
}
/**
* @inheritDoc
*/
@Override
public ContainerWithPipeline createContainer(String owner)
throws IOException {
XceiverClientSpi client = null;
try {
ContainerWithPipeline containerWithPipeline =
storageContainerLocationClient.allocateContainer(
xceiverClientManager.getType(),
xceiverClientManager.getFactor(), owner);
Pipeline pipeline = containerWithPipeline.getPipeline();
client = xceiverClientManager.acquireClient(pipeline,
containerWithPipeline.getContainerInfo().getContainerID());
// Allocated State means that SCM has allocated this pipeline in its
// namespace. The client needs to create the pipeline on the machines
// which was choosen by the SCM.
Preconditions.checkState(pipeline.getLifeCycleState() == ALLOCATED ||
pipeline.getLifeCycleState() == OPEN, "Unexpected pipeline state");
if (pipeline.getLifeCycleState() == ALLOCATED) {
createPipeline(client, pipeline);
}
createContainer(client,
containerWithPipeline.getContainerInfo().getContainerID());
return containerWithPipeline;
} finally {
if (client != null) {
xceiverClientManager.releaseClient(client);
}
}
}
/**
* Create a container over pipeline specified by the SCM.
*
* @param client - Client to communicate with Datanodes.
* @param containerId - Container ID.
* @throws IOException
*/
public void createContainer(XceiverClientSpi client,
long containerId) throws IOException {
String traceID = UUID.randomUUID().toString();
storageContainerLocationClient.notifyObjectStageChange(
ObjectStageChangeRequestProto.Type.container,
containerId,
ObjectStageChangeRequestProto.Op.create,
ObjectStageChangeRequestProto.Stage.begin);
ContainerProtocolCalls.createContainer(client, containerId, traceID);
storageContainerLocationClient.notifyObjectStageChange(
ObjectStageChangeRequestProto.Type.container,
containerId,
ObjectStageChangeRequestProto.Op.create,
ObjectStageChangeRequestProto.Stage.complete);
// Let us log this info after we let SCM know that we have completed the
// creation state.
if (LOG.isDebugEnabled()) {
LOG.debug("Created container " + containerId
+ " leader:" + client.getPipeline().getLeader()
+ " machines:" + client.getPipeline().getMachines());
}
}
/**
* Creates a pipeline over the machines choosen by the SCM.
*
* @param client - Client
* @param pipeline - pipeline to be createdon Datanodes.
* @throws IOException
*/
private void createPipeline(XceiverClientSpi client, Pipeline pipeline)
throws IOException {
Preconditions.checkNotNull(pipeline.getId(), "Pipeline " +
"name cannot be null when client create flag is set.");
// Pipeline creation is a three step process.
//
// 1. Notify SCM that this client is doing a create pipeline on
// datanodes.
//
// 2. Talk to Datanodes to create the pipeline.
//
// 3. update SCM that pipeline creation was successful.
// TODO: this has not been fully implemented on server side
// SCMClientProtocolServer#notifyObjectStageChange
// TODO: when implement the pipeline state machine, change
// the pipeline name (string) to pipeline id (long)
//storageContainerLocationClient.notifyObjectStageChange(
// ObjectStageChangeRequestProto.Type.pipeline,
// pipeline.getPipelineName(),
// ObjectStageChangeRequestProto.Op.create,
// ObjectStageChangeRequestProto.Stage.begin);
client.createPipeline(pipeline);
//storageContainerLocationClient.notifyObjectStageChange(
// ObjectStageChangeRequestProto.Type.pipeline,
// pipeline.getPipelineName(),
// ObjectStageChangeRequestProto.Op.create,
// ObjectStageChangeRequestProto.Stage.complete);
// TODO : Should we change the state on the client side ??
// That makes sense, but it is not needed for the client to work.
LOG.debug("Pipeline creation successful. Pipeline: {}",
pipeline.toString());
}
/**
* @inheritDoc
*/
@Override
public ContainerWithPipeline createContainer(HddsProtos.ReplicationType type,
HddsProtos.ReplicationFactor factor, String owner) throws IOException {
XceiverClientSpi client = null;
try {
// allocate container on SCM.
ContainerWithPipeline containerWithPipeline =
storageContainerLocationClient.allocateContainer(type, factor,
owner);
Pipeline pipeline = containerWithPipeline.getPipeline();
client = xceiverClientManager.acquireClient(pipeline,
containerWithPipeline.getContainerInfo().getContainerID());
// Allocated State means that SCM has allocated this pipeline in its
// namespace. The client needs to create the pipeline on the machines
// which was choosen by the SCM.
if (pipeline.getLifeCycleState() == ALLOCATED) {
createPipeline(client, pipeline);
}
// connect to pipeline leader and allocate container on leader datanode.
client = xceiverClientManager.acquireClient(pipeline,
containerWithPipeline.getContainerInfo().getContainerID());
createContainer(client,
containerWithPipeline.getContainerInfo().getContainerID());
return containerWithPipeline;
} finally {
if (client != null) {
xceiverClientManager.releaseClient(client);
}
}
}
/**
* Returns a set of Nodes that meet a query criteria.
*
* @param nodeStatuses - Criteria that we want the node to have.
* @param queryScope - Query scope - Cluster or pool.
* @param poolName - if it is pool, a pool name is required.
* @return A set of nodes that meet the requested criteria.
* @throws IOException
*/
@Override
public List<HddsProtos.Node> queryNode(HddsProtos.NodeState
nodeStatuses, HddsProtos.QueryScope queryScope, String poolName)
throws IOException {
return storageContainerLocationClient.queryNode(nodeStatuses, queryScope,
poolName);
}
/**
* Creates a specified replication pipeline.
*/
@Override
public Pipeline createReplicationPipeline(HddsProtos.ReplicationType type,
HddsProtos.ReplicationFactor factor, HddsProtos.NodePool nodePool)
throws IOException {
return storageContainerLocationClient.createReplicationPipeline(type,
factor, nodePool);
}
@Override
public void close() {
try {
xceiverClientManager.close();
} catch (Exception ex) {
LOG.error("Can't close " + this.getClass().getSimpleName(), ex);
}
}
/**
* Deletes an existing container.
*
* @param containerId - ID of the container.
* @param pipeline - Pipeline that represents the container.
* @param force - true to forcibly delete the container.
* @throws IOException
*/
@Override
public void deleteContainer(long containerId, Pipeline pipeline,
boolean force) throws IOException {
XceiverClientSpi client = null;
try {
client = xceiverClientManager.acquireClient(pipeline, containerId);
String traceID = UUID.randomUUID().toString();
ContainerProtocolCalls
.deleteContainer(client, containerId, force, traceID);
storageContainerLocationClient
.deleteContainer(containerId);
if (LOG.isDebugEnabled()) {
LOG.debug("Deleted container {}, leader: {}, machines: {} ",
containerId,
pipeline.getLeader(),
pipeline.getMachines());
}
} finally {
if (client != null) {
xceiverClientManager.releaseClient(client);
}
}
}
/**
* Delete the container, this will release any resource it uses.
* @param containerID - containerID.
* @param force - True to forcibly delete the container.
* @throws IOException
*/
@Override
public void deleteContainer(long containerID, boolean force)
throws IOException {
ContainerWithPipeline info = getContainerWithPipeline(containerID);
deleteContainer(containerID, info.getPipeline(), force);
}
/**
* {@inheritDoc}
*/
@Override
public List<ContainerInfo> listContainer(long startContainerID,
int count) throws IOException {
return storageContainerLocationClient.listContainer(
startContainerID, count);
}
/**
* Get meta data from an existing container.
*
* @param containerID - ID of the container.
* @param pipeline - Pipeline where the container is located.
* @return ContainerInfo
* @throws IOException
*/
@Override
public ContainerData readContainer(long containerID,
Pipeline pipeline) throws IOException {
XceiverClientSpi client = null;
try {
client = xceiverClientManager.acquireClient(pipeline, containerID);
String traceID = UUID.randomUUID().toString();
ReadContainerResponseProto response =
ContainerProtocolCalls.readContainer(client, containerID, traceID);
if (LOG.isDebugEnabled()) {
LOG.debug("Read container {}, leader: {}, machines: {} ",
containerID,
pipeline.getLeader(),
pipeline.getMachines());
}
return response.getContainerData();
} finally {
if (client != null) {
xceiverClientManager.releaseClient(client);
}
}
}
/**
* Get meta data from an existing container.
* @param containerID - ID of the container.
* @return ContainerInfo - a message of protobuf which has basic info
* of a container.
* @throws IOException
*/
@Override
public ContainerData readContainer(long containerID) throws IOException {
ContainerWithPipeline info = getContainerWithPipeline(containerID);
return readContainer(containerID, info.getPipeline());
}
/**
* Given an id, return the pipeline associated with the container.
* @param containerId - String Container ID
* @return Pipeline of the existing container, corresponding to the given id.
* @throws IOException
*/
@Override
public ContainerInfo getContainer(long containerId) throws
IOException {
return storageContainerLocationClient.getContainer(containerId);
}
/**
* Gets a container by Name -- Throws if the container does not exist.
*
* @param containerId - Container ID
* @return ContainerWithPipeline
* @throws IOException
*/
@Override
public ContainerWithPipeline getContainerWithPipeline(long containerId)
throws IOException {
return storageContainerLocationClient.getContainerWithPipeline(containerId);
}
/**
* Close a container.
*
* @param pipeline the container to be closed.
* @throws IOException
*/
@Override
public void closeContainer(long containerId, Pipeline pipeline)
throws IOException {
XceiverClientSpi client = null;
try {
LOG.debug("Close container {}", pipeline);
/*
TODO: two orders here, revisit this later:
1. close on SCM first, then on data node
2. close on data node first, then on SCM
with 1: if client failed after closing on SCM, then there is a
container SCM thinks as closed, but is actually open. Then SCM will no
longer allocate block to it, which is fine. But SCM may later try to
replicate this "closed" container, which I'm not sure is safe.
with 2: if client failed after close on datanode, then there is a
container SCM thinks as open, but is actually closed. Then SCM will still
try to allocate block to it. Which will fail when actually doing the
write. No more data can be written, but at least the correctness and
consistency of existing data will maintain.
For now, take the #2 way.
*/
// Actually close the container on Datanode
client = xceiverClientManager.acquireClient(pipeline, containerId);
String traceID = UUID.randomUUID().toString();
storageContainerLocationClient.notifyObjectStageChange(
ObjectStageChangeRequestProto.Type.container,
containerId,
ObjectStageChangeRequestProto.Op.close,
ObjectStageChangeRequestProto.Stage.begin);
ContainerProtocolCalls.closeContainer(client, containerId, traceID);
// Notify SCM to close the container
storageContainerLocationClient.notifyObjectStageChange(
ObjectStageChangeRequestProto.Type.container,
containerId,
ObjectStageChangeRequestProto.Op.close,
ObjectStageChangeRequestProto.Stage.complete);
} finally {
if (client != null) {
xceiverClientManager.releaseClient(client);
}
}
}
/**
* Close a container.
*
* @throws IOException
*/
@Override
public void closeContainer(long containerId)
throws IOException {
ContainerWithPipeline info = getContainerWithPipeline(containerId);
Pipeline pipeline = info.getPipeline();
closeContainer(containerId, pipeline);
}
/**
* Get the the current usage information.
* @param containerID - ID of the container.
* @return the size of the given container.
* @throws IOException
*/
@Override
public long getContainerSize(long containerID) throws IOException {
// TODO : Fix this, it currently returns the capacity
// but not the current usage.
long size = getContainerSizeB();
if (size == -1) {
throw new IOException("Container size unknown!");
}
return size;
}
}
| |
/*
* 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;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.*;
import java.io.*;
/**
* Defines the EwsXmlReader class.
*/
class EwsXmlReader {
/**
* The Read write buffer size.
*/
private static final int ReadWriteBufferSize = 4096;
/**
* The xml reader.
*/
private XMLEventReader xmlReader = null;
/**
* The present event.
*/
private XMLEvent presentEvent;
/**
* The prev event.
*/
private XMLEvent prevEvent;
/**
* Initializes a new instance of the EwsXmlReader class.
*
* @param stream the stream
* @throws Exception
*/
public EwsXmlReader(InputStream stream) throws Exception {
this.xmlReader = initializeXmlReader(stream);
}
/**
* Initializes the XML reader.
*
* @param stream the stream
* @return An XML reader to use.
* @throws Exception
*/
protected XMLEventReader initializeXmlReader(InputStream stream)
throws XMLStreamException, Exception {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
//inputFactory.setProperty(XMLInputFactory.RESOLVER, null);
return inputFactory.createXMLEventReader(stream);
}
/**
* Formats the name of the element.
*
* @param namespacePrefix The namespace prefix
* @param localElementName Element name
* @return the string
*/
private static String formatElementName(String namespacePrefix,
String localElementName) {
return isNullOrEmpty(namespacePrefix) ? localElementName :
namespacePrefix + ":" + localElementName;
}
/**
* Read XML element.
*
* @param xmlNamespace The XML namespace
* @param localName Name of the local
* @param nodeType Type of the node
* @throws Exception the exception
*/
private void internalReadElement(XmlNamespace xmlNamespace,
String localName, XmlNodeType nodeType) throws Exception {
if (xmlNamespace == XmlNamespace.NotSpecified) {
this.internalReadElement("", localName, nodeType);
} else {
this.read(nodeType);
if ((!this.getLocalName().equals(localName)) ||
(!this.getNamespaceUri().equals(EwsUtilities
.getNamespaceUri(xmlNamespace)))) {
throw new ServiceXmlDeserializationException(
String
.format(
Strings.UnexpectedElement,
EwsUtilities
.getNamespacePrefix(
xmlNamespace),
localName, nodeType.toString(), this
.getName(), this.getNodeType()
.toString()));
}
}
}
/**
* Read XML element.
*
* @param namespacePrefix The namespace prefix
* @param localName Name of the local
* @param nodeType Type of the node
* @throws Exception the exception
*/
private void internalReadElement(String namespacePrefix, String localName,
XmlNodeType nodeType) throws Exception {
read(nodeType);
if ((!this.getLocalName().equals(localName)) ||
(!this.getNamespacePrefix().equals(namespacePrefix))) {
throw new ServiceXmlDeserializationException(String.format(
Strings.UnexpectedElement, namespacePrefix, localName,
nodeType.toString(), this.getName(), this.getNodeType()
.toString()));
}
}
/**
* Reads the specified node type.
*
* @throws ServiceXmlDeserializationException the service xml deserialization exception
* @throws javax.xml.stream.XMLStreamException the xML stream exception
*/
public void read() throws ServiceXmlDeserializationException,
XMLStreamException {
read(false);
}
/**
* Reads the specified node type.
*
* @param keepWhiteSpace Do not remove whitespace characters if true
* @throws ServiceXmlDeserializationException the service xml deserialization exception
* @throws javax.xml.stream.XMLStreamException the xML stream exception
*/
private void read(boolean keepWhiteSpace) throws ServiceXmlDeserializationException,
XMLStreamException {
// The caller to EwsXmlReader.Read expects
// that there's another node to
// read. Throw an exception if not true.
while (true) {
if (!xmlReader.hasNext()) {
throw new ServiceXmlDeserializationException(
Strings.UnexpectedEndOfXmlDocument);
} else {
XMLEvent event = xmlReader.nextEvent();
if (event.getEventType() == XMLStreamConstants.CHARACTERS) {
Characters characters = (Characters) event;
if (!keepWhiteSpace)
if (characters.isIgnorableWhiteSpace()
|| characters.isWhiteSpace()) {
continue;
}
}
this.prevEvent = this.presentEvent;
this.presentEvent = event;
break;
}
}
}
/**
* Reads the specified node type.
*
* @param nodeType Type of the node.
* @throws Exception the exception
*/
public void read(XmlNodeType nodeType) throws Exception {
this.read();
if (!this.getNodeType().equals(nodeType)) {
throw new ServiceXmlDeserializationException(String
.format(Strings.UnexpectedElementType, nodeType, this
.getNodeType()));
}
}
/**
* Read attribute value from QName.
*
* @param qName QName of the attribute
* @return Attribute Value
* @throws Exception thrown if attribute value can not be read
*/
private String readAttributeValue(QName qName) throws Exception {
if (this.presentEvent.isStartElement()) {
StartElement startElement = this.presentEvent.asStartElement();
Attribute attr = startElement.getAttributeByName(qName);
if (null != attr) {
return attr.getValue();
} else {
return null;
}
} else {
String errMsg = String.format("Could not fetch attribute %s", qName
.toString());
throw new Exception(errMsg);
}
}
/**
* Reads the attribute value.
*
* @param xmlNamespace The XML namespace.
* @param attributeName Name of the attribute
* @return Attribute Value
* @throws Exception the exception
*/
public String readAttributeValue(XmlNamespace xmlNamespace,
String attributeName) throws Exception {
if (xmlNamespace == XmlNamespace.NotSpecified) {
return this.readAttributeValue(attributeName);
} else {
QName qName = new QName(EwsUtilities.getNamespaceUri(xmlNamespace),
attributeName);
return readAttributeValue(qName);
}
}
/**
* Reads the attribute value.
*
* @param attributeName Name of the attribute
* @return Attribute value.
* @throws Exception the exception
*/
public String readAttributeValue(String attributeName) throws Exception {
QName qName = new QName(attributeName);
return readAttributeValue(qName);
}
/**
* Reads the attribute value.
*
* @param <T> the generic type
* @param cls the cls
* @param attributeName the attribute name
* @return T
* @throws Exception the exception
*/
public <T> T readAttributeValue(Class<T> cls, String attributeName)
throws Exception {
return EwsUtilities.parse(cls, this.readAttributeValue(attributeName));
}
/**
* Reads a nullable attribute value.
*
* @param <T> the generic type
* @param cls the cls
* @param attributeName the attribute name
* @return T
* @throws Exception the exception
*/
public <T> T readNullableAttributeValue(Class<T> cls, String attributeName)
throws Exception {
String attributeValue = this.readAttributeValue(attributeName);
if (attributeValue == null) {
return null;
} else {
return EwsUtilities.parse(cls, attributeValue);
}
}
/**
* Reads the element value.
*
* @param namespacePrefix the namespace prefix
* @param localName the local name
* @return String
* @throws Exception the exception
*/
public String readElementValue(String namespacePrefix, String localName)
throws Exception {
if (!this.isStartElement(namespacePrefix, localName)) {
this.readStartElement(namespacePrefix, localName);
}
String value = null;
if (!this.isEmptyElement()) {
value = this.readValue();
}
return value;
}
/**
* Reads the element value.
*
* @param xmlNamespace the xml namespace
* @param localName the local name
* @return String
* @throws Exception the exception
*/
public String readElementValue(XmlNamespace xmlNamespace, String localName)
throws Exception {
if (!this.isStartElement(xmlNamespace, localName)) {
this.readStartElement(xmlNamespace, localName);
}
String value = null;
if (!this.isEmptyElement()) {
value = this.readValue();
} else {
this.read();
}
return value;
}
/**
* Read element value.
*
* @return String
* @throws Exception the exception
*/
public String readElementValue() throws Exception {
this.ensureCurrentNodeIsStartElement();
return this.readElementValue(this.getNamespacePrefix(), this
.getLocalName());
}
/**
* Reads the element value.
*
* @param <T> the generic type
* @param cls the cls
* @param xmlNamespace the xml namespace
* @param localName the local name
* @return T
* @throws Exception the exception
*/
public <T> T readElementValue(Class<T> cls, XmlNamespace xmlNamespace,
String localName) throws Exception {
if (!this.isStartElement(xmlNamespace, localName)) {
this.readStartElement(xmlNamespace, localName);
}
T value = null;
if (!this.isEmptyElement()) {
value = this.readValue(cls);
}
return value;
}
/**
* Read element value.
*
* @param <T> the generic type
* @param cls the cls
* @return T
* @throws Exception the exception
*/
public <T> T readElementValue(Class<T> cls) throws Exception {
this.ensureCurrentNodeIsStartElement();
T value = null;
if (!this.isEmptyElement()) {
value = this.readValue(cls);
}
return value;
}
/**
* Reads the value. Should return content element or text node as string
* Present event must be START ELEMENT. After executing this function
* Present event will be set on END ELEMENT
*
* @return String
* @throws javax.xml.stream.XMLStreamException the xML stream exception
* @throws ServiceXmlDeserializationException the service xml deserialization exception
*/
public String readValue() throws XMLStreamException,
ServiceXmlDeserializationException {
return readValue(false);
}
/**
* Reads the value. Should return content element or text node as string
* Present event must be START ELEMENT. After executing this function
* Present event will be set on END ELEMENT
*
* @param keepWhiteSpace Do not remove whitespace characters if true
* @return String
* @throws javax.xml.stream.XMLStreamException the xML stream exception
* @throws ServiceXmlDeserializationException the service xml deserialization exception
*/
public String readValue(boolean keepWhiteSpace) throws XMLStreamException,
ServiceXmlDeserializationException {
if (this.presentEvent.isStartElement()) {
// Go to next event and check for Characters event
this.read(keepWhiteSpace);
if (this.presentEvent.isCharacters()) {
final StringBuilder elementValue = new StringBuilder();
do {
if (this.getNodeType().nodeType == XmlNodeType.CHARACTERS) {
Characters characters = (Characters) this.presentEvent;
if (keepWhiteSpace || (!characters.isIgnorableWhiteSpace()
&& !characters.isWhiteSpace())) {
final String charactersData = characters.getData();
if (charactersData != null && !charactersData.isEmpty()) {
elementValue.append(charactersData);
}
}
}
this.read();
} while (!this.presentEvent.isEndElement());
// Characters chars = this.presentEvent.asCharacters();
// String elementValue = chars.getData();
// Advance to next event post Characters (ideally it will be End
// Element)
// this.read();
return elementValue.toString();
} else {
throw new ServiceXmlDeserializationException(
getReadValueErrMsg("Could not find " + XmlNodeType.getString(XmlNodeType.CHARACTERS))
);
}
} else if (this.presentEvent.getEventType() == XmlNodeType.CHARACTERS
&& this.presentEvent.isCharacters()) {
/*
* if(this.presentEvent.asCharacters().getData().equals("<")) {
*/
final String charData = this.presentEvent.asCharacters().getData();
final StringBuilder data = new StringBuilder(charData == null ? "" : charData);
do {
this.read(keepWhiteSpace);
if (this.getNodeType().nodeType == XmlNodeType.CHARACTERS) {
Characters characters = (Characters) this.presentEvent;
if (keepWhiteSpace || (!characters.isIgnorableWhiteSpace()
&& !characters.isWhiteSpace())) {
final String charactersData = characters.getData();
if (charactersData != null && !charactersData.isEmpty()) {
data.append(charactersData);
}
}
}
} while (!this.presentEvent.isEndElement());
return data.toString();// this.presentEvent. = new XMLEvent();
/*
* } else { Characters chars = this.presentEvent.asCharacters();
* String elementValue = chars.getData(); // Advance to next event
* post Characters (ideally it will be End // Element) this.read();
* return elementValue; }
*/
} else {
throw new ServiceXmlDeserializationException(
getReadValueErrMsg("Expected is " + XmlNodeType.getString(XmlNodeType.START_ELEMENT))
);
}
}
/**
* Tries to read value.
*
* @param value the value
* @return boolean
* @throws javax.xml.stream.XMLStreamException the xML stream exception
* @throws ServiceXmlDeserializationException the service xml deserialization exception
*/
public boolean tryReadValue(OutParam<String> value)
throws XMLStreamException, ServiceXmlDeserializationException {
if (!this.isEmptyElement()) {
this.read();
if (this.presentEvent.isCharacters()) {
value.setParam(this.readValue());
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* Reads the value.
*
* @param <T> the generic type
* @param cls the cls
* @return T
* @throws Exception the exception
*/
public <T> T readValue(Class<T> cls) throws Exception {
return EwsUtilities.parse(cls, this.readValue());
}
/**
* Reads the base64 element value.
*
* @return byte[]
* @throws ServiceXmlDeserializationException the service xml deserialization exception
* @throws javax.xml.stream.XMLStreamException the xML stream exception
* @throws java.io.IOException Signals that an I/O exception has occurred.
*/
public byte[] readBase64ElementValue()
throws ServiceXmlDeserializationException, XMLStreamException,
IOException {
this.ensureCurrentNodeIsStartElement();
byte[] buffer = null;
ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
buffer = Base64EncoderStream.decode(this.xmlReader.getElementText()
.toString());
byteArrayStream.write(buffer);
return byteArrayStream.toByteArray();
}
/**
* Reads the base64 element value.
*
* @param outputStream the output stream
* @throws Exception the exception
*/
public void readBase64ElementValue(OutputStream outputStream)
throws Exception {
this.ensureCurrentNodeIsStartElement();
byte[] buffer = null;
buffer = Base64EncoderStream.decode(this.xmlReader.getElementText()
.toString());
outputStream.write(buffer);
outputStream.flush();
}
/**
* Reads the start element.
*
* @param namespacePrefix the namespace prefix
* @param localName the local name
* @throws Exception the exception
*/
public void readStartElement(String namespacePrefix, String localName)
throws Exception {
this.internalReadElement(namespacePrefix, localName, new XmlNodeType(
XmlNodeType.START_ELEMENT));
}
/**
* Reads the start element.
*
* @param xmlNamespace the xml namespace
* @param localName the local name
* @throws Exception the exception
*/
public void readStartElement(XmlNamespace xmlNamespace, String localName)
throws Exception {
this.internalReadElement(xmlNamespace, localName, new XmlNodeType(
XmlNodeType.START_ELEMENT));
}
/**
* Reads the end element.
*
* @param namespacePrefix the namespace prefix
* @param elementName the element name
* @throws Exception the exception
*/
public void readEndElement(String namespacePrefix, String elementName)
throws Exception {
this.internalReadElement(namespacePrefix, elementName, new XmlNodeType(
XmlNodeType.END_ELEMENT));
}
/**
* Reads the end element.
*
* @param xmlNamespace the xml namespace
* @param localName the local name
* @throws Exception the exception
*/
public void readEndElement(XmlNamespace xmlNamespace, String localName)
throws Exception {
this.internalReadElement(xmlNamespace, localName, new XmlNodeType(
XmlNodeType.END_ELEMENT));
}
/**
* Reads the end element if necessary.
*
* @param xmlNamespace the xml namespace
* @param localName the local name
* @throws Exception the exception
*/
public void readEndElementIfNecessary(XmlNamespace xmlNamespace,
String localName) throws Exception {
if (!(this.isStartElement(xmlNamespace, localName) && this
.isEmptyElement())) {
if (!this.isEndElement(xmlNamespace, localName)) {
this.readEndElement(xmlNamespace, localName);
}
}
}
/**
* Determines whether current element is a start element.
*
* @return boolean
*/
public boolean isStartElement() {
return this.presentEvent.isStartElement();
}
/**
* Determines whether current element is a start element.
*
* @param namespacePrefix the namespace prefix
* @param localName the local name
* @return boolean
*/
public boolean isStartElement(String namespacePrefix, String localName) {
boolean isStart = false;
if (this.presentEvent.isStartElement()) {
StartElement startElement = this.presentEvent.asStartElement();
QName qName = startElement.getName();
isStart = qName.getLocalPart().equals(localName)
&& qName.getPrefix().equals(namespacePrefix);
}
return isStart;
}
/**
* Determines whether current element is a start element.
*
* @param xmlNamespace the xml namespace
* @param localName the local name
* @return true for matching start element; false otherwise.
*/
public boolean isStartElement(XmlNamespace xmlNamespace, String localName) {
return this.isStartElement()
&& EwsUtilities.stringEquals(this.getLocalName(), localName)
&& (
EwsUtilities.stringEquals(this.getNamespacePrefix(), EwsUtilities.getNamespacePrefix(xmlNamespace)) ||
EwsUtilities.stringEquals(this.getNamespaceUri(), EwsUtilities.getNamespaceUri(xmlNamespace)));
}
/**
* Determines whether current element is a end element.
*
* @param namespacePrefix the namespace prefix
* @param localName the local name
* @return boolean
*/
public boolean isEndElement(String namespacePrefix, String localName) {
boolean isEndElement = false;
if (this.presentEvent.isEndElement()) {
EndElement endElement = this.presentEvent.asEndElement();
QName qName = endElement.getName();
isEndElement = qName.getLocalPart().equals(localName)
&& qName.getPrefix().equals(namespacePrefix);
}
return isEndElement;
}
/**
* Determines whether current element is a end element.
*
* @param xmlNamespace the xml namespace
* @param localName the local name
* @return boolean
*/
public boolean isEndElement(XmlNamespace xmlNamespace, String localName) {
boolean isEndElement = false;
/*
* if(localName.equals("Body")) { return true; } else
*/
if (this.presentEvent.isEndElement()) {
EndElement endElement = this.presentEvent.asEndElement();
QName qName = endElement.getName();
isEndElement = qName.getLocalPart().equals(localName)
&& (qName.getPrefix().equals(
EwsUtilities.getNamespacePrefix(xmlNamespace)) ||
qName.getNamespaceURI().equals(
EwsUtilities.getNamespaceUri(
xmlNamespace)));
}
return isEndElement;
}
/**
* Skips the element.
*
* @param namespacePrefix the namespace prefix
* @param localName the local name
* @throws Exception the exception
*/
public void skipElement(String namespacePrefix, String localName)
throws Exception {
if (!this.isEndElement(namespacePrefix, localName)) {
if (!this.isStartElement(namespacePrefix, localName)) {
this.readStartElement(namespacePrefix, localName);
}
if (!this.isEmptyElement()) {
do {
this.read();
} while (!this.isEndElement(namespacePrefix, localName));
}
}
}
/**
* Skips the element.
*
* @param xmlNamespace the xml namespace
* @param localName the local name
* @throws Exception the exception
*/
public void skipElement(XmlNamespace xmlNamespace, String localName)
throws Exception {
if (!this.isEndElement(xmlNamespace, localName)) {
if (!this.isStartElement(xmlNamespace, localName)) {
this.readStartElement(xmlNamespace, localName);
}
if (!this.isEmptyElement()) {
do {
this.read();
} while (!this.isEndElement(xmlNamespace, localName));
}
}
}
/**
* Skips the current element.
*
* @throws Exception the exception
*/
public void skipCurrentElement() throws Exception {
this.skipElement(this.getNamespacePrefix(), this.getLocalName());
}
/**
* Ensures the current node is start element.
*
* @param xmlNamespace the xml namespace
* @param localName the local name
* @throws ServiceXmlDeserializationException the service xml deserialization exception
*/
public void ensureCurrentNodeIsStartElement(XmlNamespace xmlNamespace,
String localName) throws ServiceXmlDeserializationException {
if (!this.isStartElement(xmlNamespace, localName)) {
throw new ServiceXmlDeserializationException(
String
.format(
Strings.ElementNotFound,
localName, xmlNamespace));
}
}
/**
* Ensures the current node is start element.
*
* @throws ServiceXmlDeserializationException the service xml deserialization exception
*/
public void ensureCurrentNodeIsStartElement()
throws ServiceXmlDeserializationException {
XmlNodeType presentNodeType = new XmlNodeType(this.presentEvent
.getEventType());
if (!this.presentEvent.isStartElement()) {
throw new ServiceXmlDeserializationException(String.format(
Strings.ExpectedStartElement,
this.presentEvent.toString(), presentNodeType.toString()));
}
}
/**
* Ensures the current node is start element.
*
* @param xmlNamespace the xml namespace
* @param localName the local name
* @throws Exception the exception
*/
public void ensureCurrentNodeIsEndElement(XmlNamespace xmlNamespace,
String localName) throws Exception {
if (!this.isEndElement(xmlNamespace, localName)) {
if (!(this.isStartElement(xmlNamespace, localName) && this
.isEmptyElement())) {
throw new ServiceXmlDeserializationException(
String
.format(
Strings.ElementNotFound,
xmlNamespace, localName));
}
}
}
/**
* Outer XML as string.
*
* @return String
* @throws ServiceXmlDeserializationException the service xml deserialization exception
* @throws javax.xml.stream.XMLStreamException the xML stream exception
*/
public String readOuterXml() throws ServiceXmlDeserializationException,
XMLStreamException {
if (!this.isStartElement()) {
throw new ServiceXmlDeserializationException(
Strings.CurrentPositionNotElementStart);
}
XMLEvent startEvent = this.presentEvent;
XMLEvent event;
StringBuilder str = new StringBuilder();
str.append(startEvent);
do {
event = this.xmlReader.nextEvent();
str.append(event);
} while (!checkEndElement(startEvent, event));
return str.toString();
}
/**
* Reads the Inner XML at the given location.
*
* @return String
* @throws ServiceXmlDeserializationException the service xml deserialization exception
* @throws javax.xml.stream.XMLStreamException the xML stream exception
*/
public String readInnerXml() throws ServiceXmlDeserializationException,
XMLStreamException {
if (!this.isStartElement()) {
throw new ServiceXmlDeserializationException(
Strings.CurrentPositionNotElementStart);
}
XMLEvent startEvent = this.presentEvent;
StringBuilder str = new StringBuilder();
do {
XMLEvent event = this.xmlReader.nextEvent();
if (checkEndElement(startEvent, event)) {
break;
}
str.append(event);
} while (true);
return str.toString();
}
/**
* Check end element.
*
* @param startEvent the start event
* @param endEvent the end event
* @return true, if successful
*/
public static boolean checkEndElement(XMLEvent startEvent,
XMLEvent endEvent) {
boolean isEndElement = false;
if (endEvent.isEndElement()) {
QName qEName = endEvent.asEndElement().getName();
QName qSName = startEvent.asStartElement().getName();
isEndElement = qEName.getLocalPart().equals(qSName.getLocalPart())
&& (qEName.getPrefix().equals(qSName.getPrefix()) || qEName
.getNamespaceURI().equals(qSName.
getNamespaceURI()));
}
return isEndElement;
}
/**
* Gets the XML reader for node.
*
* @return null
* @throws javax.xml.stream.XMLStreamException
* @throws ServiceXmlDeserializationException
* @throws java.io.FileNotFoundException
*/
protected XMLEventReader getXmlReaderForNode()
throws FileNotFoundException, ServiceXmlDeserializationException, XMLStreamException {
return readSubtree(); //this.xmlReader.ReadSubtree();
}
public XMLEventReader readSubtree()
throws XMLStreamException, FileNotFoundException, ServiceXmlDeserializationException {
if (!this.isStartElement()) {
throw new ServiceXmlDeserializationException(
Strings.CurrentPositionNotElementStart);
}
XMLEventReader eventReader = null;
InputStream in = null;
XMLEvent startEvent = this.presentEvent;
XMLEvent event = startEvent;
StringBuilder str = new StringBuilder();
str.append(startEvent);
do {
event = this.xmlReader.nextEvent();
str.append(event);
} while (!checkEndElement(startEvent, event));
try {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
try {
in = new ByteArrayInputStream(str.toString().getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
eventReader = inputFactory.createXMLEventReader(in);
} catch (Exception e) {
e.printStackTrace();
}
return eventReader;
}
/**
* Reads to the next descendant element with the specified local name and
* namespace.
*
* @param xmlNamespace The namespace of the element you with to move to.
* @param localName The local name of the element you wish to move to.
* @throws javax.xml.stream.XMLStreamException
*/
public void ReadToDescendant(XmlNamespace xmlNamespace, String localName) throws XMLStreamException {
readToDescendant(localName, EwsUtilities.getNamespaceUri(xmlNamespace));
}
public boolean readToDescendant(String localName, String namespaceURI) throws XMLStreamException {
if (!this.isStartElement()) {
return false;
}
XMLEvent startEvent = this.presentEvent;
XMLEvent event = this.presentEvent;
do {
if (event.isStartElement()) {
QName qEName = event.asStartElement().getName();
if (qEName.getLocalPart().equals(localName) &&
qEName.getNamespaceURI().equals(namespaceURI)) {
return true;
}
}
event = this.xmlReader.nextEvent();
} while (!checkEndElement(startEvent, event));
return false;
}
/**
* Gets a value indicating whether this instance has attributes.
*
* @return boolean
*/
public boolean hasAttributes() {
if (this.presentEvent.isStartElement()) {
StartElement startElement = this.presentEvent.asStartElement();
return startElement.getAttributes().hasNext();
} else {
return false;
}
}
/**
* Gets a value indicating whether current element is empty.
*
* @return boolean
* @throws javax.xml.stream.XMLStreamException the xML stream exception
*/
public boolean isEmptyElement() throws XMLStreamException {
boolean isPresentStartElement = this.presentEvent.isStartElement();
boolean isNextEndElement = this.xmlReader.peek().isEndElement();
return isPresentStartElement && isNextEndElement;
}
/**
* Gets the local name of the current element.
*
* @return String
*/
public String getLocalName() {
String localName = null;
if (this.presentEvent.isStartElement()) {
localName = this.presentEvent.asStartElement().getName()
.getLocalPart();
} else {
localName = this.presentEvent.asEndElement().getName()
.getLocalPart();
}
return localName;
}
/**
* Gets the namespace prefix.
*
* @return String
*/
protected String getNamespacePrefix() {
if (this.presentEvent.isStartElement()) {
return this.presentEvent.asStartElement().getName().getPrefix();
}
if (this.presentEvent.isEndElement()) {
return this.presentEvent.asEndElement().getName().getPrefix();
}
return null;
}
/**
* Gets the namespace URI.
*
* @return String
*/
protected String getNamespaceUri() {
String nameSpaceUri = null;
if (this.presentEvent.isStartElement()) {
nameSpaceUri = this.presentEvent.asStartElement().getName()
.getNamespaceURI();
} else {
nameSpaceUri = this.presentEvent.asEndElement().getName()
.getNamespaceURI();
}
return nameSpaceUri;
}
/**
* Gets the type of the node.
*
* @return XmlNodeType
* @throws javax.xml.stream.XMLStreamException the xML stream exception
*/
public XmlNodeType getNodeType() throws XMLStreamException {
XMLEvent event = this.presentEvent;
XmlNodeType nodeType = new XmlNodeType(event.getEventType());
return nodeType;
}
/**
* Gets the name of the current element.
*
* @return Object
*/
protected Object getName() {
String name = null;
if (this.presentEvent.isStartElement()) {
name = this.presentEvent.asStartElement().getName().toString();
} else {
name = this.presentEvent.asEndElement().getName().toString();
}
return name;
}
/**
* Checks is the string is null or empty.
*
* @param namespacePrefix the namespace prefix
* @return true, if is null or empty
*/
private static boolean isNullOrEmpty(String namespacePrefix) {
return (namespacePrefix == null || namespacePrefix.isEmpty());
}
/**
* Gets the error message which happened during {@link #readValue()}.
*
* @param details details message
* @return error message with details
*/
private String getReadValueErrMsg(final String details) {
final int eventType = this.presentEvent.getEventType();
return "Could not read value from " + XmlNodeType.getString(eventType) + "." + details;
}
}
| |
/*
* 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.glaf.base.modules.sys.springmvc;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.glaf.base.modules.sys.service.SysApplicationService;
import com.glaf.core.base.TreeModel;
import com.glaf.core.config.Environment;
import com.glaf.core.config.ViewProperties;
import com.glaf.core.security.LoginContext;
import com.glaf.core.tree.helper.TreeHelper;
import com.glaf.core.util.RequestUtils;
import com.glaf.ui.service.LayoutService;
import com.glaf.ui.service.PanelService;
import com.glaf.ui.service.UserPortalService;
@Controller("/my/portal")
public class MyPortalController {
protected final static Log logger = LogFactory
.getLog(MyPortalController.class);
protected LayoutService layoutService;
protected PanelService panelService;
protected SysApplicationService sysApplicationService;
protected UserPortalService userPortalService;
protected void fill(JSONObject jsonObject, StringBuffer buffer) {
String text = jsonObject.getString("text");
if (text != null && jsonObject.getString("id") != null) {
JSONArray children = jsonObject.getJSONArray("children");
if (children != null && !children.isEmpty()) {
buffer.append("\n <li iconCls=\"icon-base\"><span>")
.append(text).append("</span>");
buffer.append("\n <ul>");
Iterator<Object> iterator = children.iterator();
while (iterator.hasNext()) {
Object obj = iterator.next();
if (obj instanceof JSONObject) {
JSONObject json = (JSONObject) obj;
this.fill(json, buffer);
}
}
buffer.append("\n </ul>");
buffer.append("\n </li>");
} else {
buffer.append("\n <li iconCls=\"icon-gears\"><a href=\"#\" ")
.append(" onclick=\"openTabs('").append(text)
.append("','").append(jsonObject.getString("id"))
.append("');\">").append(text).append("</a>");
buffer.append("\n </li>");
}
}
}
@RequestMapping("/my/home.do")
public ModelAndView home(HttpServletRequest request, ModelMap modelMap) {
RequestUtils.setRequestParameterToAttribute(request);
if (StringUtils.isNotEmpty(request.getParameter("systemName"))) {
Environment
.setCurrentSystemName(request.getParameter("systemName"));
} else {
Environment.setCurrentSystemName(Environment.DEFAULT_SYSTEM_NAME);
}
String userId = RequestUtils.getActorId(request);
long appId = RequestUtils.getLong(request, "appId", 3);
String scripts = "";
try {
org.json.JSONArray array = sysApplicationService.getUserMenu(appId,
userId);
scripts = array.toString('\n');
request.setAttribute("scripts", scripts);
} catch (Exception ex) {
ex.printStackTrace();
logger.error(ex);
}
return new ModelAndView("/modules/portal/home", modelMap);
}
@RequestMapping("/my/main.do")
public ModelAndView main(HttpServletRequest request, ModelMap modelMap) {
LoginContext loginContext = RequestUtils.getLoginContext(request);
RequestUtils.setRequestParameterToAttribute(request);
if (StringUtils.isNotEmpty(request.getParameter("systemName"))) {
Environment
.setCurrentSystemName(request.getParameter("systemName"));
} else {
Environment.setCurrentSystemName(Environment.DEFAULT_SYSTEM_NAME);
}
long appId = RequestUtils.getLong(request, "appId", 3);
TreeModel root = sysApplicationService.getTreeModelByAppId(appId);
logger.debug("####root tree id="+root.getId());
List<TreeModel> treeNodes = sysApplicationService.getTreeModels(
root.getId(), loginContext.getActorId());
Collections.sort(treeNodes);
Collection<String> roles = loginContext.getRoles();
logger.debug("user roles:" + roles);
List<String> list = new java.util.ArrayList<String>();
if (roles != null && !roles.isEmpty()) {
for (String r : roles) {
list.add(r);
}
}
modelMap.put("root", root);
modelMap.put("treeNodes", treeNodes);
logger.debug("#######################################################");
logger.debug("treeNodes:" + treeNodes.size());
TreeHelper treeHelper = new TreeHelper();
JSONObject treeJson = treeHelper.getTreeJson(root, treeNodes);
modelMap.put("treeJson", treeJson);
logger.debug(treeJson.toJSONString());
StringBuffer buffer = new StringBuffer();
String text = treeJson.getString("text");
if (text != null) {
buffer.append("\n <li iconCls=\"icon-root\"><span>").append(text)
.append("</span>");
JSONArray children = treeJson.getJSONArray("children");
if (children != null && !children.isEmpty()) {
buffer.append("\n <ul>");
Iterator<Object> iterator = children.iterator();
while (iterator.hasNext()) {
Object obj = iterator.next();
if (obj instanceof JSONObject) {
JSONObject json = (JSONObject) obj;
this.fill(json, buffer);
}
}
buffer.append("\n </ul>");
}
buffer.append("\n</li>");
}
modelMap.put("json", buffer.toString());
logger.debug("#######################################");
logger.debug(loginContext.getRoles());
String jx_view = request.getParameter("jx_view");
if (StringUtils.isNotEmpty(jx_view)) {
return new ModelAndView(jx_view, modelMap);
}
String x_view = ViewProperties.getString("my_workspace.main");
if (StringUtils.isNotEmpty(x_view)) {
return new ModelAndView(x_view, modelMap);
}
return new ModelAndView("/modules/portal/main", modelMap);
}
@javax.annotation.Resource
public void setLayoutService(LayoutService layoutService) {
this.layoutService = layoutService;
}
@javax.annotation.Resource
public void setPanelService(PanelService panelService) {
this.panelService = panelService;
}
@javax.annotation.Resource
public void setSysApplicationService(
SysApplicationService sysApplicationService) {
this.sysApplicationService = sysApplicationService;
}
@javax.annotation.Resource
public void setUserPortalService(UserPortalService userPortalService) {
this.userPortalService = userPortalService;
}
}
| |
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.managedidentities.v1.stub;
import static com.google.cloud.managedidentities.v1.ManagedIdentitiesServiceClient.ListDomainsPagedResponse;
import com.google.api.core.ApiFunction;
import com.google.api.core.ApiFuture;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.GaxProperties;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.grpc.GaxGrpcProperties;
import com.google.api.gax.grpc.GrpcTransportChannel;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.grpc.ProtoOperationTransformers;
import com.google.api.gax.longrunning.OperationSnapshot;
import com.google.api.gax.longrunning.OperationTimedPollAlgorithm;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.rpc.ApiCallContext;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.PageContext;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.PagedListDescriptor;
import com.google.api.gax.rpc.PagedListResponseFactory;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.StubSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.managedidentities.v1.AttachTrustRequest;
import com.google.cloud.managedidentities.v1.CreateMicrosoftAdDomainRequest;
import com.google.cloud.managedidentities.v1.DeleteDomainRequest;
import com.google.cloud.managedidentities.v1.DetachTrustRequest;
import com.google.cloud.managedidentities.v1.Domain;
import com.google.cloud.managedidentities.v1.GetDomainRequest;
import com.google.cloud.managedidentities.v1.ListDomainsRequest;
import com.google.cloud.managedidentities.v1.ListDomainsResponse;
import com.google.cloud.managedidentities.v1.OpMetadata;
import com.google.cloud.managedidentities.v1.ReconfigureTrustRequest;
import com.google.cloud.managedidentities.v1.ResetAdminPasswordRequest;
import com.google.cloud.managedidentities.v1.ResetAdminPasswordResponse;
import com.google.cloud.managedidentities.v1.UpdateDomainRequest;
import com.google.cloud.managedidentities.v1.ValidateTrustRequest;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.longrunning.Operation;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.List;
import javax.annotation.Generated;
import org.threeten.bp.Duration;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Settings class to configure an instance of {@link ManagedIdentitiesServiceStub}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (managedidentities.googleapis.com) and default port (443) are
* used.
* <li>Credentials are acquired automatically through Application Default Credentials.
* <li>Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object.
*
* <p>For example, to set the total timeout of resetAdminPassword to 30 seconds:
*
* <pre>{@code
* ManagedIdentitiesServiceStubSettings.Builder managedIdentitiesServiceSettingsBuilder =
* ManagedIdentitiesServiceStubSettings.newBuilder();
* managedIdentitiesServiceSettingsBuilder
* .resetAdminPasswordSettings()
* .setRetrySettings(
* managedIdentitiesServiceSettingsBuilder
* .resetAdminPasswordSettings()
* .getRetrySettings()
* .toBuilder()
* .setTotalTimeout(Duration.ofSeconds(30))
* .build());
* ManagedIdentitiesServiceStubSettings managedIdentitiesServiceSettings =
* managedIdentitiesServiceSettingsBuilder.build();
* }</pre>
*/
@Generated("by gapic-generator-java")
public class ManagedIdentitiesServiceStubSettings
extends StubSettings<ManagedIdentitiesServiceStubSettings> {
/** The default scopes of the service. */
private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES =
ImmutableList.<String>builder().add("https://www.googleapis.com/auth/cloud-platform").build();
private final UnaryCallSettings<CreateMicrosoftAdDomainRequest, Operation>
createMicrosoftAdDomainSettings;
private final OperationCallSettings<CreateMicrosoftAdDomainRequest, Domain, OpMetadata>
createMicrosoftAdDomainOperationSettings;
private final UnaryCallSettings<ResetAdminPasswordRequest, ResetAdminPasswordResponse>
resetAdminPasswordSettings;
private final PagedCallSettings<ListDomainsRequest, ListDomainsResponse, ListDomainsPagedResponse>
listDomainsSettings;
private final UnaryCallSettings<GetDomainRequest, Domain> getDomainSettings;
private final UnaryCallSettings<UpdateDomainRequest, Operation> updateDomainSettings;
private final OperationCallSettings<UpdateDomainRequest, Domain, OpMetadata>
updateDomainOperationSettings;
private final UnaryCallSettings<DeleteDomainRequest, Operation> deleteDomainSettings;
private final OperationCallSettings<DeleteDomainRequest, Empty, OpMetadata>
deleteDomainOperationSettings;
private final UnaryCallSettings<AttachTrustRequest, Operation> attachTrustSettings;
private final OperationCallSettings<AttachTrustRequest, Domain, OpMetadata>
attachTrustOperationSettings;
private final UnaryCallSettings<ReconfigureTrustRequest, Operation> reconfigureTrustSettings;
private final OperationCallSettings<ReconfigureTrustRequest, Domain, OpMetadata>
reconfigureTrustOperationSettings;
private final UnaryCallSettings<DetachTrustRequest, Operation> detachTrustSettings;
private final OperationCallSettings<DetachTrustRequest, Domain, OpMetadata>
detachTrustOperationSettings;
private final UnaryCallSettings<ValidateTrustRequest, Operation> validateTrustSettings;
private final OperationCallSettings<ValidateTrustRequest, Domain, OpMetadata>
validateTrustOperationSettings;
private static final PagedListDescriptor<ListDomainsRequest, ListDomainsResponse, Domain>
LIST_DOMAINS_PAGE_STR_DESC =
new PagedListDescriptor<ListDomainsRequest, ListDomainsResponse, Domain>() {
@Override
public String emptyToken() {
return "";
}
@Override
public ListDomainsRequest injectToken(ListDomainsRequest payload, String token) {
return ListDomainsRequest.newBuilder(payload).setPageToken(token).build();
}
@Override
public ListDomainsRequest injectPageSize(ListDomainsRequest payload, int pageSize) {
return ListDomainsRequest.newBuilder(payload).setPageSize(pageSize).build();
}
@Override
public Integer extractPageSize(ListDomainsRequest payload) {
return payload.getPageSize();
}
@Override
public String extractNextToken(ListDomainsResponse payload) {
return payload.getNextPageToken();
}
@Override
public Iterable<Domain> extractResources(ListDomainsResponse payload) {
return payload.getDomainsList() == null
? ImmutableList.<Domain>of()
: payload.getDomainsList();
}
};
private static final PagedListResponseFactory<
ListDomainsRequest, ListDomainsResponse, ListDomainsPagedResponse>
LIST_DOMAINS_PAGE_STR_FACT =
new PagedListResponseFactory<
ListDomainsRequest, ListDomainsResponse, ListDomainsPagedResponse>() {
@Override
public ApiFuture<ListDomainsPagedResponse> getFuturePagedResponse(
UnaryCallable<ListDomainsRequest, ListDomainsResponse> callable,
ListDomainsRequest request,
ApiCallContext context,
ApiFuture<ListDomainsResponse> futureResponse) {
PageContext<ListDomainsRequest, ListDomainsResponse, Domain> pageContext =
PageContext.create(callable, LIST_DOMAINS_PAGE_STR_DESC, request, context);
return ListDomainsPagedResponse.createAsync(pageContext, futureResponse);
}
};
/** Returns the object with the settings used for calls to createMicrosoftAdDomain. */
public UnaryCallSettings<CreateMicrosoftAdDomainRequest, Operation>
createMicrosoftAdDomainSettings() {
return createMicrosoftAdDomainSettings;
}
/** Returns the object with the settings used for calls to createMicrosoftAdDomain. */
public OperationCallSettings<CreateMicrosoftAdDomainRequest, Domain, OpMetadata>
createMicrosoftAdDomainOperationSettings() {
return createMicrosoftAdDomainOperationSettings;
}
/** Returns the object with the settings used for calls to resetAdminPassword. */
public UnaryCallSettings<ResetAdminPasswordRequest, ResetAdminPasswordResponse>
resetAdminPasswordSettings() {
return resetAdminPasswordSettings;
}
/** Returns the object with the settings used for calls to listDomains. */
public PagedCallSettings<ListDomainsRequest, ListDomainsResponse, ListDomainsPagedResponse>
listDomainsSettings() {
return listDomainsSettings;
}
/** Returns the object with the settings used for calls to getDomain. */
public UnaryCallSettings<GetDomainRequest, Domain> getDomainSettings() {
return getDomainSettings;
}
/** Returns the object with the settings used for calls to updateDomain. */
public UnaryCallSettings<UpdateDomainRequest, Operation> updateDomainSettings() {
return updateDomainSettings;
}
/** Returns the object with the settings used for calls to updateDomain. */
public OperationCallSettings<UpdateDomainRequest, Domain, OpMetadata>
updateDomainOperationSettings() {
return updateDomainOperationSettings;
}
/** Returns the object with the settings used for calls to deleteDomain. */
public UnaryCallSettings<DeleteDomainRequest, Operation> deleteDomainSettings() {
return deleteDomainSettings;
}
/** Returns the object with the settings used for calls to deleteDomain. */
public OperationCallSettings<DeleteDomainRequest, Empty, OpMetadata>
deleteDomainOperationSettings() {
return deleteDomainOperationSettings;
}
/** Returns the object with the settings used for calls to attachTrust. */
public UnaryCallSettings<AttachTrustRequest, Operation> attachTrustSettings() {
return attachTrustSettings;
}
/** Returns the object with the settings used for calls to attachTrust. */
public OperationCallSettings<AttachTrustRequest, Domain, OpMetadata>
attachTrustOperationSettings() {
return attachTrustOperationSettings;
}
/** Returns the object with the settings used for calls to reconfigureTrust. */
public UnaryCallSettings<ReconfigureTrustRequest, Operation> reconfigureTrustSettings() {
return reconfigureTrustSettings;
}
/** Returns the object with the settings used for calls to reconfigureTrust. */
public OperationCallSettings<ReconfigureTrustRequest, Domain, OpMetadata>
reconfigureTrustOperationSettings() {
return reconfigureTrustOperationSettings;
}
/** Returns the object with the settings used for calls to detachTrust. */
public UnaryCallSettings<DetachTrustRequest, Operation> detachTrustSettings() {
return detachTrustSettings;
}
/** Returns the object with the settings used for calls to detachTrust. */
public OperationCallSettings<DetachTrustRequest, Domain, OpMetadata>
detachTrustOperationSettings() {
return detachTrustOperationSettings;
}
/** Returns the object with the settings used for calls to validateTrust. */
public UnaryCallSettings<ValidateTrustRequest, Operation> validateTrustSettings() {
return validateTrustSettings;
}
/** Returns the object with the settings used for calls to validateTrust. */
public OperationCallSettings<ValidateTrustRequest, Domain, OpMetadata>
validateTrustOperationSettings() {
return validateTrustOperationSettings;
}
@BetaApi("A restructuring of stub classes is planned, so this may break in the future")
public ManagedIdentitiesServiceStub createStub() throws IOException {
if (getTransportChannelProvider()
.getTransportName()
.equals(GrpcTransportChannel.getGrpcTransportName())) {
return GrpcManagedIdentitiesServiceStub.create(this);
}
throw new UnsupportedOperationException(
String.format(
"Transport not supported: %s", getTransportChannelProvider().getTransportName()));
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return InstantiatingExecutorProvider.newBuilder();
}
/** Returns the default service endpoint. */
public static String getDefaultEndpoint() {
return "managedidentities.googleapis.com:443";
}
/** Returns the default mTLS service endpoint. */
public static String getDefaultMtlsEndpoint() {
return "managedidentities.mtls.googleapis.com:443";
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return DEFAULT_SERVICE_SCOPES;
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return GoogleCredentialsProvider.newBuilder()
.setScopesToApply(DEFAULT_SERVICE_SCOPES)
.setUseJwtAccessWithScope(true);
}
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() {
return InstantiatingGrpcChannelProvider.newBuilder()
.setMaxInboundMessageSize(Integer.MAX_VALUE);
}
public static TransportChannelProvider defaultTransportChannelProvider() {
return defaultGrpcTransportProviderBuilder().build();
}
@BetaApi("The surface for customizing headers is not stable yet and may change in the future.")
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return ApiClientHeaderProvider.newBuilder()
.setGeneratedLibToken(
"gapic", GaxProperties.getLibraryVersion(ManagedIdentitiesServiceStubSettings.class))
.setTransportToken(
GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion());
}
/** Returns a new builder for this class. */
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder(ClientContext clientContext) {
return new Builder(clientContext);
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
protected ManagedIdentitiesServiceStubSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
createMicrosoftAdDomainSettings = settingsBuilder.createMicrosoftAdDomainSettings().build();
createMicrosoftAdDomainOperationSettings =
settingsBuilder.createMicrosoftAdDomainOperationSettings().build();
resetAdminPasswordSettings = settingsBuilder.resetAdminPasswordSettings().build();
listDomainsSettings = settingsBuilder.listDomainsSettings().build();
getDomainSettings = settingsBuilder.getDomainSettings().build();
updateDomainSettings = settingsBuilder.updateDomainSettings().build();
updateDomainOperationSettings = settingsBuilder.updateDomainOperationSettings().build();
deleteDomainSettings = settingsBuilder.deleteDomainSettings().build();
deleteDomainOperationSettings = settingsBuilder.deleteDomainOperationSettings().build();
attachTrustSettings = settingsBuilder.attachTrustSettings().build();
attachTrustOperationSettings = settingsBuilder.attachTrustOperationSettings().build();
reconfigureTrustSettings = settingsBuilder.reconfigureTrustSettings().build();
reconfigureTrustOperationSettings = settingsBuilder.reconfigureTrustOperationSettings().build();
detachTrustSettings = settingsBuilder.detachTrustSettings().build();
detachTrustOperationSettings = settingsBuilder.detachTrustOperationSettings().build();
validateTrustSettings = settingsBuilder.validateTrustSettings().build();
validateTrustOperationSettings = settingsBuilder.validateTrustOperationSettings().build();
}
/** Builder for ManagedIdentitiesServiceStubSettings. */
public static class Builder
extends StubSettings.Builder<ManagedIdentitiesServiceStubSettings, Builder> {
private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders;
private final UnaryCallSettings.Builder<CreateMicrosoftAdDomainRequest, Operation>
createMicrosoftAdDomainSettings;
private final OperationCallSettings.Builder<CreateMicrosoftAdDomainRequest, Domain, OpMetadata>
createMicrosoftAdDomainOperationSettings;
private final UnaryCallSettings.Builder<ResetAdminPasswordRequest, ResetAdminPasswordResponse>
resetAdminPasswordSettings;
private final PagedCallSettings.Builder<
ListDomainsRequest, ListDomainsResponse, ListDomainsPagedResponse>
listDomainsSettings;
private final UnaryCallSettings.Builder<GetDomainRequest, Domain> getDomainSettings;
private final UnaryCallSettings.Builder<UpdateDomainRequest, Operation> updateDomainSettings;
private final OperationCallSettings.Builder<UpdateDomainRequest, Domain, OpMetadata>
updateDomainOperationSettings;
private final UnaryCallSettings.Builder<DeleteDomainRequest, Operation> deleteDomainSettings;
private final OperationCallSettings.Builder<DeleteDomainRequest, Empty, OpMetadata>
deleteDomainOperationSettings;
private final UnaryCallSettings.Builder<AttachTrustRequest, Operation> attachTrustSettings;
private final OperationCallSettings.Builder<AttachTrustRequest, Domain, OpMetadata>
attachTrustOperationSettings;
private final UnaryCallSettings.Builder<ReconfigureTrustRequest, Operation>
reconfigureTrustSettings;
private final OperationCallSettings.Builder<ReconfigureTrustRequest, Domain, OpMetadata>
reconfigureTrustOperationSettings;
private final UnaryCallSettings.Builder<DetachTrustRequest, Operation> detachTrustSettings;
private final OperationCallSettings.Builder<DetachTrustRequest, Domain, OpMetadata>
detachTrustOperationSettings;
private final UnaryCallSettings.Builder<ValidateTrustRequest, Operation> validateTrustSettings;
private final OperationCallSettings.Builder<ValidateTrustRequest, Domain, OpMetadata>
validateTrustOperationSettings;
private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>>
RETRYABLE_CODE_DEFINITIONS;
static {
ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions =
ImmutableMap.builder();
definitions.put(
"no_retry_0_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList()));
RETRYABLE_CODE_DEFINITIONS = definitions.build();
}
private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS;
static {
ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder();
RetrySettings settings = null;
settings =
RetrySettings.newBuilder()
.setInitialRpcTimeout(Duration.ofMillis(60000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeout(Duration.ofMillis(60000L))
.setTotalTimeout(Duration.ofMillis(60000L))
.build();
definitions.put("no_retry_0_params", settings);
RETRY_PARAM_DEFINITIONS = definitions.build();
}
protected Builder() {
this(((ClientContext) null));
}
protected Builder(ClientContext clientContext) {
super(clientContext);
createMicrosoftAdDomainSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
createMicrosoftAdDomainOperationSettings = OperationCallSettings.newBuilder();
resetAdminPasswordSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
listDomainsSettings = PagedCallSettings.newBuilder(LIST_DOMAINS_PAGE_STR_FACT);
getDomainSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
updateDomainSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
updateDomainOperationSettings = OperationCallSettings.newBuilder();
deleteDomainSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
deleteDomainOperationSettings = OperationCallSettings.newBuilder();
attachTrustSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
attachTrustOperationSettings = OperationCallSettings.newBuilder();
reconfigureTrustSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
reconfigureTrustOperationSettings = OperationCallSettings.newBuilder();
detachTrustSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
detachTrustOperationSettings = OperationCallSettings.newBuilder();
validateTrustSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
validateTrustOperationSettings = OperationCallSettings.newBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
createMicrosoftAdDomainSettings,
resetAdminPasswordSettings,
listDomainsSettings,
getDomainSettings,
updateDomainSettings,
deleteDomainSettings,
attachTrustSettings,
reconfigureTrustSettings,
detachTrustSettings,
validateTrustSettings);
initDefaults(this);
}
protected Builder(ManagedIdentitiesServiceStubSettings settings) {
super(settings);
createMicrosoftAdDomainSettings = settings.createMicrosoftAdDomainSettings.toBuilder();
createMicrosoftAdDomainOperationSettings =
settings.createMicrosoftAdDomainOperationSettings.toBuilder();
resetAdminPasswordSettings = settings.resetAdminPasswordSettings.toBuilder();
listDomainsSettings = settings.listDomainsSettings.toBuilder();
getDomainSettings = settings.getDomainSettings.toBuilder();
updateDomainSettings = settings.updateDomainSettings.toBuilder();
updateDomainOperationSettings = settings.updateDomainOperationSettings.toBuilder();
deleteDomainSettings = settings.deleteDomainSettings.toBuilder();
deleteDomainOperationSettings = settings.deleteDomainOperationSettings.toBuilder();
attachTrustSettings = settings.attachTrustSettings.toBuilder();
attachTrustOperationSettings = settings.attachTrustOperationSettings.toBuilder();
reconfigureTrustSettings = settings.reconfigureTrustSettings.toBuilder();
reconfigureTrustOperationSettings = settings.reconfigureTrustOperationSettings.toBuilder();
detachTrustSettings = settings.detachTrustSettings.toBuilder();
detachTrustOperationSettings = settings.detachTrustOperationSettings.toBuilder();
validateTrustSettings = settings.validateTrustSettings.toBuilder();
validateTrustOperationSettings = settings.validateTrustOperationSettings.toBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
createMicrosoftAdDomainSettings,
resetAdminPasswordSettings,
listDomainsSettings,
getDomainSettings,
updateDomainSettings,
deleteDomainSettings,
attachTrustSettings,
reconfigureTrustSettings,
detachTrustSettings,
validateTrustSettings);
}
private static Builder createDefault() {
Builder builder = new Builder(((ClientContext) null));
builder.setTransportChannelProvider(defaultTransportChannelProvider());
builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build());
builder.setEndpoint(getDefaultEndpoint());
builder.setMtlsEndpoint(getDefaultMtlsEndpoint());
builder.setSwitchToMtlsEndpointAllowed(true);
return initDefaults(builder);
}
private static Builder initDefaults(Builder builder) {
builder
.createMicrosoftAdDomainSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));
builder
.resetAdminPasswordSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));
builder
.listDomainsSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));
builder
.getDomainSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));
builder
.updateDomainSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));
builder
.deleteDomainSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));
builder
.attachTrustSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));
builder
.reconfigureTrustSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));
builder
.detachTrustSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));
builder
.validateTrustSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));
builder
.createMicrosoftAdDomainOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<CreateMicrosoftAdDomainRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Domain.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(OpMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelay(Duration.ofMillis(45000L))
.setInitialRpcTimeout(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeout(Duration.ZERO)
.setTotalTimeout(Duration.ofMillis(300000L))
.build()));
builder
.updateDomainOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<UpdateDomainRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Domain.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(OpMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelay(Duration.ofMillis(45000L))
.setInitialRpcTimeout(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeout(Duration.ZERO)
.setTotalTimeout(Duration.ofMillis(300000L))
.build()));
builder
.deleteDomainOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<DeleteDomainRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Empty.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(OpMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelay(Duration.ofMillis(45000L))
.setInitialRpcTimeout(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeout(Duration.ZERO)
.setTotalTimeout(Duration.ofMillis(300000L))
.build()));
builder
.attachTrustOperationSettings()
.setInitialCallSettings(
UnaryCallSettings.<AttachTrustRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Domain.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(OpMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelay(Duration.ofMillis(45000L))
.setInitialRpcTimeout(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeout(Duration.ZERO)
.setTotalTimeout(Duration.ofMillis(300000L))
.build()));
builder
.reconfigureTrustOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<ReconfigureTrustRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Domain.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(OpMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelay(Duration.ofMillis(45000L))
.setInitialRpcTimeout(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeout(Duration.ZERO)
.setTotalTimeout(Duration.ofMillis(300000L))
.build()));
builder
.detachTrustOperationSettings()
.setInitialCallSettings(
UnaryCallSettings.<DetachTrustRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Domain.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(OpMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelay(Duration.ofMillis(45000L))
.setInitialRpcTimeout(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeout(Duration.ZERO)
.setTotalTimeout(Duration.ofMillis(300000L))
.build()));
builder
.validateTrustOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<ValidateTrustRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Domain.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(OpMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelay(Duration.ofMillis(45000L))
.setInitialRpcTimeout(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeout(Duration.ZERO)
.setTotalTimeout(Duration.ofMillis(300000L))
.build()));
return builder;
}
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater);
return this;
}
public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() {
return unaryMethodSettingsBuilders;
}
/** Returns the builder for the settings used for calls to createMicrosoftAdDomain. */
public UnaryCallSettings.Builder<CreateMicrosoftAdDomainRequest, Operation>
createMicrosoftAdDomainSettings() {
return createMicrosoftAdDomainSettings;
}
/** Returns the builder for the settings used for calls to createMicrosoftAdDomain. */
@BetaApi(
"The surface for use by generated code is not stable yet and may change in the future.")
public OperationCallSettings.Builder<CreateMicrosoftAdDomainRequest, Domain, OpMetadata>
createMicrosoftAdDomainOperationSettings() {
return createMicrosoftAdDomainOperationSettings;
}
/** Returns the builder for the settings used for calls to resetAdminPassword. */
public UnaryCallSettings.Builder<ResetAdminPasswordRequest, ResetAdminPasswordResponse>
resetAdminPasswordSettings() {
return resetAdminPasswordSettings;
}
/** Returns the builder for the settings used for calls to listDomains. */
public PagedCallSettings.Builder<
ListDomainsRequest, ListDomainsResponse, ListDomainsPagedResponse>
listDomainsSettings() {
return listDomainsSettings;
}
/** Returns the builder for the settings used for calls to getDomain. */
public UnaryCallSettings.Builder<GetDomainRequest, Domain> getDomainSettings() {
return getDomainSettings;
}
/** Returns the builder for the settings used for calls to updateDomain. */
public UnaryCallSettings.Builder<UpdateDomainRequest, Operation> updateDomainSettings() {
return updateDomainSettings;
}
/** Returns the builder for the settings used for calls to updateDomain. */
@BetaApi(
"The surface for use by generated code is not stable yet and may change in the future.")
public OperationCallSettings.Builder<UpdateDomainRequest, Domain, OpMetadata>
updateDomainOperationSettings() {
return updateDomainOperationSettings;
}
/** Returns the builder for the settings used for calls to deleteDomain. */
public UnaryCallSettings.Builder<DeleteDomainRequest, Operation> deleteDomainSettings() {
return deleteDomainSettings;
}
/** Returns the builder for the settings used for calls to deleteDomain. */
@BetaApi(
"The surface for use by generated code is not stable yet and may change in the future.")
public OperationCallSettings.Builder<DeleteDomainRequest, Empty, OpMetadata>
deleteDomainOperationSettings() {
return deleteDomainOperationSettings;
}
/** Returns the builder for the settings used for calls to attachTrust. */
public UnaryCallSettings.Builder<AttachTrustRequest, Operation> attachTrustSettings() {
return attachTrustSettings;
}
/** Returns the builder for the settings used for calls to attachTrust. */
@BetaApi(
"The surface for use by generated code is not stable yet and may change in the future.")
public OperationCallSettings.Builder<AttachTrustRequest, Domain, OpMetadata>
attachTrustOperationSettings() {
return attachTrustOperationSettings;
}
/** Returns the builder for the settings used for calls to reconfigureTrust. */
public UnaryCallSettings.Builder<ReconfigureTrustRequest, Operation>
reconfigureTrustSettings() {
return reconfigureTrustSettings;
}
/** Returns the builder for the settings used for calls to reconfigureTrust. */
@BetaApi(
"The surface for use by generated code is not stable yet and may change in the future.")
public OperationCallSettings.Builder<ReconfigureTrustRequest, Domain, OpMetadata>
reconfigureTrustOperationSettings() {
return reconfigureTrustOperationSettings;
}
/** Returns the builder for the settings used for calls to detachTrust. */
public UnaryCallSettings.Builder<DetachTrustRequest, Operation> detachTrustSettings() {
return detachTrustSettings;
}
/** Returns the builder for the settings used for calls to detachTrust. */
@BetaApi(
"The surface for use by generated code is not stable yet and may change in the future.")
public OperationCallSettings.Builder<DetachTrustRequest, Domain, OpMetadata>
detachTrustOperationSettings() {
return detachTrustOperationSettings;
}
/** Returns the builder for the settings used for calls to validateTrust. */
public UnaryCallSettings.Builder<ValidateTrustRequest, Operation> validateTrustSettings() {
return validateTrustSettings;
}
/** Returns the builder for the settings used for calls to validateTrust. */
@BetaApi(
"The surface for use by generated code is not stable yet and may change in the future.")
public OperationCallSettings.Builder<ValidateTrustRequest, Domain, OpMetadata>
validateTrustOperationSettings() {
return validateTrustOperationSettings;
}
@Override
public ManagedIdentitiesServiceStubSettings build() throws IOException {
return new ManagedIdentitiesServiceStubSettings(this);
}
}
}
| |
/**
* *********************************************************************
* Copyright (c) 2016: Istituto Nazionale di Fisica Nucleare (INFN) -
* INDIGO-DataCloud
*
* See http://www.infn.it and and http://www.consorzio-cometa.it for details on
* the copyright holders.
*
* 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 it.infn.ct.indigo.futuregateway.portlet.action;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.portlet.bridges.mvc.BaseMVCActionCommand;
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCActionCommand;
import com.liferay.portal.kernel.security.auth.PrincipalException;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.theme.ThemeDisplay;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.PortalUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import it.infn.ct.indigo.futuregateway.constants.FutureGatewayAdminPortletKeys;
import it.infn.ct.indigo.futuregateway.server.FGServerConstants;
import it.infn.ct.indigo.futuregateway.server.FGServerManager;
/**
* Implementation of the add application in FG server action command.
*/
@Component(
immediate = true,
property = {
"javax.portlet.name="
+ FutureGatewayAdminPortletKeys.FUTURE_GATEWAY_ADMIN,
"mvc.command.name=/fg/addApp"
},
service = MVCActionCommand.class
)
public class FGEditAppMVCActionCommand extends BaseMVCActionCommand {
@Override
protected final void doProcessAction(final ActionRequest actionRequest,
final ActionResponse actionResponse) throws Exception {
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(
WebKeys.THEME_DISPLAY);
String redirect = PortalUtil.escapeRedirect(
ParamUtil.getString(actionRequest, "redirect"));
String id = ParamUtil.getString(actionRequest, "fg-app-id");
String name = ParamUtil.getString(actionRequest, "fg-app-name");
String description = ParamUtil.getString(actionRequest,
"fg-app-description");
boolean enabled = ParamUtil.getBoolean(actionRequest, "fg-app-enabled");
String outcome = ParamUtil.getString(actionRequest, "fg-app-outcome");
String[] paramNames = ParamUtil.getStringValues(
actionRequest, "fg-app-parameter-name");
String[] paramValues = ParamUtil.getStringValues(
actionRequest, "fg-app-parameter-value");
String[] paramDescriptions = ParamUtil.getStringValues(
actionRequest, "fg-app-parameter-description");
String[] infras = ParamUtil.getStringValues(actionRequest,
"fg-app-infrastructure");
String[] fileUrls = ParamUtil.getStringValues(actionRequest,
"fg-app-file-url");
String[] fileOld = ParamUtil.getStringValues(actionRequest,
"fg-app-file-old");
UploadPortletRequest upr = PortalUtil.
getUploadPortletRequest(actionRequest);
InputStream[] files = upr.getFilesAsStream("fg-app-file-update", true);
String[] fileNames = upr.getFileNames("fg-app-file-update");
Map<String, InputStream> fileToTransfer = new HashMap<>();
JSONObject jApp = JSONFactoryUtil.createJSONObject();
if (!id.isEmpty()) {
jApp.put("id", id);
}
jApp.put("name", name);
jApp.put("description", description);
jApp.put("enabled", enabled);
jApp.put("outcome", outcome);
JSONArray jParams = JSONFactoryUtil.createJSONArray();
for (int i = 0; i < paramNames.length; i++) {
if (Validator.isNotNull(paramNames[i])) {
JSONObject jPar = JSONFactoryUtil.createJSONObject();
jPar.put("name", paramNames[i]);
jPar.put("value", paramValues[i]);
if (paramDescriptions.length == paramNames.length) {
jPar.put("description", paramDescriptions[i]);
}
jParams.put(jPar);
}
}
jApp.put("parameters", jParams);
JSONArray jInfras = JSONFactoryUtil.createJSONArray();
for (String in: infras) {
jInfras.put(in);
}
jApp.put("infrastructures", jInfras);
if (Validator.isNotNull(fileNames)) {
JSONArray jFiles = JSONFactoryUtil.createJSONArray();
for (int i = 0; i < fileNames.length; i++) {
if (Validator.isNotNull(fileNames[i])) {
jFiles.put(fileNames[i]);
fileToTransfer.put(fileNames[i], files[i]);
} else {
if (fileUrls.length == fileNames.length
&& Validator.isNotNull(fileUrls[i])) {
jFiles.put(fileUrls[i]);
} else {
if (fileOld[i].compareTo("N/A") != 0) {
jFiles.put(fileOld[i]);
}
}
}
}
jApp.put("files", jFiles);
}
try {
String resourceId = fgServerManager.addResource(
themeDisplay.getCompanyId(),
FGServerConstants.APPLICATION_COLLECTION,
id, jApp.toJSONString(), themeDisplay.getUserId());
if (!fileToTransfer.isEmpty()) {
fgServerManager.submitFilesResource(
themeDisplay.getCompanyId(),
FGServerConstants.APPLICATION_COLLECTION,
resourceId, fileToTransfer, themeDisplay.getUserId());
}
sendRedirect(actionRequest, actionResponse, redirect);
} catch (IOException io) {
log.error(io.getMessage());
SessionErrors.add(actionRequest, io.getClass(), io);
try {
Map<String, String> mapInfras =
fgServerManager.getInfrastructures(
themeDisplay.getCompanyId(), themeDisplay.getUserId());
actionRequest.setAttribute(
FGServerConstants.INFRASTRUCTURE_COLLECTION,
mapInfras
);
} catch (Exception e) {
if (e instanceof PrincipalException) {
SessionErrors.add(actionRequest, e.getClass());
actionResponse.setRenderParameter(
"mvcPath", "/error.jsp");
} else {
throw new PortletException(e);
}
}
actionResponse.setRenderParameter(
"mvcPath", "/add_application.jsp");
}
}
/**
* Sets the FG Server manager.
* This is used to get information of the service and for interactions.
*
* @param fgServerManeger The FG Server manager
*/
@Reference(unbind = "-")
protected final void setFGServerManeger(
final FGServerManager fgServerManeger) {
this.fgServerManager = fgServerManeger;
}
/**
* The logger.
*/
private Log log = LogFactoryUtil.getLog(FGEditAppMVCActionCommand.class);
/**
* The reference to the FG Server manager.
*/
private FGServerManager fgServerManager;
}
| |
/*
* $Id: DefinitionsFactoryConfig.java 471754 2006-11-06 14:55:09Z husted $
*
* 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.struts.tiles;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.commons.beanutils.BeanUtils;
/**
* A TilesFactoryConfig object hold configuration attributes for a tile
* definition factory.
*
* @since Struts 1.1
* @version $Rev: 471754 $ $Date: 2006-11-06 15:55:09 +0100 (Lun, 06 nov 2006) $
*/
public class DefinitionsFactoryConfig implements Serializable {
/**
* Fully qualified classname of the factory to create.
* If no classname is set, a default factory is created
* (of class "org.apache.struts.tiles.xmlDefinition.I18nFactorySet").
*/
protected String factoryClassname =
"org.apache.struts.tiles.xmlDefinition.I18nFactorySet";
/**
* Specifies whether the parser will validate configuration files.
* Default value is true.
*/
protected boolean parserValidate = true;
/**
* Definition configuration file specified by user.
*/
protected String definitionConfigFiles = null;
/**
* Specifies whether the factory is "module-aware".
*/
protected boolean moduleAware = true;
/**
* The name associated to this factory.
* <br>
* With Struts 1.1, this name is the module name to which this factory
* belong. It is set by the system.
* <br>
* In prior versions, this property is not used.
*/
protected String factoryName;
/**
* Alternate name for parser debug details properties in configuration file.
* @deprecated This will be removed in a release after Struts 1.2.
*/
public static final String PARSER_DETAILS_PARAMETER_NAME =
"definitions-parser-details";
/**
* Alternate name for parser validate properties in configuration file.
*/
public static final String PARSER_VALIDATE_PARAMETER_NAME =
"definitions-parser-validate";
/**
* Alternate name for factory classname properties in configuration file.
*/
public static final String FACTORY_CLASSNAME_PARAMETER_NAME =
"definitions-factory-class";
/**
* Alternate name for definition files properties in configuration file.
*/
public static final String DEFINITIONS_CONFIG_PARAMETER_NAME =
"definitions-config";
/**
* Alternate name for definition debug details properties in configuration file.
* @deprecated This will be removed in a release after Struts 1.2.
*/
public static final String TILES_DETAILS_PARAMETER_NAME = "definitions-debug";
/**
* Map of extra attribute available.
*/
private Map extraAttributes = new HashMap();
/**
* Default constructor.
*/
public DefinitionsFactoryConfig() {
super();
}
/**
* Constructor.
* Create configuration object, and initialize it with parameters from Map.
* Parameters corresponding to an attribute are filtered and stored in appropriate
* attribute.
* @param initParameters Map.
*/
public DefinitionsFactoryConfig(Map initParameters) {
super();
}
/**
* Get the module aware flag.
* @return <code>true</code>: user wants a single factory instance,
* <code>false</code>: user wants multiple factory instances (one per module with Struts)
*/
public boolean isModuleAware() {
return moduleAware;
}
/**
* Set the module aware flag.
* @param moduleAware <code>true</code>: user wants a single factory instance,
* <code>false</code>: user wants multiple factory instances (one per module with Struts)
*/
public void setModuleAware(boolean moduleAware) {
this.moduleAware = moduleAware;
}
/**
* Get the classname of the factory.
* @return Classname.
*/
public String getFactoryClassname() {
return factoryClassname;
}
/**
* Set the classname of the factory..
* @param aFactoryClassname Classname of the factory.
*/
public void setFactoryClassname(String aFactoryClassname) {
factoryClassname = aFactoryClassname;
}
/**
* Determines if the parser is validating.
* @return <code>true<code> when in validating mode.
*/
public boolean getParserValidate() {
return parserValidate;
}
/**
* Set the validating mode for the parser.
* @param aParserValidate <code>true</code> for validation, <code>false</code> otherwise
*/
public void setParserValidate(boolean aParserValidate) {
parserValidate = aParserValidate;
}
/**
* Get the definition config files.
* @return Defition config files.
*/
public String getDefinitionConfigFiles() {
return definitionConfigFiles;
}
/**
* Set the definition config files.
* @param aDefinitionConfigFiles Definition config files.
*/
public void setDefinitionConfigFiles(String aDefinitionConfigFiles) {
definitionConfigFiles = aDefinitionConfigFiles;
}
/**
* Set value of an additional attribute.
* @param name Name of the attribute.
* @param value Value of the attribute.
*/
public void setAttribute(String name, Object value) {
extraAttributes.put(name, value);
}
/**
* Get value of an additional attribute.
* @param name Name of the attribute.
* @return Value of the attribute, or null if not found.
*/
public Object getAttribute(String name) {
return extraAttributes.get(name);
}
/**
* Get additional attributes as a Map.
* @return Map A Map containing attribute name - value pairs.
*/
public Map getAttributes() {
Map map = new HashMap(extraAttributes);
// Add property attributes using old names
/*
map.put(DEFINITIONS_CONFIG_PARAMETER_NAME, getDefinitionConfigFiles());
map.put(TILES_DETAILS_PARAMETER_NAME, Integer.toString(getDebugLevel()) );
map.put(PARSER_DETAILS_PARAMETER_NAME, Integer.toString(getParserDebugLevel()) );
map.put(PARSER_VALIDATE_PARAMETER_NAME, new Boolean(getParserValidate()).toString() );
if( ! "org.apache.struts.tiles.xmlDefinition.I18nFactorySet".equals(getFactoryClassname()) )
map.put(FACTORY_CLASSNAME_PARAMETER_NAME, getFactoryClassname());
*/
return map;
}
/**
* Populate this config object from properties map, based on
* the specified name/value pairs. This method uses the populate() method from
* org.apache.commons.beanutils.BeanUtil.
* <p>
* Properties keys are scanned for old property names, and linked to the new name
* if necessary. This modifies the properties map.
* <p>
* The particular setter method to be called for each property is
* determined using the usual JavaBeans introspection mechanisms. Thus,
* you may identify custom setter methods using a BeanInfo class that is
* associated with the class of the bean itself. If no such BeanInfo
* class is available, the standard method name conversion ("set" plus
* the capitalized name of the property in question) is used.
* <p>
* <strong>NOTE</strong>: It is contrary to the JavaBeans Specification
* to have more than one setter method (with different argument
* signatures) for the same property.
*
* @param properties Map keyed by property name, with the
* corresponding (String or String[]) value(s) to be set.
*
* @exception IllegalAccessException if the caller does not have
* access to the property accessor method.
* @exception InvocationTargetException if the property accessor method
* throws an exception.
* @see org.apache.commons.beanutils.BeanUtils
*/
public void populate(Map properties)
throws IllegalAccessException, InvocationTargetException {
// link old parameter names for backward compatibility
linkOldPropertyNames(properties);
BeanUtils.populate(this, properties);
}
/**
* Link old property names to new property names.
* This modifies the map.
* @param properties Map keyed by property name, with the
* corresponding (String or String[]) value(s) to be set.
*/
static public void linkOldPropertyNames(Map properties) {
Set entries = properties.entrySet();
Map toAdd = new HashMap();
Iterator i = entries.iterator();
while (i.hasNext()) {
Map.Entry entry = (Map.Entry) i.next();
if (DEFINITIONS_CONFIG_PARAMETER_NAME.equals(entry.getKey())) {
toAdd.put("definitionConfigFiles", entry.getValue());
} else if (FACTORY_CLASSNAME_PARAMETER_NAME.equals(entry.getKey())) {
toAdd.put("factoryClassname", entry.getValue());
} else if (PARSER_DETAILS_PARAMETER_NAME.equals(entry.getKey())) {
toAdd.put("parserDebugLevel", entry.getValue());
} else if (PARSER_VALIDATE_PARAMETER_NAME.equals(entry.getKey())) {
toAdd.put("parserValidate", entry.getValue());
} else if (TILES_DETAILS_PARAMETER_NAME.equals(entry.getKey())) {
toAdd.put("debugLevel", entry.getValue());
}
}
if (toAdd.size() > 0) {
properties.putAll(toAdd);
}
}
/**
* Get the factory name.
*/
public String getFactoryName() {
return factoryName;
}
/**
* Set the factory name.
* @param factoryName Name of the factory.
*/
public void setFactoryName(String factoryName) {
this.factoryName = factoryName;
}
}
| |
package com.clockwork.scene.plugins.blender.materials;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.clockwork.asset.BlenderKey.FeaturesToLoad;
import com.clockwork.material.MatParam;
import com.clockwork.material.Material;
import com.clockwork.math.ColorRGBA;
import com.clockwork.math.FastMath;
import com.clockwork.scene.plugins.blender.AbstractBlenderHelper;
import com.clockwork.scene.plugins.blender.BlenderContext;
import com.clockwork.scene.plugins.blender.BlenderContext.LoadedFeatureDataType;
import com.clockwork.scene.plugins.blender.exceptions.BlenderFileException;
import com.clockwork.scene.plugins.blender.file.Pointer;
import com.clockwork.scene.plugins.blender.file.Structure;
import com.clockwork.shader.VarType;
import com.clockwork.texture.Image;
import com.clockwork.texture.Image.Format;
import com.clockwork.texture.Texture;
import com.clockwork.util.BufferUtils;
public class MaterialHelper extends AbstractBlenderHelper {
private static final Logger LOGGER = Logger.getLogger(MaterialHelper.class.getName());
protected static final float DEFAULT_SHININESS = 20.0f;
public static final String TEXTURE_TYPE_COLOR = "ColorMap";
public static final String TEXTURE_TYPE_DIFFUSE = "DiffuseMap";
public static final String TEXTURE_TYPE_NORMAL = "NormalMap";
public static final String TEXTURE_TYPE_SPECULAR = "SpecularMap";
public static final String TEXTURE_TYPE_GLOW = "GlowMap";
public static final String TEXTURE_TYPE_ALPHA = "AlphaMap";
public static final String TEXTURE_TYPE_LIGHTMAP = "LightMap";
public static final Integer ALPHA_MASK_NONE = Integer.valueOf(0);
public static final Integer ALPHA_MASK_CIRCLE = Integer.valueOf(1);
public static final Integer ALPHA_MASK_CONE = Integer.valueOf(2);
public static final Integer ALPHA_MASK_HYPERBOLE = Integer.valueOf(3);
protected final Map<Integer, IAlphaMask> alphaMasks = new HashMap<Integer, IAlphaMask>();
/**
* The type of the material's diffuse shader.
*/
public static enum DiffuseShader {
LAMBERT, ORENNAYAR, TOON, MINNAERT, FRESNEL
}
/**
* The type of the material's specular shader.
*/
public static enum SpecularShader {
COOKTORRENCE, PHONG, BLINN, TOON, WARDISO
}
/**
* This constructor parses the given blender version and stores the result. Some functionalities may differ in different blender
* versions.
*
* @param blenderVersion
* the version read from the blend file
* @param blenderContext
* the blender context
*/
public MaterialHelper(String blenderVersion, BlenderContext blenderContext) {
super(blenderVersion, blenderContext);
// setting alpha masks
alphaMasks.put(ALPHA_MASK_NONE, new IAlphaMask() {
public void setImageSize(int width, int height) {
}
public byte getAlpha(float x, float y) {
return (byte) 255;
}
});
alphaMasks.put(ALPHA_MASK_CIRCLE, new IAlphaMask() {
private float r;
private float[] center;
public void setImageSize(int width, int height) {
r = Math.min(width, height) * 0.5f;
center = new float[] { width * 0.5f, height * 0.5f };
}
public byte getAlpha(float x, float y) {
float d = FastMath.abs(FastMath.sqrt((x - center[0]) * (x - center[0]) + (y - center[1]) * (y - center[1])));
return (byte) (d >= r ? 0 : 255);
}
});
alphaMasks.put(ALPHA_MASK_CONE, new IAlphaMask() {
private float r;
private float[] center;
public void setImageSize(int width, int height) {
r = Math.min(width, height) * 0.5f;
center = new float[] { width * 0.5f, height * 0.5f };
}
public byte getAlpha(float x, float y) {
float d = FastMath.abs(FastMath.sqrt((x - center[0]) * (x - center[0]) + (y - center[1]) * (y - center[1])));
return (byte) (d >= r ? 0 : -255.0f * d / r + 255.0f);
}
});
alphaMasks.put(ALPHA_MASK_HYPERBOLE, new IAlphaMask() {
private float r;
private float[] center;
public void setImageSize(int width, int height) {
r = Math.min(width, height) * 0.5f;
center = new float[] { width * 0.5f, height * 0.5f };
}
public byte getAlpha(float x, float y) {
float d = FastMath.abs(FastMath.sqrt((x - center[0]) * (x - center[0]) + (y - center[1]) * (y - center[1]))) / r;
return d >= 1.0f ? 0 : (byte) ((-FastMath.sqrt((2.0f - d) * d) + 1.0f) * 255.0f);
}
});
}
/**
* This method converts the material structure to CW Material.
* @param structure
* structure with material data
* @param blenderContext
* the blender context
* @return CW material
* @throws BlenderFileException
* an exception is throw when problems with blend file occur
*/
public MaterialContext toMaterialContext(Structure structure, BlenderContext blenderContext) throws BlenderFileException {
LOGGER.log(Level.FINE, "Loading material.");
MaterialContext result = (MaterialContext) blenderContext.getLoadedFeature(structure.getOldMemoryAddress(), LoadedFeatureDataType.LOADED_FEATURE);
if (result != null) {
return result;
}
result = new MaterialContext(structure, blenderContext);
LOGGER.log(Level.FINE, "Material''s name: {0}", result.name);
blenderContext.addLoadedFeatures(structure.getOldMemoryAddress(), structure.getName(), structure, result);
return result;
}
/**
* This method converts the given material into particles-usable material.
* The texture and glow color are being copied.
* The method assumes it receives the Lighting type of material.
* @param material
* the source material
* @param blenderContext
* the blender context
* @return material converted into particles-usable material
*/
public Material getParticlesMaterial(Material material, Integer alphaMaskIndex, BlenderContext blenderContext) {
Material result = new Material(blenderContext.getAssetManager(), "Common/MatDefs/Misc/Particle.j3md");
// copying texture
MatParam diffuseMap = material.getParam("DiffuseMap");
if (diffuseMap != null) {
Texture texture = ((Texture) diffuseMap.getValue()).clone();
// applying alpha mask to the texture
Image image = texture.getImage();
ByteBuffer sourceBB = image.getData(0);
sourceBB.rewind();
int w = image.getWidth();
int h = image.getHeight();
ByteBuffer bb = BufferUtils.createByteBuffer(w * h * 4);
IAlphaMask iAlphaMask = alphaMasks.get(alphaMaskIndex);
iAlphaMask.setImageSize(w, h);
for (int x = 0; x < w; ++x) {
for (int y = 0; y < h; ++y) {
bb.put(sourceBB.get());
bb.put(sourceBB.get());
bb.put(sourceBB.get());
bb.put(iAlphaMask.getAlpha(x, y));
}
}
image = new Image(Format.RGBA8, w, h, bb);
texture.setImage(image);
result.setTextureParam("Texture", VarType.Texture2D, texture);
}
// copying glow color
MatParam glowColor = material.getParam("GlowColor");
if (glowColor != null) {
ColorRGBA color = (ColorRGBA) glowColor.getValue();
result.setParam("GlowColor", VarType.Vector3, color);
}
return result;
}
/**
* This method returns the table of materials connected to the specified structure. The given structure can be of any type (ie. mesh or
* curve) but needs to have 'mat' field/
*
* @param structureWithMaterials
* the structure containing the mesh data
* @param blenderContext
* the blender context
* @return a list of vertices colors, each color belongs to a single vertex
* @throws BlenderFileException
* this exception is thrown when the blend file structure is somehow invalid or corrupted
*/
public MaterialContext[] getMaterials(Structure structureWithMaterials, BlenderContext blenderContext) throws BlenderFileException {
Pointer ppMaterials = (Pointer) structureWithMaterials.getFieldValue("mat");
MaterialContext[] materials = null;
if (ppMaterials.isNotNull()) {
List<Structure> materialStructures = ppMaterials.fetchData(blenderContext.getInputStream());
if (materialStructures != null && materialStructures.size() > 0) {
MaterialHelper materialHelper = blenderContext.getHelper(MaterialHelper.class);
materials = new MaterialContext[materialStructures.size()];
int i = 0;
for (Structure s : materialStructures) {
materials[i++] = s == null ? null : materialHelper.toMaterialContext(s, blenderContext);
}
}
}
return materials;
}
/**
* This method converts rgb values to hsv values.
*
* @param r
* red value of the color
* @param g
* green value of the color
* @param b
* blue value of the color
* @param hsv
* hsv values of a color (this table contains the result of the transformation)
*/
public void rgbToHsv(float r, float g, float b, float[] hsv) {
float cmax = r;
float cmin = r;
cmax = g > cmax ? g : cmax;
cmin = g < cmin ? g : cmin;
cmax = b > cmax ? b : cmax;
cmin = b < cmin ? b : cmin;
hsv[2] = cmax; /* value */
if (cmax != 0.0) {
hsv[1] = (cmax - cmin) / cmax;
} else {
hsv[1] = 0.0f;
hsv[0] = 0.0f;
}
if (hsv[1] == 0.0) {
hsv[0] = -1.0f;
} else {
float cdelta = cmax - cmin;
float rc = (cmax - r) / cdelta;
float gc = (cmax - g) / cdelta;
float bc = (cmax - b) / cdelta;
if (r == cmax) {
hsv[0] = bc - gc;
} else if (g == cmax) {
hsv[0] = 2.0f + rc - bc;
} else {
hsv[0] = 4.0f + gc - rc;
}
hsv[0] *= 60.0f;
if (hsv[0] < 0.0f) {
hsv[0] += 360.0f;
}
}
hsv[0] /= 360.0f;
if (hsv[0] < 0.0f) {
hsv[0] = 0.0f;
}
}
/**
* This method converts rgb values to hsv values.
*
* @param h
* hue
* @param s
* saturation
* @param v
* value
* @param rgb
* rgb result vector (should have 3 elements)
*/
public void hsvToRgb(float h, float s, float v, float[] rgb) {
h *= 360.0f;
if (s == 0.0) {
rgb[0] = rgb[1] = rgb[2] = v;
} else {
if (h == 360) {
h = 0;
} else {
h /= 60;
}
int i = (int) Math.floor(h);
float f = h - i;
float p = v * (1.0f - s);
float q = v * (1.0f - s * f);
float t = v * (1.0f - s * (1.0f - f));
switch (i) {
case 0:
rgb[0] = v;
rgb[1] = t;
rgb[2] = p;
break;
case 1:
rgb[0] = q;
rgb[1] = v;
rgb[2] = p;
break;
case 2:
rgb[0] = p;
rgb[1] = v;
rgb[2] = t;
break;
case 3:
rgb[0] = p;
rgb[1] = q;
rgb[2] = v;
break;
case 4:
rgb[0] = t;
rgb[1] = p;
rgb[2] = v;
break;
case 5:
rgb[0] = v;
rgb[1] = p;
rgb[2] = q;
break;
}
}
}
@Override
public boolean shouldBeLoaded(Structure structure, BlenderContext blenderContext) {
return (blenderContext.getBlenderKey().getFeaturesToLoad() & FeaturesToLoad.MATERIALS) != 0;
}
}
| |
/*
* Copyright (c) 2002-2011 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opengles;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.opengl.OpenGLException;
import java.nio.Buffer;
import static org.lwjgl.opengles.GLES20.*;
/**
* A class to check buffer boundaries in GL methods. Many GL
* methods read data from the GL into a native Buffer at its current position. If there is unsufficient space in the buffer when
* the call is made then a buffer overflow would otherwise occur and cause unexpected behaviour, a crash, or worse, a security
* risk. Therefore in those methods where GL reads data back into a buffer, we will call a bounds check method from this class
* to ensure that there is sufficient space in the buffer.
* <p/>
* Thrown by the debug build library of the LWJGL if any OpenGL operation causes an error.
*
* @author cix_foo <cix_foo@users.sourceforge.net>
* @version $Revision: 3459 $
* $Id: GLChecks.java 3459 2010-11-29 17:21:05Z spasi $
*/
class GLChecks {
/** Static methods only! */
private GLChecks() {
}
/** Helper method to ensure that array buffer objects are disabled. If they are enabled, we'll throw an OpenGLException */
static void ensureArrayVBOdisabled() {
if ( LWJGLUtil.CHECKS && StateTracker.getTracker().arrayBuffer != 0 )
throw new OpenGLException("Cannot use Buffers when Array Buffer Object is enabled");
}
/** Helper method to ensure that array buffer objects are enabled. If they are disabled, we'll throw an OpenGLException */
static void ensureArrayVBOenabled() {
if ( LWJGLUtil.CHECKS && StateTracker.getTracker().arrayBuffer == 0 )
throw new OpenGLException("Cannot use offsets when Array Buffer Object is disabled");
}
/** Helper method to ensure that element array buffer objects are disabled. If they are enabled, we'll throw an OpenGLException */
static void ensureElementVBOdisabled() {
if ( LWJGLUtil.CHECKS && StateTracker.getTracker().elementArrayBuffer != 0 )
throw new OpenGLException("Cannot use Buffers when Element Array Buffer Object is enabled");
}
/** Helper method to ensure that element array buffer objects are enabled. If they are disabled, we'll throw an OpenGLException */
static void ensureElementVBOenabled() {
if ( LWJGLUtil.CHECKS && StateTracker.getTracker().elementArrayBuffer == 0 )
throw new OpenGLException("Cannot use offsets when Element Array Buffer Object is disabled");
}
/** Helper method to ensure that pixel pack buffer objects are disabled. If they are enabled, we'll throw an OpenGLException */
static void ensurePackPBOdisabled() {
if ( LWJGLUtil.CHECKS && StateTracker.getTracker().pixelPackBuffer != 0 )
throw new OpenGLException("Cannot use Buffers when Pixel Pack Buffer Object is enabled");
}
/** Helper method to ensure that pixel pack buffer objects are enabled. If they are disabled, we'll throw an OpenGLException */
static void ensurePackPBOenabled() {
if ( LWJGLUtil.CHECKS && StateTracker.getTracker().pixelPackBuffer == 0 )
throw new OpenGLException("Cannot use offsets when Pixel Pack Buffer Object is disabled");
}
/** Helper method to ensure that pixel unpack buffer objects are disabled. If they are enabled, we'll throw an OpenGLException */
static void ensureUnpackPBOdisabled() {
if ( LWJGLUtil.CHECKS && StateTracker.getTracker().pixelUnpackBuffer != 0 )
throw new OpenGLException("Cannot use Buffers when Pixel Unpack Buffer Object is enabled");
}
/** Helper method to ensure that pixel unpack buffer objects are enabled. If they are disabled, we'll throw an OpenGLException */
static void ensureUnpackPBOenabled() {
if ( LWJGLUtil.CHECKS && StateTracker.getTracker().pixelUnpackBuffer == 0 )
throw new OpenGLException("Cannot use offsets when Pixel Unpack Buffer Object is disabled");
}
/**
* Calculate the storage required for an image in elements
*
* @param format The format of the image (example: GL_RGBA)
* @param type The type of the image elements (example: GL_UNSIGNED_BYTE)
* @param width The width of the image
* @param height The height of the image (1 for 1D images)
* @param depth The depth of the image (1 for 2D images)
*
* @return the size, in elements, of the image
*/
static int calculateImageStorage(Buffer buffer, int format, int type, int width, int height, int depth) {
return LWJGLUtil.CHECKS ? calculateImageStorage(format, type, width, height, depth) >> BufferUtils.getElementSizeExponent(buffer) : 0;
}
static int calculateTexImage1DStorage(Buffer buffer, int format, int type, int width) {
return LWJGLUtil.CHECKS ? calculateTexImage1DStorage(format, type, width) >> BufferUtils.getElementSizeExponent(buffer) : 0;
}
static int calculateTexImage2DStorage(Buffer buffer, int format, int type, int width, int height) {
return LWJGLUtil.CHECKS ? calculateTexImage2DStorage(format, type, width, height) >> BufferUtils.getElementSizeExponent(buffer) : 0;
}
static int calculateTexImage3DStorage(Buffer buffer, int format, int type, int width, int height, int depth) {
return LWJGLUtil.CHECKS ? calculateTexImage3DStorage(format, type, width, height, depth) >> BufferUtils.getElementSizeExponent(buffer) : 0;
}
/**
* Calculate the storage required for an image in bytes.
*
* @param format The format of the image (example: GL_RGBA)
* @param type The type of the image elements (example: GL_UNSIGNED_BYTE)
* @param width The width of the image
* @param height The height of the image (1 for 1D images)
* @param depth The depth of the image (1 for 2D images)
*
* @return the size, in bytes, of the image
*/
private static int calculateImageStorage(int format, int type, int width, int height, int depth) {
return calculateBytesPerPixel(format, type) * width * height * depth;
}
private static int calculateTexImage1DStorage(int format, int type, int width) {
return calculateBytesPerPixel(format, type) * width;
}
private static int calculateTexImage2DStorage(int format, int type, int width, int height) {
return calculateTexImage1DStorage(format, type, width) * height;
}
private static int calculateTexImage3DStorage(int format, int type, int width, int height, int depth) {
return calculateTexImage2DStorage(format, type, width, height) * depth;
}
private static int calculateBytesPerPixel(int format, int type) {
int bpe;
switch ( type ) {
case GL_UNSIGNED_BYTE:
case GL_BYTE:
bpe = 1;
break;
case GL_UNSIGNED_SHORT:
case GL_SHORT:
bpe = 2;
break;
case GL_UNSIGNED_INT:
case GL_INT:
case GL_FLOAT:
bpe = 4;
break;
default:
// TODO: Add more types (like the GL12 types GL_UNSIGNED_INT_8_8_8_8
return 0;
// throw new IllegalArgumentException("Unknown type " + type);
}
int epp;
switch ( format ) {
case GL_LUMINANCE:
case GL_ALPHA:
epp = 1;
break;
case GL_LUMINANCE_ALPHA:
epp = 2;
break;
case GL_RGB:
epp = 3;
break;
case GL_RGBA:
epp = 4;
break;
default:
// TODO: Add more formats. Assuming 4 is too wasteful on buffer sizes where e.g. 1 is enough (like GL_DEPTH_COMPONENT)
return 0;
}
return bpe * epp;
}
}
| |
package net.gcdc.ittgt.client;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import net.gcdc.ittgt.model.Vehicle;
import net.gcdc.ittgt.model.WorldModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lexicalscope.jewel.cli.ArgumentValidationException;
import com.lexicalscope.jewel.cli.CliFactory;
import com.lexicalscope.jewel.cli.Option;
public class GroTrClient {
private final static Logger logger = LoggerFactory.getLogger(GroTrClient.class);
private final VehicleConnection vehicleConnection;
private final ServerConnection serverConnection;
private final static ExecutorService executor = Executors.newCachedThreadPool();
public static interface VehicleConnection {
public Vehicle receive() throws IOException;
public void send(WorldModel worldModel) throws IOException;
}
public static interface ServerConnection {
public void send(Vehicle vehicle) throws IOException;
public WorldModel receive() throws IOException;
}
public static class TcpServerConnection implements ServerConnection, AutoCloseable {
private final Socket socket;
private final BufferedReader reader;
private final BufferedWriter writer;
private final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
.create(); // TODO: unify with other gsons!
//private final Gson gson = new GsonBuilder().create();
public TcpServerConnection(final InetSocketAddress grotrServerAddress) throws IOException {
socket = new Socket(grotrServerAddress.getAddress(), grotrServerAddress.getPort());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
logger.info("Connected to server on socket {}", socket);
}
@Override public void send(final Vehicle vehicle) {
String json = null;
try {
json = gson.toJson(vehicle);
} catch (Exception e) { //TODO: which exception toJson throws?
logger.warn("can't write json", e);
}
if (json != null) {
try {
writer.write(json);
writer.newLine();
writer.flush();
} catch (IOException e) {
logger.warn("can't send json", e);
}
}
}
@Override public WorldModel receive() throws IOException {
final String line = reader.readLine();
if (line == null) {
logger.error("End of stream from ITT server, returning null world model");
return null;
}
logger.debug("Got World line from ITT server: {}", line);
try {
final WorldModel world = gson.fromJson(line, WorldModel.class);
return world;
} catch (com.google.gson.JsonSyntaxException e) {
logger.warn("Can't parse json: {}", line, e);
throw e;
}
}
@Override public void close() throws IOException {
logger.debug("Closing tcp socket to server");
reader.close();
writer.close();
socket.close();
}
}
public static class UdpSimulinkConnection implements VehicleConnection, AutoCloseable {
private final DatagramSocket socketFromSimulink;
private final static int MAX_UDP = 65535 - 28 - 1460;
private final byte[] bufferFromSimulink = new byte[MAX_UDP];
private final DatagramPacket packetFromSimulink = new DatagramPacket(bufferFromSimulink,
bufferFromSimulink.length);
private final DatagramSocket socketToSimulink;
private final byte[] bufferToSimulink = new byte[MAX_UDP];
private final DatagramPacket packetToSimulink = new DatagramPacket(bufferToSimulink,
bufferToSimulink.length);
private final int localPortForSimulink;
public UdpSimulinkConnection(
final InetSocketAddress remoteSimulinkAddress,
final int localPortForSimulink) throws SocketException {
socketFromSimulink = new DatagramSocket(localPortForSimulink);
socketToSimulink = new DatagramSocket();
packetToSimulink.setSocketAddress(remoteSimulinkAddress);
this.localPortForSimulink = localPortForSimulink;
logger.info("Connected to simulink on {} (remote) {} (local), from simulink on {} (remote) {} (local)",
socketToSimulink.getRemoteSocketAddress(),
socketToSimulink.getLocalSocketAddress(),
socketFromSimulink.getRemoteSocketAddress(),
socketFromSimulink.getLocalSocketAddress()
);
}
@Override public Vehicle receive() throws IOException {
try {
socketFromSimulink.receive(packetFromSimulink);
} catch (SocketException e) {
logger.error("can't read from simulink", e);
throw e;
}
byte[] data = Arrays.copyOf(packetFromSimulink.getData(),
packetFromSimulink.getLength());
SimulinkGt simulinkGt = SimulinkParser.parse(data, SimulinkGt.class);
logger.debug("Got from simulink: {}", simulinkGt);
Vehicle vehicle = vehicleFromSimulinkGt(simulinkGt);
return vehicle;
}
@Override public void send(WorldModel worldModel) throws IOException {
if (worldModel == null) {
throw new NullPointerException("Can't send null world model to simulink");
}
logger.debug("trying to send world model {} to simulink", worldModel);
SimulinkWorld simulinkWorldFromWorld = simulinkWorldFromWorld(worldModel);
byte[] bytes = SimulinkParser.encode(simulinkWorldFromWorld);
System.arraycopy(bytes, 0, bufferToSimulink, 0, bytes.length);
packetToSimulink.setLength(bytes.length);
socketToSimulink.send(packetToSimulink);
logger.debug("world model of size {} was sent to Simulink on udp port {} ({})",
bytes.length, packetToSimulink.getPort(), packetToSimulink.getSocketAddress());
}
@Override public void close() {
logger.debug("Closing simulink sockets");
socketFromSimulink.close();
socketToSimulink.close();
}
private static Vehicle vehicleFromSimulinkGt(SimulinkGt simulinkGt) {
Vehicle vehicle = new Vehicle();
vehicle.id = (int) simulinkGt.vehicleId;
vehicle.lat = simulinkGt.x;
vehicle.lon = simulinkGt.y;
vehicle.height = 0; // Altitude?
vehicle.speedMetersPerSecond = simulinkGt.v;
vehicle.heading = simulinkGt.psi;
vehicle.orientation = vehicle.heading; // Is this correct?
vehicle.yawRate = simulinkGt.psidot;
vehicle.accelerationLon = simulinkGt.a;
vehicle.accelerationLat = 0; // How to compute this?
vehicle.vehicleLength = simulinkGt.vehicleLength;
vehicle.vehicleWidth = simulinkGt.vehicleWidth;
vehicle.distRefPointToRear = simulinkGt.rearAxleToRearBumper;
return vehicle;
}
private static SimulinkWorld simulinkWorldFromWorld(WorldModel world) {
if (world == null) {
throw new NullPointerException("Can't convert null World model.");
}
SimulinkGt[] simulinkVehicles = new SimulinkGt[world.vehicles.length];
Arrays.sort(world.vehicles, new Comparator<Vehicle>() {
@Override public int compare(Vehicle o1, Vehicle o2) {
return Integer.compare(o1.id, o2.id);
}});
for (int i = 0; i < world.vehicles.length; i++) {
simulinkVehicles[i] = simulinkGtFromVehicle(world.vehicles[i]);
}
SimulinkWorld simulinkWorld = new SimulinkWorld();
simulinkWorld.vehicles = simulinkVehicles;
return simulinkWorld;
}
private static SimulinkGt simulinkGtFromVehicle(Vehicle vehicle) {
SimulinkGt simulinkGt = new SimulinkGt();
simulinkGt.vehicleId = vehicle.id;
simulinkGt.x = vehicle.lat;
simulinkGt.y = vehicle.lon;
simulinkGt.v = vehicle.speedMetersPerSecond;
simulinkGt.psi = vehicle.heading;
simulinkGt.psidot = vehicle.yawRate;
simulinkGt.a = vehicle.accelerationLon;
simulinkGt.vehicleLength = vehicle.vehicleLength;
simulinkGt.vehicleWidth = vehicle.vehicleWidth;
simulinkGt.rearAxleToRearBumper = vehicle.distRefPointToRear;
return simulinkGt;
}
}
public static class SocketAddressFromString {
private final InetSocketAddress address;
public InetSocketAddress asInetSocketAddress() {
return address;
}
public SocketAddressFromString(final String addressStr) {
String[] hostAndPort = addressStr.split(":");
if (hostAndPort.length != 2) { throw new ArgumentValidationException(
"Expected host:port, got " + addressStr); }
this.address = new InetSocketAddress(hostAndPort[0], Integer.parseInt(hostAndPort[1]));
}
}
private static interface CliOptions {
@Option int getLocalPortForSimulink();
@Option SocketAddressFromString getRemoteSimulinkAddress();
@Option SocketAddressFromString getGrotrServerAddress();
@Option(helpRequest = true) boolean getHelp();
}
public static void main(final String[] args)
throws InterruptedException, ArgumentValidationException {
CliOptions opts = CliFactory.parseArguments(CliOptions.class, args);
try (UdpSimulinkConnection vehicleConnection = new UdpSimulinkConnection(
opts.getRemoteSimulinkAddress().asInetSocketAddress(),
opts.getLocalPortForSimulink());
TcpServerConnection serverConnection = new TcpServerConnection(
opts.getGrotrServerAddress().asInetSocketAddress());
) {
GroTrClient client = new GroTrClient(serverConnection, vehicleConnection);
client.start();
client.awaitTermination(365, TimeUnit.DAYS); // One year.
} catch (IOException e) {
logger.error("IO exception in client, terminating", e);
}
}
public GroTrClient(ServerConnection serverConnection, VehicleConnection vehicleConnection) {
this.vehicleConnection = vehicleConnection;
this.serverConnection = serverConnection;
}
public void start() {
executor.submit(this.senderThread);
executor.submit(this.receiverThread);
}
public void awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
executor.awaitTermination(timeout, unit);
}
private final Runnable senderThread = new Runnable() {
@Override public void run() {
try {
while (true) {
logger.debug("waiting for vehicle from Simulink client");
Vehicle vehicle = vehicleConnection.receive();
logger.info("got vehicle");
serverConnection.send(vehicle);
logger.debug("vehicle sent to ITT server");
}
} catch(Exception e) {
logger.error("Exception in ITT GT client sender thread", e);
}
}
};
private final Runnable receiverThread = new Runnable() {
@Override public void run() {
try {
while (true) {
try {
logger.debug("waiting for world from server");
WorldModel worldModel = serverConnection.receive();
if (worldModel == null) {
logger.error("received null world model, terminating");
return;
}
logger.info("got world");
vehicleConnection.send(worldModel);
logger.debug("World model sent to client");
} catch (IOException e) {
logger.warn("IO error in communicating world model, retrying", e);
Thread.sleep(1000);
}
}
} catch(Exception e) {
logger.error("Exception in ITT GT client receiver thread", e);
}
}
};
}
| |
// 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.xdebugger.impl.ui;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.EditorColorsUtil;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.*;
import com.intellij.openapi.util.DimensionService;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.ui.AppUIUtil;
import com.intellij.ui.EditorTextField;
import com.intellij.ui.ScreenUtil;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.popup.list.ListPopupImpl;
import com.intellij.util.Consumer;
import com.intellij.xdebugger.*;
import com.intellij.xdebugger.breakpoints.XBreakpoint;
import com.intellij.xdebugger.breakpoints.XBreakpointListener;
import com.intellij.xdebugger.breakpoints.XBreakpointManager;
import com.intellij.xdebugger.frame.XFullValueEvaluator;
import com.intellij.xdebugger.frame.XValue;
import com.intellij.xdebugger.frame.XValueModifier;
import com.intellij.xdebugger.impl.XDebugSessionImpl;
import com.intellij.xdebugger.impl.XDebuggerUtilImpl;
import com.intellij.xdebugger.impl.breakpoints.XBreakpointBase;
import com.intellij.xdebugger.impl.breakpoints.ui.BreakpointsDialogFactory;
import com.intellij.xdebugger.impl.breakpoints.ui.XLightBreakpointPropertiesPanel;
import com.intellij.xdebugger.impl.frame.XWatchesView;
import com.intellij.xdebugger.impl.ui.tree.XDebuggerTree;
import com.intellij.xdebugger.impl.ui.tree.XDebuggerTreeState;
import com.intellij.xdebugger.impl.ui.tree.nodes.XValueNodeImpl;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.concurrency.Promise;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.intellij.openapi.wm.IdeFocusManager.getGlobalInstance;
public class DebuggerUIUtil {
@NonNls public static final String FULL_VALUE_POPUP_DIMENSION_KEY = "XDebugger.FullValuePopup";
private DebuggerUIUtil() {
}
public static void enableEditorOnCheck(final JCheckBox checkbox, final JComponent textfield) {
checkbox.addActionListener(e -> {
boolean selected = checkbox.isSelected();
textfield.setEnabled(selected);
});
textfield.setEnabled(checkbox.isSelected());
}
public static void focusEditorOnCheck(final JCheckBox checkbox, final JComponent component) {
final Runnable runnable = () -> getGlobalInstance().doWhenFocusSettlesDown(() -> getGlobalInstance().requestFocus(component, true));
checkbox.addActionListener(e -> {
if (checkbox.isSelected()) {
SwingUtilities.invokeLater(runnable);
}
});
}
public static void invokeLater(Runnable runnable) {
ApplicationManager.getApplication().invokeLater(runnable);
}
@Deprecated
public static RelativePoint calcPopupLocation(@NotNull Editor editor, final int line) {
Point p = editor.logicalPositionToXY(new LogicalPosition(line + 1, 0));
final Rectangle visibleArea = editor.getScrollingModel().getVisibleArea();
if (!visibleArea.contains(p)) {
p = new Point((visibleArea.x + visibleArea.width) / 2, (visibleArea.y + visibleArea.height) / 2);
}
return new RelativePoint(editor.getContentComponent(), p);
}
@Nullable
public static RelativePoint getPositionForPopup(@NotNull Editor editor, int line) {
if (line > -1) {
Point p = editor.logicalPositionToXY(new LogicalPosition(line + 1, 0));
if (editor.getScrollingModel().getVisibleArea().contains(p)) {
return new RelativePoint(editor.getContentComponent(), p);
}
}
return null;
}
public static void showPopupForEditorLine(@NotNull JBPopup popup, @NotNull Editor editor, int line) {
RelativePoint point = getPositionForPopup(editor, line);
if (point != null) {
popup.show(point);
}
else {
Project project = editor.getProject();
if (project != null) {
popup.showCenteredInCurrentWindow(project);
}
else {
popup.showInFocusCenter();
}
}
}
public static void showValuePopup(@NotNull XFullValueEvaluator evaluator, @NotNull MouseEvent event, @NotNull Project project, @Nullable Editor editor) {
EditorTextField textArea = new TextViewer(XDebuggerUIConstants.EVALUATING_EXPRESSION_MESSAGE, project);
textArea.setBackground(HintUtil.getInformationColor());
final FullValueEvaluationCallbackImpl callback = new FullValueEvaluationCallbackImpl(textArea);
evaluator.startEvaluation(callback);
Dimension size = DimensionService.getInstance().getSize(FULL_VALUE_POPUP_DIMENSION_KEY, project);
if (size == null) {
Dimension frameSize = WindowManager.getInstance().getFrame(project).getSize();
size = new Dimension(frameSize.width / 2, frameSize.height / 2);
}
textArea.setPreferredSize(size);
JBPopup popup = createValuePopup(project, textArea, callback);
if (editor == null) {
Rectangle bounds = new Rectangle(event.getLocationOnScreen(), size);
ScreenUtil.fitToScreenVertical(bounds, 5, 5, true);
if (size.width != bounds.width || size.height != bounds.height) {
size = bounds.getSize();
textArea.setPreferredSize(size);
}
popup.showInScreenCoordinates(event.getComponent(), bounds.getLocation());
}
else {
popup.showInBestPositionFor(editor);
}
}
public static JBPopup createValuePopup(Project project,
JComponent component,
@Nullable final FullValueEvaluationCallbackImpl callback) {
ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(component, null);
builder.setResizable(true)
.setMovable(true)
.setDimensionServiceKey(project, FULL_VALUE_POPUP_DIMENSION_KEY, false)
.setRequestFocus(true);
if (callback != null) {
builder.setCancelCallback(() -> {
callback.setObsolete();
return true;
});
}
return builder.createPopup();
}
public static void showXBreakpointEditorBalloon(final Project project,
@Nullable final Point point,
final JComponent component,
final boolean showAllOptions,
final XBreakpoint breakpoint) {
final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
final XLightBreakpointPropertiesPanel propertiesPanel =
new XLightBreakpointPropertiesPanel(project, breakpointManager, (XBreakpointBase)breakpoint,
showAllOptions);
final Ref<Balloon> balloonRef = Ref.create(null);
final Ref<Boolean> isLoading = Ref.create(Boolean.FALSE);
final Ref<Boolean> moreOptionsRequested = Ref.create(Boolean.FALSE);
propertiesPanel.setDelegate(() -> {
if (!isLoading.get()) {
propertiesPanel.saveProperties();
}
if (!balloonRef.isNull()) {
balloonRef.get().hide();
}
propertiesPanel.dispose();
showXBreakpointEditorBalloon(project, point, component, true, breakpoint);
moreOptionsRequested.set(true);
});
isLoading.set(Boolean.TRUE);
propertiesPanel.loadProperties();
isLoading.set(Boolean.FALSE);
if (moreOptionsRequested.get()) {
return;
}
Runnable showMoreOptions = () -> {
propertiesPanel.saveProperties();
propertiesPanel.dispose();
BreakpointsDialogFactory.getInstance(project).showDialog(breakpoint);
};
final JComponent mainPanel = propertiesPanel.getMainPanel();
final Balloon balloon = showBreakpointEditor(project, mainPanel, point, component, showMoreOptions, breakpoint);
balloonRef.set(balloon);
Disposable disposable = Disposer.newDisposable();
balloon.addListener(new JBPopupListener() {
@Override
public void onClosed(@NotNull LightweightWindowEvent event) {
Disposer.dispose(disposable);
propertiesPanel.saveProperties();
propertiesPanel.dispose();
}
});
project.getMessageBus().connect(disposable).subscribe(XBreakpointListener.TOPIC, new XBreakpointListener<XBreakpoint<?>>() {
@Override
public void breakpointRemoved(@NotNull XBreakpoint<?> removedBreakpoint) {
if (removedBreakpoint.equals(breakpoint)) {
balloon.hide();
}
}
});
ApplicationManager.getApplication().invokeLater(() -> IdeFocusManager.findInstance().requestFocus(mainPanel, true));
}
public static Balloon showBreakpointEditor(Project project, final JComponent mainPanel,
final Point whereToShow,
final JComponent component,
@Nullable final Runnable showMoreOptions, Object breakpoint) {
final BreakpointEditor editor = new BreakpointEditor();
editor.setPropertiesPanel(mainPanel);
editor.setShowMoreOptionsLink(true);
final JPanel panel = editor.getMainPanel();
BalloonBuilder builder = JBPopupFactory.getInstance()
.createDialogBalloonBuilder(panel, null)
.setHideOnClickOutside(true)
.setCloseButtonEnabled(false)
.setAnimationCycle(0)
.setBlockClicksThroughBalloon(true);
Color borderColor = UIManager.getColor("DebuggerPopup.borderColor");
if (borderColor != null ) {
builder.setBorderColor(borderColor);
}
Balloon balloon = builder.createBalloon();
editor.setDelegate(new BreakpointEditor.Delegate() {
@Override
public void done() {
balloon.hide();
}
@Override
public void more() {
assert showMoreOptions != null;
balloon.hide();
showMoreOptions.run();
}
});
ComponentAdapter moveListener = new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent e) {
balloon.hide();
}
};
component.addComponentListener(moveListener);
Disposer.register(balloon, () -> component.removeComponentListener(moveListener));
HierarchyBoundsListener hierarchyBoundsListener = new HierarchyBoundsAdapter() {
@Override
public void ancestorMoved(HierarchyEvent e) {
balloon.hide();
}
};
component.addHierarchyBoundsListener(hierarchyBoundsListener);
Disposer.register(balloon, () -> component.removeHierarchyBoundsListener(hierarchyBoundsListener));
if (whereToShow == null) {
balloon.showInCenterOf(component);
}
else {
//todo[kb] modify and move to BalloonImpl?
final Window window = SwingUtilities.windowForComponent(component);
final RelativePoint p = new RelativePoint(component, whereToShow);
if (window != null) {
final RelativePoint point = new RelativePoint(window, new Point(0, 0));
if (p.getScreenPoint().getX() - point.getScreenPoint().getX() < 40) { // triangle + offsets is ~40px
p.getPoint().x += 40;
}
}
balloon.show(p, Balloon.Position.below);
}
BreakpointsDialogFactory.getInstance(project).setBalloonToHide(balloon, breakpoint);
return balloon;
}
@NotNull
public static EditorColorsScheme getColorScheme() {
return EditorColorsUtil.getGlobalOrDefaultColorScheme();
}
@NotNull
public static EditorColorsScheme getColorScheme(@Nullable JComponent component) {
return EditorColorsUtil.getColorSchemeForComponent(component);
}
private static class FullValueEvaluationCallbackImpl implements XFullValueEvaluator.XFullValueEvaluationCallback {
private final AtomicBoolean myObsolete = new AtomicBoolean(false);
private final EditorTextField myTextArea;
FullValueEvaluationCallbackImpl(final EditorTextField textArea) {
myTextArea = textArea;
}
@Override
public void evaluated(@NotNull final String fullValue) {
evaluated(fullValue, null);
}
@Override
public void evaluated(@NotNull final String fullValue, @Nullable final Font font) {
AppUIUtil.invokeOnEdt(() -> {
myTextArea.setText(fullValue);
if (font != null) {
myTextArea.setFont(font);
}
});
}
@Override
public void errorOccurred(@NotNull final String errorMessage) {
AppUIUtil.invokeOnEdt(() -> {
myTextArea.setForeground(XDebuggerUIConstants.ERROR_MESSAGE_ATTRIBUTES.getFgColor());
myTextArea.setText(errorMessage);
});
}
private void setObsolete() {
myObsolete.set(true);
}
@Override
public boolean isObsolete() {
return myObsolete.get();
}
}
@Nullable
public static String getNodeRawValue(@NotNull XValueNodeImpl valueNode) {
if (valueNode.getValueContainer() instanceof XValueTextProvider) {
return ((XValueTextProvider)valueNode.getValueContainer()).getValueText();
}
else {
return valueNode.getRawValue();
}
}
/**
* Checks if value has evaluation expression ready, or calculation is pending
*/
public static boolean hasEvaluationExpression(@NotNull XValue value) {
Promise<XExpression> promise = value.calculateEvaluationExpression();
try {
return promise.getState() == Promise.State.PENDING || promise.blockingGet(0) != null;
}
catch (ExecutionException | TimeoutException e) {
return true;
}
}
public static void addToWatches(@NotNull XWatchesView watchesView, @NotNull XValueNodeImpl node) {
node.getValueContainer().calculateEvaluationExpression().onSuccess(expression -> {
if (expression != null) {
invokeLater(() -> watchesView.addWatchExpression(expression, -1, false));
}
});
}
public static void registerActionOnComponent(String name, JComponent component, Disposable parentDisposable) {
AnAction action = ActionManager.getInstance().getAction(name);
action.registerCustomShortcutSet(action.getShortcutSet(), component, parentDisposable);
}
public static void registerExtraHandleShortcuts(final ListPopupImpl popup, String... actionNames) {
for (String name : actionNames) {
KeyStroke stroke = KeymapUtil.getKeyStroke(ActionManager.getInstance().getAction(name).getShortcutSet());
if (stroke != null) {
popup.registerAction("handleSelection " + stroke, stroke, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
popup.handleSelect(true);
}
});
}
}
}
@NotNull
public static String getSelectionShortcutsAdText(String... actionNames) {
return getShortcutsAdText("ad.extra.selection.shortcut", actionNames);
}
@NotNull
public static String getShortcutsAdText(String key, String... actionNames) {
String text = StreamEx.of(actionNames).map(DebuggerUIUtil::getActionShortcutText).nonNull()
.joining(XDebuggerBundle.message("xdebugger.shortcuts.text.delimiter"));
return StringUtil.isEmpty(text) ? "" : XDebuggerBundle.message(key, text);
}
@Nullable
public static String getActionShortcutText(String actionName) {
KeyStroke stroke = KeymapUtil.getKeyStroke(ActionManager.getInstance().getAction(actionName).getShortcutSet());
if (stroke != null) {
return KeymapUtil.getKeystrokeText(stroke);
}
return null;
}
public static boolean isObsolete(Object object) {
return object instanceof Obsolescent && ((Obsolescent)object).isObsolete();
}
public static void setTreeNodeValue(XValueNodeImpl valueNode, XExpression text, Consumer<? super String> errorConsumer) {
XDebuggerTree tree = valueNode.getTree();
Project project = tree.getProject();
XValueModifier modifier = valueNode.getValueContainer().getModifier();
if (modifier == null) return;
XDebuggerTreeState treeState = XDebuggerTreeState.saveState(tree);
valueNode.setValueModificationStarted();
modifier.setValue(text, new XValueModifier.XModificationCallback() {
@Override
public void valueModified() {
if (tree.isDetached()) {
AppUIUtil.invokeOnEdt(() -> tree.rebuildAndRestore(treeState));
}
XDebuggerUtilImpl.rebuildAllSessionsViews(project);
}
@Override
public void errorOccurred(@NotNull final String errorMessage) {
AppUIUtil.invokeOnEdt(() -> {
tree.rebuildAndRestore(treeState);
errorConsumer.consume(errorMessage);
});
XDebuggerUtilImpl.rebuildAllSessionsViews(project);
}
});
}
public static boolean isInDetachedTree(AnActionEvent event) {
return event.getData(XDebugSessionTab.TAB_KEY) == null;
}
public static XDebugSessionData getSessionData(AnActionEvent e) {
XDebugSessionData data = e.getData(XDebugSessionData.DATA_KEY);
if (data == null) {
Project project = e.getProject();
if (project != null) {
XDebugSession session = XDebuggerManager.getInstance(project).getCurrentSession();
if (session != null) {
data = ((XDebugSessionImpl)session).getSessionData();
}
}
}
return data;
}
public static void repaintCurrentEditor(Project project) {
Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
if (editor != null) {
editor.getContentComponent().revalidate();
editor.getContentComponent().repaint();
}
}
}
| |
/*
* Copyright 2015 Kaazing Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.real_logic.aeron.tools;
import org.apache.commons.cli.ParseException;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class ThwackerOptionsTest
{
private ThwackerOptions opts;
@Before
public void setUp()
{
opts = new ThwackerOptions();
}
@Test
public void verifyShort() throws Exception
{
final String[] args = {"-v", "yes"};
opts.parseArgs(args);
assertThat(opts.verifiable(), is(true));
}
@Test
public void verifyOn() throws Exception
{
final String[] args = {"--verify", "Yes"};
opts.parseArgs(args);
assertThat(opts.verifiable(), is(true));
}
@Test
public void verifyOff() throws Exception
{
final String[] args = {"--verify", "No"};
opts.parseArgs(args);
assertThat(opts.verifiable(), is(false));
}
@Test
public void verifyDefault() throws Exception
{
final String[] args = {};
opts.parseArgs(args);
assertThat("FAIL: Default for --verify should be false", opts.verifiable(), is(false));
}
@Test(expected = ParseException.class)
public void verifyException() throws Exception
{
final String[] args = {"--verify", "schmerify"};
opts.parseArgs(args);
}
@Test
public void sameSIDOn() throws Exception
{
final String[] args = {"--same-sid", "Yes"};
opts.parseArgs(args);
assertThat(opts.sameSID(), is(true));
}
@Test
public void sameSIDOff() throws Exception
{
final String[] args = {"--same-sid", "No"};
opts.parseArgs(args);
assertThat(opts.sameSID(), is(false));
}
@Test
public void sameSIDDefault() throws Exception
{
final String[] args = {};
opts.parseArgs(args);
assertThat("FAIL: Default for --same-sid should be false", opts.sameSID(), is(false));
}
@Test(expected = ParseException.class)
public void sameSIDException() throws Exception
{
final String[] args = {"--same-sid", "wrongstring"};
opts.parseArgs(args);
}
@Test
public void channelPerPubOn() throws Exception
{
final String[] args = {"--channel-per-pub", "Yes"};
opts.parseArgs(args);
assertThat(opts.channelPerPub(), is(true));
}
@Test
public void channelPerPubOff() throws Exception
{
final String[] args = {"--channel-per-pub", "No"};
opts.parseArgs(args);
assertThat(opts.channelPerPub(), is(false));
}
@Test
public void channelPerPubDefault() throws Exception
{
final String[] args = {};
opts.parseArgs(args);
assertThat("FAIL: Default for --channel-per-pub should be false", opts.channelPerPub(), is(false));
}
@Test(expected = ParseException.class)
public void channelPerPubException() throws Exception
{
final String[] args = {"--channel-per-pub", "chanperpub"};
opts.parseArgs(args);
}
@Test
public void channelDefault() throws Exception
{
final String[] args = {};
opts.parseArgs(args);
assertThat("FAIL: Default for --channel should be udp://localhost", opts.channel(), is("udp://localhost"));
}
@Test
public void channel() throws Exception
{
final String[] args = {"--channel", "blahblahblah"};
opts.parseArgs(args);
assertThat(opts.channel(), is("blahblahblah"));
}
@Test
public void channelShort() throws Exception
{
final String[] args = {"-c", "blahblahblah"};
opts.parseArgs(args);
assertThat(opts.channel(), is("blahblahblah"));
}
@Test
public void portPass() throws Exception
{
final String[] args = {"--port", "12345"};
opts.parseArgs(args);
assertThat(opts.port(), is(12345));
}
@Test
public void portShortPass() throws Exception
{
final String[] args = {"-p", "12345"};
opts.parseArgs(args);
assertThat(opts.port(), is(12345));
}
@Test(expected = ParseException.class)
public void portFail() throws Exception
{
final String[] args = {"--port", "-12345"};
opts.parseArgs(args);
}
@Test
public void portDefault() throws Exception
{
final String[] args = {};
opts.parseArgs(args);
assertThat("FAIL: Default for --port should be " + 51234, opts.port(), is(51234));
}
@Test
public void durationPass() throws Exception
{
final String[] args = {"--duration", "77969403"};
opts.parseArgs(args);
assertThat(opts.duration(), is(77969403));
}
@Test
public void durationShortPass() throws Exception
{
final String[] args = {"-d", "77969403"};
opts.parseArgs(args);
assertThat(opts.duration(), is(77969403));
}
@Test(expected = ParseException.class)
public void durationFail() throws Exception
{
final String[] args = {"--duration", "-2345145"};
opts.parseArgs(args);
}
@Test
public void durationDefault() throws Exception
{
final String[] args = {};
opts.parseArgs(args);
assertThat("FAIL: Default for --duration should be '30000'", opts.duration(), is(30000));
}
@Test
public void iterationsPass() throws Exception
{
final String[] args = {"--iterations", "7703"};
opts.parseArgs(args);
assertThat(opts.iterations(), is(7703));
}
@Test
public void iterationsShortPass() throws Exception
{
final String[] args = {"-i", "7703"};
opts.parseArgs(args);
assertThat(opts.iterations(), is(7703));
}
@Test(expected = ParseException.class)
public void iterationsFail() throws Exception
{
final String[] args = {"--iterations", "-235725"};
opts.parseArgs(args);
}
@Test
public void iterationsDefault() throws Exception
{
final String[] args = {};
opts.parseArgs(args);
assertThat("FAIL: Default for --iterations should be 1", opts.iterations(), is(1));
}
@Test
public void sendersPass() throws Exception
{
final String[] args = {"--senders", "7703"};
opts.parseArgs(args);
assertThat(opts.senders(), is(7703));
}
@Test
public void sendersShortPass() throws Exception
{
final String[] args = {"-s", "7703"};
opts.parseArgs(args);
assertThat(opts.senders(), is(7703));
}
@Test(expected = ParseException.class)
public void sendersFail() throws Exception
{
final String[] args = {"--senders", "-235725"};
opts.parseArgs(args);
}
@Test
public void sendersDefault() throws Exception
{
final String[] args = {};
opts.parseArgs(args);
assertThat("FAIL: Default for --iterations should be 1", opts.senders(), is(1));
}
@Test
public void receiversPass() throws Exception
{
final String[] args = {"--receivers", "7703"};
opts.parseArgs(args);
assertThat(opts.receivers(), is(7703));
}
@Test
public void receiversShortPass() throws Exception
{
final String[] args = {"-r", "7703"};
opts.parseArgs(args);
assertThat(opts.receivers(), is(7703));
}
@Test(expected = ParseException.class)
public void receiversFail() throws Exception
{
final String[] args = {"--receivers", "-235725"};
opts.parseArgs(args);
}
@Test
public void receiversDefault() throws Exception
{
final String[] args = {};
opts.parseArgs(args);
assertThat("FAIL: Default for --iterations should be 1", opts.receivers(), is(1));
}
@Test
public void addersPass() throws Exception
{
final String[] args = {"--adders", "7703"};
opts.parseArgs(args);
assertThat(opts.adders(), is(7703));
}
@Test(expected = ParseException.class)
public void addersFail() throws Exception
{
final String[] args = {"--adders", "-235725"};
opts.parseArgs(args);
}
@Test
public void addersDefault() throws Exception
{
final String[] args = {};
opts.parseArgs(args);
assertThat("FAIL: Default for --adders should be 1", opts.adders(), is(1));
}
@Test
public void removersPass() throws Exception
{
final String[] args = {"--removers", "7703"};
opts.parseArgs(args);
assertThat(opts.removers(), is(7703));
}
@Test(expected = ParseException.class)
public void removersFail() throws Exception
{
final String[] args = {"--removers", "-235725"};
opts.parseArgs(args);
}
@Test
public void removersDefault() throws Exception
{
final String[] args = {};
opts.parseArgs(args);
assertThat("FAIL: Default for --removers should be 1", opts.removers(), is(1));
}
@Test
public void elementsPass() throws Exception
{
final String[] args = {"--elements", "7703"};
opts.parseArgs(args);
assertThat(opts.elements(), is(7703));
}
@Test
public void elementsShortPass() throws Exception
{
final String[] args = {"-e", "7703"};
opts.parseArgs(args);
assertThat(opts.elements(), is(7703));
}
@Test(expected = ParseException.class)
public void elementsFail() throws Exception
{
final String[] args = {"--elements", "-235725"};
opts.parseArgs(args);
}
@Test
public void elementsDefault() throws Exception
{
final String[] args = {};
opts.parseArgs(args);
assertThat("FAIL: Default for --elements should be 10", opts.elements(), is(10));
}
@Test
public void maxSizePass() throws Exception
{
final String[] args = {"--max-size", "7703"};
opts.parseArgs(args);
assertThat(opts.maxMsgSize(), is(7703));
}
@Test(expected = ParseException.class)
public void maxSizeFail() throws Exception
{
final String[] args = {"--max-size", "-235725"};
opts.parseArgs(args);
}
@Test
public void maxSizeDefault() throws Exception
{
final String[] args = {};
opts.parseArgs(args);
assertThat("FAIL: Default for --max-size should be 35", opts.maxMsgSize(), is(35));
}
@Test
public void minSizePass() throws Exception
{
final String[] args = {"--min-size", "7703"};
opts.parseArgs(args);
assertThat(opts.minMsgSize(), is(7703));
}
@Test(expected = ParseException.class)
public void minSizeFail() throws Exception
{
final String[] args = {"--min-size", "-235725"};
opts.parseArgs(args);
}
@Test
public void minSizeDefault() throws Exception
{
final String[] args = {};
opts.parseArgs(args);
assertThat("FAIL: Default for --min-size should be 35", opts.minMsgSize(), is(35));
}
@Test
public void help() throws Exception
{
final String[] args = {"--help"};
assertThat(opts.parseArgs(args), is(1));
}
@Test
public void helpShorthand() throws Exception
{
final String[] args = {"-h"};
assertThat(opts.parseArgs(args), is(1));
}
}
| |
/**
* 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.language.simple;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.ExchangeTestSupport;
import org.apache.camel.Expression;
public class SimpleParserExpressionTest extends ExchangeTestSupport {
public void testSimpleParserEol() throws Exception {
SimpleExpressionParser parser = new SimpleExpressionParser("Hello", true);
Expression exp = parser.parseExpression();
assertEquals("Hello", exp.evaluate(exchange, String.class));
}
public void testSimpleSingleQuote() throws Exception {
SimpleExpressionParser parser = new SimpleExpressionParser("'Hello'", true);
Expression exp = parser.parseExpression();
assertEquals("'Hello'", exp.evaluate(exchange, String.class));
}
public void testSimpleStringList() throws Exception {
SimpleExpressionParser parser = new SimpleExpressionParser("\"Hello\" \"World\"", true);
Expression exp = parser.parseExpression();
assertEquals("\"Hello\" \"World\"", exp.evaluate(exchange, String.class));
}
public void testSimpleSingleQuoteWithFunction() throws Exception {
exchange.getIn().setBody("World");
SimpleExpressionParser parser = new SimpleExpressionParser("'Hello ${body} how are you?'", true);
Expression exp = parser.parseExpression();
assertEquals("'Hello World how are you?'", exp.evaluate(exchange, String.class));
}
public void testSimpleSingleQuoteWithFunctionBodyAs() throws Exception {
exchange.getIn().setBody("World");
SimpleExpressionParser parser = new SimpleExpressionParser("'Hello ${bodyAs(String)} how are you?'", true);
Expression exp = parser.parseExpression();
assertEquals("'Hello World how are you?'", exp.evaluate(exchange, String.class));
}
public void testSimpleSingleQuoteEol() throws Exception {
SimpleExpressionParser parser = new SimpleExpressionParser("'Hello' World", true);
Expression exp = parser.parseExpression();
assertEquals("'Hello' World", exp.evaluate(exchange, String.class));
}
public void testSimpleFunction() throws Exception {
exchange.getIn().setBody("World");
SimpleExpressionParser parser = new SimpleExpressionParser("${body}", true);
Expression exp = parser.parseExpression();
assertEquals("World", exp.evaluate(exchange, String.class));
}
public void testSimpleSingleQuoteDollar() throws Exception {
SimpleExpressionParser parser = new SimpleExpressionParser("Pay 200$ today", true);
Expression exp = parser.parseExpression();
assertEquals("Pay 200$ today", exp.evaluate(exchange, String.class));
}
public void testSimpleSingleQuoteDollarEnd() throws Exception {
SimpleExpressionParser parser = new SimpleExpressionParser("Pay 200$", true);
Expression exp = parser.parseExpression();
assertEquals("Pay 200$", exp.evaluate(exchange, String.class));
}
public void testSimpleUnaryInc() throws Exception {
exchange.getIn().setBody("122");
SimpleExpressionParser parser = new SimpleExpressionParser("${body}++", true);
Expression exp = parser.parseExpression();
assertEquals("123", exp.evaluate(exchange, String.class));
}
public void testSimpleUnaryDec() throws Exception {
exchange.getIn().setBody("122");
SimpleExpressionParser parser = new SimpleExpressionParser("${body}--", true);
Expression exp = parser.parseExpression();
assertEquals("121", exp.evaluate(exchange, String.class));
}
public void testSimpleUnaryIncInt() throws Exception {
exchange.getIn().setBody(122);
SimpleExpressionParser parser = new SimpleExpressionParser("${body}++", true);
Expression exp = parser.parseExpression();
assertEquals(Integer.valueOf(123), exp.evaluate(exchange, Integer.class));
}
public void testSimpleUnaryDecInt() throws Exception {
exchange.getIn().setBody(122);
SimpleExpressionParser parser = new SimpleExpressionParser("${body}--", true);
Expression exp = parser.parseExpression();
assertEquals(Integer.valueOf(121), exp.evaluate(exchange, Integer.class));
}
public void testHeaderNestedFunction() throws Exception {
exchange.getIn().setBody("foo");
exchange.getIn().setHeader("foo", "abc");
SimpleExpressionParser parser = new SimpleExpressionParser("${header.${body}}", true);
Expression exp = parser.parseExpression();
Object obj = exp.evaluate(exchange, Object.class);
assertNotNull(obj);
assertEquals("abc", obj);
}
public void testBodyAsNestedFunction() throws Exception {
exchange.getIn().setBody("123");
exchange.getIn().setHeader("foo", "Integer");
SimpleExpressionParser parser = new SimpleExpressionParser("${bodyAs(${header.foo})}", true);
Expression exp = parser.parseExpression();
Object obj = exp.evaluate(exchange, Object.class);
assertNotNull(obj);
Integer num = assertIsInstanceOf(Integer.class, obj);
assertEquals(123, num.intValue());
}
public void testThreeNestedFunctions() throws Exception {
exchange.getIn().setBody("123");
exchange.getIn().setHeader("foo", "Int");
exchange.getIn().setHeader("bar", "e");
exchange.getIn().setHeader("baz", "ger");
SimpleExpressionParser parser = new SimpleExpressionParser("${bodyAs(${header.foo}${header.bar}${header.baz})}", true);
Expression exp = parser.parseExpression();
Object obj = exp.evaluate(exchange, Object.class);
assertNotNull(obj);
Integer num = assertIsInstanceOf(Integer.class, obj);
assertEquals(123, num.intValue());
}
public void testNestedNestedFunctions() throws Exception {
exchange.getIn().setBody("123");
exchange.getIn().setHeader("foo", "Integer");
exchange.getIn().setHeader("bar", "foo");
SimpleExpressionParser parser = new SimpleExpressionParser("${bodyAs(${header.${header.bar}})}", true);
Expression exp = parser.parseExpression();
Object obj = exp.evaluate(exchange, Object.class);
assertNotNull(obj);
Integer num = assertIsInstanceOf(Integer.class, obj);
assertEquals(123, num.intValue());
}
public void testSimpleMap() throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "123");
map.put("foo bar", "456");
exchange.getIn().setBody(map);
SimpleExpressionParser parser = new SimpleExpressionParser("${body[foo]}", true);
Expression exp = parser.parseExpression();
assertEquals("123", exp.evaluate(exchange, Object.class));
parser = new SimpleExpressionParser("${body['foo bar']}", true);
exp = parser.parseExpression();
assertEquals("456", exp.evaluate(exchange, Object.class));
}
public void testUnaryLenient() throws Exception {
exchange.getIn().setHeader("JMSMessageID", "JMSMessageID-123");
exchange.getIn().setBody("THE MSG ID ${header.JMSMessageID} isA --");
SimpleExpressionParser parser = new SimpleExpressionParser("THE MSG ID ${header.JMSMessageID} isA --", true);
Expression exp = parser.parseExpression();
assertEquals("THE MSG ID JMSMessageID-123 isA --", exp.evaluate(exchange, String.class));
}
public void testUnaryLenient2() throws Exception {
exchange.getIn().setHeader("JMSMessageID", "JMSMessageID-123");
exchange.getIn().setBody("------------THE MSG ID ${header.JMSMessageID}------------");
SimpleExpressionParser parser = new SimpleExpressionParser("------------THE MSG ID ${header.JMSMessageID}------------", true);
Expression exp = parser.parseExpression();
assertEquals("------------THE MSG ID JMSMessageID-123------------", exp.evaluate(exchange, String.class));
}
public void testUnaryLenient3() throws Exception {
exchange.getIn().setHeader("JMSMessageID", "JMSMessageID-123");
exchange.getIn().setBody("------------ THE MSG ID ${header.JMSMessageID} ------------");
SimpleExpressionParser parser = new SimpleExpressionParser("------------ THE MSG ID ${header.JMSMessageID} ------------", true);
Expression exp = parser.parseExpression();
assertEquals("------------ THE MSG ID JMSMessageID-123 ------------", exp.evaluate(exchange, String.class));
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v8/common/ad_type_infos.proto
package com.google.ads.googleads.v8.common;
public interface ResponsiveDisplayAdInfoOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.ads.googleads.v8.common.ResponsiveDisplayAdInfo)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* Marketing images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 600x314 and the aspect ratio must
* be 1.91:1 (+-1%). At least one `marketing_image` is required. Combined
* with `square_marketing_images`, the maximum is 15.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset marketing_images = 1;</code>
*/
java.util.List<com.google.ads.googleads.v8.common.AdImageAsset>
getMarketingImagesList();
/**
* <pre>
* Marketing images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 600x314 and the aspect ratio must
* be 1.91:1 (+-1%). At least one `marketing_image` is required. Combined
* with `square_marketing_images`, the maximum is 15.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset marketing_images = 1;</code>
*/
com.google.ads.googleads.v8.common.AdImageAsset getMarketingImages(int index);
/**
* <pre>
* Marketing images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 600x314 and the aspect ratio must
* be 1.91:1 (+-1%). At least one `marketing_image` is required. Combined
* with `square_marketing_images`, the maximum is 15.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset marketing_images = 1;</code>
*/
int getMarketingImagesCount();
/**
* <pre>
* Marketing images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 600x314 and the aspect ratio must
* be 1.91:1 (+-1%). At least one `marketing_image` is required. Combined
* with `square_marketing_images`, the maximum is 15.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset marketing_images = 1;</code>
*/
java.util.List<? extends com.google.ads.googleads.v8.common.AdImageAssetOrBuilder>
getMarketingImagesOrBuilderList();
/**
* <pre>
* Marketing images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 600x314 and the aspect ratio must
* be 1.91:1 (+-1%). At least one `marketing_image` is required. Combined
* with `square_marketing_images`, the maximum is 15.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset marketing_images = 1;</code>
*/
com.google.ads.googleads.v8.common.AdImageAssetOrBuilder getMarketingImagesOrBuilder(
int index);
/**
* <pre>
* Square marketing images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 300x300 and the aspect ratio must
* be 1:1 (+-1%). At least one square `marketing_image` is required. Combined
* with `marketing_images`, the maximum is 15.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset square_marketing_images = 2;</code>
*/
java.util.List<com.google.ads.googleads.v8.common.AdImageAsset>
getSquareMarketingImagesList();
/**
* <pre>
* Square marketing images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 300x300 and the aspect ratio must
* be 1:1 (+-1%). At least one square `marketing_image` is required. Combined
* with `marketing_images`, the maximum is 15.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset square_marketing_images = 2;</code>
*/
com.google.ads.googleads.v8.common.AdImageAsset getSquareMarketingImages(int index);
/**
* <pre>
* Square marketing images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 300x300 and the aspect ratio must
* be 1:1 (+-1%). At least one square `marketing_image` is required. Combined
* with `marketing_images`, the maximum is 15.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset square_marketing_images = 2;</code>
*/
int getSquareMarketingImagesCount();
/**
* <pre>
* Square marketing images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 300x300 and the aspect ratio must
* be 1:1 (+-1%). At least one square `marketing_image` is required. Combined
* with `marketing_images`, the maximum is 15.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset square_marketing_images = 2;</code>
*/
java.util.List<? extends com.google.ads.googleads.v8.common.AdImageAssetOrBuilder>
getSquareMarketingImagesOrBuilderList();
/**
* <pre>
* Square marketing images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 300x300 and the aspect ratio must
* be 1:1 (+-1%). At least one square `marketing_image` is required. Combined
* with `marketing_images`, the maximum is 15.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset square_marketing_images = 2;</code>
*/
com.google.ads.googleads.v8.common.AdImageAssetOrBuilder getSquareMarketingImagesOrBuilder(
int index);
/**
* <pre>
* Logo images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 512x128 and the aspect ratio must
* be 4:1 (+-1%). Combined with `square_logo_images`, the maximum is 5.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset logo_images = 3;</code>
*/
java.util.List<com.google.ads.googleads.v8.common.AdImageAsset>
getLogoImagesList();
/**
* <pre>
* Logo images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 512x128 and the aspect ratio must
* be 4:1 (+-1%). Combined with `square_logo_images`, the maximum is 5.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset logo_images = 3;</code>
*/
com.google.ads.googleads.v8.common.AdImageAsset getLogoImages(int index);
/**
* <pre>
* Logo images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 512x128 and the aspect ratio must
* be 4:1 (+-1%). Combined with `square_logo_images`, the maximum is 5.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset logo_images = 3;</code>
*/
int getLogoImagesCount();
/**
* <pre>
* Logo images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 512x128 and the aspect ratio must
* be 4:1 (+-1%). Combined with `square_logo_images`, the maximum is 5.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset logo_images = 3;</code>
*/
java.util.List<? extends com.google.ads.googleads.v8.common.AdImageAssetOrBuilder>
getLogoImagesOrBuilderList();
/**
* <pre>
* Logo images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 512x128 and the aspect ratio must
* be 4:1 (+-1%). Combined with `square_logo_images`, the maximum is 5.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset logo_images = 3;</code>
*/
com.google.ads.googleads.v8.common.AdImageAssetOrBuilder getLogoImagesOrBuilder(
int index);
/**
* <pre>
* Square logo images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 128x128 and the aspect ratio must
* be 1:1 (+-1%). Combined with `square_logo_images`, the maximum is 5.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset square_logo_images = 4;</code>
*/
java.util.List<com.google.ads.googleads.v8.common.AdImageAsset>
getSquareLogoImagesList();
/**
* <pre>
* Square logo images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 128x128 and the aspect ratio must
* be 1:1 (+-1%). Combined with `square_logo_images`, the maximum is 5.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset square_logo_images = 4;</code>
*/
com.google.ads.googleads.v8.common.AdImageAsset getSquareLogoImages(int index);
/**
* <pre>
* Square logo images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 128x128 and the aspect ratio must
* be 1:1 (+-1%). Combined with `square_logo_images`, the maximum is 5.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset square_logo_images = 4;</code>
*/
int getSquareLogoImagesCount();
/**
* <pre>
* Square logo images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 128x128 and the aspect ratio must
* be 1:1 (+-1%). Combined with `square_logo_images`, the maximum is 5.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset square_logo_images = 4;</code>
*/
java.util.List<? extends com.google.ads.googleads.v8.common.AdImageAssetOrBuilder>
getSquareLogoImagesOrBuilderList();
/**
* <pre>
* Square logo images to be used in the ad. Valid image types are GIF,
* JPEG, and PNG. The minimum size is 128x128 and the aspect ratio must
* be 1:1 (+-1%). Combined with `square_logo_images`, the maximum is 5.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdImageAsset square_logo_images = 4;</code>
*/
com.google.ads.googleads.v8.common.AdImageAssetOrBuilder getSquareLogoImagesOrBuilder(
int index);
/**
* <pre>
* Short format headlines for the ad. The maximum length is 30 characters.
* At least 1 and max 5 headlines can be specified.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdTextAsset headlines = 5;</code>
*/
java.util.List<com.google.ads.googleads.v8.common.AdTextAsset>
getHeadlinesList();
/**
* <pre>
* Short format headlines for the ad. The maximum length is 30 characters.
* At least 1 and max 5 headlines can be specified.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdTextAsset headlines = 5;</code>
*/
com.google.ads.googleads.v8.common.AdTextAsset getHeadlines(int index);
/**
* <pre>
* Short format headlines for the ad. The maximum length is 30 characters.
* At least 1 and max 5 headlines can be specified.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdTextAsset headlines = 5;</code>
*/
int getHeadlinesCount();
/**
* <pre>
* Short format headlines for the ad. The maximum length is 30 characters.
* At least 1 and max 5 headlines can be specified.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdTextAsset headlines = 5;</code>
*/
java.util.List<? extends com.google.ads.googleads.v8.common.AdTextAssetOrBuilder>
getHeadlinesOrBuilderList();
/**
* <pre>
* Short format headlines for the ad. The maximum length is 30 characters.
* At least 1 and max 5 headlines can be specified.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdTextAsset headlines = 5;</code>
*/
com.google.ads.googleads.v8.common.AdTextAssetOrBuilder getHeadlinesOrBuilder(
int index);
/**
* <pre>
* A required long format headline. The maximum length is 90 characters.
* </pre>
*
* <code>.google.ads.googleads.v8.common.AdTextAsset long_headline = 6;</code>
* @return Whether the longHeadline field is set.
*/
boolean hasLongHeadline();
/**
* <pre>
* A required long format headline. The maximum length is 90 characters.
* </pre>
*
* <code>.google.ads.googleads.v8.common.AdTextAsset long_headline = 6;</code>
* @return The longHeadline.
*/
com.google.ads.googleads.v8.common.AdTextAsset getLongHeadline();
/**
* <pre>
* A required long format headline. The maximum length is 90 characters.
* </pre>
*
* <code>.google.ads.googleads.v8.common.AdTextAsset long_headline = 6;</code>
*/
com.google.ads.googleads.v8.common.AdTextAssetOrBuilder getLongHeadlineOrBuilder();
/**
* <pre>
* Descriptive texts for the ad. The maximum length is 90 characters. At
* least 1 and max 5 headlines can be specified.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdTextAsset descriptions = 7;</code>
*/
java.util.List<com.google.ads.googleads.v8.common.AdTextAsset>
getDescriptionsList();
/**
* <pre>
* Descriptive texts for the ad. The maximum length is 90 characters. At
* least 1 and max 5 headlines can be specified.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdTextAsset descriptions = 7;</code>
*/
com.google.ads.googleads.v8.common.AdTextAsset getDescriptions(int index);
/**
* <pre>
* Descriptive texts for the ad. The maximum length is 90 characters. At
* least 1 and max 5 headlines can be specified.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdTextAsset descriptions = 7;</code>
*/
int getDescriptionsCount();
/**
* <pre>
* Descriptive texts for the ad. The maximum length is 90 characters. At
* least 1 and max 5 headlines can be specified.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdTextAsset descriptions = 7;</code>
*/
java.util.List<? extends com.google.ads.googleads.v8.common.AdTextAssetOrBuilder>
getDescriptionsOrBuilderList();
/**
* <pre>
* Descriptive texts for the ad. The maximum length is 90 characters. At
* least 1 and max 5 headlines can be specified.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdTextAsset descriptions = 7;</code>
*/
com.google.ads.googleads.v8.common.AdTextAssetOrBuilder getDescriptionsOrBuilder(
int index);
/**
* <pre>
* Optional YouTube videos for the ad. A maximum of 5 videos can be specified.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdVideoAsset youtube_videos = 8;</code>
*/
java.util.List<com.google.ads.googleads.v8.common.AdVideoAsset>
getYoutubeVideosList();
/**
* <pre>
* Optional YouTube videos for the ad. A maximum of 5 videos can be specified.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdVideoAsset youtube_videos = 8;</code>
*/
com.google.ads.googleads.v8.common.AdVideoAsset getYoutubeVideos(int index);
/**
* <pre>
* Optional YouTube videos for the ad. A maximum of 5 videos can be specified.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdVideoAsset youtube_videos = 8;</code>
*/
int getYoutubeVideosCount();
/**
* <pre>
* Optional YouTube videos for the ad. A maximum of 5 videos can be specified.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdVideoAsset youtube_videos = 8;</code>
*/
java.util.List<? extends com.google.ads.googleads.v8.common.AdVideoAssetOrBuilder>
getYoutubeVideosOrBuilderList();
/**
* <pre>
* Optional YouTube videos for the ad. A maximum of 5 videos can be specified.
* </pre>
*
* <code>repeated .google.ads.googleads.v8.common.AdVideoAsset youtube_videos = 8;</code>
*/
com.google.ads.googleads.v8.common.AdVideoAssetOrBuilder getYoutubeVideosOrBuilder(
int index);
/**
* <pre>
* The advertiser/brand name. Maximum display width is 25.
* </pre>
*
* <code>optional string business_name = 17;</code>
* @return Whether the businessName field is set.
*/
boolean hasBusinessName();
/**
* <pre>
* The advertiser/brand name. Maximum display width is 25.
* </pre>
*
* <code>optional string business_name = 17;</code>
* @return The businessName.
*/
java.lang.String getBusinessName();
/**
* <pre>
* The advertiser/brand name. Maximum display width is 25.
* </pre>
*
* <code>optional string business_name = 17;</code>
* @return The bytes for businessName.
*/
com.google.protobuf.ByteString
getBusinessNameBytes();
/**
* <pre>
* The main color of the ad in hexadecimal, e.g. #ffffff for white.
* If one of `main_color` and `accent_color` is set, the other is required as
* well.
* </pre>
*
* <code>optional string main_color = 18;</code>
* @return Whether the mainColor field is set.
*/
boolean hasMainColor();
/**
* <pre>
* The main color of the ad in hexadecimal, e.g. #ffffff for white.
* If one of `main_color` and `accent_color` is set, the other is required as
* well.
* </pre>
*
* <code>optional string main_color = 18;</code>
* @return The mainColor.
*/
java.lang.String getMainColor();
/**
* <pre>
* The main color of the ad in hexadecimal, e.g. #ffffff for white.
* If one of `main_color` and `accent_color` is set, the other is required as
* well.
* </pre>
*
* <code>optional string main_color = 18;</code>
* @return The bytes for mainColor.
*/
com.google.protobuf.ByteString
getMainColorBytes();
/**
* <pre>
* The accent color of the ad in hexadecimal, e.g. #ffffff for white.
* If one of `main_color` and `accent_color` is set, the other is required as
* well.
* </pre>
*
* <code>optional string accent_color = 19;</code>
* @return Whether the accentColor field is set.
*/
boolean hasAccentColor();
/**
* <pre>
* The accent color of the ad in hexadecimal, e.g. #ffffff for white.
* If one of `main_color` and `accent_color` is set, the other is required as
* well.
* </pre>
*
* <code>optional string accent_color = 19;</code>
* @return The accentColor.
*/
java.lang.String getAccentColor();
/**
* <pre>
* The accent color of the ad in hexadecimal, e.g. #ffffff for white.
* If one of `main_color` and `accent_color` is set, the other is required as
* well.
* </pre>
*
* <code>optional string accent_color = 19;</code>
* @return The bytes for accentColor.
*/
com.google.protobuf.ByteString
getAccentColorBytes();
/**
* <pre>
* Advertiser's consent to allow flexible color. When true, the ad may be
* served with different color if necessary. When false, the ad will be served
* with the specified colors or a neutral color.
* The default value is `true`.
* Must be true if `main_color` and `accent_color` are not set.
* </pre>
*
* <code>optional bool allow_flexible_color = 20;</code>
* @return Whether the allowFlexibleColor field is set.
*/
boolean hasAllowFlexibleColor();
/**
* <pre>
* Advertiser's consent to allow flexible color. When true, the ad may be
* served with different color if necessary. When false, the ad will be served
* with the specified colors or a neutral color.
* The default value is `true`.
* Must be true if `main_color` and `accent_color` are not set.
* </pre>
*
* <code>optional bool allow_flexible_color = 20;</code>
* @return The allowFlexibleColor.
*/
boolean getAllowFlexibleColor();
/**
* <pre>
* The call-to-action text for the ad. Maximum display width is 30.
* </pre>
*
* <code>optional string call_to_action_text = 21;</code>
* @return Whether the callToActionText field is set.
*/
boolean hasCallToActionText();
/**
* <pre>
* The call-to-action text for the ad. Maximum display width is 30.
* </pre>
*
* <code>optional string call_to_action_text = 21;</code>
* @return The callToActionText.
*/
java.lang.String getCallToActionText();
/**
* <pre>
* The call-to-action text for the ad. Maximum display width is 30.
* </pre>
*
* <code>optional string call_to_action_text = 21;</code>
* @return The bytes for callToActionText.
*/
com.google.protobuf.ByteString
getCallToActionTextBytes();
/**
* <pre>
* Prefix before price. E.g. 'as low as'.
* </pre>
*
* <code>optional string price_prefix = 22;</code>
* @return Whether the pricePrefix field is set.
*/
boolean hasPricePrefix();
/**
* <pre>
* Prefix before price. E.g. 'as low as'.
* </pre>
*
* <code>optional string price_prefix = 22;</code>
* @return The pricePrefix.
*/
java.lang.String getPricePrefix();
/**
* <pre>
* Prefix before price. E.g. 'as low as'.
* </pre>
*
* <code>optional string price_prefix = 22;</code>
* @return The bytes for pricePrefix.
*/
com.google.protobuf.ByteString
getPricePrefixBytes();
/**
* <pre>
* Promotion text used for dynamic formats of responsive ads. For example
* 'Free two-day shipping'.
* </pre>
*
* <code>optional string promo_text = 23;</code>
* @return Whether the promoText field is set.
*/
boolean hasPromoText();
/**
* <pre>
* Promotion text used for dynamic formats of responsive ads. For example
* 'Free two-day shipping'.
* </pre>
*
* <code>optional string promo_text = 23;</code>
* @return The promoText.
*/
java.lang.String getPromoText();
/**
* <pre>
* Promotion text used for dynamic formats of responsive ads. For example
* 'Free two-day shipping'.
* </pre>
*
* <code>optional string promo_text = 23;</code>
* @return The bytes for promoText.
*/
com.google.protobuf.ByteString
getPromoTextBytes();
/**
* <pre>
* Specifies which format the ad will be served in. Default is ALL_FORMATS.
* </pre>
*
* <code>.google.ads.googleads.v8.enums.DisplayAdFormatSettingEnum.DisplayAdFormatSetting format_setting = 16;</code>
* @return The enum numeric value on the wire for formatSetting.
*/
int getFormatSettingValue();
/**
* <pre>
* Specifies which format the ad will be served in. Default is ALL_FORMATS.
* </pre>
*
* <code>.google.ads.googleads.v8.enums.DisplayAdFormatSettingEnum.DisplayAdFormatSetting format_setting = 16;</code>
* @return The formatSetting.
*/
com.google.ads.googleads.v8.enums.DisplayAdFormatSettingEnum.DisplayAdFormatSetting getFormatSetting();
/**
* <pre>
* Specification for various creative controls.
* </pre>
*
* <code>.google.ads.googleads.v8.common.ResponsiveDisplayAdControlSpec control_spec = 24;</code>
* @return Whether the controlSpec field is set.
*/
boolean hasControlSpec();
/**
* <pre>
* Specification for various creative controls.
* </pre>
*
* <code>.google.ads.googleads.v8.common.ResponsiveDisplayAdControlSpec control_spec = 24;</code>
* @return The controlSpec.
*/
com.google.ads.googleads.v8.common.ResponsiveDisplayAdControlSpec getControlSpec();
/**
* <pre>
* Specification for various creative controls.
* </pre>
*
* <code>.google.ads.googleads.v8.common.ResponsiveDisplayAdControlSpec control_spec = 24;</code>
*/
com.google.ads.googleads.v8.common.ResponsiveDisplayAdControlSpecOrBuilder getControlSpecOrBuilder();
}
| |
/*
* $Id$
* This file is a part of the Arakhne Foundation Classes, http://www.arakhne.org/afc
*
* Copyright (c) 2000-2012 Stephane GALLAND.
* Copyright (c) 2005-10, Multiagent Team, Laboratoire Systemes et Transports,
* Universite de Technologie de Belfort-Montbeliard.
* Copyright (c) 2013-2016 The original authors, and other 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.arakhne.afc.math.discrete.object2d;
import org.arakhne.afc.math.generic.PathElement2D;
import org.arakhne.afc.math.generic.PathElementType;
import org.arakhne.afc.vmutil.ReflectionUtil;
/** An element of the path.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
* @deprecated see {@link org.arakhne.afc.math.geometry.d2.i.PathElement2i}
*/
@Deprecated
@SuppressWarnings("all")
public abstract class PathElement2i implements PathElement2D {
private static final long serialVersionUID = 7757419973445894032L;
/** Create an instance of path element.
*
* @param type is the type of the new element.
* @param lastX is the coordinate of the last point.
* @param lastY is the coordinate of the last point.
* @param coords are the coordinates.
* @return the instance of path element.
*/
public static PathElement2i newInstance(PathElementType type, int lastX, int lastY, int[] coords) {
switch(type) {
case MOVE_TO:
return new MovePathElement2i(coords[0], coords[1]);
case LINE_TO:
return new LinePathElement2i(lastX, lastY, coords[0], coords[1]);
case QUAD_TO:
return new QuadPathElement2i(lastX, lastY, coords[0], coords[1], coords[2], coords[3]);
case CURVE_TO:
return new CurvePathElement2i(lastX, lastY, coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]);
case CLOSE:
return new ClosePathElement2i(lastX, lastY, coords[0], coords[1]);
default:
}
throw new IllegalArgumentException();
}
/** Type of the path element.
*/
public final PathElementType type;
/** Source point.
*/
public final int fromX;
/** Source point.
*/
public final int fromY;
/** Target point.
*/
public final int toX;
/** Target point.
*/
public final int toY;
/** First control point.
*/
public final int ctrlX1;
/** First control point.
*/
public final int ctrlY1;
/** Second control point.
*/
public final int ctrlX2;
/** Second control point.
*/
public final int ctrlY2;
/**
* @param type is the type of the element.
* @param fromx is the source point.
* @param fromy is the source point.
* @param ctrlx1 is the first control point.
* @param ctrly1 is the first control point.
* @param ctrlx2 is the first control point.
* @param ctrly2 is the first control point.
* @param tox is the target point.
* @param toy is the target point.
*/
public PathElement2i(PathElementType type, int fromx, int fromy, int ctrlx1, int ctrly1, int ctrlx2, int ctrly2, int tox, int toy) {
assert(type!=null);
this.type = type;
this.fromX = fromx;
this.fromY = fromy;
this.ctrlX1 = ctrlx1;
this.ctrlY1 = ctrly1;
this.ctrlX2 = ctrlx2;
this.ctrlY2 = ctrly2;
this.toX = tox;
this.toY = toy;
}
/** Copy the coords into the given array, except the source point.
*
* @param array
*/
public abstract void toArray(int[] array);
/** Copy the coords into the given array, except the source point.
*
* @param array
*/
public abstract void toArray(float[] array);
/** Copy the coords into an array, except the source point.
*
* @return the array of the points, except the source point.
*/
public abstract int[] toArray();
/** An element of the path that represents a <code>MOVE_TO</code>.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
public static class MovePathElement2i extends PathElement2i {
private static final long serialVersionUID = -8591881826671557331L;
/**
* @param x
* @param y
*/
public MovePathElement2i(int x, int y) {
super(PathElementType.MOVE_TO,
0, 0, 0, 0, 0, 0,
x, y);
}
@Override
public final PathElementType getType() {
return PathElementType.MOVE_TO;
}
@Override
public boolean isEmpty() {
return (this.fromX==this.toX) && (this.fromY==this.toY);
}
@Override
public boolean isDrawable() {
return false;
}
@Override
public void toArray(int[] array) {
array[0] = this.toX;
array[1] = this.toY;
}
@Override
public void toArray(float[] array) {
array[0] = this.toX;
array[1] = this.toY;
}
@Override
public int[] toArray() {
return new int[] {this.toX, this.toY};
}
@Override
public String toString() {
return ReflectionUtil.toString(this);
}
}
/** An element of the path that represents a <code>LINE_TO</code>.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
public static class LinePathElement2i extends PathElement2i {
private static final long serialVersionUID = 497492389885992535L;
/**
* @param fromx
* @param fromy
* @param tox
* @param toy
*/
public LinePathElement2i(int fromx, int fromy, int tox, int toy) {
super(PathElementType.LINE_TO,
fromx, fromy,
0, 0, 0, 0,
tox, toy);
}
@Override
public final PathElementType getType() {
return PathElementType.LINE_TO;
}
@Override
public boolean isEmpty() {
return (this.fromX==this.toX) && (this.fromY==this.toY);
}
@Override
public boolean isDrawable() {
return !isEmpty();
}
@Override
public void toArray(int[] array) {
array[0] = this.toX;
array[1] = this.toY;
}
@Override
public void toArray(float[] array) {
array[0] = this.toX;
array[1] = this.toY;
}
@Override
public int[] toArray() {
return new int[] {this.toX, this.toY};
}
@Override
public String toString() {
return ReflectionUtil.toString(this);
}
}
/** An element of the path that represents a <code>QUAD_TO</code>.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
public static class QuadPathElement2i extends PathElement2i {
private static final long serialVersionUID = 6341899683730854257L;
/**
* @param fromx
* @param fromy
* @param ctrlx
* @param ctrly
* @param tox
* @param toy
*/
public QuadPathElement2i(int fromx, int fromy, int ctrlx, int ctrly, int tox, int toy) {
super(PathElementType.QUAD_TO,
fromx, fromy,
ctrlx, ctrly,
0, 0,
tox, toy);
}
@Override
public final PathElementType getType() {
return PathElementType.QUAD_TO;
}
@Override
public boolean isEmpty() {
return (this.fromX==this.toX) && (this.fromY==this.toY) &&
(this.ctrlX1==this.toX) && (this.ctrlY1==this.toY);
}
@Override
public boolean isDrawable() {
return !isEmpty();
}
@Override
public void toArray(int[] array) {
array[0] = this.ctrlX1;
array[1] = this.ctrlY1;
array[2] = this.toX;
array[3] = this.toY;
}
@Override
public void toArray(float[] array) {
array[0] = this.ctrlX1;
array[1] = this.ctrlY1;
array[2] = this.toX;
array[3] = this.toY;
}
@Override
public int[] toArray() {
return new int[] {this.ctrlX1, this.ctrlY1, this.toX, this.toY};
}
@Override
public String toString() {
return ReflectionUtil.toString(this);
}
}
/** An element of the path that represents a <code>CURVE_TO</code>.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
public static class CurvePathElement2i extends PathElement2i {
private static final long serialVersionUID = 1043302430176113524L;
/**
* @param fromx
* @param fromy
* @param ctrlx1
* @param ctrly1
* @param ctrlx2
* @param ctrly2
* @param tox
* @param toy
*/
public CurvePathElement2i(int fromx, int fromy, int ctrlx1, int ctrly1, int ctrlx2, int ctrly2, int tox, int toy) {
super(PathElementType.CURVE_TO,
fromx, fromy,
ctrlx1, ctrly1,
ctrlx2, ctrly2,
tox, toy);
}
@Override
public final PathElementType getType() {
return PathElementType.CURVE_TO;
}
@Override
public boolean isEmpty() {
return (this.fromX==this.toX) && (this.fromY==this.toY) &&
(this.ctrlX1==this.toX) && (this.ctrlY1==this.toY) &&
(this.ctrlX2==this.toX) && (this.ctrlY2==this.toY);
}
@Override
public boolean isDrawable() {
return !isEmpty();
}
@Override
public void toArray(int[] array) {
array[0] = this.ctrlX1;
array[1] = this.ctrlY1;
array[2] = this.ctrlX2;
array[3] = this.ctrlY2;
array[4] = this.toX;
array[5] = this.toY;
}
@Override
public void toArray(float[] array) {
array[0] = this.ctrlX1;
array[1] = this.ctrlY1;
array[2] = this.ctrlX2;
array[3] = this.ctrlY2;
array[4] = this.toX;
array[5] = this.toY;
}
@Override
public int[] toArray() {
return new int[] {this.ctrlX1, this.ctrlY1, this.ctrlX2, this.ctrlY2, this.toX, this.toY};
}
@Override
public String toString() {
return ReflectionUtil.toString(this);
}
}
/** An element of the path that represents a <code>CLOSE</code>.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
public static class ClosePathElement2i extends PathElement2i {
private static final long serialVersionUID = 2745123226508569279L;
/**
* @param fromx
* @param fromy
* @param tox
* @param toy
*/
public ClosePathElement2i(int fromx, int fromy, int tox, int toy) {
super(PathElementType.CLOSE,
fromx, fromy,
0, 0, 0, 0,
tox, toy);
}
@Override
public final PathElementType getType() {
return PathElementType.CLOSE;
}
@Override
public boolean isEmpty() {
return (this.fromX==this.toX) && (this.fromY==this.toY);
}
@Override
public boolean isDrawable() {
return false;
}
@Override
public void toArray(int[] array) {
//
}
@Override
public void toArray(float[] array) {
//
}
@Override
public int[] toArray() {
return new int[0];
}
@Override
public String toString() {
return ReflectionUtil.toString(this);
}
}
}
| |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual 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 io.undertow.server.protocol.ajp;
import static io.undertow.util.Methods.ACL;
import static io.undertow.util.Methods.BASELINE_CONTROL;
import static io.undertow.util.Methods.CHECKIN;
import static io.undertow.util.Methods.CHECKOUT;
import static io.undertow.util.Methods.COPY;
import static io.undertow.util.Methods.DELETE;
import static io.undertow.util.Methods.GET;
import static io.undertow.util.Methods.HEAD;
import static io.undertow.util.Methods.LABEL;
import static io.undertow.util.Methods.LOCK;
import static io.undertow.util.Methods.MERGE;
import static io.undertow.util.Methods.MKACTIVITY;
import static io.undertow.util.Methods.MKCOL;
import static io.undertow.util.Methods.MKWORKSPACE;
import static io.undertow.util.Methods.MOVE;
import static io.undertow.util.Methods.OPTIONS;
import static io.undertow.util.Methods.POST;
import static io.undertow.util.Methods.PROPFIND;
import static io.undertow.util.Methods.PROPPATCH;
import static io.undertow.util.Methods.PUT;
import static io.undertow.util.Methods.REPORT;
import static io.undertow.util.Methods.SEARCH;
import static io.undertow.util.Methods.TRACE;
import static io.undertow.util.Methods.UNCHECKOUT;
import static io.undertow.util.Methods.UNLOCK;
import static io.undertow.util.Methods.UPDATE;
import static io.undertow.util.Methods.VERSION_CONTROL;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.util.TreeMap;
import io.undertow.UndertowLogger;
import io.undertow.UndertowMessages;
import io.undertow.security.impl.ExternalAuthenticationMechanism;
import io.undertow.server.Connectors;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import io.undertow.util.HttpString;
import io.undertow.util.ParameterLimitException;
import io.undertow.util.BadRequestException;
import io.undertow.util.URLUtils;
/**
* @author Stuart Douglas
*/
public class AjpRequestParser {
private final String encoding;
private final boolean doDecode;
private final int maxParameters;
private final int maxHeaders;
private static final HttpString[] HTTP_HEADERS;
public static final int FORWARD_REQUEST = 2;
public static final int CPONG = 9;
public static final int CPING = 10;
public static final int SHUTDOWN = 7;
private static final HttpString[] HTTP_METHODS;
private static final String[] ATTRIBUTES;
public static final String QUERY_STRING = "query_string";
public static final String SSL_CERT = "ssl_cert";
public static final String CONTEXT = "context";
public static final String SERVLET_PATH = "servlet_path";
public static final String REMOTE_USER = "remote_user";
public static final String AUTH_TYPE = "auth_type";
public static final String ROUTE = "route";
public static final String SSL_CIPHER = "ssl_cipher";
public static final String SSL_SESSION = "ssl_session";
public static final String REQ_ATTRIBUTE = "req_attribute";
public static final String SSL_KEY_SIZE = "ssl_key_size";
public static final String SECRET = "secret";
public static final String STORED_METHOD = "stored_method";
public static final String AJP_REMOTE_PORT = "AJP_REMOTE_PORT";
static {
HTTP_METHODS = new HttpString[28];
HTTP_METHODS[1] = OPTIONS;
HTTP_METHODS[2] = GET;
HTTP_METHODS[3] = HEAD;
HTTP_METHODS[4] = POST;
HTTP_METHODS[5] = PUT;
HTTP_METHODS[6] = DELETE;
HTTP_METHODS[7] = TRACE;
HTTP_METHODS[8] = PROPFIND;
HTTP_METHODS[9] = PROPPATCH;
HTTP_METHODS[10] = MKCOL;
HTTP_METHODS[11] = COPY;
HTTP_METHODS[12] = MOVE;
HTTP_METHODS[13] = LOCK;
HTTP_METHODS[14] = UNLOCK;
HTTP_METHODS[15] = ACL;
HTTP_METHODS[16] = REPORT;
HTTP_METHODS[17] = VERSION_CONTROL;
HTTP_METHODS[18] = CHECKIN;
HTTP_METHODS[19] = CHECKOUT;
HTTP_METHODS[20] = UNCHECKOUT;
HTTP_METHODS[21] = SEARCH;
HTTP_METHODS[22] = MKWORKSPACE;
HTTP_METHODS[23] = UPDATE;
HTTP_METHODS[24] = LABEL;
HTTP_METHODS[25] = MERGE;
HTTP_METHODS[26] = BASELINE_CONTROL;
HTTP_METHODS[27] = MKACTIVITY;
HTTP_HEADERS = new HttpString[0xF];
HTTP_HEADERS[1] = Headers.ACCEPT;
HTTP_HEADERS[2] = Headers.ACCEPT_CHARSET;
HTTP_HEADERS[3] = Headers.ACCEPT_ENCODING;
HTTP_HEADERS[4] = Headers.ACCEPT_LANGUAGE;
HTTP_HEADERS[5] = Headers.AUTHORIZATION;
HTTP_HEADERS[6] = Headers.CONNECTION;
HTTP_HEADERS[7] = Headers.CONTENT_TYPE;
HTTP_HEADERS[8] = Headers.CONTENT_LENGTH;
HTTP_HEADERS[9] = Headers.COOKIE;
HTTP_HEADERS[0xA] = Headers.COOKIE2;
HTTP_HEADERS[0xB] = Headers.HOST;
HTTP_HEADERS[0xC] = Headers.PRAGMA;
HTTP_HEADERS[0xD] = Headers.REFERER;
HTTP_HEADERS[0xE] = Headers.USER_AGENT;
ATTRIBUTES = new String[0xE];
ATTRIBUTES[1] = CONTEXT;
ATTRIBUTES[2] = SERVLET_PATH;
ATTRIBUTES[3] = REMOTE_USER;
ATTRIBUTES[4] = AUTH_TYPE;
ATTRIBUTES[5] = QUERY_STRING;
ATTRIBUTES[6] = ROUTE;
ATTRIBUTES[7] = SSL_CERT;
ATTRIBUTES[8] = SSL_CIPHER;
ATTRIBUTES[9] = SSL_SESSION;
ATTRIBUTES[10] = REQ_ATTRIBUTE;
ATTRIBUTES[11] = SSL_KEY_SIZE;
ATTRIBUTES[12] = SECRET;
ATTRIBUTES[13] = STORED_METHOD;
}
public AjpRequestParser(String encoding, boolean doDecode, int maxParameters, int maxHeaders) {
this.encoding = encoding;
this.doDecode = doDecode;
this.maxParameters = maxParameters;
this.maxHeaders = maxHeaders;
}
public void parse(final ByteBuffer buf, final AjpRequestParseState state, final HttpServerExchange exchange) throws IOException, BadRequestException {
if (!buf.hasRemaining()) {
return;
}
switch (state.state) {
case AjpRequestParseState.BEGIN: {
IntegerHolder result = parse16BitInteger(buf, state);
if (!result.readComplete) {
return;
} else {
if (result.value != 0x1234) {
throw new BadRequestException(UndertowMessages.MESSAGES.wrongMagicNumber(result.value));
}
}
}
case AjpRequestParseState.READING_DATA_SIZE: {
IntegerHolder result = parse16BitInteger(buf, state);
if (!result.readComplete) {
state.state = AjpRequestParseState.READING_DATA_SIZE;
return;
} else {
state.dataSize = result.value;
}
}
case AjpRequestParseState.READING_PREFIX_CODE: {
if (!buf.hasRemaining()) {
state.state = AjpRequestParseState.READING_PREFIX_CODE;
return;
} else {
final byte prefix = buf.get();
state.prefix = prefix;
if (prefix != 2) {
state.state = AjpRequestParseState.DONE;
return;
}
}
}
case AjpRequestParseState.READING_METHOD: {
if (!buf.hasRemaining()) {
state.state = AjpRequestParseState.READING_METHOD;
return;
} else {
int method = buf.get();
if (method > 0 && method < 28) {
exchange.setRequestMethod(HTTP_METHODS[method]);
} else if((method & 0xFF) != 0xFF) {
throw new BadRequestException("Unknown method type " + method);
}
}
}
case AjpRequestParseState.READING_PROTOCOL: {
StringHolder result = parseString(buf, state, StringType.OTHER);
if (result.readComplete) {
//TODO: more efficient way of doing this
exchange.setProtocol(HttpString.tryFromString(result.value));
} else {
state.state = AjpRequestParseState.READING_PROTOCOL;
return;
}
}
case AjpRequestParseState.READING_REQUEST_URI: {
StringHolder result = parseString(buf, state, StringType.URL);
if (result.readComplete) {
int colon = result.value.indexOf(';');
if (colon == -1) {
String res = decode(result.value, result.containsUrlCharacters);
exchange.setRequestURI(result.value);
exchange.setRequestPath(res);
exchange.setRelativePath(res);
} else {
final String url = result.value.substring(0, colon);
String res = decode(url, result.containsUrlCharacters);
exchange.setRequestURI(result.value);
exchange.setRequestPath(res);
exchange.setRelativePath(res);
try {
URLUtils.parsePathParms(result.value.substring(colon + 1), exchange, encoding, doDecode && result.containsUrlCharacters, maxParameters);
} catch (ParameterLimitException e) {
UndertowLogger.REQUEST_IO_LOGGER.failedToParseRequest(e);
state.badRequest = true;
}
}
} else {
state.state = AjpRequestParseState.READING_REQUEST_URI;
return;
}
}
case AjpRequestParseState.READING_REMOTE_ADDR: {
StringHolder result = parseString(buf, state, StringType.OTHER);
if (result.readComplete) {
state.remoteAddress = result.value;
} else {
state.state = AjpRequestParseState.READING_REMOTE_ADDR;
return;
}
}
case AjpRequestParseState.READING_REMOTE_HOST: {
StringHolder result = parseString(buf, state, StringType.OTHER);
if (result.readComplete) {
//exchange.setRequestURI(result.value);
} else {
state.state = AjpRequestParseState.READING_REMOTE_HOST;
return;
}
}
case AjpRequestParseState.READING_SERVER_NAME: {
StringHolder result = parseString(buf, state, StringType.OTHER);
if (result.readComplete) {
state.serverAddress = result.value;
} else {
state.state = AjpRequestParseState.READING_SERVER_NAME;
return;
}
}
case AjpRequestParseState.READING_SERVER_PORT: {
IntegerHolder result = parse16BitInteger(buf, state);
if (result.readComplete) {
state.serverPort = result.value;
} else {
state.state = AjpRequestParseState.READING_SERVER_PORT;
return;
}
}
case AjpRequestParseState.READING_IS_SSL: {
if (!buf.hasRemaining()) {
state.state = AjpRequestParseState.READING_IS_SSL;
return;
} else {
final byte isSsl = buf.get();
if (isSsl != 0) {
exchange.setRequestScheme("https");
} else {
exchange.setRequestScheme("http");
}
}
}
case AjpRequestParseState.READING_NUM_HEADERS: {
IntegerHolder result = parse16BitInteger(buf, state);
if (!result.readComplete) {
state.state = AjpRequestParseState.READING_NUM_HEADERS;
return;
} else {
state.numHeaders = result.value;
if(state.numHeaders > maxHeaders) {
UndertowLogger.REQUEST_IO_LOGGER.failedToParseRequest(new BadRequestException(UndertowMessages.MESSAGES.tooManyHeaders(maxHeaders)));
state.badRequest = true;
}
}
}
case AjpRequestParseState.READING_HEADERS: {
int readHeaders = state.readHeaders;
while (readHeaders < state.numHeaders) {
if (state.currentHeader == null) {
StringHolder result = parseString(buf, state, StringType.HEADER);
if (!result.readComplete) {
state.state = AjpRequestParseState.READING_HEADERS;
state.readHeaders = readHeaders;
return;
}
if (result.header != null) {
state.currentHeader = result.header;
} else {
state.currentHeader = HttpString.tryFromString(result.value);
Connectors.verifyToken(state.currentHeader);
}
}
StringHolder result = parseString(buf, state, StringType.OTHER);
if (!result.readComplete) {
state.state = AjpRequestParseState.READING_HEADERS;
state.readHeaders = readHeaders;
return;
}
if(!state.badRequest) {
exchange.getRequestHeaders().add(state.currentHeader, result.value);
}
state.currentHeader = null;
++readHeaders;
}
}
case AjpRequestParseState.READING_ATTRIBUTES: {
for (; ; ) {
if (state.currentAttribute == null && state.currentIntegerPart == -1) {
if (!buf.hasRemaining()) {
state.state = AjpRequestParseState.READING_ATTRIBUTES;
return;
}
int val = (0xFF & buf.get());
if (val == 0xFF) {
state.state = AjpRequestParseState.DONE;
return;
} else if (val == 0x0A) {
//we need to read the name. We overload currentIntegerPart to avoid adding another state field
state.currentIntegerPart = 1;
} else {
if(val == 0 || val >= ATTRIBUTES.length) {
//ignore unknown codes for compatibility
continue;
}
state.currentAttribute = ATTRIBUTES[val];
}
}
if (state.currentIntegerPart == 1) {
StringHolder result = parseString(buf, state, StringType.OTHER);
if (!result.readComplete) {
state.state = AjpRequestParseState.READING_ATTRIBUTES;
return;
}
state.currentAttribute = result.value;
state.currentIntegerPart = -1;
}
String result;
if (state.currentAttribute.equals(SSL_KEY_SIZE)) {
IntegerHolder resultHolder = parse16BitInteger(buf, state);
if (!resultHolder.readComplete) {
state.state = AjpRequestParseState.READING_ATTRIBUTES;
return;
}
result = Integer.toString(resultHolder.value);
} else {
StringHolder resultHolder = parseString(buf, state, state.currentAttribute.equals(QUERY_STRING) ? StringType.QUERY_STRING : StringType.OTHER);
if (!resultHolder.readComplete) {
state.state = AjpRequestParseState.READING_ATTRIBUTES;
return;
}
result = resultHolder.value;
}
//query string.
if (state.currentAttribute.equals(QUERY_STRING)) {
String resultAsQueryString = result == null ? "" : result;
exchange.setQueryString(resultAsQueryString);
try {
URLUtils.parseQueryString(resultAsQueryString, exchange, encoding, doDecode, maxParameters);
} catch (ParameterLimitException e) {
UndertowLogger.REQUEST_IO_LOGGER.failedToParseRequest(e);
state.badRequest = true;
}
} else if (state.currentAttribute.equals(REMOTE_USER)) {
exchange.putAttachment(ExternalAuthenticationMechanism.EXTERNAL_PRINCIPAL, result);
} else if (state.currentAttribute.equals(AUTH_TYPE)) {
exchange.putAttachment(ExternalAuthenticationMechanism.EXTERNAL_AUTHENTICATION_TYPE, result);
} else if (state.currentAttribute.equals(STORED_METHOD)) {
HttpString requestMethod = new HttpString(result);
Connectors.verifyToken(requestMethod);
exchange.setRequestMethod(requestMethod);
} else if (state.currentAttribute.equals(AJP_REMOTE_PORT)) {
state.remotePort = Integer.parseInt(result);
} else if (state.currentAttribute.equals(SSL_SESSION)) {
state.sslSessionId = result;
} else if (state.currentAttribute.equals(SSL_CIPHER)) {
state.sslCipher = result;
} else if (state.currentAttribute.equals(SSL_CERT)) {
state.sslCert = result;
} else if (state.currentAttribute.equals(SSL_KEY_SIZE)) {
state.sslKeySize = result;
} else {
//other attributes
if(state.attributes == null) {
state.attributes = new TreeMap<>();
}
state.attributes.put(state.currentAttribute, result);
}
state.currentAttribute = null;
}
}
}
state.state = AjpRequestParseState.DONE;
}
private String decode(String url, final boolean containsUrlCharacters) throws UnsupportedEncodingException {
if (doDecode && containsUrlCharacters) {
try {
return URLDecoder.decode(url, encoding);
} catch (Exception e) {
throw UndertowMessages.MESSAGES.failedToDecodeURL(url, encoding, e);
}
}
return url;
}
protected HttpString headers(int offset) {
return HTTP_HEADERS[offset];
}
public static final int STRING_LENGTH_MASK = 1 << 31;
protected IntegerHolder parse16BitInteger(ByteBuffer buf, AjpRequestParseState state) {
if (!buf.hasRemaining()) {
return new IntegerHolder(-1, false);
}
int number = state.currentIntegerPart;
if (number == -1) {
number = (buf.get() & 0xFF);
}
if (buf.hasRemaining()) {
final byte b = buf.get();
int result = ((0xFF & number) << 8) + (b & 0xFF);
state.currentIntegerPart = -1;
return new IntegerHolder(result, true);
} else {
state.currentIntegerPart = number;
return new IntegerHolder(-1, false);
}
}
protected StringHolder parseString(ByteBuffer buf, AjpRequestParseState state, StringType type) throws UnsupportedEncodingException {
boolean containsUrlCharacters = state.containsUrlCharacters;
if (!buf.hasRemaining()) {
return new StringHolder(null, false, false);
}
int stringLength = state.stringLength;
if (stringLength == -1) {
int number = buf.get() & 0xFF;
if (buf.hasRemaining()) {
final byte b = buf.get();
stringLength = ((0xFF & number) << 8) + (b & 0xFF);
} else {
state.stringLength = number | STRING_LENGTH_MASK;
return new StringHolder(null, false, false);
}
} else if ((stringLength & STRING_LENGTH_MASK) != 0) {
int number = stringLength & ~STRING_LENGTH_MASK;
stringLength = ((0xFF & number) << 8) + (buf.get() & 0xFF);
}
if (type == StringType.HEADER && (stringLength & 0xFF00) != 0) {
state.stringLength = -1;
return new StringHolder(headers(stringLength & 0xFF));
}
if (stringLength == 0xFFFF) {
//OxFFFF means null
state.stringLength = -1;
return new StringHolder(null, true, false);
}
int length = state.getCurrentStringLength();
while (length < stringLength) {
if (!buf.hasRemaining()) {
state.stringLength = stringLength;
state.containsUrlCharacters = containsUrlCharacters;
return new StringHolder(null, false, false);
}
byte c = buf.get();
if(type == StringType.QUERY_STRING && (c == '+' || c == '%')) {
containsUrlCharacters = true;
} else if(type == StringType.URL && c == '%') {
containsUrlCharacters = true;
}
state.addStringByte(c);
++length;
}
if (buf.hasRemaining()) {
buf.get(); //null terminator
String value = state.getStringAndClear(encoding);
state.stringLength = -1;
state.containsUrlCharacters = false;
return new StringHolder(value, true, containsUrlCharacters);
} else {
state.stringLength = stringLength;
state.containsUrlCharacters = containsUrlCharacters;
return new StringHolder(null, false, false);
}
}
protected static class IntegerHolder {
public final int value;
public final boolean readComplete;
private IntegerHolder(int value, boolean readComplete) {
this.value = value;
this.readComplete = readComplete;
}
}
protected static class StringHolder {
public final String value;
public final HttpString header;
public final boolean readComplete;
public final boolean containsUrlCharacters;
private StringHolder(String value, boolean readComplete, boolean containsUrlCharacters) {
this.value = value;
this.readComplete = readComplete;
this.containsUrlCharacters = containsUrlCharacters;
this.header = null;
}
private StringHolder(HttpString value) {
this.value = null;
this.readComplete = true;
this.header = value;
this.containsUrlCharacters = false;
}
}
enum StringType {
HEADER,
URL,
QUERY_STRING,
OTHER
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.