gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cache; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.UUID; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.IgniteKernal; import org.apache.ignite.internal.processors.cache.version.GridCacheVersion; import org.apache.ignite.marshaller.Marshaller; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import static org.apache.ignite.cache.CacheMode.REPLICATED; /** * Test cases for multi-threaded tests. */ public class GridCacheMvccSelfTest extends GridCommonAbstractTest { /** Grid. */ private IgniteKernal grid; /** VM ip finder for TCP discovery. */ private static TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true); /** * */ public GridCacheMvccSelfTest() { super(true /*start grid. */); } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { grid = (IgniteKernal)grid(); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { grid = null; } /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration() throws Exception { IgniteConfiguration cfg = super.getConfiguration(); TcpDiscoverySpi disco = new TcpDiscoverySpi(); disco.setIpFinder(ipFinder); cfg.setDiscoverySpi(disco); CacheConfiguration cacheCfg = defaultCacheConfiguration(); cacheCfg.setCacheMode(REPLICATED); cfg.setCacheConfiguration(cacheCfg); return cfg; } /** * @throws Exception If failed. */ public void testMarshalUnmarshalCandidate() throws Exception { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx parent = new GridCacheTestEntryEx(cache.context(), "1"); GridCacheMvccCandidate cand = new GridCacheMvccCandidate( parent, UUID.randomUUID(), UUID.randomUUID(), version(1), 123, version(2), /*local*/false, /*reentry*/false, true, false, false, false, null, false ); Marshaller marshaller = getTestResources().getMarshaller(); GridCacheMvccCandidate unmarshalled = marshaller.unmarshal(marshaller.marshal(cand), null); info(unmarshalled.toString()); } /** * Tests remote candidates. */ public void testRemotes() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID node1 = UUID.randomUUID(); UUID node2 = UUID.randomUUID(); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheVersion ver5 = version(5); entry.addRemote(node1, 1, ver1, true); Collection<GridCacheMvccCandidate> cands = entry.remoteMvccSnapshot(); assert cands.size() == 1; assert cands.iterator().next().version().equals(ver1); entry.addRemote(node2, 5, ver5, true); cands = entry.remoteMvccSnapshot(); assert cands.size() == 2; info(cands); // Check order. checkOrder(cands, ver1, ver5); entry.addRemote(node1, 3, ver3, true); cands = entry.remoteMvccSnapshot(); info(cands); assert cands.size() == 3; // No reordering happens. checkOrder(cands, ver1, ver5, ver3); entry.doneRemote(ver3); checkDone(entry.candidate(ver3)); entry.addRemote(node1, 2, ver2, true); cands = entry.remoteMvccSnapshot(); info(cands); assert cands.size() == 4; // Check order. checkOrder(cands, ver1, ver5, ver3, ver2); entry.orderCompleted( new GridCacheVersion(1, 2, 0, 0), Arrays.asList(new GridCacheVersion(1, 3, 4, 0), ver2, new GridCacheVersion(1, 5, 6, 0)), Collections.<GridCacheVersion>emptyList() ); cands = entry.remoteMvccSnapshot(); info(cands); assert cands.size() == 4; // Done ver 2. checkOrder(cands, ver1, ver2, ver5, ver3); checkRemote(entry.candidate(ver1), ver1, false, false); checkRemote(entry.candidate(ver2), ver2, true, false); checkRemote(entry.candidate(ver3), ver3, true, true); checkRemote(entry.candidate(ver5), ver5, false, false); entry.doneRemote(ver5); checkDone(entry.candidate(ver5)); entry.addRemote(node1, 4, ver4, true); cands = entry.remoteMvccSnapshot(); info(cands); assert cands.size() == 5; // Check order. checkOrder(cands, ver1, ver2, ver5, ver3, ver4); entry.orderCompleted(ver3, Arrays.asList(ver2, ver5), Collections.<GridCacheVersion>emptyList()); cands = entry.remoteMvccSnapshot(); info(cands); assert cands.size() == 5; checkOrder(cands, ver1, ver2, ver5, ver3, ver4); assert entry.anyOwner() == null; entry.doneRemote(ver1); checkRemoteOwner(entry.anyOwner(), ver1); entry.removeLock(ver1); assert entry.remoteMvccSnapshot().size() == 4; assert entry.anyOwner() == null; entry.doneRemote(ver2); checkRemoteOwner(entry.anyOwner(), ver2); entry.removeLock(ver2); assert entry.remoteMvccSnapshot().size() == 3; checkRemoteOwner(entry.anyOwner(), ver5); entry.removeLock(ver3); assert entry.remoteMvccSnapshot().size() == 2; checkRemoteOwner(entry.anyOwner(), ver5); entry.removeLock(ver5); assert entry.remoteMvccSnapshot().size() == 1; assert entry.anyOwner() == null; entry.doneRemote(ver4); checkRemoteOwner(entry.anyOwner(), ver4); entry.removeLock(ver4); assert entry.remoteMvccSnapshot().isEmpty(); assert entry.anyOwner() == null; } /** * Tests that orderOwned does not reorder owned locks. */ public void testNearRemoteWithOwned() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID node1 = UUID.randomUUID(); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheMvccCandidate c1 = entry.addRemote(node1, 1, ver1, true); GridCacheMvccCandidate c2 = entry.addRemote(node1, 1, ver2, true); GridCacheMvccCandidate c3 = entry.addRemote(node1, 1, ver3, true); GridCacheMvccCandidate c4 = entry.addRemote(node1, 1, ver4, true); GridCacheMvccCandidate[] candArr = new GridCacheMvccCandidate[] {c1, c2, c3, c4}; Collection<GridCacheMvccCandidate> rmtCands = entry.remoteMvccSnapshot(); assert rmtCands.size() == 4; assert rmtCands.iterator().next().version().equals(ver1); entry.orderOwned(ver1, ver2); rmtCands = entry.remoteMvccSnapshot(); int i = 0; for (GridCacheMvccCandidate cand : rmtCands) { assertTrue(cand == candArr[i]); assertTrue(ver2.equals(cand.ownerVersion()) || cand != c1); i++; } } /** * Tests that orderOwned does not reorder owned locks. */ public void testNearRemoteWithOwned1() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID node1 = UUID.randomUUID(); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheVersion ver5 = version(5); GridCacheVersion ver6 = version(6); GridCacheMvccCandidate c1 = entry.addRemote(node1, 1, ver1, true); GridCacheMvccCandidate c2 = entry.addRemote(node1, 1, ver2, true); GridCacheMvccCandidate c3 = entry.addRemote(node1, 1, ver3, true); GridCacheMvccCandidate c4 = entry.addRemote(node1, 1, ver4, true); GridCacheMvccCandidate c5 = entry.addRemote(node1, 1, ver5, true); GridCacheMvccCandidate c6 = entry.addRemote(node1, 1, ver6, true); GridCacheMvccCandidate[] candArr = new GridCacheMvccCandidate[] {c1, c2, c3, c4, c5, c6}; Collection<GridCacheMvccCandidate> cands = entry.remoteMvccSnapshot(); assert cands.size() == 6; assert cands.iterator().next().version().equals(ver1); entry.orderOwned(ver1, ver3); cands = entry.remoteMvccSnapshot(); int i = 0; for (GridCacheMvccCandidate cand : cands) { assert cand == candArr[i]; assertTrue(ver3.equals(cand.ownerVersion()) || cand != c1); i++; } } /** * Tests that orderOwned does not reorder owned locks. */ public void testNearRemoteWithOwned2() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID node1 = UUID.randomUUID(); GridCacheVersion ver0 = version(0); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheVersion ver5 = version(5); GridCacheVersion ver6 = version(6); GridCacheMvccCandidate c0 = entry.addRemote(node1, 1, ver0, true); GridCacheMvccCandidate c1 = entry.addRemote(node1, 1, ver1, true); GridCacheMvccCandidate c2 = entry.addRemote(node1, 1, ver2, true); GridCacheMvccCandidate c3 = entry.addRemote(node1, 1, ver3, true); GridCacheMvccCandidate c4 = entry.addRemote(node1, 1, ver4, true); GridCacheMvccCandidate c5 = entry.addRemote(node1, 1, ver5, true); GridCacheMvccCandidate c6 = entry.addRemote(node1, 1, ver6, true); GridCacheMvccCandidate[] candArr = new GridCacheMvccCandidate[] {c0, c1, c2, c3, c4, c5, c6}; Collection<GridCacheMvccCandidate> cands = entry.remoteMvccSnapshot(); assert cands.size() == 7; assert cands.iterator().next().version().equals(ver0); entry.orderOwned(ver1, ver2); cands = entry.remoteMvccSnapshot(); int i = 0; for (GridCacheMvccCandidate cand : cands) { assert cand == candArr[i]; assertTrue(ver2.equals(cand.ownerVersion()) || cand != c1); i++; } } /** * Tests remote candidates. */ public void testLocal() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheVersion ver5 = version(5); entry.addLocal(3, ver3, 0, true, true); Collection<GridCacheMvccCandidate> cands = entry.localCandidates(); assert cands.size() == 1; assert cands.iterator().next().version().equals(ver3); entry.addLocal(5, ver5, 0, true, true); cands = entry.localCandidates(); assert cands.size() == 2; info(cands); // Check order. checkOrder(cands, ver3, ver5); assert entry.anyOwner() == null; entry.readyLocal(ver3); checkLocalOwner(entry.anyOwner(), ver3, false); // Reentry. entry.addLocal(3, ver4, 0, true, true); checkLocalOwner(entry.anyOwner(), ver4, true); assert entry.localCandidates().size() == 2; assert entry.localCandidates(true).size() == 3; // Check order. checkOrder(entry.localCandidates(true), ver4, ver3, ver5); entry.removeLock(ver4); assert entry.localCandidates(true).size() == 2; entry.readyLocal(ver5); checkLocalOwner(entry.anyOwner(), ver3, false); // Check order. checkOrder(entry.localCandidates(true), ver3, ver5); entry.removeLock(ver3); assert entry.localCandidates(true).size() == 1; checkLocalOwner(entry.anyOwner(), ver5, false); assert !entry.lockedByAny(ver5); entry.removeLock(ver5); assert !entry.lockedByAny(); assert entry.anyOwner() == null; assert entry.localCandidates(true).isEmpty(); } /** * Tests assignment of local candidates when remote exist. */ public void testLocalWithRemote() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID nodeId = UUID.randomUUID(); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); entry.addRemote(nodeId, 1, ver2, true); entry.addLocal(3, ver3, 0, false, true); assert entry.anyOwner() == null; entry.readyLocal(ver3); assert entry.anyOwner() == null; entry.removeLock(ver2); assert entry.localCandidates().size() == 1; checkLocalOwner(entry.anyOwner(), ver3, false); entry.removeLock(ver3); assert !entry.lockedByAny(); assert entry.anyOwner() == null; assert entry.localCandidates(true).isEmpty(); } /** * */ public void testCompletedWithBaseInTheMiddle() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID node1 = UUID.randomUUID(); UUID node2 = UUID.randomUUID(); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheVersion ver5 = version(5); GridCacheVersion ver6 = version(6); GridCacheVersion ver7 = version(7); GridCacheVersion ver8 = version(8); entry.addRemote(node1, 1, ver1, true); entry.addRemote(node2, 2, ver2, true); entry.addRemote(node1, 3, ver3, true); entry.addRemote(node2, 4, ver4, true); entry.addRemote(node1, 5, ver5, true); entry.addRemote(node2, 7, ver7, true); entry.addRemote(node2, 8, ver8, true); GridCacheMvccCandidate doomed = entry.addRemote(node2, 6, ver6, true); // No reordering happens. checkOrder(entry.remoteMvccSnapshot(), ver1, ver2, ver3, ver4, ver5, ver7, ver8, ver6); List<GridCacheVersion> committed = Arrays.asList(ver4, ver7); List<GridCacheVersion> rolledback = Arrays.asList(ver6); entry.orderCompleted(ver2, committed, rolledback); assert !entry.lockedBy(ver6); checkOrder(entry.remoteMvccSnapshot(), ver1, ver4, ver7, ver2, ver3, ver5, ver8); checkRemote(entry.candidate(ver1), ver1, false, false); checkRemote(entry.candidate(ver2), ver2, false, false); checkRemote(entry.candidate(ver3), ver3, false, false); checkRemote(entry.candidate(ver4), ver4, true, false); checkRemote(entry.candidate(ver5), ver5, false, false); checkRemote(entry.candidate(ver7), ver7, true, false); checkRemote(entry.candidate(ver8), ver8, false, false); checkRemote(doomed, ver6, false, true); } /** * */ public void testCompletedWithCompletedBaseInTheMiddle() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID node1 = UUID.randomUUID(); UUID node2 = UUID.randomUUID(); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheVersion ver5 = version(5); GridCacheVersion ver6 = version(6); GridCacheVersion ver7 = version(7); entry.addRemote(node1, 1, ver1, true); entry.addRemote(node2, 2, ver2, true); entry.addRemote(node1, 3, ver3, true); entry.addRemote(node2, 4, ver4, true); entry.addRemote(node1, 5, ver5, true); entry.addRemote(node2, 6, ver6, true); entry.addRemote(node2, 7, ver7, true); List<GridCacheVersion> committed = Arrays.asList(ver4, ver6, ver2); entry.orderCompleted(ver2, committed, Collections.<GridCacheVersion>emptyList()); checkOrder(entry.remoteMvccSnapshot(), ver1, ver4, ver6, ver2, ver3, ver5, ver7); checkRemote(entry.candidate(ver1), ver1, false, false); checkRemote(entry.candidate(ver2), ver2, true, false); checkRemote(entry.candidate(ver3), ver3, false, false); checkRemote(entry.candidate(ver4), ver4, true, false); checkRemote(entry.candidate(ver5), ver5, false, false); checkRemote(entry.candidate(ver6), ver6, true, false); checkRemote(entry.candidate(ver7), ver7, false, false); } /** * */ public void testCompletedTwiceWithBaseInTheMiddle() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID node1 = UUID.randomUUID(); UUID node2 = UUID.randomUUID(); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheVersion ver5 = version(5); GridCacheVersion ver6 = version(6); GridCacheVersion ver7 = version(7); entry.addRemote(node1, 1, ver1, true); entry.addRemote(node2, 2, ver2, true); entry.addRemote(node1, 3, ver3, true); entry.addRemote(node2, 4, ver4, true); entry.addRemote(node1, 5, ver5, true); entry.addRemote(node2, 6, ver6, true); entry.addRemote(node2, 7, ver7, true); List<GridCacheVersion> completed = Arrays.asList(ver4, ver6); entry.orderCompleted(ver2, completed, Collections.<GridCacheVersion>emptyList()); checkOrder(entry.remoteMvccSnapshot(), ver1, ver4, ver6, ver2, ver3, ver5, ver7); entry.orderCompleted(ver4, completed, Collections.<GridCacheVersion>emptyList()); checkOrder(entry.remoteMvccSnapshot(), ver1, ver6, ver4, ver2, ver3, ver5, ver7); checkRemote(entry.candidate(ver1), ver1, false, false); checkRemote(entry.candidate(ver2), ver2, false, false); checkRemote(entry.candidate(ver3), ver3, false, false); checkRemote(entry.candidate(ver4), ver4, true, false); checkRemote(entry.candidate(ver5), ver5, false, false); checkRemote(entry.candidate(ver6), ver6, true, false); checkRemote(entry.candidate(ver7), ver7, false, false); } /** * */ public void testCompletedWithBaseInTheMiddleNoChange() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID node1 = UUID.randomUUID(); UUID node2 = UUID.randomUUID(); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheVersion ver5 = version(5); GridCacheVersion ver6 = version(6); GridCacheVersion ver7 = version(7); entry.addRemote(node1, 1, ver1, false); entry.addRemote(node2, 2, ver2, false); entry.addRemote(node1, 3, ver3, false); entry.addRemote(node2, 4, ver4, false); entry.addRemote(node1, 5, ver5, false); List<GridCacheVersion> committed = Arrays.asList(ver6, ver7); entry.orderCompleted(ver4, committed, Collections.<GridCacheVersion>emptyList()); checkOrder(entry.remoteMvccSnapshot(), ver1, ver2, ver3, ver4, ver5); // Nothing set to owner since there is no change. checkRemote(entry.candidate(ver1), ver1, false, false); checkRemote(entry.candidate(ver2), ver2, false, false); checkRemote(entry.candidate(ver3), ver3, false, false); checkRemote(entry.candidate(ver4), ver4, false, false); checkRemote(entry.candidate(ver5), ver5, false, false); } /** * */ public void testCompletedWithBaseInTheBeginning() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID node1 = UUID.randomUUID(); UUID node2 = UUID.randomUUID(); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheVersion ver5 = version(5); GridCacheVersion ver6 = version(6); GridCacheVersion ver7 = version(7); entry.addRemote(node1, 1, ver1, false); entry.addRemote(node2, 2, ver2, false); entry.addRemote(node1, 3, ver3, false); entry.addRemote(node2, 4, ver4, false); entry.addRemote(node1, 5, ver5, false); entry.addRemote(node2, 6, ver6, false); entry.addRemote(node2, 7, ver7, false); List<GridCacheVersion> committed = Arrays.asList(ver4, ver6, ver3); entry.orderCompleted(ver1, committed, Collections.<GridCacheVersion>emptyList()); checkOrder(entry.remoteMvccSnapshot(), ver3, ver4, ver6, ver1, ver2, ver5, ver7); checkRemote(entry.candidate(ver1), ver1, false, false); checkRemote(entry.candidate(ver2), ver2, false, false); checkRemote(entry.candidate(ver3), ver3, true, false); checkRemote(entry.candidate(ver4), ver4, true, false); checkRemote(entry.candidate(ver5), ver5, false, false); checkRemote(entry.candidate(ver6), ver6, true, false); checkRemote(entry.candidate(ver7), ver7, false, false); } /** * This case should never happen, nevertheless we need to test for it. */ public void testCompletedWithBaseInTheBeginningNoChange() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID node1 = UUID.randomUUID(); UUID node2 = UUID.randomUUID(); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheVersion ver5 = version(5); GridCacheVersion ver6 = version(6); GridCacheVersion ver7 = version(7); entry.addRemote(node1, 1, ver1, false); entry.addRemote(node2, 2, ver2, false); entry.addRemote(node1, 3, ver3, false); entry.addRemote(node2, 4, ver4, false); entry.addRemote(node1, 5, ver5, false); List<GridCacheVersion> committed = Arrays.asList(ver6, ver7); entry.orderCompleted(ver1, committed, Collections.<GridCacheVersion>emptyList()); checkOrder(entry.remoteMvccSnapshot(), ver1, ver2, ver3, ver4, ver5); // Nothing set to owner since there is no change. checkRemote(entry.candidate(ver1), ver1, false, false); checkRemote(entry.candidate(ver2), ver2, false, false); checkRemote(entry.candidate(ver3), ver3, false, false); checkRemote(entry.candidate(ver4), ver4, false, false); checkRemote(entry.candidate(ver5), ver5, false, false); } /** * This case should never happen, nevertheless we need to test for it. */ public void testCompletedWithBaseInTheEndNoChange() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID node1 = UUID.randomUUID(); UUID node2 = UUID.randomUUID(); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheVersion ver5 = version(5); GridCacheVersion ver6 = version(6); GridCacheVersion ver7 = version(7); entry.addRemote(node1, 1, ver1, false); entry.addRemote(node2, 2, ver2, false); entry.addRemote(node1, 3, ver3, false); entry.addRemote(node2, 4, ver4, false); entry.addRemote(node1, 5, ver5, false); List<GridCacheVersion> committed = Arrays.asList(ver6, ver7); entry.orderCompleted(ver5, committed, Collections.<GridCacheVersion>emptyList()); checkOrder(entry.remoteMvccSnapshot(), ver1, ver2, ver3, ver4, ver5); // Nothing set to owner since there is no change. checkRemote(entry.candidate(ver1), ver1, false, false); checkRemote(entry.candidate(ver2), ver2, false, false); checkRemote(entry.candidate(ver3), ver3, false, false); checkRemote(entry.candidate(ver4), ver4, false, false); checkRemote(entry.candidate(ver5), ver5, false, false); } /** * */ public void testCompletedWithBaseNotPresentInTheMiddle() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID node1 = UUID.randomUUID(); UUID node2 = UUID.randomUUID(); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheVersion ver5 = version(5); GridCacheVersion ver6 = version(6); GridCacheVersion ver7 = version(7); // Don't add version 2. entry.addRemote(node1, 1, ver1, true); entry.addRemote(node1, 3, ver3, true); entry.addRemote(node2, 4, ver4, true); entry.addRemote(node1, 5, ver5, true); entry.addRemote(node2, 6, ver6, true); entry.addRemote(node2, 7, ver7, true); List<GridCacheVersion> committed = Arrays.asList(ver6, ver4); entry.orderCompleted(ver2, committed, Collections.<GridCacheVersion>emptyList()); checkOrder(entry.remoteMvccSnapshot(), ver1, ver4, ver6, ver3, ver5, ver7); checkRemote(entry.candidate(ver1), ver1, false, false); checkRemote(entry.candidate(ver3), ver3, false, false); checkRemote(entry.candidate(ver4), ver4, true, false); checkRemote(entry.candidate(ver5), ver5, false, false); checkRemote(entry.candidate(ver6), ver6, true, false); checkRemote(entry.candidate(ver7), ver7, false, false); } /** * */ public void testCompletedWithBaseNotPresentInTheMiddleNoChange() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID node1 = UUID.randomUUID(); UUID node2 = UUID.randomUUID(); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheVersion ver5 = version(5); GridCacheVersion ver6 = version(6); GridCacheVersion ver7 = version(7); // Don't add versions 2, 5, 6, 7. entry.addRemote(node1, 1, ver1, true); entry.addRemote(node1, 3, ver3, true); entry.addRemote(node2, 4, ver4, true); List<GridCacheVersion> committed = Arrays.asList(ver6, ver5, ver7); entry.orderCompleted(ver2, committed, Collections.<GridCacheVersion>emptyList()); checkOrder(entry.remoteMvccSnapshot(), ver1, ver3, ver4); checkRemote(entry.candidate(ver1), ver1, false, false); checkRemote(entry.candidate(ver3), ver3, false, false); checkRemote(entry.candidate(ver4), ver4, false, false); } /** * */ public void testCompletedWithBaseNotPresentInTheBeginning() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID node1 = UUID.randomUUID(); UUID node2 = UUID.randomUUID(); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheVersion ver5 = version(5); GridCacheVersion ver6 = version(6); GridCacheVersion ver7 = version(7); // Don't add version 1. entry.addRemote(node1, 2, ver2, true); entry.addRemote(node1, 3, ver3, true); entry.addRemote(node2, 4, ver4, true); entry.addRemote(node1, 5, ver5, true); entry.addRemote(node2, 6, ver6, true); entry.addRemote(node2, 7, ver7, true); List<GridCacheVersion> committed = Arrays.asList(ver4, ver6, ver3); entry.orderCompleted(ver1, committed, Collections.<GridCacheVersion>emptyList()); checkOrder(entry.remoteMvccSnapshot(), ver3, ver4, ver6, ver2, ver5, ver7); checkRemote(entry.candidate(ver2), ver2, false, false); checkRemote(entry.candidate(ver3), ver3, true, false); checkRemote(entry.candidate(ver4), ver4, true, false); checkRemote(entry.candidate(ver5), ver5, false, false); checkRemote(entry.candidate(ver6), ver6, true, false); checkRemote(entry.candidate(ver7), ver7, false, false); } /** * */ public void testCompletedWithBaseNotPresentInTheBeginningNoChange() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID node1 = UUID.randomUUID(); UUID node2 = UUID.randomUUID(); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheVersion ver5 = version(5); GridCacheVersion ver6 = version(6); GridCacheVersion ver7 = version(7); // Don't add version 6, 7 entry.addRemote(node1, 2, ver2, true); entry.addRemote(node1, 3, ver3, true); entry.addRemote(node2, 4, ver4, true); entry.addRemote(node1, 5, ver5, true); entry.addRemote(node1, 6, ver6, true); entry.addRemote(node1, 7, ver7, true); List<GridCacheVersion> committed = Arrays.asList(ver2, ver3); entry.orderCompleted(ver1, committed, Collections.<GridCacheVersion>emptyList()); checkOrder(entry.remoteMvccSnapshot(), ver2, ver3, ver4, ver5, ver6, ver7); checkRemote(entry.candidate(ver2), ver2, true, false); checkRemote(entry.candidate(ver3), ver3, true, false); checkRemote(entry.candidate(ver4), ver4, false, false); checkRemote(entry.candidate(ver5), ver5, false, false); checkRemote(entry.candidate(ver6), ver6, false, false); checkRemote(entry.candidate(ver7), ver7, false, false); } /** * */ public void testCompletedWithBaseNotPresentInTheEndNoChange() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID node1 = UUID.randomUUID(); UUID node2 = UUID.randomUUID(); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheVersion ver5 = version(5); GridCacheVersion ver6 = version(6); GridCacheVersion ver7 = version(7); // Don't add version 5, 6, 7 entry.addRemote(node1, 1, ver1, true); entry.addRemote(node1, 2, ver2, true); entry.addRemote(node1, 3, ver3, true); entry.addRemote(node2, 4, ver4, true); List<GridCacheVersion> committed = Arrays.asList(ver6, ver7); entry.orderCompleted(ver5, committed, Collections.<GridCacheVersion>emptyList()); checkOrder(entry.remoteMvccSnapshot(), ver1, ver2, ver3, ver4); checkRemote(entry.candidate(ver1), ver1, false, false); checkRemote(entry.candidate(ver2), ver2, false, false); checkRemote(entry.candidate(ver3), ver3, false, false); checkRemote(entry.candidate(ver4), ver4, false, false); } /** * Test local and remote candidates together. */ public void testLocalAndRemote() { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); UUID node1 = UUID.randomUUID(); UUID node2 = UUID.randomUUID(); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheVersion ver5 = version(5); entry.addRemote(node1, 1, ver1, false); entry.addLocal(2, ver2, 0, true, true); Collection<GridCacheMvccCandidate> cands = entry.remoteMvccSnapshot(); assert cands.size() == 1; assert cands.iterator().next().version().equals(ver1); entry.addRemote(node2, 5, ver5, false); cands = entry.remoteMvccSnapshot(); assert cands.size() == 2; info(cands); checkOrder(cands, ver1, ver5); checkOrder(entry.localCandidates(true), ver2); entry.addRemote(node1, 3, ver3, true); entry.addLocal(4, ver4, 0, /*reenter*/true, false); cands = entry.remoteMvccSnapshot(); assert cands.size() == 3; // Check order. checkOrder(entry.remoteMvccSnapshot(), ver1, ver5, ver3); checkOrder(entry.localCandidates(), ver2, ver4); entry.orderCompleted( ver2 /*local version.*/, Arrays.asList(new GridCacheVersion(1, 1, 2, 0), ver3, new GridCacheVersion(1, 5, 6, 0)), Collections.<GridCacheVersion>emptyList() ); // Done ver3. checkOrder(entry.remoteMvccSnapshot(), ver1, ver3, ver5); checkOrder(entry.localCandidates(), ver2, ver4); checkRemote(entry.candidate(ver1), ver1, false, false); checkRemote(entry.candidate(ver3), ver3, true, false); checkRemote(entry.candidate(ver5), ver5, false, false); checkLocal(entry.candidate(ver2), ver2, false, false, false); checkLocal(entry.candidate(ver4), ver4, false, false, false); entry.readyLocal(ver2); checkLocal(entry.candidate(ver2), ver2, true, false, false); checkLocal(entry.candidate(ver4), ver4, false, false, false); assert entry.anyOwner() == null; entry.doneRemote(ver1); checkRemoteOwner(entry.anyOwner(), ver1); entry.removeLock(ver1); checkOrder(entry.remoteMvccSnapshot(), ver3, ver5); assert entry.anyOwner() == null; entry.doneRemote(ver3); checkRemoteOwner(entry.anyOwner(), ver3); entry.removeLock(ver3); checkLocalOwner(entry.anyOwner(), ver2, false); entry.removeLock(ver2); assert !entry.lockedByAny(ver4, ver5); checkOrder(entry.remoteMvccSnapshot(), ver5); checkOrder(entry.localCandidates(), ver4); assert entry.anyOwner() == null; entry.readyLocal(ver4); checkLocalOwner(entry.anyOwner(), ver4, false); entry.removeLock(ver4); assert entry.anyOwner() == null; GridCacheMvccCandidate c5 = entry.candidate(ver5); assert c5 != null; c5.setOwner(); assert entry.anyOwner() == null; entry.doneRemote(ver5); checkRemoteOwner(entry.anyOwner(), ver5); assert !entry.lockedByAny(ver5); entry.removeLock(ver5); assert !entry.lockedByAny(); assert entry.anyOwner() == null; } /** * @throws Exception If test failed. */ public void testMultipleLocalAndRemoteLocks1() throws Exception { UUID nodeId = UUID.randomUUID(); GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheContext<String, String> ctx = cache.context(); GridCacheTestEntryEx entry1 = new GridCacheTestEntryEx(ctx, "1"); GridCacheTestEntryEx entry2 = new GridCacheTestEntryEx(ctx, "2"); GridCacheTestEntryEx entry3 = new GridCacheTestEntryEx(ctx, "3"); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheMvccCandidate c13 = entry1.addLocal(1, ver3, 0, true, false); entry1.readyLocal(ver3); checkLocalOwner(entry1.candidate(ver3), ver3, false); GridCacheMvccCandidate c11 = entry1.addLocal(2, ver1, 0, true, true); GridCacheMvccCandidate c21 = entry2.addLocal(2, ver1, 0, true, true); GridCacheMvccCandidate c31 = entry3.addLocal(2, ver1, 0, true, true); GridCacheMvccCandidate c33 = entry3.addLocal(1, ver3, 0, true, false); linkCandidates(ctx, c11, c21, c31); entry1.readyLocal(ver1); entry2.readyLocal(ver1); entry3.readyLocal(ver1); checkLocal(entry1.candidate(ver1), ver1, true, false, false); checkLocal(entry2.candidate(ver1), ver1, true, false, false); checkLocal(entry3.candidate(ver1), ver1, true, false, false); checkLocal(entry3.candidate(ver3), ver3, false, false, false); linkCandidates(ctx, c13, c33); entry2.addRemote(nodeId, 3, ver2, true); checkLocal(entry2.candidate(ver1), ver1, true, false, false); entry3.addRemote(nodeId, 3, ver2, false); entry3.readyLocal(ver3); checkLocal(entry1.candidate(ver3), ver3, true, true, false); checkLocal(entry3.candidate(ver3), ver3, true, true, false); checkLocal(entry1.candidate(ver1), ver1, true, false, false); checkLocal(entry2.candidate(ver1), ver1, true, false, false); checkLocal(entry3.candidate(ver1), ver1, true, false, false); entry1.releaseLocal(1); entry2.recheckLock(); checkLocal(entry1.candidate(ver1), ver1, true, true, false); checkLocal(entry2.candidate(ver1), ver1, true, true, false); checkLocal(entry3.candidate(ver1), ver1, true, false, false); entry3.releaseLocal(1); checkLocal(entry1.candidate(ver1), ver1, true, true, false); checkLocal(entry2.candidate(ver1), ver1, true, true, false); checkLocal(entry3.candidate(ver1), ver1, true, true, false); } /** * @throws Exception If test failed. */ public void testMultipleLocalAndRemoteLocks2() throws Exception { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheContext<String, String> ctx = cache.context(); GridCacheTestEntryEx entry1 = new GridCacheTestEntryEx(ctx, "1"); GridCacheTestEntryEx entry2 = new GridCacheTestEntryEx(ctx, "2"); GridCacheTestEntryEx entry3 = new GridCacheTestEntryEx(ctx, "3"); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheMvccCandidate c13 = entry1.addLocal(1, ver3, 0, true, true); entry1.readyLocal(ver3); checkLocalOwner(entry1.candidate(ver3), ver3, false); GridCacheMvccCandidate c11 = entry1.addLocal(2, ver2, 0, true, false); GridCacheMvccCandidate c21 = entry2.addLocal(2, ver2, 0, true, false); GridCacheMvccCandidate c31 = entry3.addLocal(2, ver2, 0, true, false); GridCacheMvccCandidate c33 = entry3.addLocal(1, ver3, 0, true, true); linkCandidates(ctx, c11, c21, c31); entry1.readyLocal(ver2); entry2.readyLocal(ver2); entry3.readyLocal(ver2); checkLocal(entry1.candidate(ver2), ver2, true, false, false); checkLocal(entry2.candidate(ver2), ver2, true, false, false); checkLocal(entry3.candidate(ver2), ver2, true, false, false); checkLocal(entry3.candidate(ver3), ver3, false, false, false); linkCandidates(ctx, c13, c33); entry2.addRemote(UUID.randomUUID(), 3, ver1, true); checkLocal(entry2.candidate(ver2), ver2, true, false, false); entry3.addRemote(UUID.randomUUID(), 3, ver1, true); entry3.readyLocal(ver3); checkLocal(entry1.candidate(ver3), ver3, true, true, false); checkLocal(entry3.candidate(ver3), ver3, true, false, false); checkLocal(entry1.candidate(ver2), ver2, true, false, false); checkLocal(entry2.candidate(ver2), ver2, true, false, false); checkLocal(entry3.candidate(ver2), ver2, true, false, false); entry2.removeLock(ver1); checkLocal(entry1.candidate(ver3), ver3, true, true, false); checkLocal(entry3.candidate(ver3), ver3, true, false, false); checkLocal(entry1.candidate(ver2), ver2, true, false, false); checkLocal(entry2.candidate(ver2), ver2, true, false, false); checkLocal(entry3.candidate(ver2), ver2, true, false, false); entry3.removeLock(ver1); checkLocal(entry1.candidate(ver3), ver3, true, true, false); checkLocal(entry3.candidate(ver3), ver3, true, true, false); checkLocal(entry1.candidate(ver2), ver2, true, false, false); checkLocal(entry2.candidate(ver2), ver2, true, false, false); checkLocal(entry3.candidate(ver2), ver2, true, false, false); entry1.releaseLocal(1); entry2.recheckLock(); checkLocal(entry1.candidate(ver2), ver2, true, true, false); checkLocal(entry2.candidate(ver2), ver2, true, true, false); checkLocal(entry3.candidate(ver2), ver2, true, false, false); entry3.releaseLocal(1); checkLocal(entry1.candidate(ver2), ver2, true, true, false); checkLocal(entry2.candidate(ver2), ver2, true, true, false); checkLocal(entry3.candidate(ver2), ver2, true, true, false); } /** * @throws Exception If test failed. */ public void testMultipleLocalLocks() throws Exception { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheContext<String, String> ctx = cache.context(); GridCacheTestEntryEx entry1 = new GridCacheTestEntryEx(ctx, "1"); GridCacheTestEntryEx entry2 = new GridCacheTestEntryEx(ctx, "2"); GridCacheVersion ver1 = version(1); GridCacheVersion ver3 = version(3); GridCacheMvccCandidate c13 = entry1.addLocal(1, ver3, 0, true, false); entry1.readyLocal(ver3); checkLocalOwner(entry1.candidate(ver3), ver3, false); GridCacheMvccCandidate c11 = entry1.addLocal(2, ver1, 0, true, true); GridCacheMvccCandidate c21 = entry2.addLocal(2, ver1, 0, true, false); linkCandidates(ctx, c11, c21); entry1.readyLocal(ver1); entry2.readyLocal(ver1); checkLocal(entry1.candidate(ver1), ver1, true, false, false); checkLocal(entry2.candidate(ver1), ver1, true, false, false); GridCacheMvccCandidate c23 = entry2.addLocal(1, ver3, 0, true, true); linkCandidates(ctx, c13, c23); entry2.readyLocal(ver3); checkLocalOwner(entry2.candidate(ver3), ver3, false); } /** * @throws Exception If failed. */ @SuppressWarnings({"ObjectEquality"}) public void testUsedCandidates() throws Exception { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheContext<String, String> ctx = cache.context(); GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1"); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); GridCacheVersion ver4 = version(4); GridCacheMvccCandidate c1 = entry.addLocal(1, ver1, 0, true, false); ctx.mvcc().addNext(ctx, c1); ctx.mvcc().contextReset(); GridCacheMvccCandidate c2 = entry.addLocal(2, ver2, 0, true, false); ctx.mvcc().addNext(ctx, c2); ctx.mvcc().contextReset(); GridCacheMvccCandidate c3 = entry.addLocal(3, ver3, 0, true, true); ctx.mvcc().addNext(ctx, c3); ctx.mvcc().contextReset(); checkLocal(entry.candidate(ver1), ver1, false, false, false); checkLocal(entry.candidate(ver2), ver2, false, false, false); checkLocal(entry.candidate(ver3), ver3, false, false, false); entry.readyLocal(ver1); entry.readyLocal(ver3); checkLocal(entry.candidate(ver1), ver1, true, true, false); checkLocal(entry.candidate(ver2), ver2, false, false, false); checkLocal(entry.candidate(ver3), ver3, true, false, false); entry.removeLock(ver2); assert c3 != null; assert c2 != null; checkLocal(c2, ver2, false, false, false, true); checkLocal(entry.candidate(ver1), ver1, true, true, false); checkLocal(entry.candidate(ver3), ver3, true, false, false); entry.removeLock(ver1); checkLocal(entry.candidate(ver3), ver3, true, true, false); GridCacheMvccCandidate c4 = entry.addLocal(4, ver4, 0, true, true); ctx.mvcc().addNext(ctx, c4); assert c4 != null; } /** * Test 2 keys with candidates in reverse order. */ public void testReverseOrder1() { UUID id = UUID.randomUUID(); GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheContext<String, String> ctx = cache.context(); GridCacheTestEntryEx entry1 = new GridCacheTestEntryEx(cache.context(), "1"); GridCacheTestEntryEx entry2 = new GridCacheTestEntryEx(cache.context(), "2"); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheMvccCandidate c1k1 = entry1.addLocal(2, ver2, 0, true, false); // Link up. ctx.mvcc().addNext(ctx, c1k1); entry1.readyLocal(ver2); checkLocal(c1k1, ver2, true, true, false); GridCacheMvccCandidate c2k1 = entry1.addRemote(id, 2, ver1, true); // Force recheck of assignments. entry1.recheckLock(); checkLocal(c1k1, ver2, true, true, false); checkRemote(c2k1, ver1, false, false); GridCacheMvccCandidate c1k2 = entry2.addLocal(2, ver2, 0, true, false); assert c1k2 != null; ctx.mvcc().addNext(ctx, c1k2); assert c1k2.previous() == c1k1; GridCacheMvccCandidate c2k2 = entry2.addRemote(id, 3, ver1, true); entry2.readyLocal(c1k2); // Local entry2 should become owner, because otherwise remote will be stuck, waiting // for local entry1, which in turn awaits for local entry2. checkLocal(c1k2, ver2, true, true, false); checkRemote(c2k2, ver1, false, false); } /** * Test 2 keys with candidates in reverse order. * * @throws Exception If failed. */ public void testReverseOrder2() throws Exception { UUID id = UUID.randomUUID(); GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheContext<String, String> ctx = cache.context(); GridCacheTestEntryEx entry1 = new GridCacheTestEntryEx(ctx, "1"); GridCacheTestEntryEx entry2 = new GridCacheTestEntryEx(ctx, "2"); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); // Local with higher version. GridCacheMvccCandidate v3k1 = entry1.addLocal(3, ver3, 0, true, true); GridCacheMvccCandidate v3k2 = entry2.addLocal(3, ver3, 0, true, true); // Link up. linkCandidates(ctx, v3k1, v3k2); entry1.readyLocal(v3k1); checkLocal(v3k1, ver3, true, true, false); checkLocal(v3k2, ver3, false, false, false); // Remote locks. GridCacheMvccCandidate v2k1 = entry1.addRemote(id, 3, ver2, false); GridCacheMvccCandidate v2k2 = entry2.addRemote(id, 3, ver2, false); checkRemote(v2k1, ver2, false, false); checkRemote(v2k2, ver2, false, false); // Local with lower version. GridCacheMvccCandidate v1k1 = entry1.addLocal(4, ver1, 0, true, true); GridCacheMvccCandidate v1k2 = entry2.addLocal(4, ver1, 0, true, true); // Link up. linkCandidates(ctx, v1k1, v1k2); entry1.readyLocal(v1k1); entry2.readyLocal(v1k2); checkLocal(v1k1, ver1, true, false, false); checkLocal(v1k2, ver1, true, false, false); checkLocal(v3k2, ver3, false, false, false); entry2.readyLocal(v3k2); // Note, ver3 should be acquired before ver1 (i.e. in reverse order from natural versions order). checkLocal(v3k2, ver3, true, true, false); checkLocal(v1k1, ver1, true, false, false); checkLocal(v1k2, ver1, true, false, false); } /** * Tests local-only locks in reverse order. * * @throws Exception If failed. */ public void testReverseOrder3() throws Exception { GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheContext<String, String> ctx = cache.context(); GridCacheTestEntryEx entry1 = new GridCacheTestEntryEx(ctx, "1"); GridCacheTestEntryEx entry2 = new GridCacheTestEntryEx(ctx, "2"); GridCacheVersion ver1 = version(1); GridCacheVersion ver3 = version(3); // Local with higher version. GridCacheMvccCandidate v3k1 = entry1.addLocal(3, ver3, 0, true, false); GridCacheMvccCandidate v3k2 = entry2.addLocal(3, ver3, 0, true, false); linkCandidates(ctx, v3k1, v3k2); entry1.readyLocal(ver3); checkLocal(v3k1, ver3, true, true, false); checkLocal(v3k2, ver3, false, false, false); GridCacheMvccCandidate v1k1 = entry1.addLocal(4, ver1, 0, true, true); GridCacheMvccCandidate v1k2 = entry2.addLocal(4, ver1, 0, true, true); // Link up. linkCandidates(ctx, v1k1, v1k2); entry1.readyLocal(ver1); entry2.readyLocal(ver1); checkLocal(v3k1, ver3, true, true, false); // Owner. checkLocal(v3k2, ver3, false, false, false); checkLocal(v1k1, ver1, true, false, false); checkLocal(v1k2, ver1, true, false, false); entry2.readyLocal(v3k2); checkLocal(v3k1, ver3, true, true, false); checkLocal(v3k2, ver3, true, true, false); } /** * Tests local candidates with remote version in the middle on key2. * * @throws Exception If failed. */ public void testReverseOrder4() throws Exception { UUID id = UUID.randomUUID(); GridCacheAdapter<String, String> cache = grid.internalCache(); GridCacheContext<String, String> ctx = cache.context(); GridCacheTestEntryEx entry1 = new GridCacheTestEntryEx(ctx, "1"); GridCacheTestEntryEx entry2 = new GridCacheTestEntryEx(ctx, "2"); GridCacheVersion ver1 = version(1); GridCacheVersion ver2 = version(2); GridCacheVersion ver3 = version(3); // Local with higher version. GridCacheMvccCandidate v3k1 = entry1.addLocal(3, ver3, 0, true, false); GridCacheMvccCandidate v3k2 = entry2.addLocal(3, ver3, 0, true, false); linkCandidates(ctx, v3k1, v3k2); entry1.readyLocal(ver3); checkLocal(v3k1, ver3, true, true, false); checkLocal(v3k2, ver3, false, false, false); GridCacheMvccCandidate v1k1 = entry1.addLocal(4, ver1, 0, true, true); GridCacheMvccCandidate v1k2 = entry2.addLocal(4, ver1, 0, true, true); // Link up. linkCandidates(ctx, v1k1, v1k2); entry1.readyLocal(ver1); entry2.readyLocal(ver1); checkLocal(v3k1, ver3, true, true, false); // Owner. checkLocal(v3k2, ver3, false, false, false); checkLocal(v1k1, ver1, true, false, false); checkLocal(v1k2, ver1, true, false, false); GridCacheMvccCandidate v2k2 = entry2.addRemote(id, 5, ver2, false); checkRemote(v2k2, ver2, false, false); entry2.readyLocal(v3k2); checkLocal(v3k1, ver3, true, true, false); checkLocal(v3k2, ver3, true, true, false); } /** * Gets version based on order. * * @param order Order. * @return Version. */ private GridCacheVersion version(int order) { return new GridCacheVersion(1, order, order, 0); } /** * Links candidates. * * @param ctx Cache context. * @param cands Candidates. * @throws Exception If failed. */ private void linkCandidates(final GridCacheContext<String, String> ctx, final GridCacheMvccCandidate... cands) throws Exception { multithreaded(new Runnable() { @Override public void run() { for (GridCacheMvccCandidate cand : cands) { boolean b = grid.<String, String>internalCache().context().mvcc().addNext(ctx, cand); assert b; } info("Link thread finished."); } }, 1); } /** * Check order in collection. * * @param cands Candidates to check order for. * @param vers Ordered versions. */ private void checkOrder(Collection<GridCacheMvccCandidate> cands, GridCacheVersion... vers) { assertEquals(vers.length, cands.size()); int i = 0; for (GridCacheMvccCandidate cand : cands) { assert cand.version().equals(vers[i]) : "Invalid order of candidates [cands=" + toString(cands) + ", order=" + toString(vers) + ']'; i++; } } /** * @param objs Object to print. * @return String representation. */ private String toString(Iterable<?> objs) { String eol = System.getProperty("line.separator"); StringBuilder buf = new StringBuilder(eol); for (Object obj : objs) buf.append(obj.toString()).append(eol); return buf.toString(); } /** * @param objs Object to print. * @return String representation. */ private String toString(Object[] objs) { String eol = System.getProperty("line.separator"); StringBuilder buf = new StringBuilder(eol); for (Object obj : objs) buf.append(obj.toString()).append(eol); return buf.toString(); } /** * Checks flags on done candidate. * * @param cand Candidate to check. */ private void checkDone(GridCacheMvccCandidate cand) { assert cand != null; info("Done candidate: " + cand); assert cand.used(); assert cand.owner(); assert !cand.ready(); assert !cand.reentry(); assert !cand.local(); } /** * @param cand Candidate to check. * @param ver Version. * @param owner Owner flag. * @param used Done flag. */ private void checkRemote(GridCacheMvccCandidate cand, GridCacheVersion ver, boolean owner, boolean used) { assert cand != null; info("Done candidate: " + cand); assert cand.version().equals(ver); // Check flags. assert cand.used() == used; assert cand.owner() == owner; assert !cand.ready(); assert !cand.reentry(); assert !cand.local(); } /** * Checks flags on remote owner candidate. * * @param cand Candidate to check. * @param ver Version. */ private void checkRemoteOwner(GridCacheMvccCandidate cand, GridCacheVersion ver) { assert cand != null; info("Done candidate: " + cand); assert cand.version().equals(ver); // Check flags. assert cand.used(); assert cand.owner(); assert !cand.ready(); assert !cand.reentry(); assert !cand.local(); } /** * Checks flags on local candidate. * * @param cand Candidate to check. * @param ver Cache version. * @param ready Ready flag. * @param owner Lock owner. * @param reentry Reentry flag. */ private void checkLocal(GridCacheMvccCandidate cand, GridCacheVersion ver, boolean ready, boolean owner, boolean reentry) { assert cand != null; info("Done candidate: " + cand); assert cand.version().equals(ver); // Check flags. assert cand.ready() == ready; assert cand.owner() == owner; assert cand.reentry() == reentry; assert !cand.used(); assert cand.local(); } /** * Checks flags on local candidate. * * @param cand Candidate to check. * @param ver Cache version. * @param ready Ready flag. * @param owner Lock owner. * @param reentry Reentry flag. * @param used Used flag. */ private void checkLocal(GridCacheMvccCandidate cand, GridCacheVersion ver, boolean ready, boolean owner, boolean reentry, boolean used) { assert cand != null; info("Done candidate: " + cand); assert cand.version().equals(ver); // Check flags. assert cand.ready() == ready; assert cand.owner() == owner; assert cand.reentry() == reentry; assert cand.used() == used; assert cand.local(); } /** * Checks flags on local owner candidate. * * @param cand Candidate to check. * @param ver Cache version. * @param reentry Reentry flag. */ private void checkLocalOwner(GridCacheMvccCandidate cand, GridCacheVersion ver, boolean reentry) { assert cand != null; info("Done candidate: " + cand); assert cand.version().equals(ver); // Check flags. assert cand.reentry() == reentry; assert !cand.used(); assert cand.ready(); assert cand.owner(); assert cand.local(); } /** * @param cands Candidates to print. */ private void info(Iterable<GridCacheMvccCandidate> cands) { info("Collection of candidates: "); for (GridCacheMvccCandidate c : cands) info(">>> " + c); } }
package com.hs.mail.webmail.util; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Hashtable; import java.util.Map; import java.util.StringTokenizer; import javax.mail.FetchProfile; import javax.mail.Flags; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Part; import javax.mail.internet.MailDateFormat; import javax.mail.internet.MimeUtility; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.FastDateFormat; import com.hs.mail.webmail.exception.WmaException; import com.sun.mail.imap.IMAPFolder; public class WmaUtils { private static final String ISO_8859_1 = "ISO-8859-1"; public static final FastDateFormat DEFAULT_DATETIME_FORMAT = FastDateFormat .getInstance("yyyy-MM-dd HH:mm:ss"); public static final FastDateFormat SIMPLE_DATE_FORMAT = FastDateFormat .getInstance("yyyyMMddHHmm"); private WmaUtils() { } public static String formatDate(Date date) { return DEFAULT_DATETIME_FORMAT.format(date); } public static Date parseDate(String str, String pattern) throws WmaException { DateFormat fmt = new SimpleDateFormat(pattern); try { return fmt.parse(str); } catch (ParseException pe) { // warn to user throw new WmaException("jwma.date.format"); } } public static boolean isHangul(String text) { char[] ach = text.toCharArray(); for (int i = 0; i < ach.length; i++) { if (ach[i] >= '\uAC00' && ach[i] <= '\uD7A3') // hangul return true; } return false; } private static String getEncoding(String text) throws UnsupportedEncodingException { String[] preferred = { "ISO-8859-1", "EUC-KR", "KSC5601" }; for (int i = 0; i < preferred.length; i++) { if (isHangul(new String(text.getBytes(preferred[i])))) { return preferred[i]; } } return ISO_8859_1; } private static String fixEncoding(String str) { // IBM-eucKR is database codeset of "euc-kr" if (str.indexOf("IBM-euc") > 0) return str.replaceAll("IBM-euc", "euc-"); if (str.indexOf("ks_c_5601-1987") > 0) return str.replaceAll("ks_c_5601-1987", "euc-kr"); if (str.indexOf("ks_c_5601") > 0) return str.replaceAll("ks_c_5601", "euc-kr"); if (str.indexOf("iso-2022-kr") > 0) return str.replaceAll("iso-2022-kr", "euc-kr"); if (str.indexOf("?==?") > 0) return StringUtils.replaceOnce(str, "?==?", "?= =?"); return str; } /** * Method that prepares the given <tt>String</tt> by decoding it through the * <tt>MimeUtility</tt> and encoding it through the <tt>EntitiyHandler</tt>. */ public static String prepareString(String str) throws Exception { if (null == str) { return ""; } else { try { int i = -1; if ((i = str.indexOf("=?")) > -1) { return MimeUtility .decodeText(fixEncoding(str.substring(i))); } else { return new String(str.getBytes(getEncoding(str))); } } catch (UnsupportedEncodingException skip) { // ignore } return str; } } public static String getHeader(Part p, String name) throws MessagingException { String[] headers = p.getHeader(name); return (headers != null) ? headers[0] : null; } public static String getHeader(Part p, String name, String defaultValue) { try { return getHeader(p, name); } catch (MessagingException e) { return defaultValue; } } public static Date getReceivedDate(Message msg) { try { Date d = msg.getReceivedDate(); if (null == d) { String[] s = msg.getHeader("Received"); if (null == s) { if ((s = msg.getHeader("Date")) == null) { return null; } } // RFC 2822 - Internet Message Format // received = "Received:" name-val-list ";" date-time CRLF StringTokenizer st = new StringTokenizer(s[0], "\n"); while (st.hasMoreTokens()) { s[0] = st.nextToken(); } s[0] = s[0].substring(s[0].indexOf(";") + 1).trim(); MailDateFormat mdf = new MailDateFormat(); d = mdf.parse(s[0]); } return d; } catch (ParseException e) { return null; } catch (MessagingException mes) { return null; } } public static int getPriority(Message msg) { try { String p = getHeader(msg, "X-Priority"); if (p != null) return Integer.parseInt(p.substring(0, 1)); } catch (Exception e) { } return 3; // 3 (Normal) } public static Flags getFlags(String flag) { return (Flags) flagMap.get(flag); } public static FetchProfile getFetchProfile() { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); // contains the headers fp.add(FetchProfile.Item.FLAGS); // contains the flags fp.add(FetchProfile.Item.CONTENT_INFO); // contains the content types // fetch header values fp.add("Subject"); fp.add("Received"); fp.add("X-Priority"); fp.add("X-Secure"); return fp; } public static Message[] getMessagesByUID(IMAPFolder f, long[] uids, int mod) throws MessagingException { int len = uids.length; if (len < mod) { return f.getMessagesByUID(uids); } Message[] msgs = new Message[len]; long[] utmp = new long[mod]; int sz = len / mod; for (int i = 0; i < sz; i++) { System.arraycopy(uids, i * mod, utmp, 0, mod); Message[] temp = f.getMessagesByUID(utmp); System.arraycopy(temp, 0, msgs, i * mod, mod); } int rest = len % mod; if (rest > 0) { utmp = new long[rest]; System.arraycopy(uids, sz * mod, utmp, 0, rest); Message[] temp = f.getMessagesByUID(utmp); System.arraycopy(temp, 0, msgs, sz * mod, rest); } return msgs; } static private Map<String, Flags> flagMap = new Hashtable<String, Flags>(); // declare supported message flags static { flagMap.put("answered", new Flags(Flags.Flag.ANSWERED)); flagMap.put("deleted", new Flags(Flags.Flag.DELETED)); flagMap.put("draft", new Flags(Flags.Flag.DRAFT)); flagMap.put("flagged", new Flags(Flags.Flag.FLAGGED)); flagMap.put("recent", new Flags(Flags.Flag.RECENT)); flagMap.put("seen", new Flags(Flags.Flag.SEEN)); } }
package org.kie.server.controller.client; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.jboss.resteasy.client.ClientExecutor; import org.jboss.resteasy.client.ClientRequest; import org.jboss.resteasy.client.ClientResponse; import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor; import org.jboss.resteasy.spi.ReaderException; import org.kie.server.api.marshalling.Marshaller; import org.kie.server.api.marshalling.MarshallerFactory; import org.kie.server.api.marshalling.MarshallingException; import org.kie.server.api.marshalling.MarshallingFormat; import org.kie.server.api.model.KieContainerResource; import org.kie.server.controller.api.model.KieServerInstance; import org.kie.server.controller.api.model.KieServerInstanceInfo; import org.kie.server.controller.api.model.KieServerInstanceList; import org.kie.server.controller.api.model.KieServerSetup; import org.kie.server.controller.api.model.KieServerStatus; import org.kie.server.controller.api.model.runtime.Container; import org.kie.server.controller.api.model.runtime.ContainerKey; import org.kie.server.controller.api.model.runtime.ServerInstance; import org.kie.server.controller.api.model.runtime.ServerInstanceKey; import org.kie.server.controller.api.model.spec.Capability; import org.kie.server.controller.api.model.spec.ContainerConfig; import org.kie.server.controller.api.model.spec.ContainerSpec; import org.kie.server.controller.api.model.spec.ContainerSpecKey; import org.kie.server.controller.api.model.spec.ContainerSpecList; import org.kie.server.controller.api.model.spec.ProcessConfig; import org.kie.server.controller.api.model.spec.RuleConfig; import org.kie.server.controller.api.model.spec.ServerConfig; import org.kie.server.controller.api.model.spec.ServerTemplate; import org.kie.server.controller.api.model.spec.ServerTemplateKey; import org.kie.server.controller.api.model.spec.ServerTemplateList; import org.kie.server.controller.client.exception.UnexpectedResponseCodeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KieServerMgmtControllerClient { private static Logger logger = LoggerFactory.getLogger(KieServerMgmtControllerClient.class); private static final String MANAGEMENT_LAST_URI_PART = "/management/servers"; private static final String CONTAINERS_LAST_URI_PART = "/containers"; private static final String MANAGEMENT_URI_PART = MANAGEMENT_LAST_URI_PART + "/"; private static final String CONTAINERS_URI_PART = CONTAINERS_LAST_URI_PART + "/"; private static final String STARTED_STATUS_URI_PART = "/status/started"; private static final String STOPPED_STATUS_URI_PART = "/status/stopped"; private static final String CONFIG_URI_PART = "/config/"; private ClientExecutor executor; private String controllerBaseUrl; private MarshallingFormat format = MarshallingFormat.JAXB; private CloseableHttpClient httpClient; protected Marshaller marshaller; public KieServerMgmtControllerClient(String controllerBaseUrl, String login, String password) { URL url; try { url = new URL(controllerBaseUrl); } catch (MalformedURLException e) { throw new RuntimeException("Malformed controller URL was specified: '" + controllerBaseUrl + "'!", e); } this.controllerBaseUrl = controllerBaseUrl; HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); if (login != null) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(login, password)); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } this.httpClient = httpClientBuilder.build(); this.executor = new ApacheHttpClient4Executor(httpClient); } public ServerTemplate getServerTemplate(String serverTemplateId) { return makeGetRequestAndCreateCustomResponse(controllerBaseUrl + MANAGEMENT_URI_PART + serverTemplateId, ServerTemplate.class); } public void saveContainerSpec(String serverTemplateId, ContainerSpec containerSpec ) { makePutRequestAndCreateCustomResponse(controllerBaseUrl + MANAGEMENT_URI_PART + serverTemplateId + CONTAINERS_URI_PART +containerSpec.getId(), containerSpec, Object.class); } public void saveServerTemplate(ServerTemplate serverTemplate) { makePutRequestAndCreateCustomResponse(controllerBaseUrl + MANAGEMENT_URI_PART + serverTemplate.getId(), serverTemplate, Object.class); } public void deleteServerTemplate(String serverTemplateId) { makeDeleteRequest(controllerBaseUrl + MANAGEMENT_URI_PART + serverTemplateId); } public ContainerSpec getContainerInfo(String serverTemplateId, String containerId) { return makeGetRequestAndCreateCustomResponse(controllerBaseUrl + MANAGEMENT_URI_PART + serverTemplateId + CONTAINERS_URI_PART + containerId, ContainerSpec.class); } public void deleteContainerSpec(String serverTemplateId, String containerId) { makeDeleteRequest(controllerBaseUrl + MANAGEMENT_URI_PART + serverTemplateId + CONTAINERS_URI_PART + containerId); } public Collection<ServerTemplate> listServerTemplates() { ServerTemplateList serverTemplateList = makeGetRequestAndCreateCustomResponse(controllerBaseUrl + MANAGEMENT_LAST_URI_PART, ServerTemplateList.class); if (serverTemplateList != null && serverTemplateList.getServerTemplates() != null) { return Arrays.asList(serverTemplateList.getServerTemplates()); } return Collections.emptyList(); } public Collection<ContainerSpec> listContainerSpec(String serverTemplateId) { ContainerSpecList containerSpecList = makeGetRequestAndCreateCustomResponse(controllerBaseUrl + MANAGEMENT_URI_PART + serverTemplateId + CONTAINERS_LAST_URI_PART, ContainerSpecList.class); if (containerSpecList != null && containerSpecList.getContainerSpecs() != null) { return Arrays.asList(containerSpecList.getContainerSpecs()); } return Collections.emptyList(); } public void startContainer(String serverTemplateId, String containerId) { makePostRequestAndCreateCustomResponse(controllerBaseUrl + MANAGEMENT_URI_PART + serverTemplateId + CONTAINERS_URI_PART + containerId + STARTED_STATUS_URI_PART, "", null); } public void stopContainer(String serverTemplateId, String containerId) { makePostRequestAndCreateCustomResponse(controllerBaseUrl + MANAGEMENT_URI_PART + serverTemplateId + CONTAINERS_URI_PART + containerId + STOPPED_STATUS_URI_PART, "", null); } public void updateContainerConfig(String serverTemplateId, String containerId, Capability capability, ContainerConfig config) { makePostRequestAndCreateCustomResponse(controllerBaseUrl + MANAGEMENT_URI_PART + serverTemplateId + CONTAINERS_URI_PART + containerId + CONFIG_URI_PART + capability.toString(), config, Object.class); } private <T> T makeGetRequestAndCreateCustomResponse(String uri, Class<T> resultType) { ClientRequest clientRequest = new ClientRequest(uri, executor); ClientResponse<T> response; try { response = clientRequest.accept(getMediaType(format)).get(resultType); } catch (Exception e) { throw createExceptionForUnexpectedFailure(clientRequest, e); } if ( response.getStatus() == Response.Status.OK.getStatusCode() ) { return deserialize(response, resultType); } else { throw createExceptionForUnexpectedResponseCode( clientRequest, response ); } } private void makeDeleteRequest(String uri) { ClientRequest clientRequest = new ClientRequest(uri, executor); ClientResponse<?> response; try { response = clientRequest.accept(getMediaType(format)).delete(); response.releaseConnection(); } catch (Exception e) { throw createExceptionForUnexpectedFailure(clientRequest, e); } if ( response.getStatus() != Response.Status.NO_CONTENT.getStatusCode() ) { throw createExceptionForUnexpectedResponseCode( clientRequest, response ); } } private <T> T makePutRequestAndCreateCustomResponse(String uri, Object bodyObject, Class<T> resultType) { ClientRequest clientRequest = new ClientRequest(uri, executor); ClientResponse<T> response; try { response = clientRequest.accept(getMediaType(format)) .body(getMediaType(format), serialize(bodyObject)).put(resultType); } catch (Exception e) { throw createExceptionForUnexpectedFailure(clientRequest, e); } if ( response.getStatus() == Response.Status.CREATED.getStatusCode() ) { return deserialize(response, resultType); } else { throw createExceptionForUnexpectedResponseCode( clientRequest, response ); } } private <T> T makePostRequestAndCreateCustomResponse(String uri, Object bodyObject, Class<T> resultType) { ClientRequest clientRequest = new ClientRequest(uri, executor); ClientResponse<T> response; try { response = clientRequest.accept(getMediaType(format)) .body(getMediaType(format), serialize(bodyObject)).post(resultType); } catch (Exception e) { throw createExceptionForUnexpectedFailure(clientRequest, e); } if ( response.getStatus() == Response.Status.CREATED.getStatusCode() || response.getStatus() == Response.Status.OK.getStatusCode() ) { return deserialize(response, resultType); } else { throw createExceptionForUnexpectedResponseCode( clientRequest, response ); } } private RuntimeException createExceptionForUnexpectedResponseCode( ClientRequest request, ClientResponse<?> response) { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("Unexpected HTTP response code when requesting URI '"); stringBuffer.append(getClientRequestUri(request)); stringBuffer.append("'! Response code: "); stringBuffer.append(response.getStatus()); try { String responseEntity = response.getEntity(String.class); stringBuffer.append(" Response message: "); stringBuffer.append(responseEntity); } catch (ReaderException e) { response.releaseConnection(); // Exception while reading response - most probably empty response and closed input stream } logger.debug( stringBuffer.toString()); return new UnexpectedResponseCodeException(response.getStatus(), stringBuffer.toString()); } private RuntimeException createExceptionForUnexpectedFailure( ClientRequest request, Exception e) { String summaryMessage = "Unexpected exception when requesting URI '" + getClientRequestUri(request) + "'!"; logger.debug( summaryMessage); return new RuntimeException(summaryMessage, e); } private String getClientRequestUri(ClientRequest clientRequest) { String uri; try { uri = clientRequest.getUri(); } catch (Exception e) { throw new RuntimeException("Malformed client URL was specified!", e); } return uri; } public void close() { try { executor.close(); httpClient.close(); } catch (Exception e) { logger.error("Exception thrown while closing resources!", e); } } public MarshallingFormat getMarshallingFormat() { return format; } public void setMarshallingFormat(MarshallingFormat format) { this.format = format; Set<Class<?>> controllerClasses = new HashSet<Class<?>>(); controllerClasses.add(KieServerInstance.class); controllerClasses.add(KieServerInstanceList.class); controllerClasses.add(KieServerInstanceInfo.class); controllerClasses.add(KieServerSetup.class); controllerClasses.add(KieServerStatus.class); controllerClasses.add(ServerInstance.class); controllerClasses.add(ServerInstanceKey.class); controllerClasses.add(ServerTemplate.class); controllerClasses.add(ServerTemplateKey.class); controllerClasses.add(ServerConfig.class); controllerClasses.add(RuleConfig.class); controllerClasses.add(ProcessConfig.class); controllerClasses.add(ContainerSpec.class); controllerClasses.add(ContainerSpecKey.class); controllerClasses.add(Container.class); controllerClasses.add(ContainerKey.class); controllerClasses.add(ServerTemplateList.class); controllerClasses.add(ContainerSpecList.class); Set<Class<?>> minimalControllerClasses = new HashSet<Class<?>>(); minimalControllerClasses.add(RuleConfig.class); minimalControllerClasses.add(ProcessConfig.class); switch ( format ) { case JAXB: this.marshaller = MarshallerFactory.getMarshaller(controllerClasses, format, KieServerMgmtControllerClient.class.getClassLoader()); break; case JSON: this.marshaller = MarshallerFactory.getMarshaller(minimalControllerClasses, format, KieServerMgmtControllerClient.class.getClassLoader()); break; default: this.marshaller = MarshallerFactory.getMarshaller(controllerClasses, format, KieServerMgmtControllerClient.class.getClassLoader()); } } private String getMediaType( MarshallingFormat format ) { switch ( format ) { case JAXB: return MediaType.APPLICATION_XML; case JSON: return MediaType.APPLICATION_JSON; default: return MediaType.APPLICATION_XML; } } protected String serialize(Object object) { if (object == null) { return ""; } try { return marshaller.marshall( object ); } catch ( MarshallingException e ) { throw new RuntimeException( "Error while serializing request data!", e ); } } protected <T> T deserialize(ClientResponse<T> response, Class<T> type) { try { if(type == null) { return null; } String content = response.getEntity(String.class); logger.debug("About to deserialize content: \n '{}' \n into type: '{}'", content, type); if (content == null || content.isEmpty()) { return null; } T result = marshaller.unmarshall( content, type ); return result; } catch ( MarshallingException e ) { throw new RuntimeException( "Error while deserializing data received from server!", e ); } finally { response.releaseConnection(); } } @SuppressWarnings("unchecked") public static <T> Class<T> castClass(Class<?> aClass) { return (Class<T>)aClass; } }
/** * generated by Xtext 2.12.0 */ package gw4e.eclipse.dsl.ui.labeling; import com.google.inject.Inject; import gw4e.eclipse.dsl.dSLPolicies.AlgorithmType; import gw4e.eclipse.dsl.dSLPolicies.GraphElement; import gw4e.eclipse.dsl.dSLPolicies.GraphPolicies; import gw4e.eclipse.dsl.dSLPolicies.Model; import gw4e.eclipse.dsl.dSLPolicies.PathGeneratorStopCondition; import gw4e.eclipse.dsl.dSLPolicies.Policies; import gw4e.eclipse.dsl.dSLPolicies.Severity; import gw4e.eclipse.dsl.dSLPolicies.StopCondition; import java.util.Arrays; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.eclipse.xtext.common.types.JvmAnnotationType; import org.eclipse.xtext.common.types.JvmConstructor; import org.eclipse.xtext.common.types.JvmEnumerationType; import org.eclipse.xtext.common.types.JvmField; import org.eclipse.xtext.common.types.JvmFormalParameter; import org.eclipse.xtext.common.types.JvmGenericType; import org.eclipse.xtext.common.types.JvmOperation; import org.eclipse.xtext.common.types.JvmTypeParameter; import org.eclipse.xtext.xbase.XVariableDeclaration; import org.eclipse.xtext.xbase.typesystem.override.IResolvedConstructor; import org.eclipse.xtext.xbase.typesystem.override.IResolvedField; import org.eclipse.xtext.xbase.typesystem.override.IResolvedOperation; import org.eclipse.xtext.xbase.ui.labeling.XbaseLabelProvider; import org.eclipse.xtext.xtype.XImportDeclaration; import org.eclipse.xtext.xtype.XImportSection; /** * Provides labels for EObjects. * * See https://www.eclipse.org/Xtext/documentation/304_ide_concepts.html#label-provider */ @SuppressWarnings("all") public class DSLPoliciesLabelProvider extends XbaseLabelProvider { @Inject public DSLPoliciesLabelProvider(final AdapterFactoryLabelProvider delegate) { super(delegate); } public static ImageDescriptor getDefaultImageDescriptor(final String pluginid, final String path) { return AbstractUIPlugin.imageDescriptorFromPlugin(pluginid, path); } protected ImageDescriptor _imageDescriptor(final AlgorithmType at) { return DSLPoliciesLabelProvider.getDefaultImageDescriptor("org.eclipse.xtext.ui", "icons/elcl16/ch_callees.png"); } protected ImageDescriptor _imageDescriptor(final StopCondition pgsc) { return DSLPoliciesLabelProvider.getDefaultImageDescriptor("org.eclipse.ui.navigator", "icons/full/elcl16/filter_ps.gif"); } protected ImageDescriptor _imageDescriptor(final PathGeneratorStopCondition pgsc) { return DSLPoliciesLabelProvider.getDefaultImageDescriptor("org.eclipse.xtext.ui", "icons/elcl16/goto_input.gif"); } protected ImageDescriptor _imageDescriptor(final Severity model) { return DSLPoliciesLabelProvider.getDefaultImageDescriptor("org.eclipse.ui", "icons/full/etool16/editor_area.png"); } protected ImageDescriptor _imageDescriptor(final Model pgsc) { return DSLPoliciesLabelProvider.getDefaultImageDescriptor("org.eclipse.platform.doc.user", "images/help_icon_book_closed.png"); } protected ImageDescriptor _imageDescriptor(final Policies policies) { return DSLPoliciesLabelProvider.getDefaultImageDescriptor("org.eclipse.ui.forms", "icons/progress/ani/1.png"); } protected ImageDescriptor _imageDescriptor(final GraphPolicies policies) { return DSLPoliciesLabelProvider.getDefaultImageDescriptor("org.eclipse.wst.json.ui", "icons/full/obj16/json-object.png"); } protected String text(final StopCondition condition) { GraphElement gelt = condition.getGraphelement(); if ((gelt != null)) { final String ge = gelt.getName(); String _pathtype = condition.getPathtype(); String _plus = (_pathtype + "("); String _plus_1 = (_plus + ge); return (_plus_1 + ")"); } else { final String percentage = condition.getPercentage(); if ((percentage != null)) { String _pathtype_1 = condition.getPathtype(); String _plus_2 = (_pathtype_1 + "("); String _plus_3 = (_plus_2 + percentage); return (_plus_3 + ")"); } else { int _value = condition.getValue(); final String value = (Integer.valueOf(_value) + ""); String _pathtype_2 = condition.getPathtype(); String _plus_4 = (_pathtype_2 + "("); String _plus_5 = (_plus_4 + value); return (_plus_5 + ")"); } } } protected String text(final GraphPolicies gp) { return gp.getGraphModelPolicies(); } protected String text(final Severity severity) { boolean _equals = "I".equals(severity.getLevel()); if (_equals) { return "Information Severity"; } boolean _equals_1 = "W".equals(severity.getLevel()); if (_equals_1) { return "Warning Severity"; } boolean _equals_2 = "E".equals(severity.getLevel()); if (_equals_2) { return "Error Severity"; } return null; } protected String text(final Policies policies) { boolean _isSync = policies.isSync(); if (_isSync) { return "sync"; } boolean _isNocheck = policies.isNocheck(); if (_isNocheck) { return "nocheck"; } final EList<PathGeneratorStopCondition> list = policies.getPathgenerator(); int _size = list.size(); boolean _equals = (_size == 0); if (_equals) { return "?"; } int _size_1 = list.size(); boolean _equals_1 = (_size_1 == 1); if (_equals_1) { String _type = list.get(0).getAlgorithmType().getType(); return (_type + "(...)"); } String _type_1 = list.get(0).getAlgorithmType().getType(); return (_type_1 + "(...), ..."); } protected String text(final PathGeneratorStopCondition pgsc) { final GraphElement ge = pgsc.getStopCondition().getGraphelement(); if ((ge != null)) { String _type = pgsc.getAlgorithmType().getType(); String _plus = (_type + "("); String _pathtype = pgsc.getStopCondition().getPathtype(); String _plus_1 = (_plus + _pathtype); String _plus_2 = (_plus_1 + "("); String _name = ge.getName(); String _plus_3 = (_plus_2 + _name); String _plus_4 = (_plus_3 + ")"); return (_plus_4 + ")"); } else { String _percentage = pgsc.getStopCondition().getPercentage(); final String percentage = (_percentage + ""); if ((percentage != null)) { String _type_1 = pgsc.getAlgorithmType().getType(); String _plus_5 = (_type_1 + "("); String _pathtype_1 = pgsc.getStopCondition().getPathtype(); String _plus_6 = (_plus_5 + _pathtype_1); String _plus_7 = (_plus_6 + "("); String _plus_8 = (_plus_7 + percentage); String _plus_9 = (_plus_8 + ")"); return (_plus_9 + ")"); } else { int _value = pgsc.getStopCondition().getValue(); final String value = (Integer.valueOf(_value) + ""); String _type_2 = pgsc.getAlgorithmType().getType(); String _plus_10 = (_type_2 + "("); String _pathtype_2 = pgsc.getStopCondition().getPathtype(); String _plus_11 = (_plus_10 + _pathtype_2); String _plus_12 = (_plus_11 + "("); String _plus_13 = (_plus_12 + value); String _plus_14 = (_plus_13 + ")"); return (_plus_14 + ")"); } } } protected String text(final AlgorithmType at) { return at.getType(); } protected ImageDescriptor imageDescriptor(final Object at) { if (at instanceof JvmConstructor) { return _imageDescriptor((JvmConstructor)at); } else if (at instanceof JvmOperation) { return _imageDescriptor((JvmOperation)at); } else if (at instanceof JvmAnnotationType) { return _imageDescriptor((JvmAnnotationType)at); } else if (at instanceof JvmEnumerationType) { return _imageDescriptor((JvmEnumerationType)at); } else if (at instanceof JvmField) { return _imageDescriptor((JvmField)at); } else if (at instanceof JvmGenericType) { return _imageDescriptor((JvmGenericType)at); } else if (at instanceof JvmTypeParameter) { return _imageDescriptor((JvmTypeParameter)at); } else if (at instanceof JvmFormalParameter) { return _imageDescriptor((JvmFormalParameter)at); } else if (at instanceof XVariableDeclaration) { return _imageDescriptor((XVariableDeclaration)at); } else if (at instanceof AlgorithmType) { return _imageDescriptor((AlgorithmType)at); } else if (at instanceof GraphPolicies) { return _imageDescriptor((GraphPolicies)at); } else if (at instanceof Model) { return _imageDescriptor((Model)at); } else if (at instanceof PathGeneratorStopCondition) { return _imageDescriptor((PathGeneratorStopCondition)at); } else if (at instanceof Policies) { return _imageDescriptor((Policies)at); } else if (at instanceof Severity) { return _imageDescriptor((Severity)at); } else if (at instanceof StopCondition) { return _imageDescriptor((StopCondition)at); } else if (at instanceof IResolvedConstructor) { return _imageDescriptor((IResolvedConstructor)at); } else if (at instanceof IResolvedOperation) { return _imageDescriptor((IResolvedOperation)at); } else if (at instanceof XImportDeclaration) { return _imageDescriptor((XImportDeclaration)at); } else if (at instanceof XImportSection) { return _imageDescriptor((XImportSection)at); } else if (at instanceof IResolvedField) { return _imageDescriptor((IResolvedField)at); } else if (at != null) { return _imageDescriptor(at); } else { throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object>asList(at).toString()); } } }
package com.shareyourproxy.app.fragment; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.style.TextAppearanceSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.shareyourproxy.R; import com.shareyourproxy.api.domain.model.Channel; import com.shareyourproxy.api.domain.model.User; import com.shareyourproxy.api.rx.JustObserver; import com.shareyourproxy.api.rx.RxHelper; import com.shareyourproxy.api.rx.RxQuery; import com.shareyourproxy.api.rx.command.eventcallback.UserChannelAddedEventCallback; import com.shareyourproxy.api.rx.command.eventcallback.UserChannelDeletedEventCallback; import com.shareyourproxy.api.rx.event.RecyclerViewDatasetChangedEvent; import com.shareyourproxy.api.rx.event.SelectUserChannelEvent; import com.shareyourproxy.api.rx.event.SyncAllContactsSuccessEvent; import com.shareyourproxy.app.adapter.BaseRecyclerView; import com.shareyourproxy.app.adapter.BaseViewHolder.ItemLongClickListener; import com.shareyourproxy.app.adapter.ViewChannelAdapter; import com.shareyourproxy.app.dialog.EditChannelDialog; import com.shareyourproxy.widget.ContentDescriptionDrawable; import java.util.HashMap; import butterknife.Bind; import butterknife.BindColor; import butterknife.BindDimen; import butterknife.BindString; import butterknife.ButterKnife; import butterknife.OnClick; import rx.subscriptions.CompositeSubscription; import static android.view.View.GONE; import static com.shareyourproxy.Constants.ARG_USER_SELECTED_PROFILE; import static com.shareyourproxy.IntentLauncher.launchChannelListActivity; import static com.shareyourproxy.util.ViewUtils.svgToBitmapDrawable; import static com.shareyourproxy.widget.DismissibleNotificationCard.NotificationCard.SHARE_PROFILE; /** * Created by Evan on 10/10/15. */ public class UserChannelsFragment extends BaseFragment implements ItemLongClickListener { @Bind(R.id.fragment_user_channel_recyclerview) BaseRecyclerView recyclerView; @Bind(R.id.fragment_user_channel_empty_view_container) LinearLayout emptyViewContainer; @Bind(R.id.fragment_user_channel_empty_button) Button addChannelButton; @Bind(R.id.fragment_user_channel_empty_textview) TextView emptyTextView; @Bind(R.id.fragment_user_channel_coordinator) CoordinatorLayout coordinatorLayout; @BindString(R.string.fragment_userchannels_empty_title) String loggedInNullTitle; @BindString(R.string.fragment_userchannels_empty_message) String loggedInNullMessage; @BindString(R.string.fragment_userprofile_contact_empty_title) String contactNullTitle; @BindDimen(R.dimen.common_svg_null_screen_mini) int marginNullScreen; @BindColor(R.color.common_blue) int colorBlue; private boolean _isLoggedInUser; private User _userContact; private ViewChannelAdapter _adapter; private CompositeSubscription _subscriptions; private RxQuery _rxQuery = RxQuery.INSTANCE; private RxHelper _rxHelper = RxHelper.INSTANCE; /** * Constructor. */ public UserChannelsFragment() { } /** * Create a new user channel fragment. * * @return user channels fragment. */ public static UserChannelsFragment newInstance(User contact) { Bundle bundle = new Bundle(); bundle.putParcelable(ARG_USER_SELECTED_PROFILE, contact); UserChannelsFragment fragment = new UserChannelsFragment(); fragment.setArguments(bundle); return fragment; } @SuppressWarnings("unused") @OnClick(R.id.fragment_user_channel_empty_button) public void onClickAddChannel() { launchChannelListActivity(getActivity()); } @Override public void onAttach(Context context) { super.onAttach(context); _userContact = getArguments() .getParcelable(ARG_USER_SELECTED_PROFILE); _isLoggedInUser = isLoggedInUser(_userContact); } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_user_channels, container, false); ButterKnife.bind(this, rootView); initialize(); return rootView; } /** * Initialize this fragments views. */ private void initialize() { if (_isLoggedInUser) { initializeRecyclerView(getLoggedInUser().channels()); } else { addChannelButton.setVisibility(GONE); initializeRecyclerView(null); } } /** * Initialize a recyclerView with User data. */ private void initializeRecyclerView(HashMap<String, Channel> channels) { _adapter = ViewChannelAdapter.newInstance( recyclerView, getSharedPreferences(), isShowHeader(channels), this); initializeEmptyView(); recyclerView.setEmptyView(emptyViewContainer); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerView.setHasFixedSize(true); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(_adapter); } private boolean isShowHeader(HashMap<String, Channel> channels) { return channels != null && _isLoggedInUser && channels.size() > 0 && !getSharedPreferences().getBoolean(SHARE_PROFILE.getKey(), false); } private void initializeEmptyView() { Context context = getContext(); if (_isLoggedInUser) { SpannableStringBuilder sb = new SpannableStringBuilder(loggedInNullTitle).append("\n") .append(loggedInNullMessage); sb.setSpan(new TextAppearanceSpan(context, R.style.Proxy_TextAppearance_Body2), 0, loggedInNullTitle.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); sb.setSpan(new TextAppearanceSpan(context, R.style.Proxy_TextAppearance_Body), loggedInNullTitle.length() + 1, sb.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); emptyTextView.setText(sb); emptyTextView.setCompoundDrawablesWithIntrinsicBounds( null, getNullDrawable(R.raw.ic_ghost_doge), null, null); } else { String contactNullMessage = getString( R.string.fragment_userprofile_contact_empty_message, _userContact.first()); SpannableStringBuilder sb = new SpannableStringBuilder(contactNullTitle).append("\n") .append(contactNullMessage); sb.setSpan(new TextAppearanceSpan(context, R.style.Proxy_TextAppearance_Body2), 0, contactNullTitle.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); sb.setSpan(new TextAppearanceSpan(context, R.style.Proxy_TextAppearance_Body), contactNullTitle.length() + 1, sb.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); emptyTextView.setText(sb); emptyTextView.setCompoundDrawablesWithIntrinsicBounds( null, getNullDrawable(R.raw.ic_ghost_sloth), null, null); } } /** * Parse a svg and return a null screen sized {@link ContentDescriptionDrawable} . * * @return Drawable with a contentDescription */ private Drawable getNullDrawable(int resId) { return svgToBitmapDrawable(getActivity(), resId, marginNullScreen); } public void getSharedChannels() { _subscriptions.add(_rxQuery.queryPermissionedChannels(_userContact, getLoggedInUser().id()) .subscribe(permissionedObserver())); } private JustObserver<HashMap<String, Channel>> permissionedObserver() { return new JustObserver<HashMap<String, Channel>>() { @Override public void next(HashMap<String, Channel> channels) { _adapter.updateChannels(channels); } }; } @Override public void onResume() { super.onResume(); _subscriptions = _rxHelper.checkCompositeButton(_subscriptions); _subscriptions.add(getRxBus().toObservable() .subscribe(onNextEvent())); if (_isLoggedInUser) { syncUsersContacts(); } else { getSharedChannels(); } recyclerView.scrollToPosition(0); } private JustObserver<Object> onNextEvent() { return new JustObserver<Object>() { @Override public void next(Object event) { if (event instanceof UserChannelAddedEventCallback) { addUserChannel(((UserChannelAddedEventCallback) event)); } else if (event instanceof UserChannelDeletedEventCallback) { deleteUserChannel(((UserChannelDeletedEventCallback) event)); } else if (event instanceof SyncAllContactsSuccessEvent) { if (_isLoggedInUser) { syncUsersContacts(); } } } }; } public void syncUsersContacts() { HashMap<String, Channel> channels = getLoggedInUser().channels(); if (channels != null && channels.size() > 0) { _adapter.updateChannels(channels); } else { recyclerView.updateViewState(new RecyclerViewDatasetChangedEvent( _adapter, BaseRecyclerView.ViewState.EMPTY)); } } @Override public void onPause() { super.onPause(); _subscriptions.unsubscribe(); _subscriptions = null; } private void addUserChannel(UserChannelAddedEventCallback event) { if (event.oldChannel != null) { _adapter.updateItem(event.oldChannel, event.newChannel); } else { _adapter.addItem(event.newChannel); } } private void deleteUserChannel(UserChannelDeletedEventCallback event) { _adapter.removeItem(event.position); } @Override public final void onItemClick(View view, int position) { Channel channel = _adapter.getItemData(position); getRxBus().post(new SelectUserChannelEvent(channel)); } @Override public void onItemLongClick(View view, int position) { Channel channel = _adapter.getItemData(position); if (_isLoggedInUser) { EditChannelDialog.newInstance(channel, position).show(getFragmentManager()); } } }
package com.cedricziel.idea.typo3.util; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.patterns.PlatformPatterns; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.search.FilenameIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.*; import com.jetbrains.php.PhpIndex; import com.jetbrains.php.lang.parser.PhpElementTypes; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.jetbrains.php.lang.psi.elements.StringLiteralExpression; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import java.util.*; import static com.cedricziel.idea.typo3.psi.PhpElementsUtil.extractArrayIndexFromValue; public class TCAUtil { public static final String[] TCA_TABLE_FIELDS = { "foreign_table", "allowed", "MM", }; public static final String[] TCA_V8_CORE_TYPES = { "check", "flex", "group", "imageManipulation", "input", "inline", "none", "passthrough", "radio", "select", "text", "user", }; public static final String[] TCA_V9_CORE_TYPES = { "slug" }; public static final String[] TCA_V8_CORE_RENDER_TYPES = { "selectSingle", "selectSingleBox", "selectCheckBox", "selectMultipleSideBySide", "selectTree", "colorpicker", "inputDateTime", "inputLink", "rsaInput", "belayoutwizard", "t3editor", "textTable", }; public static final String[] TCA_NUMERIC_CONFIG_KEYS = { "size", "min", "max", "maxitems", "autoSizeMax", "cols", "rows", }; public static final String[] TCA_V8_DEFAULT_EVALUATIONS = { "alpha", "alphanum", "alphanum_x", "date", "datetime", "domainname", "double2", "int", "is_in", "lower", "md5", "nospace", "null", "num", "password", "required", "time", "timesec", "trim", "unique", "uniqueInPid", "upper", "year", }; public static final String[] TCA_V9_DEFAULT_EVALUATIONS = { "uniqueInSite", "uniqueInPid", }; public static final String[] TCA_CONFIG_SECTION_CHILDREN = { "appearance", "allowNonIdValues", "authMode", "authMode_enforce", "autoSizeMax", "allowed", "behaviour", "checkbox", "cols", "dbType", "default", "disableNoMatchingValueElement", "disable_controls", "disallowed", "dontRemapTablesOnCopy", "ds", "ds_tableField", "ds_pointerField", "ds_pointerField_searchParent", "ds_pointerField_searchParent_subField", "enableMultiSelectFilterTextfield", "exclusiveKeys", "eval", "items", "itemsProcFunc", "itemListStyle", "filter", "fixedRows", "fieldWizard", "fileFolder", "fileFolder_extList", "fileFolder_recursions", "form_type", "format", "foreign_match_fields", "foreign_default_sortby", "foreign_field", "foreign_label", "foreign_record_defaults", "foreign_sortby", "foreign_selector", "foreign_selector_fieldTcaOverride", "foreign_table", "foreign_table_field", "foreign_table_loadIcons", "foreign_table_prefix", "foreign_table_where", "foreign_types", "foreign_unique", "is_in", "internal_type", "iconsInOptionTags", "localizeReferencesAtParentLocalization", "max", "mode", "MM", "MM_oppositeUsage", "MM_hasUidField", "MM_insert_fields", "MM_match_fields", "MM_opposite_field", "MM_table_where", "maxitems", "minitems", "max_size", "multiple", "multiSelectFilterItems", "neg_foreign_table", "noTableWrapping", "noIconsBelowSelect", "parameters", "pass_content", "placeholder", "prepend_tname", "range", "renderType", "renderMode", "rootLevel", "rows", "show_thumbs", "selicon_cols", "search", "selectedListStyle", "showIfRte", "size", "softref", "special", "suppress_icons", "symmetric_field", "symmetric_label", "symmetric_sortby", "readOnly", "treeConfig", "type", "userFunc", "uploadfolder", "validation", "wizards", "wrap", // type slug "generatorOptions", "fallbackCharacter", }; private static final String EXT_LOCALCONF_FILENAME = "ext_localconf.php"; private static final String NODE_FACTORY_CLASS = "TYPO3\\CMS\\Backend\\Form\\NodeFactory"; private static final Key<CachedValue<Set<String>>> RENDER_TYPES_KEY = new Key<>("TYPO3_CMS_RENDER_TYPES"); public static boolean arrayIndexIsTCATableNameField(PsiElement element) { String arrayIndex = extractArrayIndexFromValue(element); return Arrays.asList(TCA_TABLE_FIELDS).contains(arrayIndex); } @NotNull public static Set<String> getAvailableRenderTypes(PsiElement element) { return getAvailableRenderTypes(element.getProject()); } @NotNull private synchronized static Set<String> getAvailableRenderTypes(Project project) { CachedValue<Set<String>> cachedRenderTypes = project.getUserData(RENDER_TYPES_KEY); if (cachedRenderTypes != null && cachedRenderTypes.hasUpToDateValue()) { return cachedRenderTypes.getValue(); } CachedValue<Set<String>> cachedValue = CachedValuesManager.getManager(project).createCachedValue(() -> { Set<PsiElement> elementsFromExtLocalConf = findAvailableRenderTypes(project); // add static list of render types Set<String> renderTypes = new HashSet<>(Arrays.asList(TCA_V8_CORE_RENDER_TYPES)); // add dynamic list of render types from nodeRegistry for (PsiElement el : elementsFromExtLocalConf) { if (el instanceof StringLiteralExpression) { renderTypes.add(((StringLiteralExpression) el).getContents()); } } return CachedValueProvider.Result.create(renderTypes, PsiModificationTracker.MODIFICATION_COUNT); }, false); project.putUserData(RENDER_TYPES_KEY, cachedValue); return cachedValue.getValue(); } public static Set<String> getAvailableColumnTypes(@NotNull Project project) { List<String> columnTypes = new ArrayList<>(Arrays.asList(TCA_V8_CORE_TYPES)); // add v9 column types if branch is higher than 8.7 if (TYPO3Utility.compareMajorMinorVersion(project, "8.7") > 0) { columnTypes.addAll(Arrays.asList(TCA_V9_CORE_TYPES)); } return new HashSet<>(columnTypes); } private static Set<PsiElement> findAvailableRenderTypes(Project project) { PhpIndex phpIndex = PhpIndex.getInstance(project); PsiFile[] extLocalConfFiles = FilenameIndex.getFilesByName(project, EXT_LOCALCONF_FILENAME, GlobalSearchScope.allScope(project)); Collection<PhpClass> nodeRegistries = phpIndex.getClassesByFQN(NODE_FACTORY_CLASS); Set<PsiElement> elements = new HashSet<>(); for (PhpClass registry : nodeRegistries) { Collections.addAll( elements, PsiTreeUtil.collectElements(registry, element -> PlatformPatterns .psiElement(StringLiteralExpression.class) .withParent( PlatformPatterns.psiElement(PhpElementTypes.ARRAY_KEY) .withAncestor( 3, PlatformPatterns.psiElement(PhpElementTypes.CLASS_FIELD).withName("nodeTypes") ) ) .accepts(element) ) ); } for (PsiFile file : extLocalConfFiles) { Collections.addAll( elements, PsiTreeUtil.collectElements(file, element -> PlatformPatterns .psiElement(StringLiteralExpression.class) .withParent( PlatformPatterns .psiElement(PhpElementTypes.ARRAY_VALUE) .withParent( PlatformPatterns .psiElement(PhpElementTypes.HASH_ARRAY_ELEMENT) .withChild( PlatformPatterns .psiElement(PhpElementTypes.ARRAY_KEY) .withText("'nodeName'") ) ) ).accepts(element)) ); } return elements; } public static boolean insideTCAColumnDefinition(PsiElement element) { return PlatformPatterns.psiElement() .withAncestor( 11, PlatformPatterns .psiElement(PhpElementTypes.HASH_ARRAY_ELEMENT) .withChild( PlatformPatterns.psiElement(PhpElementTypes.ARRAY_KEY).withText("'columns'") ) ) .accepts(element); } @NotNull public static Set<String> getAvailableEvaluations(@NotNull Project project) { Set<String> evaluations = new THashSet<>(); evaluations.addAll(Arrays.asList(TCA_V8_DEFAULT_EVALUATIONS)); if (TYPO3Utility.compareMajorMinorVersion(project, "8.7") > 0) { evaluations.addAll(Arrays.asList(TCA_V9_DEFAULT_EVALUATIONS)); } return evaluations; } public static String[] getConfigSectionChildren() { return TCA_CONFIG_SECTION_CHILDREN; } }
/* -*- mode: java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2013 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.real_logic.sbe.xml; import uk.co.real_logic.sbe.SbeTool; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import uk.co.real_logic.sbe.PrimitiveType; import uk.co.real_logic.sbe.PrimitiveValue; import uk.co.real_logic.sbe.TestUtil; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.lang.Integer.valueOf; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static uk.co.real_logic.sbe.xml.XmlSchemaParser.parse; public class EnumTypeTest { @Test public void shouldHandleBinaryEnumType() throws Exception { final String testXmlString = "<types>" + "<enum name=\"biOp\" encodingType=\"uint8\">" + " <validValue name=\"off\" description=\"switch is off\">0</validValue>" + " <validValue name=\"on\" description=\"switch is on\">1</validValue>" + "</enum>" + "</types>"; final Map<String, Type> map = parseTestXmlWithMap("/types/enum", testXmlString); final EnumType e = (EnumType)map.get("biOp"); assertThat(e.name(), is("biOp")); assertThat(e.encodingType(), is(PrimitiveType.UINT8)); assertThat(valueOf(e.validValues().size()), is(valueOf(2))); assertThat(e.getValidValue("on").primitiveValue(), is(PrimitiveValue.parse("1", PrimitiveType.UINT8))); assertThat(e.getValidValue("off").primitiveValue(), is(PrimitiveValue.parse("0", PrimitiveType.UINT8))); } @Test public void shouldHandleBooleanEnumType() throws Exception { final String testXmlString = "<types>" + "<enum name=\"Boolean\" encodingType=\"uint8\" semanticType=\"Boolean\">" + " <validValue name=\"False\">0</validValue>" + " <validValue name=\"True\">1</validValue>" + "</enum>" + "</types>"; final Map<String, Type> map = parseTestXmlWithMap("/types/enum", testXmlString); final EnumType e = (EnumType)map.get("Boolean"); assertThat(e.name(), is("Boolean")); assertThat(e.encodingType(), is(PrimitiveType.UINT8)); assertThat(valueOf(e.validValues().size()), is(valueOf(2))); assertThat(e.getValidValue("True").primitiveValue(), is(PrimitiveValue.parse("1", PrimitiveType.UINT8))); assertThat(e.getValidValue("False").primitiveValue(), is(PrimitiveValue.parse("0", PrimitiveType.UINT8))); } @Test public void shouldHandleOptionalBooleanEnumType() throws Exception { final String nullValueStr = "255"; final String testXmlString = "<types>" + "<enum name=\"optionalBoolean\" encodingType=\"uint8\" presence=\"optional\"" + " nullValue=\"" + nullValueStr + "\" semanticType=\"Boolean\">" + " <validValue name=\"False\">0</validValue>" + " <validValue name=\"True\">1</validValue>" + "</enum>" + "</types>"; final Map<String, Type> map = parseTestXmlWithMap("/types/enum", testXmlString); final EnumType e = (EnumType)map.get("optionalBoolean"); assertThat(e.name(), is("optionalBoolean")); assertThat(e.encodingType(), is(PrimitiveType.UINT8)); assertThat(valueOf(e.validValues().size()), is(valueOf(2))); assertThat(e.getValidValue("True").primitiveValue(), is(PrimitiveValue.parse("1", PrimitiveType.UINT8))); assertThat(e.getValidValue("False").primitiveValue(), is(PrimitiveValue.parse("0", PrimitiveType.UINT8))); assertThat(e.nullValue(), is(PrimitiveValue.parse(nullValueStr, PrimitiveType.UINT8))); } @Test public void shouldHandleEnumTypeList() throws Exception { final String testXmlString = "<types>" + "<enum name=\"triOp\" encodingType=\"uint8\">" + " <validValue name=\"off\" description=\"switch is off\">0</validValue>" + " <validValue name=\"on\" description=\"switch is on\">1</validValue>" + " <validValue name=\"notKnown\" description=\"switch is unknown\">2</validValue>" + "</enum>" + "</types>"; final Map<String, Type> map = parseTestXmlWithMap("/types/enum", testXmlString); final EnumType e = (EnumType)map.get("triOp"); assertThat(e.name(), is("triOp")); assertThat(e.encodingType(), is(PrimitiveType.UINT8)); int foundOn = 0, foundOff = 0, foundNotKnown = 0, count = 0; for (final EnumType.ValidValue v : e.validValues()) { if (v.name().equals("on")) { foundOn++; } else if (v.name().equals("off")) { foundOff++; } else if (v.name().equals("notKnown")) { foundNotKnown++; } count++; } assertThat(valueOf(count), is(valueOf(3))); assertThat(valueOf(foundOn), is(valueOf(1))); assertThat(valueOf(foundOff), is(valueOf(1))); assertThat(valueOf(foundNotKnown), is(valueOf(1))); } @Test public void shouldHandleCharEnumEncodingType() throws Exception { final String testXmlString = "<types>" + "<enum name=\"mixed\" encodingType=\"char\">" + " <validValue name=\"Cee\">C</validValue>" + " <validValue name=\"One\">1</validValue>" + " <validValue name=\"Two\">2</validValue>" + " <validValue name=\"Eee\">E</validValue>" + "</enum>" + "</types>"; Map<String, Type> map = parseTestXmlWithMap("/types/enum", testXmlString); EnumType e = (EnumType)map.get("mixed"); assertThat(e.encodingType(), is(PrimitiveType.CHAR)); assertThat(e.getValidValue("Cee").primitiveValue(), is(PrimitiveValue.parse("C", PrimitiveType.CHAR))); assertThat(e.getValidValue("One").primitiveValue(), is(PrimitiveValue.parse("1", PrimitiveType.CHAR))); assertThat(e.getValidValue("Two").primitiveValue(), is(PrimitiveValue.parse("2", PrimitiveType.CHAR))); assertThat(e.getValidValue("Eee").primitiveValue(), is(PrimitiveValue.parse("E", PrimitiveType.CHAR))); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenIllegalEncodingTypeSpecified() throws Exception { final String testXmlString = "<types>" + "<enum name=\"boolean\" encodingType=\"int64\" semanticType=\"Boolean\">" + " <validValue name=\"false\">0</validValue>" + " <validValue name=\"true\">1</validValue>" + "</enum>" + "</types>"; parseTestXmlWithMap("/types/enum", testXmlString); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenDuplicateValueSpecified() throws Exception { final String testXmlString = "<types>" + "<enum name=\"boolean\" encodingType=\"uint8\" semanticType=\"Boolean\">" + " <validValue name=\"false\">0</validValue>" + " <validValue name=\"anotherFalse\">0</validValue>" + " <validValue name=\"true\">1</validValue>" + "</enum>" + "</types>"; parseTestXmlWithMap("/types/enum", testXmlString); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenDuplicateNameSpecified() throws Exception { final String testXmlString = "<types>" + "<enum name=\"boolean\" encodingType=\"uint8\" semanticType=\"Boolean\">" + " <validValue name=\"false\">0</validValue>" + " <validValue name=\"false\">2</validValue>" + " <validValue name=\"true\">1</validValue>" + "</enum>" + "</types>"; parseTestXmlWithMap("/types/enum", testXmlString); } @Test public void shouldHandleEncodingTypesWithNamedTypes() throws Exception { MessageSchema schema = parse(TestUtil.getLocalResource("EncodingTypesFileTest.xml")); List<Field> fields = schema.getMessage(1).fields(); assertNotNull(fields); EnumType type = (EnumType)fields.get(1).type(); assertThat(type.encodingType(), is(PrimitiveType.CHAR)); type = (EnumType)fields.get(2).type(); assertThat(type.encodingType(), is(PrimitiveType.UINT8)); } private static Map<String, Type> parseTestXmlWithMap(final String xPathExpr, final String xml) throws ParserConfigurationException, XPathExpressionException, IOException, SAXException { final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes())); final XPath xPath = XPathFactory.newInstance().newXPath(); final NodeList list = (NodeList)xPath.compile(xPathExpr).evaluate(document, XPathConstants.NODESET); final Map<String, Type> map = new HashMap<>(); System.setProperty(SbeTool.VALIDATION_STOP_ON_ERROR, "true"); System.setProperty(SbeTool.VALIDATION_SUPPRESS_OUTPUT, "true"); System.setProperty(SbeTool.VALIDATION_WARNINGS_FATAL, "true"); document.setUserData(XmlSchemaParser.ERROR_HANDLER_KEY, new ErrorHandler(), null); for (int i = 0, size = list.getLength(); i < size; i++) { Type t = new EnumType(list.item(i)); map.put(t.name(), t); } return map; } }
/** * Copyright (c) 2012, Cloudera, Inc. All Rights Reserved. * * Cloudera, Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"). You may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This software 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.cloudera.kitten.lua; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.luaj.vm2.LoadState; import org.luaj.vm2.LuaTable; import org.luaj.vm2.LuaValue; import org.luaj.vm2.Varargs; import org.luaj.vm2.lib.jse.CoerceJavaToLua; import org.luaj.vm2.lib.jse.JsePlatform; import com.cloudera.kitten.util.LocalDataHelper; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Maps; /** * A wrapper object to make it nicer to work with LuaTables. */ public class LuaWrapper implements Iterable<LuaPair> { private static final Log LOG = LogFactory.getLog(LuaWrapper.class); private final LuaTable env; public LuaWrapper(String script) { this(script, ImmutableMap.<String, Object>of()); } public LuaWrapper(String script, Map<String, Object> extras) { try { this.env = JsePlatform.standardGlobals(); LoadState.load(getClass().getResourceAsStream("/lua/kitten.lua"), "kitten.lua", env).call(); for (Map.Entry<String, Object> e : extras.entrySet()) { env.set(e.getKey(), CoerceJavaToLua.coerce(e.getValue())); } InputStream luaCode = LocalDataHelper.getFileOrResource(script); LoadState.load(luaCode, script, env).call(); } catch (IOException e) { LOG.error("Lua initialization error", e); throw new RuntimeException(e); } } public LuaWrapper(LuaTable table) { this.env = Preconditions.checkNotNull(table); } public boolean isNil(String name) { return env.get(name).isnil(); } public boolean isTable(String name) { return env.get(name).istable(); } public LuaWrapper getTable(String name) { return new LuaWrapper(env.get(name).checktable()); } public Map<String, String> asMap() { Map<String, String> map = Maps.newHashMap(); for (LuaValue lv : env.keys()) { map.put(lv.tojstring(), env.get(lv).tojstring()); } return map; } public List<String> asList() { List<String> list = Lists.newArrayList(); for (int i = 0; i < env.length(); i++) { list.add(env.get(i).tojstring()); } return list; } public LuaWrapper createTable(String name) { LuaTable lt = new LuaTable(); env.set(name, lt); return new LuaWrapper(lt); } public String getString(String name) { return env.get(name).tojstring(); } public int getInteger(String name) { return env.get(name).toint(); } public long getLong(String name) { return env.get(name).tolong(); } public boolean getBoolean(String name) { return env.get(name).toboolean(); } public double getDouble(String name) { return env.get(name).todouble(); } public LuaWrapper setString(String field, String value) { env.set(field, LuaValue.valueOf(value)); return this; } public LuaWrapper setInteger(String field, int value) { env.set(field, LuaValue.valueOf(value)); return this; } public LuaWrapper setBoolean(String field, boolean value) { env.set(field, LuaValue.valueOf(value)); return this; } public LuaWrapper setDouble(String field, double value) { env.set(field, LuaValue.valueOf(value)); return this; } public LuaWrapper addString(String value) { env.set(env.getn().toint() + 1, value); return this; } @Override public Iterator<LuaPair> iterator() { return new LuaIterator(env, false); } public Iterator<LuaPair> hashIterator() { return Iterators.filter(iterator(), new Predicate<LuaPair>() { @Override public boolean apply(LuaPair lp) { return !lp.key.isint(); } }); } public Iterator<LuaPair> arrayIterator() { return new LuaIterator(env, true); } private static class LuaIterator implements Iterator<LuaPair> { private final LuaTable t; private final boolean array; private LuaValue currentKey; private Varargs varargs; public LuaIterator(LuaTable t, boolean array) { this.t = t; this.array = array; this.currentKey = array ? LuaValue.ZERO : LuaValue.NIL; step(); } @Override public boolean hasNext() { return !currentKey.isnil(); } @Override public LuaPair next() { LuaPair lp = new LuaPair(currentKey, varargs.arg(2)); step(); return lp; } @Override public void remove() { throw new UnsupportedOperationException("Read-only iterator"); } private void step() { this.varargs = array ? t.inext(currentKey) : t.next(currentKey); currentKey = varargs.arg1(); } } }
package com.bumptech.glide.supportapp.github._639_cache_fallback_3g_wifi; import java.io.File; import java.util.Locale; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import android.content.Context; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.*; import android.widget.Toast; import com.bumptech.glide.*; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.*; import com.bumptech.glide.supportapp.GlideImageFragment; import com.bumptech.glide.supportapp.utils.*; public class TestFragment extends GlideImageFragment { @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); menu.add(0, 10, 0, "Load"); menu.add(0, 11, 0, "Cache 3G").setIcon(android.R.drawable.presence_audio_online); menu.add(0, 12, 0, "Cache Wifi").setIcon(android.R.drawable.presence_video_online); menu.add(0, 13, 0, "On 3G"); menu.add(0, 14, 0, "On Wifi"); } private boolean net3g = false; private boolean netWifi = true; @Override public boolean onOptionsItemSelected(MenuItem item) { String fast = "http://placehold.it/1920x1080?text=wifi"; String slow = "http://placehold.it/640x480?text=3g"; switch (item.getItemId()) { case 11: Glide.with(this) .load(slow) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .skipMemoryCache(true) .listener(new RequestListener<String, GlideDrawable>() { @Override public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) { Log.i("GLIDE", "3g preload failed", e); return false; } @Override public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { Log.i("GLIDE", "3g preloaded"); return false; } }) .preload() ; return true; case 12: Glide.with(this) .load(fast) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .skipMemoryCache(true) .listener(new RequestListener<String, GlideDrawable>() { @Override public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) { Log.i("GLIDE", "wifi preload failed", e); return false; } @Override public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { Log.i("GLIDE", "wifi preloaded"); return false; } }) .preload() ; return true; case 13: net3g = true; netWifi = false; Toast.makeText(getActivity(), "On 3G now", Toast.LENGTH_SHORT).show(); return true; case 14: net3g = false; netWifi = true; Toast.makeText(getActivity(), "On Wifi now", Toast.LENGTH_SHORT).show(); return true; case 10: DrawableRequestBuilder<String> slowLoad; DrawableRequestBuilder<String> fastLoad; if (net3g) { slowLoad = Glide.with(this).load(slow); fastLoad = Glide.with(this).using(new NetworkDisablingLoader<String>()).load(fast); } else { slowLoad = Glide.with(this).load(slow); fastLoad = Glide.with(this).load(fast); } slowLoad .diskCacheStrategy(DiskCacheStrategy.SOURCE) .skipMemoryCache(true) .error(new TextDrawable("slow failed")) .listener(new SlowListener()); fastLoad .diskCacheStrategy(DiskCacheStrategy.SOURCE) .skipMemoryCache(true) .error(new TextDrawable("fast failed")) .listener(new FastListener()); fastLoad.thumbnail(slowLoad).into(imageView); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void load(final Context context) throws Exception { } boolean syncTry1(final String url) { boolean cached = false; try { final AtomicReference<File> file = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); new Thread() { @Override public void run() { File cached; try { cached = Glide .with(getActivity()) .using(new NetworkDisablingLoader<String>()) .load(url) .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) .get(); file.set(cached); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } finally { latch.countDown(); } } }.start(); latch.await(); Log.wtf("GLIDE", String.valueOf(file)); cached = file.get() != null; } catch (InterruptedException e) { e.printStackTrace(); } return cached; } boolean syncTry2(String url) { Log.i("GLIDE", "Checking isCached()"); final AtomicBoolean cached = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); Glide .with(getActivity()) .using(new NetworkDisablingLoader<String>()) .load(url) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .skipMemoryCache(true) //.imageDecoder(new NullDecoder<InputStream, Bitmap>()) .into(new SimpleTarget<GlideDrawable>() { @Override public void onLoadFailed(Exception e, Drawable errorDrawable) { Log.i("GLIDE", String.format(Locale.ROOT, "onLoadFailed(%s, %s)", e, errorDrawable), e); cached.set(false); latch.countDown(); } @Override public void onResourceReady( GlideDrawable resource, GlideAnimation<?super GlideDrawable> glideAnimation) { Log.i("GLIDE", String.format(Locale.ROOT, "onResourceReady(%s, %s)", resource, glideAnimation)); cached.set(true); latch.countDown(); } }); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } return cached.get(); } private static class SlowListener implements RequestListener<String, GlideDrawable> { @Override public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) { Log.i("GLIDE", "slow failed", e); return false; } @Override public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { Log.i("GLIDE", "slow loaded"); return false; } } private static class FastListener implements RequestListener<String, GlideDrawable> { @Override public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) { Log.i("GLIDE", "fast failed", e); return false; } @Override public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { Log.i("GLIDE", "fast loaded"); return false; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket.markup; import java.util.Iterator; import org.apache.wicket.markup.parser.filter.HtmlHandler; import org.apache.wicket.util.lang.Args; import org.apache.wicket.util.string.AppendingStringBuffer; /** * Represents a portion of a markup file, but always spans a complete tag. E.g. * * <pre> * open-body-close: &lt;span&gt;body&lt;/span&gt; * open-close: &lt;span/&gt; * open-no-close: &lt;input ...&gt;body * </pre> * * @see Markup * @see MarkupElement * * @author Juergen Donnerstag */ public class MarkupFragment implements IMarkupFragment { /** The parent markup. Must not be null. */ private final IMarkupFragment markup; /** The index at which the fragment starts, relative to the parent markup */ private final int startIndex; /** The size of the fragment (usually from open to close tag) */ private final int size; /** * Construct. * * @param markup * The parent markup. May not be null. * @param startIndex * The start index of the child markup * @throws IndexOutOfBoundsException * if the index is out of range (<tt>index &lt; 0 || index &gt;= size()</tt>) */ public MarkupFragment(final IMarkupFragment markup, final int startIndex) { Args.notNull(markup, "markup"); if (startIndex < 0) { throw new IllegalArgumentException("Parameter 'startIndex' must not be < 0"); } // cache the value for better performance int markupSize = markup.size(); if (startIndex >= markupSize) { throw new IllegalArgumentException( "Parameter 'startIndex' must not be >= markup.size()"); } this.markup = markup; this.startIndex = startIndex; // Make sure we are at an open tag MarkupElement startElem = markup.get(startIndex); if ((startElem instanceof ComponentTag) == false) { throw new IllegalArgumentException( "Parameter 'startIndex' does not point to a Wicket open tag"); } // Determine the size. Find the close tag int endIndex; ComponentTag startTag = (ComponentTag)startElem; if (startTag.isOpenClose()) { endIndex = startIndex; } else if (startTag.hasNoCloseTag()) { if (HtmlHandler.requiresCloseTag(startTag.getName()) == false) { // set endIndex to a "good" value endIndex = startIndex; } else { // set endIndex to a value which will indicate an error endIndex = markupSize; } } else { for (endIndex = startIndex + 1; endIndex < markupSize; endIndex++) { MarkupElement elem = markup.get(endIndex); if (elem instanceof ComponentTag) { ComponentTag tag = (ComponentTag)elem; if (tag.closes(startTag)) { break; } } } } if (endIndex >= markupSize) { throw new MarkupException("Unable to find close tag for: '" + startTag.toString() + "' in " + getRootMarkup().getMarkupResourceStream().toString()); } size = endIndex - startIndex + 1; } @Override public final MarkupElement get(final int index) { if ((index < 0) || (index > size)) { throw new IndexOutOfBoundsException("Parameter 'index' is out of range: 0 <= " + index + " <= " + size); } // Ask the parent markup return markup.get(startIndex + index); } @Override public final IMarkupFragment find(final String id) { Args.notEmpty(id, "id"); MarkupStream stream = new MarkupStream(this); stream.setCurrentIndex(1); while (stream.hasMore()) { MarkupElement elem = stream.get(); if (elem instanceof ComponentTag) { ComponentTag tag = stream.getTag(); if (tag.isOpen() || tag.isOpenClose()) { if (tag.getId().equals(id)) { return stream.getMarkupFragment(); } if (tag.isOpen() && !tag.hasNoCloseTag() && !tag.isAutoComponentTag()) { stream.skipToMatchingCloseTag(tag); } } } stream.next(); } return null; } @Override public final MarkupResourceStream getMarkupResourceStream() { return markup.getMarkupResourceStream(); } @Override public final int size() { return size; } /** * @return The parent markup. Null if that is a a markup file. */ private final IMarkupFragment getParentMarkup() { return markup; } /** * @return The Markup representing the underlying markup file with all its content */ public final Markup getRootMarkup() { IMarkupFragment markup = getParentMarkup(); while ((markup != null) && !(markup instanceof Markup)) { markup = ((MarkupFragment)markup).getParentMarkup(); } return (Markup)markup; } @Override public String toString() { return toString(false); } @Override public String toString(boolean markupOnly) { final AppendingStringBuffer buf = new AppendingStringBuffer(400); if (markupOnly == false) { buf.append(getRootMarkup().getMarkupResourceStream().toString()); buf.append("\n"); } for (int i = 0; i < size(); i++) { buf.append(get(i)); } return buf.toString(); } /** * @see java.lang.Iterable#iterator() */ @Override public Iterator<MarkupElement> iterator() { return getRootMarkup().iterator(startIndex, size); } }
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.java.psi.impl.source.tree.java; import com.intellij.codeInsight.CodeInsightUtilCore; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.psi.*; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.javadoc.PsiDocTag; import com.intellij.testFramework.LightIdeaTestCase; import com.intellij.util.IncorrectOperationException; /** * @author dsl */ public class JavadocParamTagsTest extends LightIdeaTestCase { public void testDeleteTag1() { final PsiElementFactory factory = getFactory(); final PsiMethod method = factory.createMethodFromText( "/**\n" + " * Javadoc\n" + " * @param p1\n" + " * @param p2\n" + " */" + " void m() {}", null); final PsiDocComment docComment = method.getDocComment(); assertNotNull(docComment); final PsiDocTag[] tags = docComment.getTags(); WriteCommandAction.runWriteCommandAction(null, () -> tags[0].delete()); assertEquals("/**\n" + " * Javadoc\n" + " * @param p2\n" + " */", docComment.getText()); } public void testDeleteTag2() { final PsiElementFactory factory = getFactory(); final PsiMethod method = factory.createMethodFromText( "/**\n" + " * Javadoc\n" + " * @param p1\n" + " * @param p2\n" + " */" + " void m() {}", null); final PsiDocComment docComment = method.getDocComment(); assertNotNull(docComment); final PsiDocTag[] tags = docComment.getTags(); ApplicationManager.getApplication().runWriteAction(() -> tags[1].delete()); assertEquals("/**\n" + " * Javadoc\n" + " * @param p1\n" + " */", docComment.getText()); } public void testDeleteTag3() { final PsiElementFactory factory = getFactory(); final PsiMethod method = factory.createMethodFromText( "/**\n" + " * Javadoc\n" + " * @param p1\n" + " * @param p2\n" + " * @param p3\n" + " */" + " void m() {}", null); final PsiDocComment docComment = method.getDocComment(); assertNotNull(docComment); final PsiDocTag[] tags = docComment.getTags(); ApplicationManager.getApplication().runWriteAction(() -> tags[1].delete()); assertEquals("/**\n" + " * Javadoc\n" + " * @param p1\n" + " * @param p3\n" + " */", docComment.getText()); } public void testTagCreation() { createAndTestTag("@param p1 Text", "p1", "Text"); createAndTestTag("@param p2", "p2", ""); createAndTestTag("@param p2 FirstLine\n * SecondLine", "p2", "FirstLine\nSecondLine"); } public void testAddTag1() { final PsiElementFactory factory = getFactory(); final PsiMethod method = factory.createMethodFromText( "/**\n" + " * Javadoc\n" + " * @param p1\n" + " */\n" + "void m();", null); final PsiDocComment docComment = method.getDocComment(); assertNotNull(docComment); final PsiDocTag[] tags = docComment.getTags(); final PsiDocTag tag2 = factory.createParamTag("p2", ""); docComment.addAfter(tag2, tags[0]); assertEquals( "/**\n" + " * Javadoc\n" + " * @param p1\n" + " * @param p2\n" + " */", docComment.getText()); } public void testAddTag2() { final PsiElementFactory factory = getFactory(); final PsiMethod method = factory.createMethodFromText( "/**\n" + " * Javadoc\n" + " * @param p1\n" + " */\n" + "void m();", null); final PsiDocComment docComment = method.getDocComment(); assertNotNull(docComment); final PsiDocTag[] tags = docComment.getTags(); final PsiDocTag tag2 = factory.createParamTag("p2", ""); docComment.addBefore(tag2, tags[0]); assertEquals( "/**\n" + " * Javadoc\n" + " * @param p2\n" + " * @param p1\n" + " */", docComment.getText()); } public void testAddTag3() { CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { final PsiElementFactory factory = getFactory(); final PsiJavaFile psiFile; try { psiFile = (PsiJavaFile)createFile("aaa.java", "class A {/**\n" + " * Javadoc\n" + " * @param p1\n" + " * @param p3\n" + " */\n" + "void m();}"); final PsiClass psiClass = psiFile.getClasses()[0]; final PsiMethod method = psiClass.getMethods()[0]; PsiDocComment docComment = method.getDocComment(); assertNotNull(docComment); final PsiDocTag[] tags = docComment.getTags(); final PsiDocTag tag2 = factory.createParamTag("p2", ""); docComment.addAfter(tag2, tags[0]); docComment = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(docComment); assertEquals( "/**\n" + " * Javadoc\n" + " * @param p1\n" + " * @param p2\n" + " * @param p3\n" + " */", docComment.getText()); } catch (IncorrectOperationException e) {} }), "", null); } public void testAddTag4() { final PsiElementFactory factory = getFactory(); final PsiMethod method = factory.createMethodFromText( "/**\n" + " * Javadoc\n" + " */\n" + "void m();", null); final PsiDocComment docComment = method.getDocComment(); assertNotNull(docComment); final PsiDocTag tag2 = factory.createParamTag("p2", ""); docComment.add(tag2); assertEquals( "/**\n" + " * Javadoc\n" + " * @param p2\n" + " */", docComment.getText()); } private static PsiElementFactory getFactory() { final PsiManager manager = getPsiManager(); return JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); } private static void createAndTestTag(String expectedText, String parameterName, String description) throws IncorrectOperationException { PsiElementFactory factory = getFactory(); final PsiDocTag paramTag = factory.createParamTag(parameterName, description); assertEquals(expectedText, paramTag.getText()); } }
/* * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://duracloud.org/license/ */ package org.duracloud.account.security.vote; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.aopalliance.intercept.MethodInvocation; import org.duracloud.account.db.model.AccountRights; import org.duracloud.account.db.model.DuracloudUser; import org.duracloud.account.db.model.Role; import org.duracloud.account.db.repo.DuracloudRepoMgr; import org.duracloud.account.db.repo.DuracloudRightsRepo; import org.duracloud.account.db.util.error.DBNotFoundException; import org.duracloud.account.db.util.impl.AccountManagerServiceImpl; import org.duracloud.account.security.domain.SecuredRule; import org.easymock.EasyMock; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; /** * @author Andrew Woods * Date: 4/1/11 */ public class AccountManagerAccessDecisionVoterTest { private AccountManagerAccessDecisionVoter voter; private DuracloudRepoMgr repoMgr; private Authentication authentication; private MethodInvocation invocation; private Collection<ConfigAttribute> securityConfig; private Role accessRole = Role.ROLE_USER; private Role badRole = Role.ROLE_ADMIN; @Before public void setUp() throws Exception { repoMgr = EasyMock.createMock("DuracloudRepoMgr", DuracloudRepoMgr.class); } @After public void tearDown() throws Exception { EasyMock.verify(authentication, repoMgr, invocation); } @Test public void testVoteScopeAny() throws Exception { Role userRole = Role.ROLE_USER; int expectedDecision = AccessDecisionVoter.ACCESS_GRANTED; doTestScopeAny(userRole, expectedDecision); } @Test public void testVoteScopeAnyFail() { Role userRole = Role.ROLE_ADMIN; int expectedDecision = AccessDecisionVoter.ACCESS_DENIED; doTestScopeAny(userRole, expectedDecision); } private void doTestScopeAny(Role userRole, int expectedDecision) { Long userId = 5L; authentication = createAuthentication(userId, userRole); invocation = createInvocation(null); securityConfig = createSecurityConfig(SecuredRule.Scope.ANY); doTest(expectedDecision); } private void doTest(int expectedDecision) { replayMocks(); voter = new AccountManagerAccessDecisionVoter(repoMgr); int decision = voter.vote(authentication, invocation, securityConfig); Assert.assertEquals(expectedDecision, decision); } @Test public void testScopeSelfAcct() throws DBNotFoundException { Role userRole = Role.ROLE_USER; int expectedDecision = AccessDecisionVoter.ACCESS_GRANTED; doTestScopeSelfAcct(userRole, expectedDecision); } @Test public void testScopeSelfAcctFail() throws DBNotFoundException { Role userRole = Role.ROLE_ADMIN; int expectedDecision = AccessDecisionVoter.ACCESS_DENIED; doTestScopeSelfAcct(userRole, expectedDecision); } private void doTestScopeSelfAcct(Role userRole, int expectedDecision) throws DBNotFoundException { Long userId = 5L; Long acctId = 9L; authentication = createAuthentication(userId, userRole); invocation = createInvocation(acctId); securityConfig = createSecurityConfig(SecuredRule.Scope.SELF_ACCT); repoMgr = createRepoMgr(createRights(userRole)); doTest(expectedDecision); } @Test public void testScopeSelf() throws DBNotFoundException { Role userRole = accessRole; int expectedDecision = AccessDecisionVoter.ACCESS_GRANTED; doTestScopeSelf(userRole, expectedDecision); } @Test public void testScopeSelfFailRole() throws DBNotFoundException { Role userRole = badRole; int expectedDecision = AccessDecisionVoter.ACCESS_DENIED; doTestScopeSelf(userRole, expectedDecision); } @Test public void testScopeSelfFailId() throws DBNotFoundException { Role userRole = accessRole; int expectedDecision = AccessDecisionVoter.ACCESS_DENIED; int targetUserId = 99; doTestScopeSelf(userRole, expectedDecision, targetUserId); } private void doTestScopeSelf(Role userRole, int expectedDecision) { doTestScopeSelf(userRole, expectedDecision, -1); } private void doTestScopeSelf(Role userRole, int expectedDecision, int targetId) { Long userId = 5L; Long targetUserId = targetId > -1 ? targetId : userId; authentication = createAuthentication(userId, userRole); invocation = createInvocation(userRole.equals(accessRole) ? targetUserId : null); securityConfig = createSecurityConfig(SecuredRule.Scope.SELF_ID); doTest(expectedDecision); } /** * Mocks created below. */ private AccountRights createRights(Role role) { Set<Role> roles = new HashSet<Role>(); roles.add(role); AccountRights accountRights = new AccountRights(); accountRights.setRoles(roles); return accountRights; } private DuracloudRepoMgr createRepoMgr(AccountRights rights) throws DBNotFoundException { DuracloudRepoMgr mgr = EasyMock.createMock("DuracloudRepoMgr", DuracloudRepoMgr.class); DuracloudRightsRepo rightsRepo = EasyMock.createMock( "DuracloudRightsRepo", DuracloudRightsRepo.class); EasyMock.expect(rightsRepo.findByAccountIdAndUserId(EasyMock.anyLong(), EasyMock.anyLong())) .andReturn(rights); EasyMock.expect(mgr.getRightsRepo()).andReturn(rightsRepo); EasyMock.replay(rightsRepo); return mgr; } private Authentication createAuthentication(Long userId, Role role) { Authentication auth = EasyMock.createMock("Authentication", Authentication.class); DuracloudUser user = new DuracloudUser(); user.setId(userId); user.setUsername("username"); user.setPassword("password"); user.setFirstName("firstName"); user.setLastName("lastName"); user.setEmail("email"); user.setSecurityQuestion("question"); user.setSecurityAnswer("answer"); EasyMock.expect(auth.getPrincipal()).andReturn(user); Collection<GrantedAuthority> userRoles = new HashSet<GrantedAuthority>(); userRoles.add(new SimpleGrantedAuthority(role.name())); EasyMock.expect(auth.getAuthorities()).andReturn((Collection) userRoles); return auth; } private MethodInvocation createInvocation(Long id) { MethodInvocation inv = EasyMock.createMock("MethodInvocation", MethodInvocation.class); EasyMock.expect(inv.getMethod()).andReturn(this.getClass() .getMethods()[0]); EasyMock.expect(inv.getArguments()).andReturn(new Object[0]); AccountManagerServiceImpl serviceImpl = new AccountManagerServiceImpl( null, null, null); EasyMock.expect(inv.getThis()).andReturn(serviceImpl).times(2); if (null != id) { EasyMock.expect(inv.getArguments()).andReturn(new Object[] {id}); } return inv; } private Collection<ConfigAttribute> createSecurityConfig(SecuredRule.Scope scope) { Collection<ConfigAttribute> attributes = new HashSet<ConfigAttribute>(); ConfigAttribute att = new SecurityConfig( "role:" + accessRole.name() + ",scope:" + scope.name()); attributes.add(att); return attributes; } private void replayMocks() { EasyMock.replay(authentication, repoMgr, invocation); } }
/* Copyright (c) 2015, Semcon Sweden AB All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the Semcon Sweden AB nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.caran.agaadapter; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import org.slf4j.Logger; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import android.swedspot.scs.data.DataType; /** * Loader for object defining the conversion from a MQTT signal to a SDP signal, * or the opposite. * */ public class LoadConversionConfig { /** * Logger. */ private Logger logger = null; /** * Signal conversion information. */ public ArrayList<SignalInfo> approvedSignals = null; /** * Signal conversion information. The AGA ID is the key. */ public HashMap<Integer, SignalInfo> signalFromAgaId = null; /** * Signal conversion information. The MQTT topic is the key. */ public HashMap<String, SignalInfo> signalFromTopic = null; /** * Load a .JSON file describing the conversion from MQTT to SDP * (and opposite). * @param fileName name of the .JSON file * @throws JsonSyntaxException TODO * @throws IOException TODO */ public final void loadConversionConfig(final String fileName) throws JsonSyntaxException, IOException { ConversionInfo conversionInfo = null; Gson jsonParser = new Gson(); final Float agaMultiplierDefault = 1.0f; final Float agaMultiplierMin = 0.0000001f; // Avoid divide by zero final int agaIdMax = 0xFFFF; final String[] settingsAgaTypesAllowed = new String[] { DataType.UINT8.name(), DataType.SHORT.name(), DataType.INTEGER.name(), DataType.FLOAT.name(), DataType.DOUBLE.name() }; // Read configuration file BufferedReader reader = new BufferedReader(new FileReader(fileName)); conversionInfo = jsonParser.fromJson(reader, ConversionInfo.class); // Initialize array to store approved signals approvedSignals = new ArrayList<SignalInfo>(); for (SignalInfo signal : conversionInfo.signals) { // Verify AGA id if (signal.agaId <= 0 || signal.agaId > agaIdMax) { //logger.warn("Wrong agaId for signal " + signal); continue; } // Verify AGA Type if (!(Arrays.asList(settingsAgaTypesAllowed). contains(signal.agaType))) { //logger.warn("Wrong agaType for signal " + signal + //". Not implemented."); continue; } // Give AGA multiplier a value if none was given in config file if (signal.agaMultiplier == null) { signal.agaMultiplier = agaMultiplierDefault; } // Verify that AGA multiplier is larger than MIN_ if (signal.agaMultiplier < agaMultiplierMin) { // logger.warn("Wrong agaMultiplier for signal " + signal); continue; } // Verify that MQTT topic is given if (signal.mqttTopic == null) { // logger.warn("Wrong mqttTopic for signal " + signal); continue; } // Signal is approved approvedSignals.add(signal); } // Create hash tables to ease signal lookup signalFromAgaId = new HashMap<Integer, SignalInfo>(); signalFromTopic = new HashMap<String, SignalInfo>(); for (SignalInfo signal : approvedSignals) { signalFromAgaId.put(signal.agaId, signal); signalFromTopic.put(signal.mqttTopic, signal); } // Check if topic or agaId has been duplicated if (approvedSignals.size() != signalFromAgaId.size() || approvedSignals.size() != signalFromTopic.size()) { // logger.error("mqttTopic and/or AGAid duplication found in " //+ "conversion file"); JsonSyntaxException e = new JsonSyntaxException("Duplicate data found"); throw e; } } /** * @return an object holding the approved signals. */ public final ArrayList<SignalInfo> getApprovedSignals() { return approvedSignals; } /** * Set the approved signals. * @param approvedSignals An object holding signal conversion information, * where the AGA ID is the key. */ public final void setApprovedSignals( final ArrayList<SignalInfo> approvedSignals) { this.approvedSignals = approvedSignals; } /** * @return an object holding signal conversion information, * where the AGA ID is the key. */ public final HashMap<Integer, SignalInfo> getSignalFromAgaId() { return signalFromAgaId; } /** * Set the signal conversion info. * @param signalFromAgaId An object holding signal conversion information, * where the AGA ID is the key. */ public final void setSignalFromAgaId( final HashMap<Integer, SignalInfo> signalFromAgaId) { this.signalFromAgaId = signalFromAgaId; } /** * @return an object holding signal conversion information, * where the MQTT topic is the key. */ public final HashMap<String, SignalInfo> getSignalFromTopic() { return signalFromTopic; } /** * Set the signal conversion info. * @param signalFromTopic An object holding signal conversion information, * where the MQTT topic is the key. */ public final void setSignalFromTopic( final HashMap<String, SignalInfo> signalFromTopic) { this.signalFromTopic = signalFromTopic; } }
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.externalSystem.service.project.manage; import com.intellij.ide.projectView.ProjectView; import com.intellij.ide.projectView.impl.ProjectViewPane; import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.externalSystem.ExternalSystemModulePropertyManager; import com.intellij.openapi.externalSystem.model.*; import com.intellij.openapi.externalSystem.model.project.ContentRootData; import com.intellij.openapi.externalSystem.model.project.ContentRootData.SourceRoot; import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType; import com.intellij.openapi.externalSystem.model.project.ModuleData; import com.intellij.openapi.externalSystem.model.project.ProjectData; import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider; import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemSettings; import com.intellij.openapi.externalSystem.settings.ExternalProjectSettings; import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil; import com.intellij.openapi.externalSystem.util.ExternalSystemConstants; import com.intellij.openapi.externalSystem.util.ExternalSystemUtil; import com.intellij.openapi.externalSystem.util.Order; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ContentEntry; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.SourceFolder; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.ContainerUtilRt; import com.intellij.util.containers.MultiMap; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes; import org.jetbrains.jps.model.java.JavaResourceRootType; import org.jetbrains.jps.model.java.JavaSourceRootProperties; import org.jetbrains.jps.model.java.JavaSourceRootType; import org.jetbrains.jps.model.module.JpsModuleSourceRootType; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; import static com.intellij.openapi.vfs.VfsUtilCore.pathToUrl; /** * @author Denis Zhdanov */ @Order(ExternalSystemConstants.BUILTIN_SERVICE_ORDER) public class ContentRootDataService extends AbstractProjectDataService<ContentRootData, ContentEntry> { public static final com.intellij.openapi.util.Key<Boolean> CREATE_EMPTY_DIRECTORIES = com.intellij.openapi.util.Key.create("createEmptyDirectories"); private static final Logger LOG = Logger.getInstance(ContentRootDataService.class); @NotNull @Override public Key<ContentRootData> getTargetDataKey() { return ProjectKeys.CONTENT_ROOT; } @Override public void importData(@NotNull Collection<DataNode<ContentRootData>> toImport, @Nullable ProjectData projectData, @NotNull Project project, @NotNull IdeModifiableModelsProvider modelsProvider) { logUnitTest("Importing data. Data size is [" + toImport.size() + "]"); if (toImport.isEmpty()) { return; } final SourceFolderManager sourceFolderManager = SourceFolderManager.getInstance(project); boolean isNewlyImportedProject = project.getUserData(ExternalSystemDataKeys.NEWLY_IMPORTED_PROJECT) == Boolean.TRUE; boolean forceDirectoriesCreation = false; DataNode<ProjectData> projectDataNode = ExternalSystemApiUtil.findParent(toImport.iterator().next(), ProjectKeys.PROJECT); if (projectDataNode != null) { forceDirectoriesCreation = projectDataNode.getUserData(CREATE_EMPTY_DIRECTORIES) == Boolean.TRUE; } Set<Module> modulesToExpand = ContainerUtil.newTroveSet(); MultiMap<DataNode<ModuleData>, DataNode<ContentRootData>> byModule = ExternalSystemApiUtil.groupBy(toImport, ModuleData.class); filterAndReportDuplicatingContentRoots(byModule, project); for (Map.Entry<DataNode<ModuleData>, Collection<DataNode<ContentRootData>>> entry : byModule.entrySet()) { Module module = entry.getKey().getUserData(AbstractModuleDataService.MODULE_KEY); module = module != null ? module : modelsProvider.findIdeModule(entry.getKey().getData()); if (module == null) { LOG.warn(String.format( "Can't import content roots. Reason: target module (%s) is not found at the ide. Content roots: %s", entry.getKey(), entry.getValue() )); continue; } importData(modelsProvider, sourceFolderManager, entry.getValue(), module, forceDirectoriesCreation); if (forceDirectoriesCreation || (isNewlyImportedProject && projectData != null && projectData.getLinkedExternalProjectPath().equals(ExternalSystemApiUtil.getExternalProjectPath(module)))) { modulesToExpand.add(module); } } if (!ApplicationManager.getApplication().isHeadlessEnvironment() && !modulesToExpand.isEmpty()) { for (Module module : modulesToExpand) { String productionModuleName = modelsProvider.getProductionModuleName(module); if (productionModuleName == null || !modulesToExpand.contains(modelsProvider.findIdeModule(productionModuleName))) { VirtualFile[] roots = modelsProvider.getModifiableRootModel(module).getContentRoots(); if (roots.length > 0) { VirtualFile virtualFile = roots[0]; ExternalSystemUtil.invokeLater(project, ModalityState.NON_MODAL, () -> StartupManager.getInstance(project).runWhenProjectIsInitialized(() -> { final ProjectView projectView = ProjectView.getInstance(project); projectView.changeViewCB(ProjectViewPane.ID, null).doWhenProcessed(() -> projectView.selectCB(null, virtualFile, false)); })); } } } } } private static void importData(@NotNull IdeModifiableModelsProvider modelsProvider, @NotNull SourceFolderManager sourceFolderManager, @NotNull final Collection<? extends DataNode<ContentRootData>> data, @NotNull final Module module, boolean forceDirectoriesCreation) { logUnitTest("Import data for module [" + module.getName() + "], data size [" + data.size() + "]"); final ModifiableRootModel modifiableRootModel = modelsProvider.getModifiableRootModel(module); final ContentEntry[] contentEntries = modifiableRootModel.getContentEntries(); final Map<String, ContentEntry> contentEntriesMap = ContainerUtilRt.newHashMap(); for (ContentEntry contentEntry : contentEntries) { contentEntriesMap.put(contentEntry.getUrl(), contentEntry); } boolean createEmptyContentRootDirectories = forceDirectoriesCreation; if (!forceDirectoriesCreation && !data.isEmpty()) { ProjectSystemId projectSystemId = data.iterator().next().getData().getOwner(); AbstractExternalSystemSettings externalSystemSettings = ExternalSystemApiUtil.getSettings(module.getProject(), projectSystemId); String path = ExternalSystemModulePropertyManager.getInstance(module).getRootProjectPath(); if (path != null) { ExternalProjectSettings projectSettings = externalSystemSettings.getLinkedProjectSettings(path); createEmptyContentRootDirectories = projectSettings != null && projectSettings.isCreateEmptyContentRootDirectories(); } } sourceFolderManager.removeSourceFolders(module); final Set<ContentEntry> importedContentEntries = ContainerUtil.newIdentityTroveSet(); for (final DataNode<ContentRootData> node : data) { final ContentRootData contentRoot = node.getData(); final ContentEntry contentEntry = findOrCreateContentRoot(modifiableRootModel, contentRoot.getRootPath()); if (!importedContentEntries.contains(contentEntry)) { removeSourceFoldersIfAbsent(contentEntry, contentRoot); importedContentEntries.add(contentEntry); } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Importing content root '%s' for module '%s'", contentRoot.getRootPath(), module.getName())); } for (ExternalSystemSourceType externalSrcType : ExternalSystemSourceType.values()) { final JpsModuleSourceRootType<?> type = getJavaSourceRootType(externalSrcType); if (type != null) { for (SourceRoot path : contentRoot.getPaths(externalSrcType)) { createSourceRootIfAbsent( sourceFolderManager, contentEntry, path, module, type, externalSrcType.isGenerated(), createEmptyContentRootDirectories); } } } for (SourceRoot path : contentRoot.getPaths(ExternalSystemSourceType.EXCLUDED)) { createExcludedRootIfAbsent(contentEntry, path, module.getName(), module.getProject()); } contentEntriesMap.remove(contentEntry.getUrl()); } for (ContentEntry contentEntry : contentEntriesMap.values()) { modifiableRootModel.removeContentEntry(contentEntry); } } @Nullable private static JpsModuleSourceRootType<?> getJavaSourceRootType(ExternalSystemSourceType type) { switch (type) { case SOURCE: return JavaSourceRootType.SOURCE; case TEST: return JavaSourceRootType.TEST_SOURCE; case EXCLUDED: return null; case SOURCE_GENERATED: return JavaSourceRootType.SOURCE; case TEST_GENERATED: return JavaSourceRootType.TEST_SOURCE; case RESOURCE: return JavaResourceRootType.RESOURCE; case TEST_RESOURCE: return JavaResourceRootType.TEST_RESOURCE; } return null; } @NotNull private static ContentEntry findOrCreateContentRoot(@NotNull ModifiableRootModel model, @NotNull String path) { ContentEntry[] entries = model.getContentEntries(); for (ContentEntry entry : entries) { VirtualFile file = entry.getFile(); if (file == null) { continue; } if (ExternalSystemApiUtil.getLocalFileSystemPath(file).equals(path)) { return entry; } } return model.addContentEntry(pathToUrl(path)); } private static Set<String> getSourceRoots(@NotNull ContentRootData contentRoot) { Set<String> sourceRoots = new THashSet<>(FileUtil.PATH_HASHING_STRATEGY); for (ExternalSystemSourceType externalSrcType : ExternalSystemSourceType.values()) { final JpsModuleSourceRootType<?> type = getJavaSourceRootType(externalSrcType); if (type == null) continue; for (SourceRoot path : contentRoot.getPaths(externalSrcType)) { if (path == null) continue; sourceRoots.add(path.getPath()); } } return sourceRoots; } private static void removeSourceFoldersIfAbsent(@NotNull ContentEntry contentEntry, @NotNull ContentRootData contentRoot) { Set<String> sourceRoots = getSourceRoots(contentRoot); SourceFolder[] sourceFolders = contentEntry.getSourceFolders(); for (SourceFolder sourceFolder : sourceFolders) { String url = sourceFolder.getUrl(); String path = VfsUtilCore.urlToPath(url); if (!sourceRoots.contains(path)) { contentEntry.removeSourceFolder(sourceFolder); } } } private static void createSourceRootIfAbsent( @NotNull SourceFolderManager sourceFolderManager, @NotNull ContentEntry entry, @NotNull final SourceRoot root, @NotNull Module module, @NotNull JpsModuleSourceRootType<?> sourceRootType, boolean generated, boolean createEmptyContentRootDirectories) { logUnitTest("create source root if absent entry.url=[" + entry.getUrl() + "] root.path=[" + root.getPath() + "]" + " generated=[" + generated + "] createEmptyContentRootDirectories=[" + createEmptyContentRootDirectories + "]"); SourceFolder[] folders = entry.getSourceFolders(); for (SourceFolder folder : folders) { VirtualFile file = folder.getFile(); if (file == null) { continue; } if (ExternalSystemApiUtil.getLocalFileSystemPath(file).equals(root.getPath())) { final JpsModuleSourceRootType<?> folderRootType = folder.getRootType(); if(JavaSourceRootType.SOURCE.equals(folderRootType) || sourceRootType.equals(folderRootType)) { return; } if(JavaSourceRootType.TEST_SOURCE.equals(folderRootType) && JavaResourceRootType.TEST_RESOURCE.equals(sourceRootType)) { return; } entry.removeSourceFolder(folder); } } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Importing %s for content root '%s' of module '%s'", root, entry.getUrl(), module.getName())); } if (!createEmptyContentRootDirectories && !generated) { if (!FileUtil.exists(root.getPath())) { if (LOG.isDebugEnabled()) { LOG.debug("Source folder [" + root.getPath() + "] does not exist and will not be created, will add when dir is created"); } logUnitTest("Adding source folder listener to watch [" + root.getPath() + "] for creation in project [hashCode=" + module.getProject().hashCode() + "]"); String url = pathToUrl(root.getPath()); String packagePrefix = StringUtil.notNullize(root.getPackagePrefix()); sourceFolderManager.addSourceFolder(module, url, sourceRootType, packagePrefix); return; } } SourceFolder sourceFolder = entry.addSourceFolder(pathToUrl(root.getPath()), sourceRootType); if (!StringUtil.isEmpty(root.getPackagePrefix())) { sourceFolder.setPackagePrefix(root.getPackagePrefix()); } if (generated) { JavaSourceRootProperties properties = sourceFolder.getJpsElement().getProperties(JavaModuleSourceRootTypes.SOURCES); if(properties != null) { properties.setForGeneratedSources(true); } } if(createEmptyContentRootDirectories && !FileUtil.exists(root.getPath())) { ExternalSystemApiUtil.doWriteAction(() -> { try { VfsUtil.createDirectoryIfMissing(root.getPath()); } catch (IOException e) { LOG.warn(String.format("Unable to create directory for the path: %s", root.getPath()), e); } }); } } private static void logUnitTest(String message) { if (ApplicationManager.getApplication().isUnitTestMode()) { LOG.info(message); } } private static void createExcludedRootIfAbsent(@NotNull ContentEntry entry, @NotNull SourceRoot root, @NotNull String moduleName, @NotNull Project project) { String rootPath = root.getPath(); for (VirtualFile file : entry.getExcludeFolderFiles()) { if (ExternalSystemApiUtil.getLocalFileSystemPath(file).equals(rootPath)) { return; } } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Importing excluded root '%s' for content root '%s' of module '%s'", root, entry.getUrl(), moduleName)); } entry.addExcludeFolder(pathToUrl(rootPath)); if (!Registry.is("ide.hide.excluded.files")) { ChangeListManager.getInstance(project).addDirectoryToIgnoreImplicitly(rootPath); } } private static void filterAndReportDuplicatingContentRoots(@NotNull MultiMap<DataNode<ModuleData>, DataNode<ContentRootData>> moduleNodeToRootNodes, @NotNull Project project) { Map<String, DuplicateModuleReport> filter = ContainerUtil.newLinkedHashMap(); for (Map.Entry<DataNode<ModuleData>, Collection<DataNode<ContentRootData>>> entry : moduleNodeToRootNodes.entrySet()) { ModuleData moduleData = entry.getKey().getData(); Collection<DataNode<ContentRootData>> crDataNodes = entry.getValue(); for (Iterator<DataNode<ContentRootData>> iterator = crDataNodes.iterator(); iterator.hasNext(); ) { DataNode<ContentRootData> crDataNode = iterator.next(); String rootPath = crDataNode.getData().getRootPath(); DuplicateModuleReport report = filter.putIfAbsent(rootPath, new DuplicateModuleReport(moduleData)); if (report != null) { report.addDuplicate(moduleData); iterator.remove(); crDataNode.clear(true); } } } Map<String, DuplicateModuleReport> toReport = filter.entrySet().stream() .filter(e -> e.getValue().hasDuplicates()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (r1, r2) -> { LOG.warn("Unexpected duplicates in keys while collecting filtered reports"); return r2; }, LinkedHashMap::new)); if (!toReport.isEmpty()) { String notificationMessage = prepareMessageAndLogWarnings(toReport); if (notificationMessage != null) { showNotificationsPopup(project, toReport.size(), notificationMessage); } } } @Nullable private static String prepareMessageAndLogWarnings(@NotNull Map<String, DuplicateModuleReport> toReport) { String firstMessage = null; LOG.warn("Duplicating content roots detected."); for (Map.Entry<String, DuplicateModuleReport> entry : toReport.entrySet()) { String path = entry.getKey(); DuplicateModuleReport report = entry.getValue(); String message = String.format("Path [%s] of module [%s] was removed from modules [%s]", path, report.getOriginalName(), StringUtil.join(report.getDuplicatesNames(), ", ")); if (firstMessage == null) { firstMessage = message; } LOG.warn(message); } return firstMessage; } private static void showNotificationsPopup(@NotNull Project project, int reportsCount, @NotNull String notificationMessage) { int extraReportsCount = reportsCount - 1; if (extraReportsCount > 0) { notificationMessage += "<br>Also " + extraReportsCount + " more " + StringUtil.pluralize("path", extraReportsCount) + " " + (extraReportsCount == 1 ? "was" : "were") + " deduplicated. See idea log for details"; } Notification notification = new Notification("Content root duplicates", "Duplicate content roots detected", notificationMessage, NotificationType.WARNING); Notifications.Bus.notify(notification, project); } private static class DuplicateModuleReport { private final ModuleData myOriginal; private final List<ModuleData> myDuplicates = new ArrayList<>(); public DuplicateModuleReport(@NotNull ModuleData original) { myOriginal = original; } public void addDuplicate(@NotNull ModuleData duplicate) { myDuplicates.add(duplicate); } public boolean hasDuplicates() { return !myDuplicates.isEmpty(); } public String getOriginalName() { return myOriginal.getInternalName(); } public Collection<String> getDuplicatesNames() { return ContainerUtil.map(myDuplicates, ModuleData::getInternalName); } } }
package io.protolang; import static io.protolang.Generator.unQuote; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Generated; import javax.validation.constraints.NotNull; import org.apache.commons.lang.WordUtils; import org.slf4j.Logger; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.helger.jcodemodel.AbstractJClass; import com.helger.jcodemodel.AbstractJType; import com.helger.jcodemodel.IJExpression; import com.helger.jcodemodel.JAnnotationArrayMember; import com.helger.jcodemodel.JAnnotationUse; import com.helger.jcodemodel.JArray; import com.helger.jcodemodel.JAtom; import com.helger.jcodemodel.JClassAlreadyExistsException; import com.helger.jcodemodel.JCodeModel; import com.helger.jcodemodel.JDefinedClass; import com.helger.jcodemodel.JEnumConstant; import com.helger.jcodemodel.JExpr; import com.helger.jcodemodel.JFieldVar; import com.helger.jcodemodel.JMethod; import com.helger.jcodemodel.JMod; import com.helger.jcodemodel.JMods; import com.helger.jcodemodel.JPackage; import io.protolang.ProtoParserParser.All_identifiersContext; import io.protolang.ProtoParserParser.Any_of_defContext; import io.protolang.ProtoParserParser.CollectionContext; import io.protolang.ProtoParserParser.Collection_mapContext; import io.protolang.ProtoParserParser.Collection_map_valueContext; import io.protolang.ProtoParserParser.Collection_typeContext; import io.protolang.ProtoParserParser.Constant_defContext; import io.protolang.ProtoParserParser.Enum_defContext; import io.protolang.ProtoParserParser.Enum_member_tagContext; import io.protolang.ProtoParserParser.Import_defContext; import io.protolang.ProtoParserParser.Literal_valueContext; import io.protolang.ProtoParserParser.MapContext; import io.protolang.ProtoParserParser.Map_keyContext; import io.protolang.ProtoParserParser.Map_valueContext; import io.protolang.ProtoParserParser.Message_defContext; import io.protolang.ProtoParserParser.Message_field_defContext; import io.protolang.ProtoParserParser.Message_field_default_valueContext; import io.protolang.ProtoParserParser.Message_field_json_typeContext; import io.protolang.ProtoParserParser.Message_field_optionsContext; import io.protolang.ProtoParserParser.Message_field_requiredContext; import io.protolang.ProtoParserParser.Message_field_typeContext; import io.protolang.ProtoParserParser.One_of_defContext; import io.protolang.ProtoParserParser.One_of_def_memberContext; import io.protolang.ProtoParserParser.Package_defContext; import io.protolang.ProtoParserParser.ProtoContext; import io.protolang.ProtoParserParser.Service_defContext; import io.protolang.ProtoParserParser.Service_method_defContext; import io.protolang.ProtoParserParser.Service_method_excpContext; public class Antlr4ProtoVisitor extends ProtoParserBaseVisitor<Void> { protected final Logger logger = Generator.LOGGER; protected final JCodeModel codeModel; protected final String containerName; protected final Set<String> importedContainers; protected final Map<String, JCodeModel> importedModels; public Antlr4ProtoVisitor(JCodeModel codeModel, String containerName, Map<String, JCodeModel> importedModels) { this.codeModel = codeModel; this.containerName = containerName; this.importedModels = importedModels; this.importedContainers = new HashSet<String>(); } @Override public Void visitImport_def(Import_defContext ctx) { String toImport = unQuote( ctx.import_value().STRING_LITERAL().getText() ); String c = Generator.toContainerName( toImport ); importedContainers.add( c ); return super.visitImport_def( ctx ); } @Override public Void visitPackage_def(Package_defContext ctx) { try { String pkg = ctx.package_name().getText(); JDefinedClass container = codeModel._package( pkg )._interface( containerName ); logger.info( "Proto({}.{})", container._package().name(), container.name() ); return super.visitPackage_def( ctx ); } catch ( JClassAlreadyExistsException err ) { throw new RuntimeException( err ); } } @Override public Void visitConstant_def(Constant_defContext ctx) { String constName = ctx.constant_name().IDENTIFIER().getText(); String constType = ctx.constant_type().TYPE_LITERAL().getText(); Literal_valueContext lit = ctx.literal_value(); ProtoTypes type = ProtoTypes.valueOf( constType.toUpperCase() ); ProtoContext pkgCtx = (ProtoContext) ctx.getParent(); String pkg = pkgCtx.package_def().package_name().QUALIFIED_IDENTIFIER().getText(); JDefinedClass container = codeModel._package( pkg )._getClass( containerName ); int modifier = JMod.PUBLIC | JMod.STATIC | JMod.FINAL; AbstractJType jtype = primitiveType( type ).unboxify(); JFieldVar f = container.field( modifier, jtype, constName.toUpperCase(), parse( type, container, lit ) ); logger.info( "\t +-> {} {} = {}", f.type().name(), f.name(), lit.getText() ); return super.visitConstant_def( ctx ); } @Override public Void visitMessage_def(Message_defContext ctx) { try { boolean isError = ctx.messsage_type().ERROR_LITERAL() != null; String name = ctx.message_name().IDENTIFIER().getText(); AbstractJClass parent = isError ? codeModel.ref( Exception.class ) : codeModel.ref( Object.class ); ProtoContext pkgCtx = (ProtoContext) ctx.getParent(); String pkg = pkgCtx.package_def().package_name().QUALIFIED_IDENTIFIER().getText(); JPackage jPackage = codeModel._package( pkg ); JDefinedClass m = jPackage._class( name ); JDefinedClass container = jPackage._getClass( containerName ); if ( ctx.message_parent() != null && ctx.message_parent().message_parent_message() != null ) { All_identifiersContext parentCtx = ctx.message_parent().message_parent_message().all_identifiers(); parent = resolveType( container, parentCtx ); } if ( parent != null ) { m._extends( parent ); } container.field( JMod.PUBLIC | JMod.FINAL | JMod.STATIC, m, name, JExpr._new( m ) ); addDenifition( container, m ); JAnnotationUse generated = m.annotate( Generated.class ); generated.param( "date", new Date().toString() ); generated.paramArray( JAnnotationUse.SPECIAL_KEY_VALUE ).param( Generator.class.getName() ); logger.info( "Message({}.{})", m._package().name(), m.name() ); return super.visitMessage_def( ctx ); } catch ( JClassAlreadyExistsException err ) { throw new RuntimeException( err ); } } @Override public Void visitMessage_field_def(Message_field_defContext ctx) { try { int fieldTag = Integer.parseInt( ctx.message_field_tag().INTEGER_LITERAL().getText() ); String fieldName = ctx.message_field_name().IDENTIFIER().getText(); List<Message_field_optionsContext> optionsCtxs = ctx.message_field_options(); Message_defContext mCtx = ( (Message_defContext) ctx.getParent().getRuleContext() ); ProtoContext pkgCtx = (ProtoContext) mCtx.getParent(); String pkg = pkgCtx.package_def().package_name().QUALIFIED_IDENTIFIER().getText(); JPackage jPackage = codeModel._package( pkg ); String msgName = mCtx.message_name().IDENTIFIER().getText(); JDefinedClass m = jPackage._getClass( msgName ); JDefinedClass container = jPackage._getClass( containerName ); Message_field_requiredContext requiredCtx = null; Message_field_default_valueContext defaultValueCtx = null; Message_field_json_typeContext jsonTypeCtx = null; if ( optionsCtxs != null ) { for ( Message_field_optionsContext option : optionsCtxs ) { if ( option.message_field_default_value() != null ) { defaultValueCtx = option.message_field_default_value(); } if ( option.message_field_json_type() != null ) { jsonTypeCtx = option.message_field_json_type(); } if ( option.message_field_required() != null ) { requiredCtx = option.message_field_required(); } } } String jsonType = null; if ( jsonTypeCtx != null ) { jsonType = parseString( container, jsonTypeCtx.literal_value() ); } AbstractJClass fieldType = null; JFieldVar field = null; IJExpression fieldInit = null; List<AbstractJClass> oneOfSubTypes = new LinkedList<AbstractJClass>(); AbstractJClass anyOfType = null; Message_field_typeContext mftCtx = ctx.message_field_type(); One_of_defContext oneOfCtx = mftCtx.one_of_def(); Any_of_defContext anyOfCtx = mftCtx.any_of_def(); if ( oneOfCtx != null ) { fieldType = codeModel.ref( Object.class ); for ( One_of_def_memberContext next : oneOfCtx.one_of_def_member() ) { oneOfSubTypes.add( resolveType( container, next.all_identifiers() ) ); } } else if ( anyOfCtx != null ) { fieldType = resolveType( container, anyOfCtx.any_of_def_base_type().all_identifiers() ); anyOfType = fieldType; } else { Collection_map_valueContext collectionMapValueCtx = mftCtx.collection_map_value(); if ( defaultValueCtx != null ) { ProtoTypes type = ProtoTypes.valueOf( collectionMapValueCtx.TYPE_LITERAL().getText().toUpperCase() ); fieldInit = parse( type, container, defaultValueCtx.literal_value() ); } fieldType = resolveType( container, collectionMapValueCtx ); } field = m.field( JMod.PRIVATE, fieldType, fieldName, fieldInit ); // // field meta-data // int staticMod = JMod.PUBLIC | JMod.FINAL | JMod.STATIC; String constTagName = Generator.toConstTagName( field ); String constFieldName = Generator.toConstFieldName( field ); m.field( staticMod, int.class, constTagName, JExpr.lit( fieldTag ) ); m.field( staticMod, String.class, constFieldName, JExpr.lit( field.name() ) ); // // getter // String getterName = Generator.getterName( field, m, codeModel ); JMethod getter = m.method( JMod.PUBLIC, field.type(), getterName ); getter.body()._return( field ); JAnnotationUse jsonProperty = getter.annotate( JsonProperty.class ); jsonProperty.param( "index", JExpr.ref( constTagName ) ); jsonProperty.param( JAnnotationUse.SPECIAL_KEY_VALUE, JExpr.ref( constFieldName ) ); if ( !oneOfSubTypes.isEmpty() ) { JAnnotationUse jsonTypeInfo = getter.annotate( JsonTypeInfo.class ); jsonTypeInfo.param( "use", JsonTypeInfo.Id.NAME ); jsonTypeInfo.param( "include", JsonTypeInfo.As.PROPERTY ); if ( jsonType != null ) { jsonTypeInfo.param( "property", jsonType ); } JAnnotationUse jsonSubTypes = getter.annotate( JsonSubTypes.class ); JAnnotationArrayMember jsonSubTypesArray = jsonSubTypes.paramArray( JAnnotationUse.SPECIAL_KEY_VALUE ); for ( AbstractJClass oneOf : oneOfSubTypes ) { JAnnotationUse jsonSubType = jsonSubTypesArray.annotate( JsonSubTypes.Type.class ); jsonSubType.param( JAnnotationUse.SPECIAL_KEY_VALUE, oneOf ); } } if ( anyOfType != null ) { JAnnotationUse jsonTypeInfo = getter.annotate( JsonTypeInfo.class ); jsonTypeInfo.param( "use", JsonTypeInfo.Id.CLASS ); jsonTypeInfo.param( "include", JsonTypeInfo.As.PROPERTY ); if ( jsonType != null ) { jsonTypeInfo.param( "property", jsonType ); } } if ( optionsCtxs != null ) { if ( fieldInit != null ) { jsonProperty.param( "defaultValue", JExpr.lit( Generator.expressionValue( fieldInit ).toString() ) ); } if ( requiredCtx != null ) { boolean required = parseBool( container, requiredCtx.literal_value() ); jsonProperty.param( "required", required ); getter.annotate( NotNull.class ); } } // // setter // String var = "var"; JMethod setter = m.method( JMod.PUBLIC, void.class, "set" + WordUtils.capitalize( field.name() ) ); setter.param( fieldType, var ); setter.body().assign( JExpr._this().ref( field.name() ), JExpr.ref( var ) ); logger.info( "\t +-> {}.{} {}({})", m._package().name(), m.name(), field.name(), field.type().name() ); return super.visitMessage_field_def( ctx ); } catch ( Throwable err ) { throw new RuntimeException( err ); } } @Override public Void visitEnum_def(Enum_defContext ctx) { try { String name = ctx.enum_name().IDENTIFIER().getText(); ProtoContext pkgCtx = (ProtoContext) ctx.getParent(); String pkg = pkgCtx.package_def().package_name().QUALIFIED_IDENTIFIER().getText(); JPackage jPackage = codeModel._package( pkg ); JDefinedClass m = codeModel._package( pkg )._enum( name ); JDefinedClass container = jPackage._getClass( containerName ); String tag = "tag"; m.field( JMod.PUBLIC | JMod.FINAL, codeModel.INT, tag ); JMethod constructor = m.constructor( JMod.PRIVATE ); constructor.param( codeModel.INT, tag ); constructor.body().assign( JExpr._this().ref( tag ), JExpr.ref( tag ) ); addDenifition( container, m ); logger.info( "Enum({}.{})", m._package().name(), m.name() ); return super.visitEnum_def( ctx ); } catch ( JClassAlreadyExistsException err ) { throw new RuntimeException( err ); } } @Override public Void visitEnum_member_tag(Enum_member_tagContext ctx) { int enumTag = Integer.parseInt( ctx.enum_tag().INTEGER_LITERAL().getText() ); String enumMember = ctx.enum_member().IDENTIFIER().getText(); Enum_defContext enumCtx = (Enum_defContext) ctx.getParent(); String enumName = enumCtx.enum_name().IDENTIFIER().getText(); ProtoContext pkgCtx = (ProtoContext) enumCtx.getParent(); String pkg = pkgCtx.package_def().package_name().QUALIFIED_IDENTIFIER().getText(); JDefinedClass m = codeModel._package( pkg )._getClass( enumName ); JEnumConstant enumConstant = m.enumConstant( enumMember ); enumConstant.arg( JExpr.lit( enumTag ) ).annotate( JsonProperty.class ).param( "index", enumTag ); logger.info( "\t +-> {}.{} {}", m._package().name(), m.name(), enumMember ); return super.visitEnum_member_tag( ctx ); } @Override public Void visitService_def(Service_defContext ctx) { try { String name = ctx.service_name().IDENTIFIER().getText(); ProtoContext pkgCtx = (ProtoContext) ctx.getParent(); String pkg = pkgCtx.package_def().package_name().QUALIFIED_IDENTIFIER().getText(); JPackage jPackage = codeModel._package( pkg ); JDefinedClass i = jPackage._interface( name ); JDefinedClass container = jPackage._getClass( containerName ); if ( ctx.service_parent() != null && ctx.service_parent().service_parent_message() != null ) { All_identifiersContext parent = ctx.service_parent().service_parent_message().all_identifiers(); i._extends( resolveType( container, parent ) ); } addDenifition( container, i ); logger.info( "Interface({}.{})", i._package().name(), i.name() ); return super.visitService_def( ctx ); } catch ( JClassAlreadyExistsException err ) { throw new RuntimeException( err ); } } @Override public Void visitService_method_def(Service_method_defContext ctx) { String methodName = ctx.service_method_name().IDENTIFIER().getText(); ProtoContext pkgCtx = (ProtoContext) ctx.getParent().getParent(); String pkg = pkgCtx.package_def().package_name().QUALIFIED_IDENTIFIER().getText(); JPackage jPackage = codeModel._package( pkg ); JDefinedClass container = jPackage._getClass( containerName ); Service_defContext sCtx = (Service_defContext) ctx.getParent(); String serviceName = sCtx.service_name().IDENTIFIER().getText(); JDefinedClass service = jPackage._getClass( serviceName ); Collection_map_valueContext reqCtx = ctx.service_method_req().collection_map_value(); AbstractJClass respType = resolveType( container, ctx.service_method_resp().collection_map_value() ); AbstractJClass reqType = null; JMethod m = service.method( JMod.PUBLIC, respType, methodName ); if ( reqCtx != null ) { reqType = resolveType( container, reqCtx ); m.param( reqType, "var" ); } List<Service_method_excpContext> excpCtxs = ctx.service_method_throws().service_method_excp(); for ( Service_method_excpContext excpCtx : excpCtxs ) { AbstractJClass exception = resolveType( container, excpCtx.all_identifiers() ); m._throws( exception ); } logger.info( "\t +-> {}({}) -> {}", m.name(), ( reqType != null ? reqType.name() : "" ), respType.name() ); return super.visitService_method_def( ctx ); } private AbstractJClass resolveType(JDefinedClass container, All_identifiersContext identifier) { AbstractJClass definedClass = null; if ( identifier.IDENTIFIER() != null ) { String name = identifier.IDENTIFIER().getText(); definedClass = container.getPackage()._getClass( name ); if ( definedClass == null ) { List<String> pkgs = new LinkedList<String>(); for ( String ic : importedContainers ) { JCodeModel cm = importedModels.get( ic ); Iterator<JPackage> it = cm.packages(); while ( it.hasNext() ) { JPackage jPackage = it.next(); pkgs.add( jPackage.name() ); AbstractJClass toUpdate = jPackage._getClass( name ); if ( toUpdate != null ) { if ( definedClass != null && !definedClass.equals( toUpdate ) ) throw new IllegalStateException( "no unique type reference to " + identifier.getText() ); definedClass = toUpdate; } } } if ( definedClass == null ) { String err = String.format( "unable to resolve type %s in any of %s packages", name, pkgs ); throw new IllegalStateException( err ); } } } else { String qname = identifier.QUALIFIED_IDENTIFIER().getText(); int idx = qname.lastIndexOf( '.' ); String pkg = qname.substring( 0, idx ); String msgName = qname.substring( idx + 1 ); for ( String ic : importedContainers ) { JCodeModel cm = importedModels.get( ic ); Iterator<JPackage> it = cm.packages(); while ( it.hasNext() ) { JPackage jPackage = it.next(); if ( pkg.equals( jPackage.name() ) ) { definedClass = jPackage._getClass( msgName ); } } } if ( definedClass == null ) { String err = String.format( "unable to resolve fully qualified type %s, check imports", qname ); throw new IllegalStateException( err ); } } return definedClass; } private AbstractJClass resolveType(JDefinedClass container, Collection_map_valueContext cmp) { // // resolve primitive type or reference // if ( cmp.TYPE_LITERAL() != null ) return primitiveType( ProtoTypes.valueOf( cmp.TYPE_LITERAL().getText().toUpperCase() ) ); else if ( cmp.all_identifiers() != null ) return resolveType( container, cmp.all_identifiers() ); // // resolve (set/list) // Collection_mapContext cmCtx = cmp.collection_map(); CollectionContext collectionCtx = cmCtx.collection(); if ( collectionCtx != null ) { Collection_typeContext typeContext = collectionCtx.collection_type(); boolean isSet = "set".equalsIgnoreCase( collectionCtx.COLLECTION_LITERAL().getText() ); AbstractJClass collectionClass = isSet ? codeModel.ref( Set.class ) : codeModel.ref( List.class ); if ( typeContext.TYPE_LITERAL() != null ) return collectionClass.narrow( primitiveType( ProtoTypes.valueOf( typeContext.TYPE_LITERAL().getText().toUpperCase() ) ) ); return collectionClass.narrow( resolveType( container, typeContext.all_identifiers() ) ); } // // resolve map // MapContext mapCtx = cmCtx.map(); Map_keyContext map_key = mapCtx.map_key(); Map_valueContext map_value = mapCtx.map_value(); AbstractJClass keyClass; AbstractJClass valueClass; if ( map_key.TYPE_LITERAL() != null ) { keyClass = primitiveType( ProtoTypes.valueOf( map_key.TYPE_LITERAL().getText().toUpperCase() ) ); } else { keyClass = resolveType( container, map_key.all_identifiers() ); } if ( map_value.TYPE_LITERAL() != null ) { valueClass = primitiveType( ProtoTypes.valueOf( map_value.TYPE_LITERAL().getText().toUpperCase() ) ); } else { valueClass = resolveType( container, map_value.all_identifiers() ); } AbstractJClass mapClass = codeModel.ref( Map.class ); return mapClass.narrow( keyClass, valueClass ); } private AbstractJClass primitiveType(ProtoTypes type) { switch ( type ) { case INT16: return codeModel.ref( Short.class ); case INT32: return codeModel.ref( Integer.class ); case INT64: return codeModel.ref( Long.class ); case DOUBLE: return codeModel.ref( Double.class ); case FLOAT: return codeModel.ref( Float.class ); case BYTE: return codeModel.ref( Byte.class ); case STRING: return codeModel.ref( String.class ); case BOOLEAN: return codeModel.ref( Boolean.class ); case BINARY: { return codeModel.ref( byte[].class ); } default: throw new IllegalStateException( type.name() ); } } private IJExpression parseSubstitution(JDefinedClass container, All_identifiersContext identifier) { JFieldVar f = null; if ( identifier.IDENTIFIER() != null ) { String contantName = identifier.IDENTIFIER().getText(); if ( container.containsField( contantName ) ) { f = container.fields().get( contantName ); } else { Set<String> pkgs = new HashSet<String>(); for ( String ic : importedContainers ) { JCodeModel cm = importedModels.get( ic ); Iterator<JPackage> it = cm.packages(); while ( it.hasNext() ) { JPackage jPackage = it.next(); pkgs.add( jPackage.name() ); JDefinedClass c = jPackage._getClass( ic ); Collection<JFieldVar> fields = c.fields().values(); for ( JFieldVar candidate : fields ) { JMods mods = candidate.mods(); if ( mods.isStatic() ) { if ( candidate.name().equals( contantName ) ) { if ( f != null ) throw new IllegalStateException( "no unique substitution of " + identifier.getText() ); f = candidate; } } } } } if ( f == null ) { String err = String.format( "unable to resolve subsitution %s in any of %s packages", contantName, pkgs ); throw new IllegalStateException( err ); } } } else { String qname = identifier.QUALIFIED_IDENTIFIER().getText(); int idx = qname.lastIndexOf( '.' ); String pkg = qname.substring( 0, idx ); String contantName = qname.substring( idx + 1 ); for ( String ic : importedContainers ) { JCodeModel cm = importedModels.get( ic ); Iterator<JPackage> it = cm.packages(); while ( it.hasNext() ) { JPackage jPackage = it.next(); if ( pkg.equals( jPackage.name() ) ) { JDefinedClass c = jPackage._getClass( ic ); Collection<JFieldVar> fields = c.fields().values(); for ( JFieldVar candidate : fields ) { JMods mods = candidate.mods(); if ( mods.isStatic() ) { if ( candidate.name().equals( contantName ) ) { f = candidate; } } } } } } if ( f == null ) { String err = String.format( "unable to resolve fully qualified subsitution %s, check imports", qname ); throw new IllegalStateException( err ); } } return Generator.fieldInit( f ); } private IJExpression parse(ProtoTypes type, JDefinedClass container, Literal_valueContext literal) { switch ( type ) { case INT16: { return JExpr.lit( parseShort( container, literal ) ); } case INT32: { return JExpr.lit( parseInt( container, literal ) ); } case INT64: { return JExpr.lit( parseLong( container, literal ) ); } case DOUBLE: { return JExpr.lit( parseDouble( container, literal ) ); } case FLOAT: { return JExpr.lit( parseFloat( container, literal ) ); } case BYTE: { return JExpr.lit( parseByte( container, literal ) ); } case STRING: { return JExpr.lit( parseString( container, literal ) ); } case BOOLEAN: { return JExpr.lit( parseBool( container, literal ) ); } default: throw new IllegalStateException( literal.getText() ); } } private String parseString(JDefinedClass container, Literal_valueContext l) { if ( l.literal_substitude() != null ) { All_identifiersContext subsitude = l.literal_substitude().all_identifiers(); IJExpression expression = parseSubstitution( container, subsitude ); return Generator.expressionValue( expression ).toString(); } String text = l.literal_without_substitude().STRING_LITERAL().getText(); return text.substring( 1, text.length() - 1 ); } private float parseFloat(JDefinedClass container, Literal_valueContext l) { if ( l.literal_substitude() != null ) { All_identifiersContext subsitude = l.literal_substitude().all_identifiers(); return Float.parseFloat( Generator.expressionValue( parseSubstitution( container, subsitude ) ).toString() ); } return Float.parseFloat( l.literal_without_substitude().FLOAT_LITERAL().getText() ); } private double parseDouble(JDefinedClass container, Literal_valueContext l) { if ( l.literal_substitude() != null ) { All_identifiersContext subsitude = l.literal_substitude().all_identifiers(); return Double.parseDouble( Generator.expressionValue( parseSubstitution( container, subsitude ) ).toString() ); } return Double.parseDouble( l.literal_without_substitude().FLOAT_LITERAL().getText() ); } private long parseLong(JDefinedClass container, Literal_valueContext l) { if ( l.literal_substitude() != null ) { All_identifiersContext subsitude = l.literal_substitude().all_identifiers(); return Long.parseLong( Generator.expressionValue( parseSubstitution( container, subsitude ) ).toString() ); } return Long.parseLong( l.literal_without_substitude().INTEGER_LITERAL().getText() ); } private int parseInt(JDefinedClass container, Literal_valueContext l) { if ( l.literal_substitude() != null ) { All_identifiersContext subsitude = l.literal_substitude().all_identifiers(); return Integer.parseInt( Generator.expressionValue( parseSubstitution( container, subsitude ) ).toString() ); } return Integer.parseInt( l.literal_without_substitude().INTEGER_LITERAL().getText() ); } private short parseShort(JDefinedClass container, Literal_valueContext l) { if ( l.literal_substitude() != null ) { All_identifiersContext subsitude = l.literal_substitude().all_identifiers(); return Short.parseShort( Generator.expressionValue( parseSubstitution( container, subsitude ) ).toString() ); } return Short.parseShort( l.literal_without_substitude().INTEGER_LITERAL().getText() ); } private byte parseByte(JDefinedClass container, Literal_valueContext l) { if ( l.literal_substitude() != null ) { All_identifiersContext subsitude = l.literal_substitude().all_identifiers(); return Byte.parseByte( Generator.expressionValue( parseSubstitution( container, subsitude ) ).toString() ); } return Byte.parseByte( l.literal_without_substitude().INTEGER_LITERAL().getText() ); } private boolean parseBool(JDefinedClass container, Literal_valueContext l) { String asText; if ( l.literal_substitude() != null ) { All_identifiersContext subsitude = l.literal_substitude().all_identifiers(); JAtom init = (JAtom) parseSubstitution( container, subsitude ); asText = init.what(); } else { asText = l.literal_without_substitude().BOOL_LITERAL().getText(); } if ( Boolean.TRUE.toString().equals( asText ) ) return true; else if ( Boolean.FALSE.toString().equals( asText ) ) return false; throw new IllegalArgumentException( "unable to parse boolean value " + asText ); } private void addDenifition(JDefinedClass container, JDefinedClass member) { if ( !container.containsField( Generator.MESSAGES_FIELD ) ) { container.field( JMod.PUBLIC | JMod.FINAL | JMod.STATIC, Class[].class, Generator.MESSAGES_FIELD, JExpr.newArray( codeModel.ref( Class.class ) ) ); } for ( JFieldVar next : container.fields().values() ) { if ( next.name().equals( Generator.MESSAGES_FIELD ) ) { JArray fieldInit = (JArray) Generator.fieldInit( next ); fieldInit.add( member.dotclass() ); break; } } } }
/* * 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.gateway; import org.apache.logging.log4j.message.ParameterizedMessage; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.Version; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.FailedNodeException; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.nodes.BaseNodeRequest; import org.elasticsearch.action.support.nodes.BaseNodeResponse; import org.elasticsearch.action.support.nodes.BaseNodesRequest; import org.elasticsearch.action.support.nodes.BaseNodesResponse; import org.elasticsearch.action.support.nodes.TransportNodesAction; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.env.NodeEnvironment; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.shard.ShardPath; import org.elasticsearch.index.shard.ShardStateMetaData; import org.elasticsearch.index.store.Store; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import java.io.IOException; import java.util.List; /** * This transport action is used to fetch the shard version from each node during primary allocation in {@link GatewayAllocator}. * We use this to find out which node holds the latest shard version and which of them used to be a primary in order to allocate * shards after node or cluster restarts. */ public class TransportNodesListGatewayStartedShards extends TransportNodesAction<TransportNodesListGatewayStartedShards.Request, TransportNodesListGatewayStartedShards.NodesGatewayStartedShards, TransportNodesListGatewayStartedShards.NodeRequest, TransportNodesListGatewayStartedShards.NodeGatewayStartedShards> implements AsyncShardFetch.Lister<TransportNodesListGatewayStartedShards.NodesGatewayStartedShards, TransportNodesListGatewayStartedShards.NodeGatewayStartedShards> { public static final String ACTION_NAME = "internal:gateway/local/started_shards"; private final NodeEnvironment nodeEnv; private final IndicesService indicesService; @Inject public TransportNodesListGatewayStartedShards(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService, ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver, NodeEnvironment env, IndicesService indicesService) { super(settings, ACTION_NAME, threadPool, clusterService, transportService, actionFilters, indexNameExpressionResolver, Request::new, NodeRequest::new, ThreadPool.Names.FETCH_SHARD_STARTED, NodeGatewayStartedShards.class); this.nodeEnv = env; this.indicesService = indicesService; } @Override public void list(ShardId shardId, DiscoveryNode[] nodes, ActionListener<NodesGatewayStartedShards> listener) { execute(new Request(shardId, nodes), listener); } @Override protected boolean transportCompress() { return true; // this can become big... } @Override protected NodeRequest newNodeRequest(String nodeId, Request request) { return new NodeRequest(nodeId, request); } @Override protected NodeGatewayStartedShards newNodeResponse() { return new NodeGatewayStartedShards(); } @Override protected NodesGatewayStartedShards newResponse(Request request, List<NodeGatewayStartedShards> responses, List<FailedNodeException> failures) { return new NodesGatewayStartedShards(clusterService.getClusterName(), responses, failures); } @Override protected NodeGatewayStartedShards nodeOperation(NodeRequest request) { try { final ShardId shardId = request.getShardId(); logger.trace("{} loading local shard state info", shardId); ShardStateMetaData shardStateMetaData = ShardStateMetaData.FORMAT.loadLatestState(logger, NamedXContentRegistry.EMPTY, nodeEnv.availableShardPaths(request.shardId)); if (shardStateMetaData != null) { IndexMetaData metaData = clusterService.state().metaData().index(shardId.getIndex()); if (metaData == null) { // we may send this requests while processing the cluster state that recovered the index // sometimes the request comes in before the local node processed that cluster state // in such cases we can load it from disk metaData = IndexMetaData.FORMAT.loadLatestState(logger, NamedXContentRegistry.EMPTY, nodeEnv.indexPaths(shardId.getIndex())); } if (metaData == null) { ElasticsearchException e = new ElasticsearchException("failed to find local IndexMetaData"); e.setShard(request.shardId); throw e; } if (indicesService.getShardOrNull(shardId) == null) { // we don't have an open shard on the store, validate the files on disk are openable ShardPath shardPath = null; try { IndexSettings indexSettings = new IndexSettings(metaData, settings); shardPath = ShardPath.loadShardPath(logger, nodeEnv, shardId, indexSettings); if (shardPath == null) { throw new IllegalStateException(shardId + " no shard path found"); } Store.tryOpenIndex(shardPath.resolveIndex(), shardId, nodeEnv::shardLock, logger); } catch (Exception exception) { final ShardPath finalShardPath = shardPath; logger.trace(() -> new ParameterizedMessage( "{} can't open index for shard [{}] in path [{}]", shardId, shardStateMetaData, (finalShardPath != null) ? finalShardPath.resolveIndex() : ""), exception); String allocationId = shardStateMetaData.allocationId != null ? shardStateMetaData.allocationId.getId() : null; return new NodeGatewayStartedShards(clusterService.localNode(), allocationId, shardStateMetaData.primary, exception); } } logger.debug("{} shard state info found: [{}]", shardId, shardStateMetaData); String allocationId = shardStateMetaData.allocationId != null ? shardStateMetaData.allocationId.getId() : null; return new NodeGatewayStartedShards(clusterService.localNode(), allocationId, shardStateMetaData.primary); } logger.trace("{} no local shard info found", shardId); return new NodeGatewayStartedShards(clusterService.localNode(), null, false); } catch (Exception e) { throw new ElasticsearchException("failed to load started shards", e); } } public static class Request extends BaseNodesRequest<Request> { private ShardId shardId; public Request() { } public Request(ShardId shardId, DiscoveryNode[] nodes) { super(nodes); this.shardId = shardId; } public ShardId shardId() { return this.shardId; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); shardId = ShardId.readShardId(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); shardId.writeTo(out); } } public static class NodesGatewayStartedShards extends BaseNodesResponse<NodeGatewayStartedShards> { public NodesGatewayStartedShards(ClusterName clusterName, List<NodeGatewayStartedShards> nodes, List<FailedNodeException> failures) { super(clusterName, nodes, failures); } @Override protected List<NodeGatewayStartedShards> readNodesFrom(StreamInput in) throws IOException { return in.readStreamableList(NodeGatewayStartedShards::new); } @Override protected void writeNodesTo(StreamOutput out, List<NodeGatewayStartedShards> nodes) throws IOException { out.writeStreamableList(nodes); } } public static class NodeRequest extends BaseNodeRequest { private ShardId shardId; public NodeRequest() { } public NodeRequest(String nodeId, Request request) { super(nodeId); this.shardId = request.shardId(); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); shardId = ShardId.readShardId(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); shardId.writeTo(out); } public ShardId getShardId() { return shardId; } } public static class NodeGatewayStartedShards extends BaseNodeResponse { private String allocationId = null; private boolean primary = false; private Exception storeException = null; public NodeGatewayStartedShards() { } public NodeGatewayStartedShards(DiscoveryNode node, String allocationId, boolean primary) { this(node, allocationId, primary, null); } public NodeGatewayStartedShards(DiscoveryNode node, String allocationId, boolean primary, Exception storeException) { super(node); this.allocationId = allocationId; this.primary = primary; this.storeException = storeException; } public String allocationId() { return this.allocationId; } public boolean primary() { return this.primary; } public Exception storeException() { return this.storeException; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); if (in.getVersion().before(Version.V_6_0_0_alpha1)) { // legacy version in.readLong(); } allocationId = in.readOptionalString(); primary = in.readBoolean(); if (in.readBoolean()) { storeException = in.readException(); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); if (out.getVersion().before(Version.V_6_0_0_alpha1)) { // legacy version out.writeLong(-1L); } out.writeOptionalString(allocationId); out.writeBoolean(primary); if (storeException != null) { out.writeBoolean(true); out.writeException(storeException); } else { out.writeBoolean(false); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NodeGatewayStartedShards that = (NodeGatewayStartedShards) o; if (primary != that.primary) { return false; } if (allocationId != null ? !allocationId.equals(that.allocationId) : that.allocationId != null) { return false; } return storeException != null ? storeException.equals(that.storeException) : that.storeException == null; } @Override public int hashCode() { int result = (allocationId != null ? allocationId.hashCode() : 0); result = 31 * result + (primary ? 1 : 0); result = 31 * result + (storeException != null ? storeException.hashCode() : 0); return result; } @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("NodeGatewayStartedShards[") .append("allocationId=").append(allocationId) .append(",primary=").append(primary); if (storeException != null) { buf.append(",storeException=").append(storeException); } buf.append("]"); return buf.toString(); } } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.deploymentmanager.model; /** * An Operation resource, used to manage asynchronous API requests. (== resource_for * v1.globalOperations ==) (== resource_for beta.globalOperations ==) (== resource_for * v1.regionOperations ==) (== resource_for beta.regionOperations ==) (== resource_for * v1.zoneOperations ==) (== resource_for beta.zoneOperations ==) * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Google Cloud Deployment Manager Alpha API. For a * detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Operation extends com.google.api.client.json.GenericJson { /** * [Output Only] The value of `requestId` if you provided it in the request. Not present * otherwise. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String clientOperationId; /** * [Deprecated] This field is deprecated. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String creationTimestamp; /** * [Output Only] A textual description of the operation, which is set when the operation is * created. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String description; /** * [Output Only] The time that this operation was completed. This value is in RFC3339 text format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String endTime; /** * [Output Only] If errors are generated during processing of the operation, this field will be * populated. * The value may be {@code null}. */ @com.google.api.client.util.Key private Error error; /** * [Output Only] If the operation fails, this field contains the HTTP error message that was * returned, such as NOT FOUND. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String httpErrorMessage; /** * [Output Only] If the operation fails, this field contains the HTTP error status code that was * returned. For example, a 404 means the resource was not found. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer httpErrorStatusCode; /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.math.BigInteger id; /** * [Output Only] The time that this operation was requested. This value is in RFC3339 text format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String insertTime; /** * [Output Only] Type of the resource. Always compute#operation for Operation resources. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * [Output Only] Name of the resource. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * [Output Only] The type of operation, such as insert, update, or delete, and so on. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String operationType; /** * [Output Only] An optional progress indicator that ranges from 0 to 100. There is no requirement * that this be linear or support any granularity of operations. This should not be used to guess * when the operation will be complete. This number should monotonically increase as the operation * progresses. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer progress; /** * [Output Only] The URL of the region where the operation resides. Only available when performing * regional operations. You must specify this field as part of the HTTP request URL. It is not * settable as a field in the request body. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String region; /** * [Output Only] Server-defined URL for the resource. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String selfLink; /** * [Output Only] The time that this operation was started by the server. This value is in RFC3339 * text format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String startTime; /** * [Output Only] The status of the operation, which can be one of the following: PENDING, RUNNING, * or DONE. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String status; /** * [Output Only] An optional textual description of the current status of the operation. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String statusMessage; /** * [Output Only] The unique target ID, which identifies a specific incarnation of the target * resource. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.math.BigInteger targetId; /** * [Output Only] The URL of the resource that the operation modifies. For operations related to * creating a snapshot, this points to the persistent disk that the snapshot was created from. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String targetLink; /** * [Output Only] User who requested the operation, for example: user@example.com. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String user; /** * [Output Only] If warning messages are generated during processing of the operation, this field * will be populated. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Warnings> warnings; static { // hack to force ProGuard to consider Warnings used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(Warnings.class); } /** * [Output Only] The URL of the zone where the operation resides. Only available when performing * per-zone operations. You must specify this field as part of the HTTP request URL. It is not * settable as a field in the request body. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String zone; /** * [Output Only] The value of `requestId` if you provided it in the request. Not present * otherwise. * @return value or {@code null} for none */ public java.lang.String getClientOperationId() { return clientOperationId; } /** * [Output Only] The value of `requestId` if you provided it in the request. Not present * otherwise. * @param clientOperationId clientOperationId or {@code null} for none */ public Operation setClientOperationId(java.lang.String clientOperationId) { this.clientOperationId = clientOperationId; return this; } /** * [Deprecated] This field is deprecated. * @return value or {@code null} for none */ public java.lang.String getCreationTimestamp() { return creationTimestamp; } /** * [Deprecated] This field is deprecated. * @param creationTimestamp creationTimestamp or {@code null} for none */ public Operation setCreationTimestamp(java.lang.String creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } /** * [Output Only] A textual description of the operation, which is set when the operation is * created. * @return value or {@code null} for none */ public java.lang.String getDescription() { return description; } /** * [Output Only] A textual description of the operation, which is set when the operation is * created. * @param description description or {@code null} for none */ public Operation setDescription(java.lang.String description) { this.description = description; return this; } /** * [Output Only] The time that this operation was completed. This value is in RFC3339 text format. * @return value or {@code null} for none */ public java.lang.String getEndTime() { return endTime; } /** * [Output Only] The time that this operation was completed. This value is in RFC3339 text format. * @param endTime endTime or {@code null} for none */ public Operation setEndTime(java.lang.String endTime) { this.endTime = endTime; return this; } /** * [Output Only] If errors are generated during processing of the operation, this field will be * populated. * @return value or {@code null} for none */ public Error getError() { return error; } /** * [Output Only] If errors are generated during processing of the operation, this field will be * populated. * @param error error or {@code null} for none */ public Operation setError(Error error) { this.error = error; return this; } /** * [Output Only] If the operation fails, this field contains the HTTP error message that was * returned, such as NOT FOUND. * @return value or {@code null} for none */ public java.lang.String getHttpErrorMessage() { return httpErrorMessage; } /** * [Output Only] If the operation fails, this field contains the HTTP error message that was * returned, such as NOT FOUND. * @param httpErrorMessage httpErrorMessage or {@code null} for none */ public Operation setHttpErrorMessage(java.lang.String httpErrorMessage) { this.httpErrorMessage = httpErrorMessage; return this; } /** * [Output Only] If the operation fails, this field contains the HTTP error status code that was * returned. For example, a 404 means the resource was not found. * @return value or {@code null} for none */ public java.lang.Integer getHttpErrorStatusCode() { return httpErrorStatusCode; } /** * [Output Only] If the operation fails, this field contains the HTTP error status code that was * returned. For example, a 404 means the resource was not found. * @param httpErrorStatusCode httpErrorStatusCode or {@code null} for none */ public Operation setHttpErrorStatusCode(java.lang.Integer httpErrorStatusCode) { this.httpErrorStatusCode = httpErrorStatusCode; return this; } /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * @return value or {@code null} for none */ public java.math.BigInteger getId() { return id; } /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * @param id id or {@code null} for none */ public Operation setId(java.math.BigInteger id) { this.id = id; return this; } /** * [Output Only] The time that this operation was requested. This value is in RFC3339 text format. * @return value or {@code null} for none */ public java.lang.String getInsertTime() { return insertTime; } /** * [Output Only] The time that this operation was requested. This value is in RFC3339 text format. * @param insertTime insertTime or {@code null} for none */ public Operation setInsertTime(java.lang.String insertTime) { this.insertTime = insertTime; return this; } /** * [Output Only] Type of the resource. Always compute#operation for Operation resources. * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * [Output Only] Type of the resource. Always compute#operation for Operation resources. * @param kind kind or {@code null} for none */ public Operation setKind(java.lang.String kind) { this.kind = kind; return this; } /** * [Output Only] Name of the resource. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * [Output Only] Name of the resource. * @param name name or {@code null} for none */ public Operation setName(java.lang.String name) { this.name = name; return this; } /** * [Output Only] The type of operation, such as insert, update, or delete, and so on. * @return value or {@code null} for none */ public java.lang.String getOperationType() { return operationType; } /** * [Output Only] The type of operation, such as insert, update, or delete, and so on. * @param operationType operationType or {@code null} for none */ public Operation setOperationType(java.lang.String operationType) { this.operationType = operationType; return this; } /** * [Output Only] An optional progress indicator that ranges from 0 to 100. There is no requirement * that this be linear or support any granularity of operations. This should not be used to guess * when the operation will be complete. This number should monotonically increase as the operation * progresses. * @return value or {@code null} for none */ public java.lang.Integer getProgress() { return progress; } /** * [Output Only] An optional progress indicator that ranges from 0 to 100. There is no requirement * that this be linear or support any granularity of operations. This should not be used to guess * when the operation will be complete. This number should monotonically increase as the operation * progresses. * @param progress progress or {@code null} for none */ public Operation setProgress(java.lang.Integer progress) { this.progress = progress; return this; } /** * [Output Only] The URL of the region where the operation resides. Only available when performing * regional operations. You must specify this field as part of the HTTP request URL. It is not * settable as a field in the request body. * @return value or {@code null} for none */ public java.lang.String getRegion() { return region; } /** * [Output Only] The URL of the region where the operation resides. Only available when performing * regional operations. You must specify this field as part of the HTTP request URL. It is not * settable as a field in the request body. * @param region region or {@code null} for none */ public Operation setRegion(java.lang.String region) { this.region = region; return this; } /** * [Output Only] Server-defined URL for the resource. * @return value or {@code null} for none */ public java.lang.String getSelfLink() { return selfLink; } /** * [Output Only] Server-defined URL for the resource. * @param selfLink selfLink or {@code null} for none */ public Operation setSelfLink(java.lang.String selfLink) { this.selfLink = selfLink; return this; } /** * [Output Only] The time that this operation was started by the server. This value is in RFC3339 * text format. * @return value or {@code null} for none */ public java.lang.String getStartTime() { return startTime; } /** * [Output Only] The time that this operation was started by the server. This value is in RFC3339 * text format. * @param startTime startTime or {@code null} for none */ public Operation setStartTime(java.lang.String startTime) { this.startTime = startTime; return this; } /** * [Output Only] The status of the operation, which can be one of the following: PENDING, RUNNING, * or DONE. * @return value or {@code null} for none */ public java.lang.String getStatus() { return status; } /** * [Output Only] The status of the operation, which can be one of the following: PENDING, RUNNING, * or DONE. * @param status status or {@code null} for none */ public Operation setStatus(java.lang.String status) { this.status = status; return this; } /** * [Output Only] An optional textual description of the current status of the operation. * @return value or {@code null} for none */ public java.lang.String getStatusMessage() { return statusMessage; } /** * [Output Only] An optional textual description of the current status of the operation. * @param statusMessage statusMessage or {@code null} for none */ public Operation setStatusMessage(java.lang.String statusMessage) { this.statusMessage = statusMessage; return this; } /** * [Output Only] The unique target ID, which identifies a specific incarnation of the target * resource. * @return value or {@code null} for none */ public java.math.BigInteger getTargetId() { return targetId; } /** * [Output Only] The unique target ID, which identifies a specific incarnation of the target * resource. * @param targetId targetId or {@code null} for none */ public Operation setTargetId(java.math.BigInteger targetId) { this.targetId = targetId; return this; } /** * [Output Only] The URL of the resource that the operation modifies. For operations related to * creating a snapshot, this points to the persistent disk that the snapshot was created from. * @return value or {@code null} for none */ public java.lang.String getTargetLink() { return targetLink; } /** * [Output Only] The URL of the resource that the operation modifies. For operations related to * creating a snapshot, this points to the persistent disk that the snapshot was created from. * @param targetLink targetLink or {@code null} for none */ public Operation setTargetLink(java.lang.String targetLink) { this.targetLink = targetLink; return this; } /** * [Output Only] User who requested the operation, for example: user@example.com. * @return value or {@code null} for none */ public java.lang.String getUser() { return user; } /** * [Output Only] User who requested the operation, for example: user@example.com. * @param user user or {@code null} for none */ public Operation setUser(java.lang.String user) { this.user = user; return this; } /** * [Output Only] If warning messages are generated during processing of the operation, this field * will be populated. * @return value or {@code null} for none */ public java.util.List<Warnings> getWarnings() { return warnings; } /** * [Output Only] If warning messages are generated during processing of the operation, this field * will be populated. * @param warnings warnings or {@code null} for none */ public Operation setWarnings(java.util.List<Warnings> warnings) { this.warnings = warnings; return this; } /** * [Output Only] The URL of the zone where the operation resides. Only available when performing * per-zone operations. You must specify this field as part of the HTTP request URL. It is not * settable as a field in the request body. * @return value or {@code null} for none */ public java.lang.String getZone() { return zone; } /** * [Output Only] The URL of the zone where the operation resides. Only available when performing * per-zone operations. You must specify this field as part of the HTTP request URL. It is not * settable as a field in the request body. * @param zone zone or {@code null} for none */ public Operation setZone(java.lang.String zone) { this.zone = zone; return this; } @Override public Operation set(String fieldName, Object value) { return (Operation) super.set(fieldName, value); } @Override public Operation clone() { return (Operation) super.clone(); } /** * [Output Only] If errors are generated during processing of the operation, this field will be * populated. */ public static final class Error extends com.google.api.client.json.GenericJson { /** * [Output Only] The array of errors encountered while processing this operation. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Errors> errors; static { // hack to force ProGuard to consider Errors used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(Errors.class); } /** * [Output Only] The array of errors encountered while processing this operation. * @return value or {@code null} for none */ public java.util.List<Errors> getErrors() { return errors; } /** * [Output Only] The array of errors encountered while processing this operation. * @param errors errors or {@code null} for none */ public Error setErrors(java.util.List<Errors> errors) { this.errors = errors; return this; } @Override public Error set(String fieldName, Object value) { return (Error) super.set(fieldName, value); } @Override public Error clone() { return (Error) super.clone(); } /** * Model definition for OperationErrorErrors. */ public static final class Errors extends com.google.api.client.json.GenericJson { /** * [Output Only] The error type identifier for this error. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String code; /** * [Output Only] Indicates the field in the request that caused the error. This property is * optional. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String location; /** * [Output Only] An optional, human-readable error message. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String message; /** * [Output Only] The error type identifier for this error. * @return value or {@code null} for none */ public java.lang.String getCode() { return code; } /** * [Output Only] The error type identifier for this error. * @param code code or {@code null} for none */ public Errors setCode(java.lang.String code) { this.code = code; return this; } /** * [Output Only] Indicates the field in the request that caused the error. This property is * optional. * @return value or {@code null} for none */ public java.lang.String getLocation() { return location; } /** * [Output Only] Indicates the field in the request that caused the error. This property is * optional. * @param location location or {@code null} for none */ public Errors setLocation(java.lang.String location) { this.location = location; return this; } /** * [Output Only] An optional, human-readable error message. * @return value or {@code null} for none */ public java.lang.String getMessage() { return message; } /** * [Output Only] An optional, human-readable error message. * @param message message or {@code null} for none */ public Errors setMessage(java.lang.String message) { this.message = message; return this; } @Override public Errors set(String fieldName, Object value) { return (Errors) super.set(fieldName, value); } @Override public Errors clone() { return (Errors) super.clone(); } } } /** * Model definition for OperationWarnings. */ public static final class Warnings extends com.google.api.client.json.GenericJson { /** * [Output Only] A warning code, if applicable. For example, Compute Engine returns * NO_RESULTS_ON_PAGE if there are no results in the response. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String code; /** * [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": * "scope", "value": "zones/us-east1-d" } * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Data> data; static { // hack to force ProGuard to consider Data used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(Data.class); } /** * [Output Only] A human-readable description of the warning code. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String message; /** * [Output Only] A warning code, if applicable. For example, Compute Engine returns * NO_RESULTS_ON_PAGE if there are no results in the response. * @return value or {@code null} for none */ public java.lang.String getCode() { return code; } /** * [Output Only] A warning code, if applicable. For example, Compute Engine returns * NO_RESULTS_ON_PAGE if there are no results in the response. * @param code code or {@code null} for none */ public Warnings setCode(java.lang.String code) { this.code = code; return this; } /** * [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": * "scope", "value": "zones/us-east1-d" } * @return value or {@code null} for none */ public java.util.List<Data> getData() { return data; } /** * [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": * "scope", "value": "zones/us-east1-d" } * @param data data or {@code null} for none */ public Warnings setData(java.util.List<Data> data) { this.data = data; return this; } /** * [Output Only] A human-readable description of the warning code. * @return value or {@code null} for none */ public java.lang.String getMessage() { return message; } /** * [Output Only] A human-readable description of the warning code. * @param message message or {@code null} for none */ public Warnings setMessage(java.lang.String message) { this.message = message; return this; } @Override public Warnings set(String fieldName, Object value) { return (Warnings) super.set(fieldName, value); } @Override public Warnings clone() { return (Warnings) super.clone(); } /** * Model definition for OperationWarningsData. */ public static final class Data extends com.google.api.client.json.GenericJson { /** * [Output Only] A key that provides more detail on the warning being returned. For example, for * warnings where there are no results in a list request for a particular zone, this key might be * scope and the key value might be the zone name. Other examples might be a key indicating a * deprecated resource and a suggested replacement, or a warning about invalid network settings * (for example, if an instance attempts to perform IP forwarding but is not enabled for IP * forwarding). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String key; /** * [Output Only] A warning data value corresponding to the key. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String value; /** * [Output Only] A key that provides more detail on the warning being returned. For example, for * warnings where there are no results in a list request for a particular zone, this key might be * scope and the key value might be the zone name. Other examples might be a key indicating a * deprecated resource and a suggested replacement, or a warning about invalid network settings * (for example, if an instance attempts to perform IP forwarding but is not enabled for IP * forwarding). * @return value or {@code null} for none */ public java.lang.String getKey() { return key; } /** * [Output Only] A key that provides more detail on the warning being returned. For example, for * warnings where there are no results in a list request for a particular zone, this key might be * scope and the key value might be the zone name. Other examples might be a key indicating a * deprecated resource and a suggested replacement, or a warning about invalid network settings * (for example, if an instance attempts to perform IP forwarding but is not enabled for IP * forwarding). * @param key key or {@code null} for none */ public Data setKey(java.lang.String key) { this.key = key; return this; } /** * [Output Only] A warning data value corresponding to the key. * @return value or {@code null} for none */ public java.lang.String getValue() { return value; } /** * [Output Only] A warning data value corresponding to the key. * @param value value or {@code null} for none */ public Data setValue(java.lang.String value) { this.value = value; return this; } @Override public Data set(String fieldName, Object value) { return (Data) super.set(fieldName, value); } @Override public Data clone() { return (Data) super.clone(); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cache.index; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import javax.cache.processor.EntryProcessor; import javax.cache.processor.EntryProcessorException; import javax.cache.processor.MutableEntry; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; import org.apache.ignite.cache.CacheEntryProcessor; import org.apache.ignite.cache.query.SqlFieldsQuery; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.processors.cache.GatewayProtectedCacheProxy; import org.apache.ignite.internal.processors.cache.query.IgniteQueryErrorCode; import org.apache.ignite.internal.processors.query.QueryUtils; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.X; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteFuture; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.transactions.Transaction; import org.apache.ignite.transactions.TransactionState; import org.junit.Test; /** * Tests to check behavior regarding transactions started via SQL. */ public class SqlTransactionsSelfTest extends AbstractSchemaSelfTest { /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); startGrid(commonConfiguration(0)); super.execute(node(), "CREATE TABLE INTS(k int primary key, v int) WITH \"wrap_value=false,cache_name=ints," + "atomicity=transactional_snapshot\""); } /** * Test that BEGIN opens a transaction. */ @Test public void testBegin() { execute(node(), "BEGIN"); assertTxPresent(); assertTxState(tx(), TransactionState.ACTIVE); } /** * Test that COMMIT commits a transaction. */ @Test public void testCommit() { execute(node(), "BEGIN WORK"); assertTxPresent(); Transaction tx = tx(); assertTxState(tx, TransactionState.ACTIVE); execute(node(), "COMMIT TRANSACTION"); assertTxState(tx, TransactionState.COMMITTED); assertSqlTxNotPresent(); } /** * Test that COMMIT without a transaction yields nothing. */ @Test public void testCommitNoTransaction() { execute(node(), "COMMIT"); } /** * Test that ROLLBACK without a transaction yields nothing. */ @Test public void testRollbackNoTransaction() { execute(node(), "ROLLBACK"); } /** * Test that ROLLBACK rolls back a transaction. */ @Test public void testRollback() { execute(node(), "BEGIN TRANSACTION"); assertTxPresent(); Transaction tx = tx(); assertTxState(tx, TransactionState.ACTIVE); execute(node(), "ROLLBACK TRANSACTION"); assertTxState(tx, TransactionState.ROLLED_BACK); assertSqlTxNotPresent(); } /** * Test that attempting to perform various SQL operations within non SQL transaction yields an exception. */ @Test public void testSqlOperationsWithinNonSqlTransaction() { assertSqlOperationWithinNonSqlTransactionThrows("COMMIT"); assertSqlOperationWithinNonSqlTransactionThrows("ROLLBACK"); assertSqlOperationWithinNonSqlTransactionThrows("SELECT * from ints"); assertSqlOperationWithinNonSqlTransactionThrows("DELETE from ints"); assertSqlOperationWithinNonSqlTransactionThrows("INSERT INTO ints(k, v) values(10, 15)"); assertSqlOperationWithinNonSqlTransactionThrows("MERGE INTO ints(k, v) values(10, 15)"); assertSqlOperationWithinNonSqlTransactionThrows("UPDATE ints SET v = 100 WHERE k = 5"); assertSqlOperationWithinNonSqlTransactionThrows("create index idx on ints(v)"); assertSqlOperationWithinNonSqlTransactionThrows("CREATE TABLE T(k int primary key, v int)"); } /** * Check that trying to run given SQL statement both locally and in distributed mode yields an exception * if transaction already has been marked as being of SQL type. * @param sql SQL statement. */ private void assertSqlOperationWithinNonSqlTransactionThrows(final String sql) { try (Transaction ignored = node().transactions().txStart()) { node().cache("ints").put(1, 1); assertSqlException(new RunnableX() { @Override public void run() throws Exception { execute(node(), sql); } }, IgniteQueryErrorCode.TRANSACTION_TYPE_MISMATCH); } try (Transaction ignored = node().transactions().txStart()) { node().cache("ints").put(1, 1); assertSqlException(new RunnableX() { @Override public void run() throws Exception { node().cache("ints").query(new SqlFieldsQuery(sql).setLocal(true)).getAll(); } }, IgniteQueryErrorCode.TRANSACTION_TYPE_MISMATCH); } } /** * Test that attempting to perform a cache API operation from within an SQL transaction fails. */ private void checkCacheOperationThrows(final String opName, final Object... args) { execute(node(), "BEGIN"); try { GridTestUtils.assertThrows(null, new Callable<Object>() { @Override public Object call() throws Exception { try { // We need to detect types based on arguments due to multiple overloads. Class[] types; if (F.isEmpty(args)) types = (Class[]) X.EMPTY_OBJECT_ARRAY; else { types = new Class[args.length]; for (int i = 0; i < args.length; i++) types[i] = argTypeForObject(args[i]); } Object res = U.invoke(GatewayProtectedCacheProxy.class, node().cache("ints"), opName, types, args); if (opName.endsWith("Async")) ((IgniteFuture)res).get(); } catch (IgniteCheckedException e) { if (e.getCause() != null) { try { if (e.getCause().getCause() != null) throw (Exception)e.getCause().getCause(); else fail(); } catch (IgniteException e1) { // Some public API methods don't have IgniteCheckedException on their signature // and thus may wrap it into an IgniteException. if (e1.getCause() != null) throw (Exception)e1.getCause(); else fail(); } } else fail(); } return null; } }, IgniteCheckedException.class, "SQL queries and cache operations may not be used in the same transaction."); } finally { try { execute(node(), "ROLLBACK"); } catch (Throwable e) { // No-op. } } } /** * */ private static Class<?> argTypeForObject(Object arg) { if (arg instanceof Set) return Set.class; else if (arg instanceof Map) return Map.class; else if (arg.getClass().getName().startsWith("java.lang.")) return Object.class; else if (arg instanceof CacheEntryProcessor) return CacheEntryProcessor.class; else if (arg instanceof EntryProcessor) return EntryProcessor.class; else return arg.getClass(); } /** * Test that attempting to perform a cache PUT operation from within an SQL transaction fails. */ @Test public void testCacheOperationsFromSqlTransaction() { checkCacheOperationThrows("get", 1); checkCacheOperationThrows("getAsync", 1); checkCacheOperationThrows("getEntry", 1); checkCacheOperationThrows("getEntryAsync", 1); checkCacheOperationThrows("getAndPut", 1, 1); checkCacheOperationThrows("getAndPutAsync", 1, 1); checkCacheOperationThrows("getAndPutIfAbsent", 1, 1); checkCacheOperationThrows("getAndPutIfAbsentAsync", 1, 1); checkCacheOperationThrows("getAndReplace", 1, 1); checkCacheOperationThrows("getAndReplaceAsync", 1, 1); checkCacheOperationThrows("getAndRemove", 1); checkCacheOperationThrows("getAndRemoveAsync", 1); checkCacheOperationThrows("containsKey", 1); checkCacheOperationThrows("containsKeyAsync", 1); checkCacheOperationThrows("put", 1, 1); checkCacheOperationThrows("putAsync", 1, 1); checkCacheOperationThrows("putIfAbsent", 1, 1); checkCacheOperationThrows("putIfAbsentAsync", 1, 1); checkCacheOperationThrows("remove", 1); checkCacheOperationThrows("removeAsync", 1); checkCacheOperationThrows("remove", 1, 1); checkCacheOperationThrows("removeAsync", 1, 1); checkCacheOperationThrows("replace", 1, 1); checkCacheOperationThrows("replaceAsync", 1, 1); checkCacheOperationThrows("replace", 1, 1, 1); checkCacheOperationThrows("replaceAsync", 1, 1, 1); checkCacheOperationThrows("getAll", new HashSet<>(Arrays.asList(1, 2))); checkCacheOperationThrows("containsKeys", new HashSet<>(Arrays.asList(1, 2))); checkCacheOperationThrows("getEntries", new HashSet<>(Arrays.asList(1, 2))); checkCacheOperationThrows("putAll", Collections.singletonMap(1, 1)); checkCacheOperationThrows("removeAll", new HashSet<>(Arrays.asList(1, 2))); checkCacheOperationThrows("getAllAsync", new HashSet<>(Arrays.asList(1, 2))); checkCacheOperationThrows("containsKeysAsync", new HashSet<>(Arrays.asList(1, 2))); checkCacheOperationThrows("getEntriesAsync", new HashSet<>(Arrays.asList(1, 2))); checkCacheOperationThrows("putAllAsync", Collections.singletonMap(1, 1)); checkCacheOperationThrows("removeAllAsync", new HashSet<>(Arrays.asList(1, 2))); checkCacheOperationThrows("invoke", 1, ENTRY_PROC, X.EMPTY_OBJECT_ARRAY); checkCacheOperationThrows("invoke", 1, CACHE_ENTRY_PROC, X.EMPTY_OBJECT_ARRAY); checkCacheOperationThrows("invokeAsync", 1, ENTRY_PROC, X.EMPTY_OBJECT_ARRAY); checkCacheOperationThrows("invokeAsync", 1, CACHE_ENTRY_PROC, X.EMPTY_OBJECT_ARRAY); checkCacheOperationThrows("invokeAll", Collections.singletonMap(1, CACHE_ENTRY_PROC), X.EMPTY_OBJECT_ARRAY); checkCacheOperationThrows("invokeAll", Collections.singleton(1), CACHE_ENTRY_PROC, X.EMPTY_OBJECT_ARRAY); checkCacheOperationThrows("invokeAll", Collections.singleton(1), ENTRY_PROC, X.EMPTY_OBJECT_ARRAY); checkCacheOperationThrows("invokeAllAsync", Collections.singletonMap(1, CACHE_ENTRY_PROC), X.EMPTY_OBJECT_ARRAY); checkCacheOperationThrows("invokeAllAsync", Collections.singleton(1), CACHE_ENTRY_PROC, X.EMPTY_OBJECT_ARRAY); checkCacheOperationThrows("invokeAllAsync", Collections.singleton(1), ENTRY_PROC, X.EMPTY_OBJECT_ARRAY); } /** */ private static final EntryProcessor<Integer, Integer, Object> ENTRY_PROC = new EntryProcessor<Integer, Integer, Object>() { @Override public Object process(MutableEntry<Integer, Integer> entry, Object... arguments) throws EntryProcessorException { return null; } }; /** */ private static final CacheEntryProcessor<Integer, Integer, Object> CACHE_ENTRY_PROC = new CacheEntryProcessor<Integer, Integer, Object>() { @Override public Object process(MutableEntry<Integer, Integer> entry, Object... arguments) throws EntryProcessorException { return null; } }; /** * @return Node. */ private IgniteEx node() { return grid(0); } /** * @return Currently open transaction. */ private Transaction tx() { return node().transactions().tx(); } /** * Check that there's an open transaction with SQL flag. */ private void assertTxPresent() { assertNotNull(tx()); } /** {@inheritDoc} */ @Override protected List<List<?>> execute(Ignite node, String sql) { return node.cache("ints").query(new SqlFieldsQuery(sql).setSchema(QueryUtils.DFLT_SCHEMA)).getAll(); } /** * Check that there's no open transaction. */ private void assertSqlTxNotPresent() { assertNull(tx()); } /** * Check transaction state. */ private static void assertTxState(Transaction tx, TransactionState state) { assertEquals(state, tx.state()); } }
package biz.franch.protoi2.information; /** * Created by Admin on 30.06.2015. */ import android.content.Context; import android.graphics.Matrix; import android.graphics.PointF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.widget.ImageView; public class TouchImageView extends ImageView { Matrix matrix; // We can be in one of these 3 states static final int NONE = 0; static final int DRAG = 1; static final int ZOOM = 2; int mode = NONE; // Remember some things for zooming PointF last = new PointF(); PointF start = new PointF(); float minScale = 1f; float maxScale = 3f; float[] m; int viewWidth, viewHeight; static final int CLICK = 3; float saveScale = 1f; protected float origWidth, origHeight; int oldMeasuredWidth, oldMeasuredHeight; ScaleGestureDetector mScaleDetector; Context context; public TouchImageView(Context context) { super(context); sharedConstructing(context); } public TouchImageView(Context context, AttributeSet attrs) { super(context, attrs); sharedConstructing(context); } private void sharedConstructing(Context context) { super.setClickable(true); this.context = context; mScaleDetector = new ScaleGestureDetector(context, new ScaleListener()); matrix = new Matrix(); m = new float[9]; setImageMatrix(matrix); setScaleType(ScaleType.MATRIX); setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { mScaleDetector.onTouchEvent(event); PointF curr = new PointF(event.getX(), event.getY()); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: last.set(curr); start.set(last); mode = DRAG; break; case MotionEvent.ACTION_MOVE: if (mode == DRAG) { float deltaX = curr.x - last.x; float deltaY = curr.y - last.y; float fixTransX = getFixDragTrans(deltaX, viewWidth, origWidth * saveScale); float fixTransY = getFixDragTrans(deltaY, viewHeight, origHeight * saveScale); matrix.postTranslate(fixTransX, fixTransY); fixTrans(); last.set(curr.x, curr.y); } break; case MotionEvent.ACTION_UP: mode = NONE; int xDiff = (int) Math.abs(curr.x - start.x); int yDiff = (int) Math.abs(curr.y - start.y); if (xDiff < CLICK && yDiff < CLICK) performClick(); break; case MotionEvent.ACTION_POINTER_UP: mode = NONE; break; } setImageMatrix(matrix); invalidate(); return true; // indicate event was handled } }); } public void setMaxZoom(float x) { maxScale = x; } private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScaleBegin(ScaleGestureDetector detector) { mode = ZOOM; return true; } @Override public boolean onScale(ScaleGestureDetector detector) { float mScaleFactor = detector.getScaleFactor(); float origScale = saveScale; saveScale *= mScaleFactor; if (saveScale > maxScale) { saveScale = maxScale; mScaleFactor = maxScale / origScale; } else if (saveScale < minScale) { saveScale = minScale; mScaleFactor = minScale / origScale; } if (origWidth * saveScale <= viewWidth || origHeight * saveScale <= viewHeight) matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2, viewHeight / 2); else matrix.postScale(mScaleFactor, mScaleFactor, detector.getFocusX(), detector.getFocusY()); fixTrans(); return true; } } void fixTrans() { matrix.getValues(m); float transX = m[Matrix.MTRANS_X]; float transY = m[Matrix.MTRANS_Y]; float fixTransX = getFixTrans(transX, viewWidth, origWidth * saveScale); float fixTransY = getFixTrans(transY, viewHeight, origHeight * saveScale); if (fixTransX != 0 || fixTransY != 0) matrix.postTranslate(fixTransX, fixTransY); } float getFixTrans(float trans, float viewSize, float contentSize) { float minTrans, maxTrans; if (contentSize <= viewSize) { minTrans = 0; maxTrans = viewSize - contentSize; } else { minTrans = viewSize - contentSize; maxTrans = 0; } if (trans < minTrans) return -trans + minTrans; if (trans > maxTrans) return -trans + maxTrans; return 0; } float getFixDragTrans(float delta, float viewSize, float contentSize) { if (contentSize <= viewSize) { return 0; } return delta; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); viewWidth = MeasureSpec.getSize(widthMeasureSpec); viewHeight = MeasureSpec.getSize(heightMeasureSpec); // // Rescales image on rotation // if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight || viewWidth == 0 || viewHeight == 0) return; oldMeasuredHeight = viewHeight; oldMeasuredWidth = viewWidth; if (saveScale == 1) { //Fit to screen. float scale; Drawable drawable = getDrawable(); if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0) return; int bmWidth = drawable.getIntrinsicWidth(); int bmHeight = drawable.getIntrinsicHeight(); Log.d("bmSize", "bmWidth: " + bmWidth + " bmHeight : " + bmHeight); float scaleX = (float) viewWidth / (float) bmWidth; float scaleY = (float) viewHeight / (float) bmHeight; scale = Math.min(scaleX, scaleY); matrix.setScale(scale, scale); // Center the image float redundantYSpace = (float) viewHeight - (scale * (float) bmHeight); float redundantXSpace = (float) viewWidth - (scale * (float) bmWidth); redundantYSpace /= (float) 2; redundantXSpace /= (float) 2; matrix.postTranslate(redundantXSpace, redundantYSpace); origWidth = viewWidth - 2 * redundantXSpace; origHeight = viewHeight - 2 * redundantYSpace; setImageMatrix(matrix); } fixTrans(); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.policyinsights.models; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; import com.azure.resourcemanager.policyinsights.fluent.models.RemediationInner; /** Resource collection API of Remediations. */ public interface Remediations { /** * Gets all deployments for a remediation at management group scope. * * @param managementGroupId Management group ID. * @param remediationName The name of the remediation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all deployments for a remediation at management group scope. */ PagedIterable<RemediationDeployment> listDeploymentsAtManagementGroup( String managementGroupId, String remediationName); /** * Gets all deployments for a remediation at management group scope. * * @param managementGroupId Management group ID. * @param remediationName The name of the remediation. * @param top Maximum number of records to return. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all deployments for a remediation at management group scope. */ PagedIterable<RemediationDeployment> listDeploymentsAtManagementGroup( String managementGroupId, String remediationName, Integer top, Context context); /** * Cancels a remediation at management group scope. * * @param managementGroupId Management group ID. * @param remediationName The name of the remediation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Remediation cancelAtManagementGroup(String managementGroupId, String remediationName); /** * Cancels a remediation at management group scope. * * @param managementGroupId Management group ID. * @param remediationName The name of the remediation. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Response<Remediation> cancelAtManagementGroupWithResponse( String managementGroupId, String remediationName, Context context); /** * Gets all remediations for the management group. * * @param managementGroupId Management group ID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all remediations for the management group. */ PagedIterable<Remediation> listForManagementGroup(String managementGroupId); /** * Gets all remediations for the management group. * * @param managementGroupId Management group ID. * @param top Maximum number of records to return. * @param filter OData filter expression. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all remediations for the management group. */ PagedIterable<Remediation> listForManagementGroup( String managementGroupId, Integer top, String filter, Context context); /** * Creates or updates a remediation at management group scope. * * @param managementGroupId Management group ID. * @param remediationName The name of the remediation. * @param parameters The remediation parameters. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Remediation createOrUpdateAtManagementGroup( String managementGroupId, String remediationName, RemediationInner parameters); /** * Creates or updates a remediation at management group scope. * * @param managementGroupId Management group ID. * @param remediationName The name of the remediation. * @param parameters The remediation parameters. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Response<Remediation> createOrUpdateAtManagementGroupWithResponse( String managementGroupId, String remediationName, RemediationInner parameters, Context context); /** * Gets an existing remediation at management group scope. * * @param managementGroupId Management group ID. * @param remediationName The name of the remediation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an existing remediation at management group scope. */ Remediation getAtManagementGroup(String managementGroupId, String remediationName); /** * Gets an existing remediation at management group scope. * * @param managementGroupId Management group ID. * @param remediationName The name of the remediation. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an existing remediation at management group scope. */ Response<Remediation> getAtManagementGroupWithResponse( String managementGroupId, String remediationName, Context context); /** * Deletes an existing remediation at management group scope. * * @param managementGroupId Management group ID. * @param remediationName The name of the remediation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Remediation deleteAtManagementGroup(String managementGroupId, String remediationName); /** * Deletes an existing remediation at management group scope. * * @param managementGroupId Management group ID. * @param remediationName The name of the remediation. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Response<Remediation> deleteAtManagementGroupWithResponse( String managementGroupId, String remediationName, Context context); /** * Gets all deployments for a remediation at subscription scope. * * @param remediationName The name of the remediation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all deployments for a remediation at subscription scope. */ PagedIterable<RemediationDeployment> listDeploymentsAtSubscription(String remediationName); /** * Gets all deployments for a remediation at subscription scope. * * @param remediationName The name of the remediation. * @param top Maximum number of records to return. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all deployments for a remediation at subscription scope. */ PagedIterable<RemediationDeployment> listDeploymentsAtSubscription( String remediationName, Integer top, Context context); /** * Cancels a remediation at subscription scope. * * @param remediationName The name of the remediation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Remediation cancelAtSubscription(String remediationName); /** * Cancels a remediation at subscription scope. * * @param remediationName The name of the remediation. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Response<Remediation> cancelAtSubscriptionWithResponse(String remediationName, Context context); /** * Gets all remediations for the subscription. * * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all remediations for the subscription. */ PagedIterable<Remediation> list(); /** * Gets all remediations for the subscription. * * @param top Maximum number of records to return. * @param filter OData filter expression. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all remediations for the subscription. */ PagedIterable<Remediation> list(Integer top, String filter, Context context); /** * Creates or updates a remediation at subscription scope. * * @param remediationName The name of the remediation. * @param parameters The remediation parameters. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Remediation createOrUpdateAtSubscription(String remediationName, RemediationInner parameters); /** * Creates or updates a remediation at subscription scope. * * @param remediationName The name of the remediation. * @param parameters The remediation parameters. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Response<Remediation> createOrUpdateAtSubscriptionWithResponse( String remediationName, RemediationInner parameters, Context context); /** * Gets an existing remediation at subscription scope. * * @param remediationName The name of the remediation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an existing remediation at subscription scope. */ Remediation getAtSubscription(String remediationName); /** * Gets an existing remediation at subscription scope. * * @param remediationName The name of the remediation. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an existing remediation at subscription scope. */ Response<Remediation> getAtSubscriptionWithResponse(String remediationName, Context context); /** * Deletes an existing remediation at subscription scope. * * @param remediationName The name of the remediation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Remediation deleteAtSubscription(String remediationName); /** * Deletes an existing remediation at subscription scope. * * @param remediationName The name of the remediation. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Response<Remediation> deleteAtSubscriptionWithResponse(String remediationName, Context context); /** * Gets all deployments for a remediation at resource group scope. * * @param resourceGroupName Resource group name. * @param remediationName The name of the remediation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all deployments for a remediation at resource group scope. */ PagedIterable<RemediationDeployment> listDeploymentsAtResourceGroup( String resourceGroupName, String remediationName); /** * Gets all deployments for a remediation at resource group scope. * * @param resourceGroupName Resource group name. * @param remediationName The name of the remediation. * @param top Maximum number of records to return. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all deployments for a remediation at resource group scope. */ PagedIterable<RemediationDeployment> listDeploymentsAtResourceGroup( String resourceGroupName, String remediationName, Integer top, Context context); /** * Cancels a remediation at resource group scope. * * @param resourceGroupName Resource group name. * @param remediationName The name of the remediation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Remediation cancelAtResourceGroup(String resourceGroupName, String remediationName); /** * Cancels a remediation at resource group scope. * * @param resourceGroupName Resource group name. * @param remediationName The name of the remediation. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Response<Remediation> cancelAtResourceGroupWithResponse( String resourceGroupName, String remediationName, Context context); /** * Gets all remediations for the subscription. * * @param resourceGroupName Resource group name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all remediations for the subscription. */ PagedIterable<Remediation> listByResourceGroup(String resourceGroupName); /** * Gets all remediations for the subscription. * * @param resourceGroupName Resource group name. * @param top Maximum number of records to return. * @param filter OData filter expression. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all remediations for the subscription. */ PagedIterable<Remediation> listByResourceGroup( String resourceGroupName, Integer top, String filter, Context context); /** * Gets an existing remediation at resource group scope. * * @param resourceGroupName Resource group name. * @param remediationName The name of the remediation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an existing remediation at resource group scope. */ Remediation getByResourceGroup(String resourceGroupName, String remediationName); /** * Gets an existing remediation at resource group scope. * * @param resourceGroupName Resource group name. * @param remediationName The name of the remediation. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an existing remediation at resource group scope. */ Response<Remediation> getByResourceGroupWithResponse( String resourceGroupName, String remediationName, Context context); /** * Deletes an existing remediation at resource group scope. * * @param resourceGroupName Resource group name. * @param remediationName The name of the remediation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Remediation deleteByResourceGroup(String resourceGroupName, String remediationName); /** * Deletes an existing remediation at resource group scope. * * @param resourceGroupName Resource group name. * @param remediationName The name of the remediation. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Response<Remediation> deleteWithResponse(String resourceGroupName, String remediationName, Context context); /** * Gets all deployments for a remediation at resource scope. * * @param resourceId Resource ID. * @param remediationName The name of the remediation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all deployments for a remediation at resource scope. */ PagedIterable<RemediationDeployment> listDeploymentsAtResource(String resourceId, String remediationName); /** * Gets all deployments for a remediation at resource scope. * * @param resourceId Resource ID. * @param remediationName The name of the remediation. * @param top Maximum number of records to return. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all deployments for a remediation at resource scope. */ PagedIterable<RemediationDeployment> listDeploymentsAtResource( String resourceId, String remediationName, Integer top, Context context); /** * Cancel a remediation at resource scope. * * @param resourceId Resource ID. * @param remediationName The name of the remediation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Remediation cancelAtResource(String resourceId, String remediationName); /** * Cancel a remediation at resource scope. * * @param resourceId Resource ID. * @param remediationName The name of the remediation. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Response<Remediation> cancelAtResourceWithResponse(String resourceId, String remediationName, Context context); /** * Gets all remediations for a resource. * * @param resourceId Resource ID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all remediations for a resource. */ PagedIterable<Remediation> listForResource(String resourceId); /** * Gets all remediations for a resource. * * @param resourceId Resource ID. * @param top Maximum number of records to return. * @param filter OData filter expression. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all remediations for a resource. */ PagedIterable<Remediation> listForResource(String resourceId, Integer top, String filter, Context context); /** * Creates or updates a remediation at resource scope. * * @param resourceId Resource ID. * @param remediationName The name of the remediation. * @param parameters The remediation parameters. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Remediation createOrUpdateAtResource(String resourceId, String remediationName, RemediationInner parameters); /** * Creates or updates a remediation at resource scope. * * @param resourceId Resource ID. * @param remediationName The name of the remediation. * @param parameters The remediation parameters. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Response<Remediation> createOrUpdateAtResourceWithResponse( String resourceId, String remediationName, RemediationInner parameters, Context context); /** * Gets an existing remediation at resource scope. * * @param resourceId Resource ID. * @param remediationName The name of the remediation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an existing remediation at resource scope. */ Remediation getAtResource(String resourceId, String remediationName); /** * Gets an existing remediation at resource scope. * * @param resourceId Resource ID. * @param remediationName The name of the remediation. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an existing remediation at resource scope. */ Response<Remediation> getAtResourceWithResponse(String resourceId, String remediationName, Context context); /** * Deletes an existing remediation at individual resource scope. * * @param resourceId Resource ID. * @param remediationName The name of the remediation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Remediation deleteAtResource(String resourceId, String remediationName); /** * Deletes an existing remediation at individual resource scope. * * @param resourceId Resource ID. * @param remediationName The name of the remediation. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Response<Remediation> deleteAtResourceWithResponse(String resourceId, String remediationName, Context context); /** * Gets an existing remediation at resource group scope. * * @param id the resource ID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an existing remediation at resource group scope. */ Remediation getById(String id); /** * Gets an existing remediation at resource group scope. * * @param id the resource ID. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an existing remediation at resource group scope. */ Response<Remediation> getByIdWithResponse(String id, Context context); /** * Deletes an existing remediation at resource group scope. * * @param id the resource ID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Remediation deleteById(String id); /** * Deletes an existing remediation at resource group scope. * * @param id the resource ID. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the remediation definition. */ Response<Remediation> deleteByIdWithResponse(String id, Context context); /** * Begins definition for a new Remediation resource. * * @param name resource name. * @return the first stage of the new Remediation definition. */ Remediation.DefinitionStages.Blank define(String name); }
/* * 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.query; import com.fasterxml.jackson.databind.Module; 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.common.collect.Maps; import com.google.common.io.Files; import com.metamx.common.guava.Sequence; import com.metamx.common.guava.Sequences; import io.druid.data.input.Row; import io.druid.data.input.impl.CSVParseSpec; import io.druid.data.input.impl.DimensionsSpec; import io.druid.data.input.impl.StringInputRowParser; import io.druid.data.input.impl.TimestampSpec; import io.druid.granularity.QueryGranularity; import io.druid.query.aggregation.AggregationTestHelper; import io.druid.query.aggregation.AggregatorFactory; import io.druid.query.aggregation.CountAggregatorFactory; import io.druid.query.dimension.DefaultDimensionSpec; import io.druid.query.dimension.DimensionSpec; import io.druid.query.dimension.ListFilteredDimensionSpec; import io.druid.query.dimension.RegexFilteredDimensionSpec; import io.druid.query.filter.SelectorDimFilter; import io.druid.query.groupby.GroupByQuery; import io.druid.query.groupby.GroupByQueryRunnerTestHelper; import io.druid.query.spec.LegacySegmentSpec; import io.druid.query.topn.TopNQuery; import io.druid.query.topn.TopNQueryBuilder; import io.druid.query.topn.TopNQueryConfig; import io.druid.query.topn.TopNQueryQueryToolChest; import io.druid.query.topn.TopNQueryRunnerFactory; import io.druid.query.topn.TopNResultValue; import io.druid.segment.IncrementalIndexSegment; import io.druid.segment.IndexSpec; import io.druid.segment.QueryableIndex; import io.druid.segment.QueryableIndexSegment; import io.druid.segment.TestHelper; import io.druid.segment.incremental.IncrementalIndex; import io.druid.segment.incremental.OnheapIncrementalIndex; import org.apache.commons.io.FileUtils; import org.joda.time.DateTime; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; /** */ public class MultiValuedDimensionTest { private AggregationTestHelper helper; private static IncrementalIndex incrementalIndex; private static QueryableIndex queryableIndex; private static File persistedSegmentDir; public MultiValuedDimensionTest() throws Exception { helper = AggregationTestHelper.createGroupByQueryAggregationTestHelper( ImmutableList.<Module>of(), null ); } @BeforeClass public static void setupClass() throws Exception { incrementalIndex = new OnheapIncrementalIndex( 0, QueryGranularity.NONE, new AggregatorFactory[]{ new CountAggregatorFactory("count") }, true, true, true, 5000 ); StringInputRowParser parser = new StringInputRowParser( new CSVParseSpec( new TimestampSpec("timestamp", "iso", null), new DimensionsSpec(DimensionsSpec.getDefaultSchemas(ImmutableList.of("product", "tags")), null, null), "\t", ImmutableList.of("timestamp", "product", "tags") ), "UTF-8" ); String[] rows = new String[]{ "2011-01-12T00:00:00.000Z,product_1,t1\tt2\tt3", "2011-01-13T00:00:00.000Z,product_2,t3\tt4\tt5", "2011-01-14T00:00:00.000Z,product_3,t5\tt6\tt7", }; for (String row : rows) { incrementalIndex.add(parser.parse(row)); } persistedSegmentDir = Files.createTempDir(); TestHelper.getTestIndexMerger() .persist(incrementalIndex, persistedSegmentDir, new IndexSpec()); queryableIndex = TestHelper.getTestIndexIO().loadIndex(persistedSegmentDir); } @Test public void testGroupByNoFilter() throws Exception { GroupByQuery query = GroupByQuery .builder() .setDataSource("xx") .setQuerySegmentSpec(new LegacySegmentSpec("1970/3000")) .setGranularity(QueryGranularity.ALL) .setDimensions(Lists.<DimensionSpec>newArrayList(new DefaultDimensionSpec("tags", "tags"))) .setAggregatorSpecs( Arrays.asList( new AggregatorFactory[] { new CountAggregatorFactory("count") } ) ) .build(); Sequence<Row> result = helper.runQueryOnSegmentsObjs( ImmutableList.of( new QueryableIndexSegment("sid1", queryableIndex), new IncrementalIndexSegment(incrementalIndex, "sid2") ), query ); List<Row> expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow("1970-01-01T00:00:00.000Z", "tags", "t1", "count", 2L), GroupByQueryRunnerTestHelper.createExpectedRow("1970-01-01T00:00:00.000Z", "tags", "t2", "count", 2L), GroupByQueryRunnerTestHelper.createExpectedRow("1970-01-01T00:00:00.000Z", "tags", "t3", "count", 4L), GroupByQueryRunnerTestHelper.createExpectedRow("1970-01-01T00:00:00.000Z", "tags", "t4", "count", 2L), GroupByQueryRunnerTestHelper.createExpectedRow("1970-01-01T00:00:00.000Z", "tags", "t5", "count", 4L), GroupByQueryRunnerTestHelper.createExpectedRow("1970-01-01T00:00:00.000Z", "tags", "t6", "count", 2L), GroupByQueryRunnerTestHelper.createExpectedRow("1970-01-01T00:00:00.000Z", "tags", "t7", "count", 2L) ); TestHelper.assertExpectedObjects(expectedResults, Sequences.toList(result, new ArrayList<Row>()), ""); result = helper.runQueryOnSegmentsObjs( ImmutableList.of( new QueryableIndexSegment("sid1", queryableIndex), new IncrementalIndexSegment(incrementalIndex, "sid2") ), query ); } @Test public void testGroupByWithDimFilter() throws Exception { GroupByQuery query = GroupByQuery .builder() .setDataSource("xx") .setQuerySegmentSpec(new LegacySegmentSpec("1970/3000")) .setGranularity(QueryGranularity.ALL) .setDimensions(Lists.<DimensionSpec>newArrayList(new DefaultDimensionSpec("tags", "tags"))) .setAggregatorSpecs( Arrays.asList( new AggregatorFactory[] { new CountAggregatorFactory("count") } ) ) .setDimFilter( new SelectorDimFilter("tags", "t3", null) ) .build(); Sequence<Row> result = helper.runQueryOnSegmentsObjs( ImmutableList.of( new QueryableIndexSegment("sid1", queryableIndex), new IncrementalIndexSegment(incrementalIndex, "sid2") ), query ); List<Row> expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow("1970-01-01T00:00:00.000Z", "tags", "t1", "count", 2L), GroupByQueryRunnerTestHelper.createExpectedRow("1970-01-01T00:00:00.000Z", "tags", "t2", "count", 2L), GroupByQueryRunnerTestHelper.createExpectedRow("1970-01-01T00:00:00.000Z", "tags", "t3", "count", 4L), GroupByQueryRunnerTestHelper.createExpectedRow("1970-01-01T00:00:00.000Z", "tags", "t4", "count", 2L), GroupByQueryRunnerTestHelper.createExpectedRow("1970-01-01T00:00:00.000Z", "tags", "t5", "count", 2L) ); TestHelper.assertExpectedObjects(expectedResults, Sequences.toList(result, new ArrayList<Row>()), ""); } @Test public void testGroupByWithDimFilterAndWithFilteredDimSpec() throws Exception { GroupByQuery query = GroupByQuery .builder() .setDataSource("xx") .setQuerySegmentSpec(new LegacySegmentSpec("1970/3000")) .setGranularity(QueryGranularity.ALL) .setDimensions( Lists.<DimensionSpec>newArrayList( new RegexFilteredDimensionSpec( new DefaultDimensionSpec("tags", "tags"), "t3" ) ) ) .setAggregatorSpecs( Arrays.asList( new AggregatorFactory[] { new CountAggregatorFactory("count") } ) ) .setDimFilter( new SelectorDimFilter("tags", "t3", null) ) .build(); Sequence<Row> result = helper.runQueryOnSegmentsObjs( ImmutableList.of( new QueryableIndexSegment("sid1", queryableIndex), new IncrementalIndexSegment(incrementalIndex, "sid2") ), query ); List<Row> expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow("1970-01-01T00:00:00.000Z", "tags", "t3", "count", 4L) ); TestHelper.assertExpectedObjects(expectedResults, Sequences.toList(result, new ArrayList<Row>()), ""); } @Test public void testTopNWithDimFilterAndWithFilteredDimSpec() throws Exception { TopNQuery query = new TopNQueryBuilder() .dataSource("xx") .granularity(QueryGranularity.ALL) .dimension(new ListFilteredDimensionSpec( new DefaultDimensionSpec("tags", "tags"), ImmutableSet.of("t3"), null )) .metric("count") .intervals(QueryRunnerTestHelper.fullOnInterval) .aggregators( Arrays.asList( new AggregatorFactory[] { new CountAggregatorFactory("count") } )) .threshold(5) .filters(new SelectorDimFilter("tags", "t3", null)).build(); QueryRunnerFactory factory = new TopNQueryRunnerFactory( TestQueryRunners.getPool(), new TopNQueryQueryToolChest( new TopNQueryConfig(), QueryRunnerTestHelper.NoopIntervalChunkingQueryRunnerDecorator() ), QueryRunnerTestHelper.NOOP_QUERYWATCHER ); QueryRunner<Result<TopNResultValue>> runner = QueryRunnerTestHelper.makeQueryRunner( factory, new QueryableIndexSegment("sid1", queryableIndex) ); Map<String, Object> context = Maps.newHashMap(); Sequence<Result<TopNResultValue>> result = runner.run(query, context); List<Result<TopNResultValue>> expectedResults = Arrays.asList( new Result<TopNResultValue>( new DateTime("2011-01-12T00:00:00.000Z"), new TopNResultValue( Arrays.<Map<String, Object>>asList( ImmutableMap.<String, Object>of( "tags", "t3", "count", 2L ) ) ) ) ); TestHelper.assertExpectedObjects( expectedResults, Sequences.toList(result, new ArrayList<Result<TopNResultValue>>()), "" ); } @AfterClass public static void cleanup() throws Exception { queryableIndex.close(); incrementalIndex.close(); FileUtils.deleteDirectory(persistedSegmentDir); } }
/* * oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.xdi.oxauth.userinfo.ws.rs; import org.apache.commons.lang.StringUtils; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.gluu.site.ldap.persistence.exception.EntryPersistenceException; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.log.Log; import org.xdi.model.GluuAttribute; import org.xdi.oxauth.model.authorize.Claim; import org.xdi.oxauth.model.common.*; import org.xdi.oxauth.model.config.ConfigurationFactory; import org.xdi.oxauth.model.crypto.PublicKey; import org.xdi.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm; import org.xdi.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm; import org.xdi.oxauth.model.crypto.signature.ECDSAPrivateKey; import org.xdi.oxauth.model.crypto.signature.RSAPrivateKey; import org.xdi.oxauth.model.crypto.signature.RSAPublicKey; import org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm; import org.xdi.oxauth.model.error.ErrorResponseFactory; import org.xdi.oxauth.model.exception.InvalidClaimException; import org.xdi.oxauth.model.exception.InvalidJweException; import org.xdi.oxauth.model.exception.InvalidJwtException; import org.xdi.oxauth.model.jwe.Jwe; import org.xdi.oxauth.model.jwe.JweEncrypter; import org.xdi.oxauth.model.jwe.JweEncrypterImpl; import org.xdi.oxauth.model.jwk.JSONWebKey; import org.xdi.oxauth.model.jwk.JSONWebKeySet; import org.xdi.oxauth.model.jws.ECDSASigner; import org.xdi.oxauth.model.jws.HMACSigner; import org.xdi.oxauth.model.jws.RSASigner; import org.xdi.oxauth.model.jwt.Jwt; import org.xdi.oxauth.model.jwt.JwtHeaderName; import org.xdi.oxauth.model.jwt.JwtSubClaimObject; import org.xdi.oxauth.model.jwt.JwtType; import org.xdi.oxauth.model.ldap.PairwiseIdentifier; import org.xdi.oxauth.model.token.JsonWebResponse; import org.xdi.oxauth.model.userinfo.UserInfoErrorResponseType; import org.xdi.oxauth.model.userinfo.UserInfoParamsValidator; import org.xdi.oxauth.model.util.JwtUtil; import org.xdi.oxauth.model.util.Util; import org.xdi.oxauth.service.AttributeService; import org.xdi.oxauth.service.PairwiseIdentifierService; import org.xdi.oxauth.service.ScopeService; import org.xdi.oxauth.service.UserService; import org.xdi.oxauth.service.external.ExternalDynamicScopeService; import org.xdi.util.security.StringEncrypter; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import java.io.UnsupportedEncodingException; import java.security.SignatureException; import java.util.*; /** * Provides interface for User Info REST web services * * @author Javier Rojas Blum * @version August 21, 2015 */ @Name("requestUserInfoRestWebService") public class UserInfoRestWebServiceImpl implements UserInfoRestWebService { @Logger private Log log; @In private ErrorResponseFactory errorResponseFactory; @In private AuthorizationGrantList authorizationGrantList; @In private ScopeService scopeService; @In private AttributeService attributeService; @In private UserService userService; @In private ExternalDynamicScopeService externalDynamicScopeService; @In private ConfigurationFactory configurationFactory; @In private PairwiseIdentifierService pairwiseIdentifierService; @Override public Response requestUserInfoGet(String accessToken, String authorization, SecurityContext securityContext) { return requestUserInfo(accessToken, authorization, securityContext); } @Override public Response requestUserInfoPost(String accessToken, String authorization, SecurityContext securityContext) { return requestUserInfo(accessToken, authorization, securityContext); } public Response requestUserInfo(String accessToken, String authorization, SecurityContext securityContext) { if (authorization != null && !authorization.isEmpty() && authorization.startsWith("Bearer ")) { accessToken = authorization.substring(7); } log.debug("Attempting to request User Info, Access token = {0}, Is Secure = {1}", accessToken, securityContext.isSecure()); Response.ResponseBuilder builder = Response.ok(); try { if (!UserInfoParamsValidator.validateParams(accessToken)) { builder = Response.status(400); builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INVALID_REQUEST)); } else { AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken); if (authorizationGrant == null) { builder = Response.status(400); builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INVALID_TOKEN)); } else if (!authorizationGrant.getScopes().contains(DefaultScope.OPEN_ID.toString()) && !authorizationGrant.getScopes().contains(DefaultScope.PROFILE.toString())) { builder = Response.status(403); builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INSUFFICIENT_SCOPE)); } else { CacheControl cacheControl = new CacheControl(); cacheControl.setPrivate(true); cacheControl.setNoTransform(false); cacheControl.setNoStore(true); builder.cacheControl(cacheControl); builder.header("Pragma", "no-cache"); User currentUser = authorizationGrant.getUser(); try { currentUser = userService.getUserByDn(authorizationGrant.getUserDn()); } catch (EntryPersistenceException ex) { log.warn("Failed to reload user entry: '{0}'", authorizationGrant.getUserDn()); } if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseAlg() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseEnc() != null) { KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseAlg()); BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseEnc()); builder.type("application/jwt"); builder.entity(getJweResponse( keyEncryptionAlgorithm, blockEncryptionAlgorithm, currentUser, authorizationGrant, authorizationGrant.getScopes())); } else if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoSignedResponseAlg() != null) { SignatureAlgorithm algorithm = SignatureAlgorithm.fromName(authorizationGrant.getClient().getUserInfoSignedResponseAlg()); builder.type("application/jwt"); builder.entity(getJwtResponse(algorithm, currentUser, authorizationGrant, authorizationGrant.getScopes())); } else { builder.type((MediaType.APPLICATION_JSON)); builder.entity(getJSonResponse(currentUser, authorizationGrant, authorizationGrant.getScopes())); } } } } catch (StringEncrypter.EncryptionException e) { builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500 log.error(e.getMessage(), e); } catch (InvalidJwtException e) { builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500 log.error(e.getMessage(), e); } catch (SignatureException e) { builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500 log.error(e.getMessage(), e); } catch (InvalidClaimException e) { builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500 log.error(e.getMessage(), e); } catch (Exception e) { builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500 log.error(e.getMessage(), e); } return builder.build(); } public String getJwtResponse(SignatureAlgorithm signatureAlgorithm, User user, AuthorizationGrant authorizationGrant, Collection<String> scopes) throws StringEncrypter.EncryptionException, InvalidJwtException, InvalidClaimException, SignatureException { Jwt jwt = new Jwt(); JSONWebKeySet jwks = ConfigurationFactory.instance().getWebKeys(); // Header if (signatureAlgorithm == SignatureAlgorithm.NONE) { jwt.getHeader().setType(JwtType.JWT); } else { jwt.getHeader().setType(JwtType.JWS); } jwt.getHeader().setAlgorithm(signatureAlgorithm); List<JSONWebKey> availableKeys = jwks.getKeys(signatureAlgorithm); if (availableKeys.size() > 0) { jwt.getHeader().setKeyId(availableKeys.get(0).getKeyId()); } // Claims List<String> dynamicScopes = new ArrayList<String>(); for (String scopeName : scopes) { Scope scope = scopeService.getScopeByDisplayName(scopeName); if (org.xdi.oxauth.model.common.ScopeType.DYNAMIC == scope.getScopeType()) { dynamicScopes.add(scope.getDisplayName()); continue; } if (scope.getOxAuthClaims() != null) { for (String claimDn : scope.getOxAuthClaims()) { GluuAttribute gluuAttribute = attributeService.getAttributeByDn(claimDn); String claimName = gluuAttribute.getOxAuthClaimName(); String ldapName = gluuAttribute.getName(); String attributeValue = null; if (StringUtils.isNotBlank(claimName) && StringUtils.isNotBlank(ldapName)) { if (ldapName.equals("uid")) { attributeValue = user.getUserId(); } else { attributeValue = user.getAttribute(gluuAttribute.getName()); } jwt.getClaims().setClaim(claimName, attributeValue); } } } } if (authorizationGrant.getJwtAuthorizationRequest() != null && authorizationGrant.getJwtAuthorizationRequest().getUserInfoMember() != null) { for (Claim claim : authorizationGrant.getJwtAuthorizationRequest().getUserInfoMember().getClaims()) { boolean optional = true; // ClaimValueType.OPTIONAL.equals(claim.getClaimValue().getClaimValueType()); GluuAttribute gluuAttribute = attributeService.getByClaimName(claim.getName()); if (gluuAttribute != null) { String ldapClaimName = gluuAttribute.getName(); Object attribute = user.getAttribute(ldapClaimName, optional); if (attribute != null) { if (attribute instanceof JSONArray) { JSONArray jsonArray = (JSONArray) attribute; List<String> values = new ArrayList<String>(); for (int i = 0; i < jsonArray.length(); i++) { String value = jsonArray.optString(i); if (value != null) { values.add(value); } } jwt.getClaims().setClaim(claim.getName(), values); } else { String value = (String) attribute; jwt.getClaims().setClaim(claim.getName(), value); } } } } } // Check for Subject Identifier Type if (authorizationGrant.getClient().getSubjectType() != null && SubjectType.fromString(authorizationGrant.getClient().getSubjectType()).equals(SubjectType.PAIRWISE)) { String sectorIdentifier = null; if (StringUtils.isNotBlank(authorizationGrant.getClient().getSectorIdentifierUri())) { sectorIdentifier = authorizationGrant.getClient().getSectorIdentifierUri(); } else { sectorIdentifier = authorizationGrant.getClient().getRedirectUris()[0]; } String userInum = authorizationGrant.getUser().getAttribute("inum"); PairwiseIdentifier pairwiseIdentifier = pairwiseIdentifierService.findPairWiseIdentifier( userInum, sectorIdentifier); if (pairwiseIdentifier == null) { pairwiseIdentifier = new PairwiseIdentifier(sectorIdentifier); pairwiseIdentifier.setId(UUID.randomUUID().toString()); pairwiseIdentifier.setDn(pairwiseIdentifierService.getDnForPairwiseIdentifier( pairwiseIdentifier.getId(), userInum)); pairwiseIdentifierService.addPairwiseIdentifier(userInum, pairwiseIdentifier); } jwt.getClaims().setSubjectIdentifier(pairwiseIdentifier.getId()); } else { String openidSubAttribute = configurationFactory.getConfiguration().getOpenidSubAttribute(); jwt.getClaims().setSubjectIdentifier(authorizationGrant.getUser().getAttribute(openidSubAttribute)); } if ((dynamicScopes.size() > 0) && externalDynamicScopeService.isEnabled()) { externalDynamicScopeService.executeExternalUpdateMethods(dynamicScopes, jwt, authorizationGrant.getUser()); } // Signature JSONWebKey jwk = null; switch (signatureAlgorithm) { case HS256: case HS384: case HS512: HMACSigner hmacSigner = new HMACSigner(signatureAlgorithm, authorizationGrant.getClient().getClientSecret()); jwt = hmacSigner.sign(jwt); break; case RS256: case RS384: case RS512: jwk = jwks.getKey(jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID)); RSAPrivateKey rsaPrivateKey = new RSAPrivateKey( jwk.getPrivateKey().getModulus(), jwk.getPrivateKey().getPrivateExponent()); RSASigner rsaSigner = new RSASigner(signatureAlgorithm, rsaPrivateKey); jwt = rsaSigner.sign(jwt); break; case ES256: case ES384: case ES512: jwk = jwks.getKey(jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID)); ECDSAPrivateKey ecdsaPrivateKey = new ECDSAPrivateKey(jwk.getPrivateKey().getD()); ECDSASigner ecdsaSigner = new ECDSASigner(signatureAlgorithm, ecdsaPrivateKey); jwt = ecdsaSigner.sign(jwt); break; case NONE: break; default: break; } return jwt.toString(); } public String getJweResponse(KeyEncryptionAlgorithm keyEncryptionAlgorithm, BlockEncryptionAlgorithm blockEncryptionAlgorithm, User user, AuthorizationGrant authorizationGrant, Collection<String> scopes) throws InvalidClaimException, InvalidJweException { Jwe jwe = new Jwe(); // Header jwe.getHeader().setType(JwtType.JWE); jwe.getHeader().setAlgorithm(keyEncryptionAlgorithm); jwe.getHeader().setEncryptionMethod(blockEncryptionAlgorithm); // Claims List<String> dynamicScopes = new ArrayList<String>(); for (String scopeName : scopes) { Scope scope = scopeService.getScopeByDisplayName(scopeName); if (org.xdi.oxauth.model.common.ScopeType.DYNAMIC == scope.getScopeType()) { dynamicScopes.add(scope.getDisplayName()); continue; } if (scope.getOxAuthClaims() != null) { for (String claimDn : scope.getOxAuthClaims()) { GluuAttribute gluuAttribute = attributeService.getAttributeByDn(claimDn); String claimName = gluuAttribute.getOxAuthClaimName(); String ldapName = gluuAttribute.getName(); String attributeValue = null; if (StringUtils.isNotBlank(claimName) && StringUtils.isNotBlank(ldapName)) { if (ldapName.equals("uid")) { attributeValue = user.getUserId(); } else { attributeValue = user.getAttribute(gluuAttribute.getName()); } jwe.getClaims().setClaim(claimName, attributeValue); } } } } if (authorizationGrant.getJwtAuthorizationRequest() != null && authorizationGrant.getJwtAuthorizationRequest().getUserInfoMember() != null) { for (Claim claim : authorizationGrant.getJwtAuthorizationRequest().getUserInfoMember().getClaims()) { boolean optional = true; // ClaimValueType.OPTIONAL.equals(claim.getClaimValue().getClaimValueType()); GluuAttribute gluuAttribute = attributeService.getByClaimName(claim.getName()); if (gluuAttribute != null) { String ldapClaimName = gluuAttribute.getName(); Object attribute = user.getAttribute(ldapClaimName, optional); if (attribute != null) { if (attribute instanceof JSONArray) { JSONArray jsonArray = (JSONArray) attribute; List<String> values = new ArrayList<String>(); for (int i = 0; i < jsonArray.length(); i++) { String value = jsonArray.optString(i); if (value != null) { values.add(value); } } jwe.getClaims().setClaim(claim.getName(), values); } else { String value = (String) attribute; jwe.getClaims().setClaim(claim.getName(), value); } } } } } // Check for Subject Identifier Type if (authorizationGrant.getClient().getSubjectType() != null && SubjectType.fromString(authorizationGrant.getClient().getSubjectType()).equals(SubjectType.PAIRWISE)) { String sectorIdentifier = null; if (StringUtils.isNotBlank(authorizationGrant.getClient().getSectorIdentifierUri())) { sectorIdentifier = authorizationGrant.getClient().getSectorIdentifierUri(); } else { sectorIdentifier = authorizationGrant.getClient().getRedirectUris()[0]; } String userInum = authorizationGrant.getUser().getAttribute("inum"); PairwiseIdentifier pairwiseIdentifier = pairwiseIdentifierService.findPairWiseIdentifier( userInum, sectorIdentifier); if (pairwiseIdentifier == null) { pairwiseIdentifier = new PairwiseIdentifier(sectorIdentifier); pairwiseIdentifier.setId(UUID.randomUUID().toString()); pairwiseIdentifier.setDn(pairwiseIdentifierService.getDnForPairwiseIdentifier( pairwiseIdentifier.getId(), userInum)); pairwiseIdentifierService.addPairwiseIdentifier(userInum, pairwiseIdentifier); } jwe.getClaims().setSubjectIdentifier(pairwiseIdentifier.getId()); } else { String openidSubAttribute = configurationFactory.getConfiguration().getOpenidSubAttribute(); jwe.getClaims().setSubjectIdentifier(authorizationGrant.getUser().getAttribute(openidSubAttribute)); } if ((dynamicScopes.size() > 0) && externalDynamicScopeService.isEnabled()) { externalDynamicScopeService.executeExternalUpdateMethods(dynamicScopes, jwe, authorizationGrant.getUser()); } // Encryption if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA_OAEP || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA1_5) { PublicKey publicKey = JwtUtil.getPublicKey(authorizationGrant.getClient().getJwksUri(), null, SignatureAlgorithm.RS256, null); if (publicKey != null && publicKey instanceof RSAPublicKey) { JweEncrypter jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, (RSAPublicKey) publicKey); jwe = jweEncrypter.encrypt(jwe); } else { throw new InvalidJweException("The public key is not valid"); } } else if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A128KW || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A256KW) { try { byte[] sharedSymmetricKey = authorizationGrant.getClient().getClientSecret().getBytes(Util.UTF8_STRING_ENCODING); JweEncrypter jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, sharedSymmetricKey); jwe = jweEncrypter.encrypt(jwe); } catch (UnsupportedEncodingException e) { throw new InvalidJweException(e); } catch (StringEncrypter.EncryptionException e) { throw new InvalidJweException(e); } catch (Exception e) { throw new InvalidJweException(e); } } return jwe.toString(); } /** * Builds a JSon String with the response parameters. */ public String getJSonResponse(User user, AuthorizationGrant authorizationGrant, Collection<String> scopes) throws JSONException, InvalidClaimException { JsonWebResponse jsonWebResponse = new JsonWebResponse(); // Claims List<String> dynamicScopes = new ArrayList<String>(); for (String scopeName : scopes) { org.xdi.oxauth.model.common.Scope scope = scopeService.getScopeByDisplayName(scopeName); if ((scope != null) && (org.xdi.oxauth.model.common.ScopeType.DYNAMIC == scope.getScopeType())) { dynamicScopes.add(scope.getDisplayName()); continue; } Map<String, Object> claims = getClaims(user, scope); if (scope.getIsOxAuthGroupClaims()) { JwtSubClaimObject groupClaim = new JwtSubClaimObject(); groupClaim.setName(scope.getDisplayName()); for (Map.Entry<String, Object> entry : claims.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (value instanceof List) { groupClaim.setClaim(key, (List<String>) value); } else { groupClaim.setClaim(key, (String) value); } } jsonWebResponse.getClaims().setClaim(scope.getDisplayName(), groupClaim); } else { for (Map.Entry<String, Object> entry : claims.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (value instanceof List) { jsonWebResponse.getClaims().setClaim(key, (List<String>) value); } else { jsonWebResponse.getClaims().setClaim(key, (String) value); } } } jsonWebResponse.getClaims().setSubjectIdentifier(authorizationGrant.getUser().getAttribute("inum")); } if (authorizationGrant.getJwtAuthorizationRequest() != null && authorizationGrant.getJwtAuthorizationRequest().getUserInfoMember() != null) { for (Claim claim : authorizationGrant.getJwtAuthorizationRequest().getUserInfoMember().getClaims()) { boolean optional = true; // ClaimValueType.OPTIONAL.equals(claim.getClaimValue().getClaimValueType()); GluuAttribute gluuAttribute = attributeService.getByClaimName(claim.getName()); if (gluuAttribute != null) { String ldapClaimName = gluuAttribute.getName(); Object attribute = user.getAttribute(ldapClaimName, optional); if (attribute != null) { if (attribute instanceof JSONArray) { JSONArray jsonArray = (JSONArray) attribute; List<String> values = new ArrayList<String>(); for (int i = 0; i < jsonArray.length(); i++) { String value = jsonArray.optString(i); if (value != null) { values.add(value); } } jsonWebResponse.getClaims().setClaim(claim.getName(), values); } else { String value = (String) attribute; jsonWebResponse.getClaims().setClaim(claim.getName(), value); } } } } } // Check for Subject Identifier Type if (authorizationGrant.getClient().getSubjectType() != null && SubjectType.fromString(authorizationGrant.getClient().getSubjectType()).equals(SubjectType.PAIRWISE)) { String sectorIdentifier = null; if (StringUtils.isNotBlank(authorizationGrant.getClient().getSectorIdentifierUri())) { sectorIdentifier = authorizationGrant.getClient().getSectorIdentifierUri(); } else { sectorIdentifier = authorizationGrant.getClient().getRedirectUris()[0]; } String userInum = authorizationGrant.getUser().getAttribute("inum"); PairwiseIdentifier pairwiseIdentifier = pairwiseIdentifierService.findPairWiseIdentifier( userInum, sectorIdentifier); if (pairwiseIdentifier == null) { pairwiseIdentifier = new PairwiseIdentifier(sectorIdentifier); pairwiseIdentifier.setId(UUID.randomUUID().toString()); pairwiseIdentifier.setDn(pairwiseIdentifierService.getDnForPairwiseIdentifier( pairwiseIdentifier.getId(), userInum)); pairwiseIdentifierService.addPairwiseIdentifier(userInum, pairwiseIdentifier); } jsonWebResponse.getClaims().setSubjectIdentifier(pairwiseIdentifier.getId()); } else { String openidSubAttribute = configurationFactory.getConfiguration().getOpenidSubAttribute(); jsonWebResponse.getClaims().setSubjectIdentifier(authorizationGrant.getUser().getAttribute(openidSubAttribute)); } if ((dynamicScopes.size() > 0) && externalDynamicScopeService.isEnabled()) { externalDynamicScopeService.executeExternalUpdateMethods(dynamicScopes, jsonWebResponse, authorizationGrant.getUser()); } return jsonWebResponse.toString(); } public Map<String, Object> getClaims(User user, Scope scope) throws InvalidClaimException { Map<String, Object> claims = new HashMap<String, Object>(); if (scope != null && scope.getOxAuthClaims() != null) { for (String claimDn : scope.getOxAuthClaims()) { GluuAttribute gluuAttribute = attributeService.getAttributeByDn(claimDn); String claimName = gluuAttribute.getOxAuthClaimName(); String ldapName = gluuAttribute.getName(); Object attribute = null; if (StringUtils.isNotBlank(claimName) && StringUtils.isNotBlank(ldapName)) { if (ldapName.equals("uid")) { attribute = user.getUserId(); } else { attribute = user.getAttribute(gluuAttribute.getName(), true); } if (attribute != null) { if (attribute instanceof JSONArray) { JSONArray jsonArray = (JSONArray) attribute; List<String> values = new ArrayList<String>(); for (int i = 0; i < jsonArray.length(); i++) { String value = jsonArray.optString(i); if (value != null) { values.add(value); } } claims.put(claimName, values); } else { claims.put(claimName, attribute); } } } } } return claims; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gp; import java.util.HashMap ; import javax.swing.GroupLayout.Alignment ; import javax.swing.GroupLayout ; import javax.swing.LayoutStyle.ComponentPlacement ; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JButton; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.JSpinner; import javax.swing.JTextArea; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.SpinnerNumberModel; import javax.swing.SwingUtilities; //import gp.math.JaTeX; /** * * @author User */ public class test extends javax.swing.JFrame { public String tst=""; public String tp ="Above"; MainWindow main = null; /** * Creates new form mcq */ main_frame g; public test(main_frame a) { initComponents(); g=a; } @SuppressWarnings("unused") private void addtActionPerformed(java.awt.event.ActionEvent evt){ // TODO add your handling code here: table2 a=new table2(this); a.setVisible(true); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { setTitle("MCQ"); question_1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); add = new javax.swing.JButton(); op4.setColumns(10); op3.setColumns(10); op2.setColumns(10); op1.setColumns(10); add.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int no= (int) qno.getValue(); int mark=(int)marks.getValue(); g.mcc+=1; g.mcm+=mark; g.mc.setText(String.valueOf(g.mcc)); g.mm.setText(String.valueOf(g.mcm)); g.tq.setText(String.valueOf(g.mcc)); g.tm.setText(String.valueOf(g.mcm)); String dtable=""; String utable=""; if(tst!=""){ if(tp=="Above"){ utable =tst; } else{ dtable=tst; } } String MCQ = utable+"\\subquestion{"+question.getText()+"\r\n"+dtable+ "\\begin{enumerate}\r\n"+ "\\item "+op1.getText()+"\r\n"+ "\\item "+op2.getText()+"\r\n"+ "\\item "+op3.getText()+"\r\n"+ "\\item "+op4.getText()+"\r\n"+ "\\end{enumerate}\r\n"+ "\\qmarks{"+marks.getValue()+"}\r\n"+ "}\r\n"; if(main_frame.mapper.containsKey(no)){ mcqq testa=(mcqq)main_frame.mapper.get(no); main_frame.mapper.remove(no); testa.title="\\question {"+title.getText()+".\r\n"; testa.utitle=title.getText(); testa.mcq+=MCQ; //System.out.println(testa.mcq); main_frame.mapper.put(no,testa); } else{ mcqq testa=new mcqq(no); testa.title="\\question {"+title.getText()+".\r\n"; testa.utitle=title.getText(); testa.mcq+=MCQ; main_frame.mapper.put(no,testa); } question.setText(""); op1.setText(""); op2.setText(""); op3.setText(""); op4.setText(""); this.mcqset(); g.mcqupd(); tst=""; } public void getwhole(){ for (Object o : main_frame.mapper.values()){ mcqq a=(mcqq)o; System.out.println(a.title); System.out.println(a.mcq); System.out.println("_______________"); System.out.print("\n\n\n"); } } public void mcqset(){ String x=""; for (Object o : main_frame.mapper.values()){ mcqq a=(mcqq)o; x+=a.get(); } main_frame.mcq=x; } private void setVisible(boolean b) { // TODO Auto-generated method stub dispose(); } }); // setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); question_1.setText(" Question"); qno.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent arg0) { Integer no= (Integer) qno.getValue(); String a=no.toString(); int r=no.intValue(); if(g.mapper.containsKey(r)){ mcqq o=(mcqq)g.mapper.get(r); String tit=o.utitle; title.setText(tit); } else{ title.setText(""); } } }); qno.setModel(new javax.swing.SpinnerNumberModel(1, 1, 999, 1)); jLabel2.setText(" Option 1"); jLabel3.setText(" Option 2"); jLabel4.setText(" Option 3"); jLabel5.setText(" Option 4"); add.setText("ADD"); addt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addtActionPerformed(evt); } }); marks.setModel(new SpinnerNumberModel(2, 0, 10, 1)); title.setColumns(10); JButton btnAddMath = new JButton("Add Math"); btnAddMath.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { // Create an instance of our application. //JaTeX j=new JaTeX(); if(main != null){ main.setVisible(true); }else{ main = new MainWindow(null); main.setVisible(true); } } catch (Throwable e) { e.printStackTrace(); } } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(lblTitle, GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE) .addPreferredGap(ComponentPlacement.RELATED)) .addGroup(layout.createSequentialGroup() .addComponent(question_1, GroupLayout.PREFERRED_SIZE, 65, GroupLayout.PREFERRED_SIZE) .addGap(23))) .addGroup(layout.createParallelGroup(Alignment.LEADING, false) .addComponent(title) .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 670, Short.MAX_VALUE)) .addGap(26) .addGroup(layout.createParallelGroup(Alignment.TRAILING, false) .addGroup(layout.createSequentialGroup() .addComponent(lblTitleNo) .addGap(18) .addComponent(qno, GroupLayout.PREFERRED_SIZE, 63, GroupLayout.PREFERRED_SIZE)) .addComponent(addt, GroupLayout.PREFERRED_SIZE, 91, GroupLayout.PREFERRED_SIZE) .addComponent(btnChangeTitle) .addGroup(layout.createSequentialGroup() .addComponent(lblMarks, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(ComponentPlacement.UNRELATED) .addComponent(marks, GroupLayout.PREFERRED_SIZE, 62, GroupLayout.PREFERRED_SIZE)))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(Alignment.LEADING, false) .addComponent(jLabel3, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2, GroupLayout.DEFAULT_SIZE, 79, Short.MAX_VALUE) .addComponent(jLabel5, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4, GroupLayout.DEFAULT_SIZE, 76, Short.MAX_VALUE)) .addPreferredGap(ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(Alignment.TRAILING) .addComponent(op2, Alignment.LEADING, 675, 675, 675) .addComponent(op3, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 677, Short.MAX_VALUE) .addComponent(op4, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 677, Short.MAX_VALUE) .addComponent(op1, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 677, Short.MAX_VALUE)) .addGap(56) .addGroup(layout.createParallelGroup(Alignment.TRAILING) .addComponent(blm) .addComponent(btnAddMath))) .addComponent(add, Alignment.TRAILING)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(14) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblTitle) .addComponent(title, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(qno, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblTitleNo)) .addGroup(layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(ComponentPlacement.RELATED) .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 123, GroupLayout.PREFERRED_SIZE) .addGap(32) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(jLabel2, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE) .addComponent(op1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(blm)) .addPreferredGap(ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(Alignment.TRAILING) .addComponent(jLabel3, GroupLayout.PREFERRED_SIZE, 21, GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(op2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(btnAddMath))) .addPreferredGap(ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(jLabel4, GroupLayout.PREFERRED_SIZE, 21, GroupLayout.PREFERRED_SIZE) .addComponent(op3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(18) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(jLabel5, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE) .addComponent(op4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGap(26) .addGroup(layout.createParallelGroup(Alignment.TRAILING) .addComponent(question_1, GroupLayout.PREFERRED_SIZE, 28, GroupLayout.PREFERRED_SIZE) .addComponent(btnChangeTitle)) .addGap(18) .addComponent(addt) .addGap(18) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(marks, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblMarks)))) .addGap(38) .addComponent(add) .addContainerGap()) ); blm.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { BT x=new BT(); x.setVisible(true); } }); btnChangeTitle.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { int no=(int) qno.getValue(); if(g.mapper.containsKey(no)){ mcqq o=(mcqq)g.mapper.get(no); o.title="\\question {"+title.getText()+".\r\n"; o.utitle=title.getText(); }else{ title.setText(""); } } }); jScrollPane1.setViewportView(question); getContentPane().setLayout(layout); pack(); }// </editor-fold> /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(mcq.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(mcq.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(mcq.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(mcq.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { //new test().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton add; private javax.swing.JLabel question_1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JScrollPane jScrollPane1; private final JButton addt = new JButton("ADD Table"); public static JTextField title = new JTextField(); private final JLabel lblTitle = new JLabel(" Title"); private final JSpinner qno = new JSpinner(); private final JLabel lblTitleNo = new JLabel("Title No:"); private final JTextField op1 = new JTextField(); private final JTextField op2 = new JTextField(); private final JTextField op3 = new JTextField(); private final JTextField op4 = new JTextField(); private final JTextArea question = new JTextArea(); private final JButton btnChangeTitle = new JButton("Change Title"); private final JSpinner marks = new JSpinner(); private final JLabel lblMarks = new JLabel("Marks"); private final JButton blm = new JButton("Bloom's tex"); }
/* * InputOutputOJ.java * -- documented * * methods to load and save project and results */ package oj.io; import java.util.logging.Level; import java.util.logging.Logger; import ij.IJ; import ij.Macro; import ij.io.OpenDialog; import ij.util.Java2; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.PrintWriter; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import oj.OJ; import oj.util.UtilsOJ; import oj.project.*; import oj.io.spi.IIOProviderOJ; import oj.io.spi.IOFactoryOJ; import oj.project.results.ColumnsOJ; public class InputOutputOJ { private static String currentDirectory = ""; /** * @return directory containing the ojj file */ public static String getCurrentDirectory() { return currentDirectory; } /** * directory containing the ojj file */ public static void setCurrentDirectory(String directory) { currentDirectory = directory; } /** * currently not used- later we will save the macro only as zip entry */ public void saveMacro(String title, String defaultDir, String defaultName, String content, double unusedSpoiler) { Java2.setSystemLookAndFeel(); JFileChooser fc = new JFileChooser(); if (defaultDir != null) { File f = new File(defaultDir); if (f != null) { fc.setCurrentDirectory(f); } } if (defaultName != null) { fc.setSelectedFile(new File(defaultName)); } int returnVal = fc.showSaveDialog(IJ.getInstance()); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } InputOutputOJ.setCurrentDirectory(fc.getCurrentDirectory().getAbsolutePath()); File f = fc.getSelectedFile(); if (f.exists()) { int ret = JOptionPane.showConfirmDialog(fc, "The file " + f.getName() + " already exists, \nwould you like to overwrite it?", "Overwrite?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (ret != JOptionPane.OK_OPTION) { f = null; } } if (f == null) { Macro.abort(); } else { String dir = fc.getCurrentDirectory().getPath() + File.separator; String name = fc.getName(f); try { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dir + name))); out.writeBytes(content); } catch (Exception e) { IJ.error("Error 8563: " + e.getMessage()); return; } } } //usually there is already a project file that now needs to be overwritten. //If old project file does not exist, then a warning is issued: //e.g. the old project file may have been moved or trashed in the Finder. //now the user can save it under this or a different name. /** * saves the project in an .ojj file. old version: xml text is saved * uncompressed new version: binary and macro are put in a compressed zip * archive * * @return true if successful */ public boolean saveProject(DataOJ data, boolean itsBinary) { ij.IJ.showStatus("Saving ObjectJ project..."); if ((data.getDirectory() != null) && (data.getFilename() != null) && (new File(data.getDirectory(), data.getFilename()).exists())) { File f = new File(data.getDirectory(), data.getName() + FileFilterOJ.objectJFileFilter().getExtension()); if (!oj.OJ.loadedAsBinary) { boolean flag = ij.IJ.showMessageWithCancel("Saving Project", "Project file was loaded in XML format, and will now be saved in the newer Binary format."); if (!flag) { return false; } oj.OJ.loadedAsBinary = true; } if (f.exists()) { boolean useBinary = OJ.saveAsBinary;//10.4.2010 return saveProject(data, data.getDirectory(), data.getFilename(), useBinary); } else { boolean pathMayChange = false; return saveProjectAs(data, itsBinary, pathMayChange);//, true } } else { boolean pathMayChange = true; IJ.showMessage("Couldn't relocate project file on disk"); return saveProjectAs(data, itsBinary, pathMayChange);//, true } } /** * Saves a copy of current project for backup */ public boolean saveACopy(DataOJ data) { boolean ok = true; String tmpName = data.getName(); String tmpDir = data.getDirectory(); String tmpFileName = data.getFilename(); String fName = data.getName(); if (fName.length() < 20) { fName += "-Copy"; } fName += ".ojj"; String fNameNoExtension = ""; String dir = ""; SaveDialogOJ sd = new SaveDialogOJ("Save a copy of project ...", fName, FileFilterOJ.objectJFileFilter()); if (sd.isApproved()) { try { fName = sd.getFilename(); dir = sd.getDirectory(); int index = fName.lastIndexOf("."); fNameNoExtension = fName; if (index > 0) { fNameNoExtension = fName.substring(0, index); } } catch (Exception e) { IJ.error("error 5456"); ok = false; } if (ok) { try { data.setName(fNameNoExtension); IIOProviderOJ ioProvider = IOFactoryOJ.getFactory().getProvider("javaobject"); ioProvider.saveProject(data, dir, fName); } catch (Exception e) { IJ.error("error 9843"); ok = false; } } } //data.setImages(tmpImages); //data.setCells(tmpCells); data.setName(tmpName); data.setDirectory(tmpDir); data.setFilename(tmpFileName); return ok; } /** * Sets Images and Cells temporarily to zero and saves an empty copy, so it * can be used for a similar experiment. All other information is retained: * macros, object defs, column defs. Caution: unlinked columns are not * emptied. */ public boolean saveEmptyProject(DataOJ data) { boolean ok = true; CellsOJ tmpCells = data.getCells(); ImagesOJ tmpImages = data.getImages(); String tmpName = data.getName(); String tmpDir = data.getDirectory(); String tmpFileName = data.getFilename(); data.setCells(new CellsOJ()); data.setImages(new ImagesOJ()); String fName = "Untitled.ojj"; String fNameNoExtension = ""; String dir = ""; SaveDialogOJ sd = new SaveDialogOJ("Save empty copy ...", fName, FileFilterOJ.objectJFileFilter()); if (sd.isApproved()) { try { fName = sd.getFilename(); dir = sd.getDirectory(); int index = fName.lastIndexOf("."); fNameNoExtension = fName; if (index > 0) { fNameNoExtension = fName.substring(0, index); } } catch (Exception e) { IJ.error("error 9895"); ok = false; } if (ok) { try { data.setName(fNameNoExtension); IIOProviderOJ ioProvider = IOFactoryOJ.getFactory().getProvider("javaobject"); ioProvider.saveProject(data, dir, fName); } catch (Exception e) { IJ.error("error 8871"); ok = false; } } } data.setImages(tmpImages); data.setCells(tmpCells); data.setName(tmpName); data.setDirectory(tmpDir); data.setFilename(tmpFileName); return ok; } /** * will only be used in the new zipped version which contains the macro */ //public boolean saveProjectAs(DataOJ data, boolean itsBinary, boolean saveACopy/*, boolean withContent*/) { public boolean saveProjectAs(DataOJ data, boolean itsBinary, boolean pathMayChange) { boolean ok = false; if (data != null) { String oldDir = data.getDirectory(); String oldFileName = data.getFilename(); String oldProjectName = data.getName(); String newDir = ""; String newFileName = ""; String newProjectName = ""; String defaultName = data.getName(); if ((data.getFilename() != null) && (!data.getFilename().equals(""))) { int index = data.getFilename().lastIndexOf("."); if (index > 0) { defaultName = data.getFilename().substring(0, index); } } else { defaultName = "Untitled"; } SaveDialogOJ sd; if (itsBinary) { sd = new SaveDialogOJ("Save project ...", defaultName, FileFilterOJ.objectJFileFilter()); } else { sd = new SaveDialogOJ("Save project ...", defaultName, FileFilterOJ.xmlFileFilter()); } if (sd.isApproved()) { try { newFileName = sd.getFilename(); newDir = sd.getDirectory(); int index = sd.getFilename().lastIndexOf("."); if (index > 0) { newProjectName = sd.getFilename().substring(0, index); } data.setName(newProjectName); ok = saveProject(data, sd.getDirectory(), sd.getFilename(), itsBinary);//30.9.2010 } catch (Exception e) { IJ.error("OJ_Prefs.txt contains binary=true?"); ok = false; } } else { ok = false; } if (!pathMayChange) { data.setDirectory(oldDir); data.setFilename(oldFileName); data.setName(oldProjectName); } else { data.setDirectory(newDir); data.setFilename(newFileName); data.setName(newProjectName); } } OJ.isProjectOpen = true;//4.10.2010 return ok; } /** * saves current project under same name. depending on flag "asBinary", * selects either "xmlstream" or "javaobject" provider, then calls that * provider's "saveProject()" method. Before saving, killBadCells() removes * cells with zero ytems, and ytems with zero points * * @return true if successful */ private boolean saveProject(DataOJ data, String directory, String filename, boolean asBinary) { //asBinary = false; int error = 6004; if (data != null) { data.getCells().killBadCells(); data.setDescription(data.xmlComment); } try { data.setFilename(filename); data.setDirectory(directory); error = 6005; data.getResults().recalculate(); error = 6006; data.updateChangeDate(); if (asBinary) { IIOProviderOJ ioProvider = IOFactoryOJ.getFactory().getProvider("javaobject"); ioProvider.saveProject(data, directory, filename); return true; } else { IIOProviderOJ ioProvider = IOFactoryOJ.getFactory().getProvider("xmlstream"); ioProvider.saveProject(data, directory, filename); return true; } } catch (Exception e) { IJ.error("error = " + error + ": " + e.getMessage()); return false; } } /** * Called by ResultActionsOJ to save results as text */ public void saveResultsAsText(String txt, String defaultName) { DataOJ data = oj.OJ.getData(); if (data != null) { OpenDialog.setDefaultDirectory(data.getDirectory());//26.8.2010 } SaveDialogOJ sd = new SaveDialogOJ("Save results ...", defaultName, FileFilterOJ.objectResultTextFileFilter()); if (sd.isApproved()) { try { FileWriter fos = new FileWriter(new File(sd.getDirectory(), sd.getFilename())); PrintWriter out = new PrintWriter(fos); out.println(txt); out.close(); } catch (Exception e) { IJ.error("error 3365: " + e.getMessage()); } } } public void saveIgorAsText(String txt, String dir, String name) { try { FileWriter fos = new FileWriter(new File(dir, name)); PrintWriter out = new PrintWriter(fos); out.println(txt); out.close(); } catch (Exception e) { IJ.error("error 3715: " + e.getMessage()); } } /** * Asks to load a project */ public DataOJ loadProjectWithDialog() { OpenDialogOJ od = new OpenDialogOJ("Open ObjectJ project ...", FileFilterOJ.objectJFileFilter()); if (od.isApproved()) { return loadAProject(od.getDirectory(), od.getFilename()); } else { return null; } } /** * Depending on file type, selects either the "xmlstream" or the "javaobject * provider, then calls that provider's "loadProject" method. * * @return dataOJ or null */ public DataOJ loadAProject(String directory, String filename) { DataOJ dataOj = null; //OJ.doubleBuffered = false; //10.2.2011 String theType = UtilsOJ.getFileType(directory, filename); try { if (theType.startsWith("isZipped")) { IIOProviderOJ ioProvider = IOFactoryOJ.getFactory().getProvider("javaobject"); dataOj = ioProvider.loadProject(directory, filename); oj.OJ.loadedAsBinary = true; OJ.isProjectOpen = true; } else { IIOProviderOJ ioProvider = IOFactoryOJ.getFactory().getProvider("xmlstream"); if (ioProvider.isValidData(directory, filename)) { IJ.showStatus("Please wait while loading project file ..."); dataOj = ioProvider.loadProject(directory, filename); oj.OJ.loadedAsBinary = false; OJ.isProjectOpen = true; } } } catch (ProjectIOExceptionOJ ex) { Logger.getLogger(InputOutputOJ.class.getName()).log(Level.SEVERE, null, ex); IJ.showMessage(ex.getMessage()); return null; } if (dataOj != null) {//repair if z=0 int nCells = dataOj.getCells().getCellsCount(); int hits = 0; boolean repairFlag = false; for (int pass = 1; pass <= 2; pass++) { for (int jj = 0; jj < nCells; jj++) { CellOJ cell = dataOj.getCells().getCellByIndex(jj); int nYtems = cell.getYtemsCount(); for (int ytm = 0; ytm < nYtems; ytm++) { YtemOJ ytem = cell.getYtemByIndex(ytm); int slice = ytem.getStackIndex(); for (int ll = 0; ll < ytem.getLocationsCount(); ll++) { double z = ytem.getLocation(ll).z; if (z == 0.0) { hits++; if (repairFlag) { ytem.getLocation(ll).z = slice; } } } } } if (pass == 1 && hits > 0) { repairFlag = ij.IJ.showMessageWithCancel("", "Found coordinates z==0; Repair?\n (you should click \"OK\")"); } } } try { dataOj.getResults().getColumns().fixColumnsOrder();//2.2.2014 } catch (Exception e) { } return dataOj; } /** * * Special exception object for project IO doesn't do anything special */ public static class ProjectIOExceptionOJ extends Exception { public ProjectIOExceptionOJ(String message) { super(message); } } }
package org.batfish.common.topology; import static com.google.common.base.MoreObjects.firstNonNull; import static org.batfish.common.topology.TopologyUtil.computeNodeInterfaces; import static org.batfish.common.util.CollectionUtil.toImmutableMap; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.util.GlobalTracer; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Nonnull; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.batfish.datamodel.AclIpSpace; import org.batfish.datamodel.ConcreteInterfaceAddress; import org.batfish.datamodel.Configuration; import org.batfish.datamodel.EmptyIpSpace; import org.batfish.datamodel.Interface; import org.batfish.datamodel.Ip; import org.batfish.datamodel.IpSpace; import org.batfish.datamodel.IpWildcard; import org.batfish.datamodel.IpWildcardSetIpSpace; import org.batfish.datamodel.NetworkConfigurations; import org.batfish.datamodel.Prefix; import org.batfish.datamodel.collections.NodeInterfacePair; import org.batfish.datamodel.hsrp.HsrpGroup; import org.batfish.datamodel.tracking.HsrpPriorityEvaluator; import org.batfish.datamodel.tracking.StaticTrackMethodEvaluator; import org.batfish.datamodel.tracking.TrackMethod; /** A utility class for working with IPs owned by network devices. */ public final class IpOwners { private static final Logger LOGGER = LogManager.getLogger(IpOwners.class); /** * Mapping from a IP to hostname to set of interfaces that own that IP (including inactive * interfaces) */ private final Map<Ip, Map<String, Set<String>>> _allDeviceOwnedIps; /** * Mapping from a IP to hostname to set of interfaces that own that IP (for active interfaces * only) */ private final Map<Ip, Map<String, Set<String>>> _activeDeviceOwnedIps; /** Mapping from hostname to interface name to IpSpace owned by that interface */ private final Map<String, Map<String, IpSpace>> _hostToInterfaceToIpSpace; /** Mapping from hostname to VRF name to interface name to IpSpace owned by that interface */ private final Map<String, Map<String, Map<String, IpSpace>>> _hostToVrfToInterfaceToIpSpace; /** * Mapping from hostname to interface name to host IP subnet. * * @see Prefix#toHostIpSpace() */ private final Map<String, Map<String, IpSpace>> _allInterfaceHostIps; /** Mapping from an IP to hostname to set of VRFs that own that IP. */ private final Map<Ip, Map<String, Set<String>>> _ipVrfOwners; public IpOwners(Map<String, Configuration> configurations, L3Adjacencies l3Adjacencies) { /* Mapping from a hostname to a set of all (including inactive) interfaces that node owns */ Map<String, Set<Interface>> allInterfaces = ImmutableMap.copyOf(computeNodeInterfaces(configurations)); { _allDeviceOwnedIps = ImmutableMap.copyOf( computeIpInterfaceOwners( allInterfaces, false, l3Adjacencies, NetworkConfigurations.of(configurations))); _activeDeviceOwnedIps = ImmutableMap.copyOf( computeIpInterfaceOwners( allInterfaces, true, l3Adjacencies, NetworkConfigurations.of(configurations))); } { Map<Ip, Map<String, Map<String, Set<String>>>> ipIfaceOwners = computeIpIfaceOwners(allInterfaces, _activeDeviceOwnedIps); _ipVrfOwners = computeIpVrfOwners(ipIfaceOwners); _hostToVrfToInterfaceToIpSpace = computeIfaceOwnedIpSpaces(ipIfaceOwners); } { _hostToInterfaceToIpSpace = computeInterfaceOwnedIpSpaces(_hostToVrfToInterfaceToIpSpace); _allInterfaceHostIps = computeInterfaceHostSubnetIps(configurations, false); } } /** * Computes a map of hostname -&gt; interface name -&gt; {@link IpSpace} from a map of hostname * -&gt; vrf name -&gt; interface name -&gt; {@link IpSpace}. */ private static Map<String, Map<String, IpSpace>> computeInterfaceOwnedIpSpaces( Map<String, Map<String, Map<String, IpSpace>>> ipOwners) { return toImmutableMap( ipOwners, Entry::getKey, /* host */ hostEntry -> hostEntry.getValue().values().stream() /* Skip VRF keys */ .flatMap(ifaceMap -> ifaceMap.entrySet().stream()) .collect(ImmutableMap.toImmutableMap(Entry::getKey, Entry::getValue))); } @VisibleForTesting static Map<String, Map<String, IpSpace>> computeInterfaceHostSubnetIps( Map<String, Configuration> configs, boolean excludeInactive) { Span span = GlobalTracer.get().buildSpan("IpOwners.computeInterfaceHostSubnetIps").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning return toImmutableMap( configs, Entry::getKey, /* hostname */ nodeEntry -> toImmutableMap( excludeInactive ? nodeEntry.getValue().getActiveInterfaces() : nodeEntry.getValue().getAllInterfaces(), Entry::getKey, /* interface */ ifaceEntry -> firstNonNull( AclIpSpace.union( ifaceEntry.getValue().getAllConcreteAddresses().stream() .map(ConcreteInterfaceAddress::getPrefix) .map(Prefix::toHostIpSpace) .collect(ImmutableList.toImmutableList())), EmptyIpSpace.INSTANCE))); } finally { span.finish(); } } /** * Invert a mapping from {@link Ip} to owner interfaces (Ip -&gt; hostname -&gt; interface name) * to (hostname -&gt; interface name -&gt; Ip). */ public Map<String, Map<String, Set<Ip>>> getInterfaceOwners(boolean excludeInactive) { return computeInterfaceOwners(excludeInactive ? _activeDeviceOwnedIps : _allDeviceOwnedIps); } @VisibleForTesting static Map<String, Map<String, Set<Ip>>> computeInterfaceOwners( Map<Ip, Map<String, Set<String>>> deviceOwnedIps) { Map<String, Map<String, Set<Ip>>> ownedIps = new HashMap<>(); deviceOwnedIps.forEach( (ip, owners) -> owners.forEach( (host, ifaces) -> ifaces.forEach( iface -> ownedIps .computeIfAbsent(host, k -> new HashMap<>()) .computeIfAbsent(iface, k -> new HashSet<>()) .add(ip)))); // freeze return toImmutableMap( ownedIps, Entry::getKey, /* host */ hostEntry -> toImmutableMap( hostEntry.getValue(), Entry::getKey, /* interface */ ifaceEntry -> ImmutableSet.copyOf(ifaceEntry.getValue()))); } /** * Returns a mapping of IP addresses to a set of hostnames that "own" this IP (e.g., as a network * interface address) * * @param excludeInactive Whether to exclude inactive interfaces * @return A map of {@link Ip}s to a set of hostnames that own this IP */ public Map<Ip, Set<String>> getNodeOwners(boolean excludeInactive) { return computeNodeOwners(excludeInactive ? _activeDeviceOwnedIps : _allDeviceOwnedIps); } @VisibleForTesting static Map<Ip, Set<String>> computeNodeOwners(Map<Ip, Map<String, Set<String>>> deviceOwnedIps) { Span span = GlobalTracer.get().buildSpan("TopologyUtil.computeNodeOwners").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning return toImmutableMap( deviceOwnedIps, Entry::getKey, /* Ip */ ipInterfaceOwnersEntry -> /* project away interfaces */ ipInterfaceOwnersEntry.getValue().keySet()); } finally { span.finish(); } } /** * Compute a mapping from IP address to the interfaces that "own" that IP (e.g., as a network * interface address). * * <p>Takes into account VRRP configuration. * * @param allInterfaces A mapping of interfaces: hostname -&gt; set of {@link Interface} * @param excludeInactive whether to ignore inactive interfaces * @param l3Adjacencies L3Adjacencies (used to disambiguate VRRP ownership among multiple domains * that use the same virtual IP) * @return A map from {@link Ip}s to hostname to set of interface names that own that IP. */ @VisibleForTesting static Map<Ip, Map<String, Set<String>>> computeIpInterfaceOwners( Map<String, Set<Interface>> allInterfaces, boolean excludeInactive, L3Adjacencies l3Adjacencies, NetworkConfigurations nc) { Map<Ip, Map<String, Set<String>>> ipOwners = new HashMap<>(); // vrid -> sync interface -> interface to own IPs if sync interface wins election -> IPs Map<Integer, Map<NodeInterfacePair, Map<String, Set<Ip>>>> vrrpGroups = new HashMap<>(); // group -> interface -> IPs to own if interface wins election Map<Integer, Map<NodeInterfacePair, Set<Ip>>> hsrpGroups = new HashMap<>(); allInterfaces.forEach( (hostname, interfaces) -> interfaces.forEach( i -> { if (!i.getActive() && excludeInactive) { return; } extractVrrp(vrrpGroups, i); extractHsrp(hsrpGroups, i); // collect prefixes i.getAllConcreteAddresses().stream() .map(ConcreteInterfaceAddress::getIp) .forEach( ip -> ipOwners .computeIfAbsent(ip, k -> new HashMap<>()) .computeIfAbsent(hostname, k -> new HashSet<>()) .add(i.getName())); })); processVrrpGroups(ipOwners, vrrpGroups, l3Adjacencies, nc); processHsrpGroups(ipOwners, hsrpGroups, l3Adjacencies, nc); // freeze return toImmutableMap( ipOwners, Entry::getKey, ipOwnersEntry -> toImmutableMap( ipOwnersEntry.getValue(), Entry::getKey, // hostname hostIpOwnersEntry -> ImmutableSet.copyOf(hostIpOwnersEntry.getValue()))); } /** * Extract HSRP info from a given interface and add it to the {@code hsrpGroups}. * * @param hsrpGroups Output map: groupid -> interface -> IPs to own if interface wins election */ @VisibleForTesting static void extractHsrp(Map<Integer, Map<NodeInterfacePair, Set<Ip>>> hsrpGroups, Interface i) { // Inactive interfaces could never win a HSRP election if (!i.getActive()) { return; } // collect hsrp info i.getHsrpGroups() .forEach( (groupNum, hsrpGroup) -> { Set<Ip> ips = hsrpGroup.getVirtualAddresses(); /* * Invalid HSRP configuration. The HSRP group has no source IP address that * would be used for VRRP election. This interface could never win the * election, so is not a candidate. */ if (hsrpGroup.getSourceAddress() == null) { /* * Invalid VRRP configuration. The VRRP has no source IP address that * would be used for VRRP election. This interface could never win the * election, so is not a candidate. */ return; } if (ips.isEmpty()) { /* * Invalid HSRP configuration. The HSRP group has no virtual IP addresses set, so * should not participate in HSRP election. This interface could never win the * election, so is not a candidate. * * TODO: Technically according to * https://datatracker.ietf.org/doc/html/rfc2281#section-5.1 the virtual IP * (there is only one primary IP communicatd via an HSRP packet) may be * learned from the active router via a HELLO message, but we do not support * this mode of operation. */ return; } ips.forEach( ip -> { Map<NodeInterfacePair, Set<Ip>> candidates = hsrpGroups.get(groupNum); if (candidates == null) { candidates = new HashMap<>(); hsrpGroups.put(groupNum, candidates); } candidates.put(NodeInterfacePair.of(i), hsrpGroup.getVirtualAddresses()); }); }); } /** * Take {@code hsrpGroups} table, run master interface selection process, and add that * IP/interface pair to ip owners */ @VisibleForTesting static void processHsrpGroups( Map<Ip, Map<String, Set<String>>> ipOwners, Map<Integer, Map<NodeInterfacePair, Set<Ip>>> hsrpGroups, L3Adjacencies l3Adjacencies, NetworkConfigurations nc) { hsrpGroups.forEach( (groupNum, ipSpaceByCandidate) -> { assert groupNum != null; Set<NodeInterfacePair> candidates = ipSpaceByCandidate.keySet(); List<List<NodeInterfacePair>> candidatePartitions = partitionCandidates(candidates, l3Adjacencies); candidatePartitions.forEach( cp -> { List<Interface> partitionInterfaces = cp.stream() .map(nip -> nc.getInterface(nip.getHostname(), nip.getInterface()).get()) .collect(ImmutableList.toImmutableList()); if (partitionInterfaces.size() != 2) { LOGGER.warn( "HSRP group {} election is not among 2 devices, which is rare: {}", groupNum, partitionInterfaces); } /* * Compare priorities first, then highest interface IP, then hostname, then interface name. */ NodeInterfacePair hsrpMaster = NodeInterfacePair.of( Collections.max( partitionInterfaces, Comparator.comparingInt( (Interface o) -> o.getHsrpGroups().get(groupNum).getPriority()) .thenComparing(o -> o.getConcreteAddress().getIp()) .thenComparing(o -> NodeInterfacePair.of(o)))); LOGGER.debug( "{} elected HSRP master for groupNum {} among candidates {}", hsrpMaster, groupNum, partitionInterfaces); ipSpaceByCandidate .get(hsrpMaster) .forEach( ip -> ipOwners .computeIfAbsent(ip, k -> new HashMap<>()) .computeIfAbsent(hsrpMaster.getHostname(), k -> new HashSet<>()) .add(hsrpMaster.getInterface())); }); }); } /** Compute HSRP priority for a given HSRP group and the interface it is associated with. */ static int computeHsrpPriority(@Nonnull Interface iface, @Nonnull HsrpGroup group) { Configuration c = iface.getOwner(); Map<String, TrackMethod> trackMethods = c.getTrackingGroups(); StaticTrackMethodEvaluator trackMethodEvaluator = new StaticTrackMethodEvaluator(c); HsrpPriorityEvaluator hsrpEvaluator = new HsrpPriorityEvaluator(group.getPriority()); group .getTrackActions() .forEach( (trackName, action) -> { TrackMethod trackMethod = trackMethods.get(trackName); if (trackMethod != null && (trackMethod.accept(trackMethodEvaluator))) { action.accept(hsrpEvaluator); } }); return hsrpEvaluator.getPriority(); } /** * Extract VRRP info from a given interface and add it to the {@code vrrpGroups}. * * @param vrrpGroups Output map: vrid -> sync interface -> interface to own IPs if sync interface * wins election -> IPs */ @VisibleForTesting static void extractVrrp( Map<Integer, Map<NodeInterfacePair, Map<String, Set<Ip>>>> vrrpGroups, Interface i) { // Inactive interfaces could never win a VRRP election if (!i.getActive()) { return; } i.getVrrpGroups() .forEach( (vrid, vrrpGroup) -> { if (vrrpGroup.getSourceAddress() == null) { /* * Invalid VRRP configuration. The VRRP has no source IP address that * would be used for VRRP election. This interface could never win the * election, so is not a candidate. */ return; } if (vrrpGroup.getVirtualAddresses().isEmpty()) { /* * Invalid VRRP configuration. The VRRP group has no virtual IP addresses set, so * should not participate in VRRP election. This interface could never win the * election, so is not a candidate. */ return; } // sync interface -> interface to receive IPs -> IPs Map<NodeInterfacePair, Map<String, Set<Ip>>> candidates = vrrpGroups.get(vrid); if (candidates == null) { candidates = new HashMap<>(); vrrpGroups.put(vrid, candidates); } candidates.put(NodeInterfacePair.of(i), vrrpGroup.getVirtualAddresses()); }); } /** * Take {@code vrrpGroups} table, run master interface selection process, and add that * IP/interface pair to ip owners */ static void processVrrpGroups( Map<Ip, Map<String, Set<String>>> ipOwners, Map<Integer, Map<NodeInterfacePair, Map<String, Set<Ip>>>> vrrpGroups, L3Adjacencies l3Adjacencies, NetworkConfigurations nc) { vrrpGroups.forEach( (vrid, ipSpaceByCandidate) -> { assert vrid != null; Set<NodeInterfacePair> candidates = ipSpaceByCandidate.keySet(); List<List<NodeInterfacePair>> candidatePartitions = partitionCandidates(candidates, l3Adjacencies); candidatePartitions.forEach( cp -> { List<Interface> partitionInterfaces = cp.stream() .map(nip -> nc.getInterface(nip.getHostname(), nip.getInterface()).get()) .collect(ImmutableList.toImmutableList()); if (partitionInterfaces.size() != 2) { LOGGER.warn( "VRRP vrid {} election is not among 2 devices, which is rare: {}", vrid, partitionInterfaces); } /* * Compare priorities first, then highest interface IP, then hostname, then interface name. */ NodeInterfacePair vrrpMaster = NodeInterfacePair.of( Collections.max( partitionInterfaces, Comparator.comparingInt( (Interface o) -> o.getVrrpGroups().get(vrid).getPriority()) .thenComparing(o -> o.getConcreteAddress().getIp()) .thenComparing(o -> NodeInterfacePair.of(o)))); LOGGER.debug( "{} elected VRRP master for vrid {} among candidates {}", vrrpMaster, vrid, partitionInterfaces); ipSpaceByCandidate .get(vrrpMaster) .forEach( (receivingInterface, ips) -> ips.forEach( ip -> ipOwners .computeIfAbsent(ip, k -> new HashMap<>()) .computeIfAbsent( vrrpMaster.getHostname(), k -> new HashSet<>()) .add(receivingInterface))); }); }); } /** * Partitions the input set of HSRP/VRRP candidates into subsets where all candidates are in the * same broadcast domain. This disambiguates VRRP groups that have the same IP and group ID */ @VisibleForTesting static List<List<NodeInterfacePair>> partitionCandidates( Set<NodeInterfacePair> candidates, L3Adjacencies l3Adjacencies) { Map<NodeInterfacePair, List<NodeInterfacePair>> partitions = new HashMap<>(); for (NodeInterfacePair cni : candidates) { boolean foundRepresentative = false; for (NodeInterfacePair representative : partitions.keySet()) { if (l3Adjacencies.inSameBroadcastDomain(representative, cni)) { partitions.get(representative).add(cni); foundRepresentative = true; break; } } if (!foundRepresentative) { partitions.put(cni, new LinkedList<>()); partitions.get(cni).add(cni); } } return ImmutableList.copyOf(partitions.values()); } /** * Compute a mapping of IP addresses to the VRFs that "own" this IP (e.g., as a network interface * address). * * @param ipVrfIfaceOwners A mapping of IP owners hostname -&gt; vrf name -&gt; interface names * @return A map of {@link Ip}s to a map of hostnames to vrfs that own the Ip. */ @VisibleForTesting static Map<Ip, Map<String, Set<String>>> computeIpVrfOwners( Map<Ip, Map<String, Map<String, Set<String>>>> ipVrfIfaceOwners) { return toImmutableMap( ipVrfIfaceOwners, Entry::getKey, /* Ip */ ipEntry -> toImmutableMap( ipEntry.getValue(), Entry::getKey, /* Hostname */ nodeEntry -> ImmutableSet.copyOf(nodeEntry.getValue().keySet()))); /* VRFs */ } /** * Compute a mapping of IP addresses to the VRFs and interfaces that "own" this IP (e.g., as a * network interface address). * * @param allInterfaces A mapping of enabled interfaces hostname -&gt; set of {@link Interface} * @param activeDeviceOwnedIps Mapping from a IP to hostname to set of interfaces that own that IP * (for active interfaces only) * @return A map of {@link Ip}s to a map of hostnames to vrfs to interfaces that own the Ip. */ @VisibleForTesting static Map<Ip, Map<String, Map<String, Set<String>>>> computeIpIfaceOwners( Map<String, Set<Interface>> allInterfaces, Map<Ip, Map<String, Set<String>>> activeDeviceOwnedIps) { // Helper mapping: hostname -> vrf -> interfaces Map<String, Map<String, Set<String>>> hostsToVrfsToIfaces = new HashMap<>(); allInterfaces.forEach( (hostname, ifaces) -> ifaces.forEach( iface -> { hostsToVrfsToIfaces .computeIfAbsent(hostname, n -> new HashMap<>()) .computeIfAbsent(iface.getVrfName(), n -> new HashSet<>()) .add(iface.getName()); })); return toImmutableMap( activeDeviceOwnedIps, Entry::getKey, /* Ip */ ipEntry -> toImmutableMap( ipEntry.getValue(), Entry::getKey, /* hostname */ nodeEntry -> { String hostname = nodeEntry.getKey(); Set<String> ownerIfaces = nodeEntry.getValue(); return hostsToVrfsToIfaces.get(hostname).entrySet().stream() // Filter to VRFs containing interfaces that own this IP .filter(vrfEntry -> !Collections.disjoint(vrfEntry.getValue(), ownerIfaces)) .collect( // Map each VRF to its set of interfaces that own this IP ImmutableMap.toImmutableMap( Entry::getKey, vrfEntry -> Sets.intersection(vrfEntry.getValue(), ownerIfaces))); })); } /** * Invert a mapping from Ip to interface owners (Ip -&gt; host name -&gt; VRF name -&gt; interface * names) and combine all IPs owned by each interface into an IpSpace. */ private static Map<String, Map<String, Map<String, IpSpace>>> computeIfaceOwnedIpSpaces( Map<Ip, Map<String, Map<String, Set<String>>>> ipIfaceOwners) { Map<String, Map<String, Map<String, IpWildcardSetIpSpace.Builder>>> builders = new HashMap<>(); ipIfaceOwners.forEach( (ip, nodeMap) -> nodeMap.forEach( (node, vrfMap) -> vrfMap.forEach( (vrf, ifaces) -> ifaces.forEach( iface -> builders .computeIfAbsent(node, k -> new HashMap<>()) .computeIfAbsent(vrf, k -> new HashMap<>()) .computeIfAbsent(iface, k -> IpWildcardSetIpSpace.builder()) .including(IpWildcard.create(ip)))))); return toImmutableMap( builders, Entry::getKey, /* node */ nodeEntry -> toImmutableMap( nodeEntry.getValue(), Entry::getKey, /* vrf */ vrfEntry -> toImmutableMap( vrfEntry.getValue(), Entry::getKey, /* interface */ ifaceEntry -> ifaceEntry.getValue().build()))); } /** * Mapping from a IP to hostname to set of interfaces that own that IP (for active interfaces * only) */ public Map<Ip, Map<String, Set<String>>> getActiveDeviceOwnedIps() { return _activeDeviceOwnedIps; } /** * Mapping from a IP to hostname to set of interfaces that own that IP (including inactive * interfaces) */ public Map<Ip, Map<String, Set<String>>> getAllDeviceOwnedIps() { return _allDeviceOwnedIps; } /** * Returns a mapping from hostname to interface name to the host {@link IpSpace} of that * interface, including inactive interfaces. * * @see Prefix#toHostIpSpace() */ public Map<String, Map<String, IpSpace>> getAllInterfaceHostIps() { return _allInterfaceHostIps; } /** * Returns a mapping from hostname to interface name to IpSpace owned by that interface, for * active interfaces only */ public Map<String, Map<String, IpSpace>> getInterfaceOwnedIpSpaces() { return _hostToInterfaceToIpSpace; } /** Returns a mapping from IP to hostname to set of VRFs that own that IP. */ public Map<Ip, Map<String, Set<String>>> getIpVrfOwners() { return _ipVrfOwners; } /** * Returns a mapping from hostname to vrf name to interface name to a space of IPs owned by that * interface. Only considers interface IPs. Considers <em>only active</em> interfaces. */ public Map<String, Map<String, Map<String, IpSpace>>> getVrfIfaceOwnedIpSpaces() { return _hostToVrfToInterfaceToIpSpace; } }
/******************************************************************************* * Copyright (c) 2015-2016, WSO2.Telco Inc. (http://www.wso2telco.com) All Rights Reserved. * * WSO2.Telco Inc. licences 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.wso2telco.dep.reportingservice.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.usage.client.exception.APIMgtUsageQueryServiceClientException; import com.wso2telco.core.dbutils.DbUtils; import com.wso2telco.core.dbutils.util.DataSourceNames; import com.wso2telco.dep.reportingservice.APIRequestDTO; import com.wso2telco.dep.reportingservice.HostObjectConstants; import com.wso2telco.dep.reportingservice.Tax; import com.wso2telco.dep.reportingservice.util.ReportingTable; /** * The Class TaxDataAccessObject. */ public class TaxDAO { /** The Constant log. */ private static final Log log = LogFactory.getLog(TaxDAO.class); /** * Gets the taxes for subscription. * * @param applicationId the application id * @param apiId the api id * @return the taxes for subscription * @throws Exception the exception */ public List<Tax> getTaxesForSubscription(int applicationId, int apiId) throws Exception { Connection connection = null; PreparedStatement ps = null; ResultSet results = null; String sql = "SELECT type,effective_from,effective_to,value FROM "+ ReportingTable.TAX +", "+ ReportingTable.SUBSCRIPTION_TAX + "WHERE subscription_tax.application_id=? AND subscription_tax.api_id=? AND tax.type=subscription_tax.tax_type "; List<Tax> taxes = new ArrayList<Tax>(); try { connection = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB); ps = connection.prepareStatement(sql); log.debug("getTaxesForSubscription for applicationId---> " + applicationId + " apiId--> " + apiId); ps.setInt(1, applicationId); ps.setInt(2, apiId); log.debug("SQL (PS) ---> " + ps.toString()); results = ps.executeQuery(); while (results.next()) { Tax tax = new Tax(); tax.setType(results.getString("type")); tax.setEffective_from(results.getDate("effective_from")); tax.setEffective_to(results.getDate("effective_to")); tax.setValue(results.getBigDecimal("value")); taxes.add(tax); } } catch (SQLException e) { log.error("SQL Error in getTaxesForSubscription"); log.error(e.getStackTrace()); handleException("Error occurred while getting Taxes for Subscription", e); } finally { DbUtils.closeAllConnections(ps, connection, results); } return taxes; } /** * Gets the taxes for tax list. * * @param taxList the tax list * @return the taxes for tax list * @throws Exception the exception */ public List<Tax> getTaxesForTaxList(List<String> taxList) throws Exception { Connection connection = null; Statement st = null; ResultSet results = null; List<Tax> taxes = new ArrayList<Tax>(); if (taxList == null || taxList.isEmpty()) { return taxes; } // CSV format surrounded by single quote String taxListStr = taxList.toString().replace("[", "'").replace("]", "'").replace(", ", "','"); String sql = "SELECT type,effective_from,effective_to,value FROM "+ ReportingTable.TAX +" WHERE type IN (" + taxListStr + ")"; try { connection = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB); st = connection.createStatement(); log.debug("In getTaxesForTaxList"); log.debug("SQL (PS) ---> " + st.toString()); results = st.executeQuery(sql); while (results.next()) { Tax tax = new Tax(); tax.setType(results.getString("type")); tax.setEffective_from(results.getDate("effective_from")); tax.setEffective_to(results.getDate("effective_to")); tax.setValue(results.getBigDecimal("value")); taxes.add(tax); } st.close(); } catch (SQLException e) { log.error("SQL Error in getTaxesForTaxList"); log.error(e.getStackTrace()); handleException("Error occurred while getting Taxes for Tax List", e); } finally { DbUtils.closeAllConnections(null, connection, results); } return taxes; } /** * Gets the API request times for subscription. * * @param year the year * @param month the month * @param apiName the api name * @param apiVersion the api version * @param consumerKey the consumer key * @param operatorId the operator id * @param operation the operation * @param category the category * @param subcategory the subcategory * @return the API request times for subscription * @throws Exception the exception */ public Set<APIRequestDTO> getAPIRequestTimesForSubscription(short year, short month, String apiName, String apiVersion, String consumerKey, String operatorId, int operation, String category, String subcategory) throws Exception { Connection connection = null; PreparedStatement ps = null; ResultSet results = null; String sql = "SELECT api_version,response_count AS count,STR_TO_DATE(time,'%Y-%m-%d') as date FROM " + HostObjectConstants.SB_RESPONSE_SUMMARY_TABLE + " WHERE consumerKey=? and api=? and api_version=? and operatorId=? and responseCode like '20_' and month=? and year=? and operationType=? and category =? and subcategory=? "; Set<APIRequestDTO> apiRequests = new HashSet<APIRequestDTO>(); try { connection = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB); ps = connection.prepareStatement(sql); ps.setString(1, consumerKey); ps.setString(2, apiName); ps.setString(3, apiVersion); ps.setString(4, operatorId); ps.setShort(5, month); ps.setShort(6, year); ps.setInt(7, operation); ps.setString(8, category); ps.setString(9, subcategory); log.debug("SQL (PS) st ---> " + ps.toString()); results = ps.executeQuery(); log.debug("SQL (PS) ed ---> "); while (results.next()) { APIRequestDTO req = new APIRequestDTO(); req.setApiVersion(results.getString("api_version")); req.setRequestCount(results.getInt("count")); req.setDate(results.getDate("date")); apiRequests.add(req); } } catch (SQLException e) { handleException("Error occurred while getting Request Times for Subscription", e); } finally { DbUtils.closeAllConnections(ps, connection, results); } log.debug("done getAPIRequestTimesForSubscription"); return apiRequests; } /** * Gets the nb api request times for subscription. * * @param year the year * @param month the month * @param apiName the api name * @param apiVersion the api version * @param consumerKey the consumer key * @param operation the operation * @param category the category * @param subcategory the subcategory * @return the nb api request times for subscription * @throws Exception the exception */ public Set<APIRequestDTO> getNbAPIRequestTimesForSubscription(short year, short month, String apiName, String apiVersion, String consumerKey, int operation, String category, String subcategory) throws Exception { Connection connection = null; PreparedStatement ps = null; ResultSet results = null; String sql = "SELECT api_version,response_count AS count,STR_TO_DATE(time,'%Y-%m-%d') as date FROM " + ReportingTable.NB_API_RESPONSE_SUMMARY + " WHERE year=? and month=? and consumerKey=? and " + "api=? and api_version=? and operationType=? and category =? and subcategory=? and responseCode like '2%'"; Set<APIRequestDTO> apiRequests = new HashSet<APIRequestDTO>(); try { connection = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB); ps = connection.prepareStatement(sql); ps.setShort(1, year); ps.setShort(2, month); ps.setString(3, consumerKey); ps.setString(4, apiName); ps.setString(5, apiVersion); ps.setInt(6, operation); ps.setString(7, category); ps.setString(8, subcategory); results = ps.executeQuery(); while (results.next()) { APIRequestDTO req = new APIRequestDTO(); req.setApiVersion(results.getString("api_version")); req.setRequestCount(results.getInt("count")); req.setDate(results.getDate("date")); apiRequests.add(req); } } catch (SQLException e) { handleException("Error occurred while getting Request Times for Subscription", e); } finally { DbUtils.closeAllConnections(ps, connection, results); } return apiRequests; } /** * Gets the API request times for application. * * @param consumerKey the consumer key * @param year the year * @param month the month * @param userId the user id * @return the API request times for application * @throws Exception the exception */ public Map<String, List<APIRequestDTO>> getAPIRequestTimesForApplication(String consumerKey, short year, short month, String userId) throws Exception { Connection connection = null; PreparedStatement ps = null; ResultSet results = null; String sql = "SELECT api_version,total_request_count AS count,STR_TO_DATE(time,'%Y-%m-%d') as date FROM "+ ReportingTable.API_REQUEST_SUMMARY + "WHERE consumerKey=? AND userId=? AND month=? AND year=?;"; Map<String, List<APIRequestDTO>> apiRequests = new HashMap<String, List<APIRequestDTO>>(); try { connection = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB); ps = connection.prepareStatement(sql); ps.setString(1, consumerKey); ps.setString(2, userId); ps.setShort(3, month); ps.setShort(4, year); log.debug("SQL (PS) st ---> " + ps.toString()); results = ps.executeQuery(); log.debug("SQL (PS) ed ---> "); while (results.next()) { APIRequestDTO req = new APIRequestDTO(); req.setApiVersion(results.getString("api_version")); req.setRequestCount(results.getInt("count")); req.setDate(results.getDate("date")); if (apiRequests.containsKey(req.getApiVersion())) { apiRequests.get(req.getApiVersion()).add(req); } else { List<APIRequestDTO> list = new ArrayList<APIRequestDTO>(); list.add(req); apiRequests.put(req.getApiVersion(), list); } } } catch (SQLException e) { handleException("Error occurred while getting Request Times for Application", e); } finally { DbUtils.closeAllConnections(ps, connection, results); } return apiRequests; } /** * Handle exception. * * @param msg the msg * @param t the t * @throws APIManagementException the API management exception */ private static void handleException(String msg, Throwable t) throws APIManagementException { log.error(msg, t); throw new APIManagementException(msg, t); } /** * The main method. * * @param args the arguments * @throws Exception the exception */ public static void main(String[] args) throws Exception { TaxDAO taxDAO = new TaxDAO(); try { List<Tax> taxList = taxDAO.getTaxesForSubscription(00,25); for (int i = 0; i < taxList.size(); i++) { Tax tax = taxList.get(i); System.out.println(tax.getType() + " ~ " + tax.getEffective_from() + " ~ " + tax.getEffective_to() + " ~ " + tax.getValue()); } Map<String, List<APIRequestDTO>> reqMap = taxDAO.getAPIRequestTimesForApplication("yx1eZTmtbBaYqfIuEYMVgIKonSga", (short)2014, (short)1, "admin"); System.out.println(reqMap); } catch (APIManagementException e) { e.printStackTrace(); } catch (APIMgtUsageQueryServiceClientException e) { e.printStackTrace(); } } }
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.vulkan; import javax.annotation.*; import java.nio.*; import org.lwjgl.*; import org.lwjgl.system.*; import static org.lwjgl.system.Checks.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.MemoryStack.*; import org.lwjgl.system.windows.*; /** * Import Win32 memory created on the same physical device. * * <h5>Description</h5> * * <p>If {@code handleType} is 0, this structure is ignored by consumers of the {@link VkMemoryAllocateInfo} structure it is chained from.</p> * * <h5>Valid Usage</h5> * * <ul> * <li>{@code handleType} <b>must</b> not have more than one bit set</li> * <li>{@code handle} <b>must</b> be a valid handle to memory, obtained as specified by {@code handleType}</li> * </ul> * * <h5>Valid Usage (Implicit)</h5> * * <ul> * <li>{@code sType} <b>must</b> be {@link NVExternalMemoryWin32#VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_NV STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_NV}</li> * <li>{@code handleType} <b>must</b> be a valid combination of {@code VkExternalMemoryHandleTypeFlagBitsNV} values</li> * </ul> * * <h3>Layout</h3> * * <pre><code> * struct VkImportMemoryWin32HandleInfoNV { * VkStructureType {@link #sType}; * void const * {@link #pNext}; * VkExternalMemoryHandleTypeFlagsNV {@link #handleType}; * HANDLE {@link #handle}; * }</code></pre> */ public class VkImportMemoryWin32HandleInfoNV extends Struct implements NativeResource { /** The struct size in bytes. */ public static final int SIZEOF; /** The struct alignment in bytes. */ public static final int ALIGNOF; /** The struct member offsets. */ public static final int STYPE, PNEXT, HANDLETYPE, HANDLE; static { Layout layout = __struct( __member(4), __member(POINTER_SIZE), __member(4), __member(POINTER_SIZE) ); SIZEOF = layout.getSize(); ALIGNOF = layout.getAlignment(); STYPE = layout.offsetof(0); PNEXT = layout.offsetof(1); HANDLETYPE = layout.offsetof(2); HANDLE = layout.offsetof(3); } /** * Creates a {@code VkImportMemoryWin32HandleInfoNV} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be * visible to the struct instance and vice versa. * * <p>The created instance holds a strong reference to the container object.</p> */ public VkImportMemoryWin32HandleInfoNV(ByteBuffer container) { super(memAddress(container), __checkContainer(container, SIZEOF)); } @Override public int sizeof() { return SIZEOF; } /** the type of this structure. */ @NativeType("VkStructureType") public int sType() { return nsType(address()); } /** {@code NULL} or a pointer to a structure extending this structure. */ @NativeType("void const *") public long pNext() { return npNext(address()); } /** 0 or a {@code VkExternalMemoryHandleTypeFlagBitsNV} value specifying the type of memory handle in {@code handle}. */ @NativeType("VkExternalMemoryHandleTypeFlagsNV") public int handleType() { return nhandleType(address()); } /** a Windows {@code HANDLE} referring to the memory. */ @NativeType("HANDLE") public long handle() { return nhandle(address()); } /** Sets the specified value to the {@link #sType} field. */ public VkImportMemoryWin32HandleInfoNV sType(@NativeType("VkStructureType") int value) { nsType(address(), value); return this; } /** Sets the {@link NVExternalMemoryWin32#VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_NV STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_NV} value to the {@link #sType} field. */ public VkImportMemoryWin32HandleInfoNV sType$Default() { return sType(NVExternalMemoryWin32.VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_NV); } /** Sets the specified value to the {@link #pNext} field. */ public VkImportMemoryWin32HandleInfoNV pNext(@NativeType("void const *") long value) { npNext(address(), value); return this; } /** Sets the specified value to the {@link #handleType} field. */ public VkImportMemoryWin32HandleInfoNV handleType(@NativeType("VkExternalMemoryHandleTypeFlagsNV") int value) { nhandleType(address(), value); return this; } /** Sets the specified value to the {@link #handle} field. */ public VkImportMemoryWin32HandleInfoNV handle(@NativeType("HANDLE") long value) { nhandle(address(), value); return this; } /** Initializes this struct with the specified values. */ public VkImportMemoryWin32HandleInfoNV set( int sType, long pNext, int handleType, long handle ) { sType(sType); pNext(pNext); handleType(handleType); handle(handle); return this; } /** * Copies the specified struct data to this struct. * * @param src the source struct * * @return this struct */ public VkImportMemoryWin32HandleInfoNV set(VkImportMemoryWin32HandleInfoNV src) { memCopy(src.address(), address(), SIZEOF); return this; } // ----------------------------------- /** Returns a new {@code VkImportMemoryWin32HandleInfoNV} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */ public static VkImportMemoryWin32HandleInfoNV malloc() { return wrap(VkImportMemoryWin32HandleInfoNV.class, nmemAllocChecked(SIZEOF)); } /** Returns a new {@code VkImportMemoryWin32HandleInfoNV} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */ public static VkImportMemoryWin32HandleInfoNV calloc() { return wrap(VkImportMemoryWin32HandleInfoNV.class, nmemCallocChecked(1, SIZEOF)); } /** Returns a new {@code VkImportMemoryWin32HandleInfoNV} instance allocated with {@link BufferUtils}. */ public static VkImportMemoryWin32HandleInfoNV create() { ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF); return wrap(VkImportMemoryWin32HandleInfoNV.class, memAddress(container), container); } /** Returns a new {@code VkImportMemoryWin32HandleInfoNV} instance for the specified memory address. */ public static VkImportMemoryWin32HandleInfoNV create(long address) { return wrap(VkImportMemoryWin32HandleInfoNV.class, address); } /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static VkImportMemoryWin32HandleInfoNV createSafe(long address) { return address == NULL ? null : wrap(VkImportMemoryWin32HandleInfoNV.class, address); } /** * Returns a new {@link VkImportMemoryWin32HandleInfoNV.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static VkImportMemoryWin32HandleInfoNV.Buffer malloc(int capacity) { return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity); } /** * Returns a new {@link VkImportMemoryWin32HandleInfoNV.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static VkImportMemoryWin32HandleInfoNV.Buffer calloc(int capacity) { return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity); } /** * Returns a new {@link VkImportMemoryWin32HandleInfoNV.Buffer} instance allocated with {@link BufferUtils}. * * @param capacity the buffer capacity */ public static VkImportMemoryWin32HandleInfoNV.Buffer create(int capacity) { ByteBuffer container = __create(capacity, SIZEOF); return wrap(Buffer.class, memAddress(container), capacity, container); } /** * Create a {@link VkImportMemoryWin32HandleInfoNV.Buffer} instance at the specified memory. * * @param address the memory address * @param capacity the buffer capacity */ public static VkImportMemoryWin32HandleInfoNV.Buffer create(long address, int capacity) { return wrap(Buffer.class, address, capacity); } /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static VkImportMemoryWin32HandleInfoNV.Buffer createSafe(long address, int capacity) { return address == NULL ? null : wrap(Buffer.class, address, capacity); } // ----------------------------------- /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */ @Deprecated public static VkImportMemoryWin32HandleInfoNV mallocStack() { return malloc(stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */ @Deprecated public static VkImportMemoryWin32HandleInfoNV callocStack() { return calloc(stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */ @Deprecated public static VkImportMemoryWin32HandleInfoNV mallocStack(MemoryStack stack) { return malloc(stack); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */ @Deprecated public static VkImportMemoryWin32HandleInfoNV callocStack(MemoryStack stack) { return calloc(stack); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */ @Deprecated public static VkImportMemoryWin32HandleInfoNV.Buffer mallocStack(int capacity) { return malloc(capacity, stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */ @Deprecated public static VkImportMemoryWin32HandleInfoNV.Buffer callocStack(int capacity) { return calloc(capacity, stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */ @Deprecated public static VkImportMemoryWin32HandleInfoNV.Buffer mallocStack(int capacity, MemoryStack stack) { return malloc(capacity, stack); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */ @Deprecated public static VkImportMemoryWin32HandleInfoNV.Buffer callocStack(int capacity, MemoryStack stack) { return calloc(capacity, stack); } /** * Returns a new {@code VkImportMemoryWin32HandleInfoNV} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate */ public static VkImportMemoryWin32HandleInfoNV malloc(MemoryStack stack) { return wrap(VkImportMemoryWin32HandleInfoNV.class, stack.nmalloc(ALIGNOF, SIZEOF)); } /** * Returns a new {@code VkImportMemoryWin32HandleInfoNV} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate */ public static VkImportMemoryWin32HandleInfoNV calloc(MemoryStack stack) { return wrap(VkImportMemoryWin32HandleInfoNV.class, stack.ncalloc(ALIGNOF, 1, SIZEOF)); } /** * Returns a new {@link VkImportMemoryWin32HandleInfoNV.Buffer} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static VkImportMemoryWin32HandleInfoNV.Buffer malloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity); } /** * Returns a new {@link VkImportMemoryWin32HandleInfoNV.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static VkImportMemoryWin32HandleInfoNV.Buffer calloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity); } // ----------------------------------- /** Unsafe version of {@link #sType}. */ public static int nsType(long struct) { return UNSAFE.getInt(null, struct + VkImportMemoryWin32HandleInfoNV.STYPE); } /** Unsafe version of {@link #pNext}. */ public static long npNext(long struct) { return memGetAddress(struct + VkImportMemoryWin32HandleInfoNV.PNEXT); } /** Unsafe version of {@link #handleType}. */ public static int nhandleType(long struct) { return UNSAFE.getInt(null, struct + VkImportMemoryWin32HandleInfoNV.HANDLETYPE); } /** Unsafe version of {@link #handle}. */ public static long nhandle(long struct) { return memGetAddress(struct + VkImportMemoryWin32HandleInfoNV.HANDLE); } /** Unsafe version of {@link #sType(int) sType}. */ public static void nsType(long struct, int value) { UNSAFE.putInt(null, struct + VkImportMemoryWin32HandleInfoNV.STYPE, value); } /** Unsafe version of {@link #pNext(long) pNext}. */ public static void npNext(long struct, long value) { memPutAddress(struct + VkImportMemoryWin32HandleInfoNV.PNEXT, value); } /** Unsafe version of {@link #handleType(int) handleType}. */ public static void nhandleType(long struct, int value) { UNSAFE.putInt(null, struct + VkImportMemoryWin32HandleInfoNV.HANDLETYPE, value); } /** Unsafe version of {@link #handle(long) handle}. */ public static void nhandle(long struct, long value) { memPutAddress(struct + VkImportMemoryWin32HandleInfoNV.HANDLE, check(value)); } /** * Validates pointer members that should not be {@code NULL}. * * @param struct the struct to validate */ public static void validate(long struct) { check(memGetAddress(struct + VkImportMemoryWin32HandleInfoNV.HANDLE)); } // ----------------------------------- /** An array of {@link VkImportMemoryWin32HandleInfoNV} structs. */ public static class Buffer extends StructBuffer<VkImportMemoryWin32HandleInfoNV, Buffer> implements NativeResource { private static final VkImportMemoryWin32HandleInfoNV ELEMENT_FACTORY = VkImportMemoryWin32HandleInfoNV.create(-1L); /** * Creates a new {@code VkImportMemoryWin32HandleInfoNV.Buffer} instance backed by the specified container. * * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided * by {@link VkImportMemoryWin32HandleInfoNV#SIZEOF}, and its mark will be undefined. * * <p>The created buffer instance holds a strong reference to the container object.</p> */ public Buffer(ByteBuffer container) { super(container, container.remaining() / SIZEOF); } public Buffer(long address, int cap) { super(address, null, -1, 0, cap, cap); } Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) { super(address, container, mark, pos, lim, cap); } @Override protected Buffer self() { return this; } @Override protected VkImportMemoryWin32HandleInfoNV getElementFactory() { return ELEMENT_FACTORY; } /** @return the value of the {@link VkImportMemoryWin32HandleInfoNV#sType} field. */ @NativeType("VkStructureType") public int sType() { return VkImportMemoryWin32HandleInfoNV.nsType(address()); } /** @return the value of the {@link VkImportMemoryWin32HandleInfoNV#pNext} field. */ @NativeType("void const *") public long pNext() { return VkImportMemoryWin32HandleInfoNV.npNext(address()); } /** @return the value of the {@link VkImportMemoryWin32HandleInfoNV#handleType} field. */ @NativeType("VkExternalMemoryHandleTypeFlagsNV") public int handleType() { return VkImportMemoryWin32HandleInfoNV.nhandleType(address()); } /** @return the value of the {@link VkImportMemoryWin32HandleInfoNV#handle} field. */ @NativeType("HANDLE") public long handle() { return VkImportMemoryWin32HandleInfoNV.nhandle(address()); } /** Sets the specified value to the {@link VkImportMemoryWin32HandleInfoNV#sType} field. */ public VkImportMemoryWin32HandleInfoNV.Buffer sType(@NativeType("VkStructureType") int value) { VkImportMemoryWin32HandleInfoNV.nsType(address(), value); return this; } /** Sets the {@link NVExternalMemoryWin32#VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_NV STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_NV} value to the {@link VkImportMemoryWin32HandleInfoNV#sType} field. */ public VkImportMemoryWin32HandleInfoNV.Buffer sType$Default() { return sType(NVExternalMemoryWin32.VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_NV); } /** Sets the specified value to the {@link VkImportMemoryWin32HandleInfoNV#pNext} field. */ public VkImportMemoryWin32HandleInfoNV.Buffer pNext(@NativeType("void const *") long value) { VkImportMemoryWin32HandleInfoNV.npNext(address(), value); return this; } /** Sets the specified value to the {@link VkImportMemoryWin32HandleInfoNV#handleType} field. */ public VkImportMemoryWin32HandleInfoNV.Buffer handleType(@NativeType("VkExternalMemoryHandleTypeFlagsNV") int value) { VkImportMemoryWin32HandleInfoNV.nhandleType(address(), value); return this; } /** Sets the specified value to the {@link VkImportMemoryWin32HandleInfoNV#handle} field. */ public VkImportMemoryWin32HandleInfoNV.Buffer handle(@NativeType("HANDLE") long value) { VkImportMemoryWin32HandleInfoNV.nhandle(address(), value); return 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 brooklyn.entity.nosql.cassandra; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import brooklyn.enricher.Enrichers; import brooklyn.entity.Entity; import brooklyn.entity.basic.Attributes; import brooklyn.entity.basic.DynamicGroup; import brooklyn.entity.basic.Entities; import brooklyn.entity.basic.EntityPredicates; import brooklyn.entity.basic.Lifecycle; import brooklyn.entity.effector.EffectorBody; import brooklyn.entity.group.AbstractMembershipTrackingPolicy; import brooklyn.entity.group.DynamicClusterImpl; import brooklyn.entity.proxying.EntitySpec; import brooklyn.event.AttributeSensor; import brooklyn.event.SensorEvent; import brooklyn.event.SensorEventListener; import brooklyn.location.Location; import brooklyn.location.basic.Machines; import brooklyn.policy.PolicySpec; import brooklyn.util.ResourceUtils; import brooklyn.util.collections.MutableList; import brooklyn.util.collections.MutableMap; import brooklyn.util.collections.MutableSet; import brooklyn.util.config.ConfigBag; import brooklyn.util.text.Strings; import brooklyn.util.time.Time; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.base.Supplier; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.common.net.HostAndPort; /** * Implementation of {@link CassandraDatacenter}. * <p> * Several subtleties to note: * - a node may take some time after it is running and serving JMX to actually be contactable on its thrift port * (so we wait for thrift port to be contactable) * - sometimes new nodes take a while to peer, and/or take a while to get a consistent schema * (each up to 1m; often very close to the 1m) */ public class CassandraDatacenterImpl extends DynamicClusterImpl implements CassandraDatacenter { /* * TODO Seed management is hard! * - The ServiceRestarter is not doing customize(), so is not refreshing the seeds in cassandra.yaml. * If we have two nodes that were seeds for each other and they both restart at the same time, we'll have a split brain. */ private static final Logger log = LoggerFactory.getLogger(CassandraDatacenterImpl.class); // Mutex for synchronizing during re-size operations private final Object mutex = new Object[0]; private final Supplier<Set<Entity>> defaultSeedSupplier = new Supplier<Set<Entity>>() { // Mutex for (re)calculating our seeds // TODO is this very dangerous?! Calling out to SeedTracker, which calls out to alien getAttribute()/getConfig(). But I think that's ok. // TODO might not need mutex? previous race was being caused by something else, other than concurrent calls! private final Object seedMutex = new Object(); @Override public Set<Entity> get() { synchronized (seedMutex) { boolean hasPublishedSeeds = Boolean.TRUE.equals(getAttribute(HAS_PUBLISHED_SEEDS)); int quorumSize = getSeedQuorumSize(); Set<Entity> potentialSeeds = gatherPotentialSeeds(); Set<Entity> potentialRunningSeeds = gatherPotentialRunningSeeds(); boolean stillWaitingForQuorum = (!hasPublishedSeeds) && (potentialSeeds.size() < quorumSize); if (stillWaitingForQuorum) { if (log.isDebugEnabled()) log.debug("Not refreshed seeds of cluster {}, because still waiting for quorum (need {}; have {} potentials)", new Object[] {CassandraDatacenterImpl.class, quorumSize, potentialSeeds.size()}); return ImmutableSet.of(); } else if (hasPublishedSeeds) { Set<Entity> currentSeeds = getAttribute(CURRENT_SEEDS); if (getAttribute(SERVICE_STATE) == Lifecycle.STARTING) { if (Sets.intersection(currentSeeds, potentialSeeds).isEmpty()) { log.warn("Cluster {} lost all its seeds while starting! Subsequent failure likely, but changing seeds during startup would risk split-brain: seeds={}", new Object[] {this, currentSeeds}); } return currentSeeds; } else if (potentialRunningSeeds.isEmpty()) { // TODO Could be race where nodes have only just returned from start() and are about to // transition to serviceUp; so don't just abandon all our seeds! log.warn("Cluster {} has no running seeds (yet?); leaving seeds as-is; but risks split-brain if these seeds come back up!", new Object[] {this}); return currentSeeds; } else { Set<Entity> result = trim(quorumSize, potentialRunningSeeds); log.debug("Cluster {} updating seeds: chosen={}; potentialRunning={}", new Object[] {this, result, potentialRunningSeeds}); return result; } } else { Set<Entity> result = trim(quorumSize, potentialSeeds); if (log.isDebugEnabled()) log.debug("Cluster {} has reached seed quorum: seeds={}", new Object[] {this, result}); return result; } } } private Set<Entity> trim(int num, Set<Entity> contenders) { // Prefer existing seeds wherever possible; otherwise accept any other contenders Set<Entity> currentSeeds = (getAttribute(CURRENT_SEEDS) != null) ? getAttribute(CURRENT_SEEDS) : ImmutableSet.<Entity>of(); Set<Entity> result = Sets.newLinkedHashSet(); result.addAll(Sets.intersection(currentSeeds, contenders)); result.addAll(contenders); return ImmutableSet.copyOf(Iterables.limit(result, num)); } }; protected SeedTracker seedTracker = new SeedTracker(); protected TokenGenerator tokenGenerator = null; private MemberTrackingPolicy policy; public CassandraDatacenterImpl() { } @Override public void init() { super.init(); /* * subscribe to hostname, and keep an accurate set of current seeds in a sensor; * then at nodes we set the initial seeds to be the current seeds when ready (non-empty) */ subscribeToMembers(this, Attributes.HOSTNAME, new SensorEventListener<String>() { @Override public void onEvent(SensorEvent<String> event) { seedTracker.onHostnameChanged(event.getSource(), event.getValue()); } }); subscribe(this, DynamicGroup.MEMBER_REMOVED, new SensorEventListener<Entity>() { @Override public void onEvent(SensorEvent<Entity> event) { seedTracker.onMemberRemoved(event.getValue()); } }); subscribeToMembers(this, Attributes.SERVICE_UP, new SensorEventListener<Boolean>() { @Override public void onEvent(SensorEvent<Boolean> event) { seedTracker.onServiceUpChanged(event.getSource(), event.getValue()); } }); // Track the datacenters for this cluster subscribeToMembers(this, CassandraNode.DATACENTER_NAME, new SensorEventListener<String>() { @Override public void onEvent(SensorEvent<String> event) { Entity member = event.getSource(); String dcName = event.getValue(); if (dcName != null) { Multimap<String, Entity> datacenterUsage = getAttribute(DATACENTER_USAGE); Multimap<String, Entity> mutableDatacenterUsage = (datacenterUsage == null) ? LinkedHashMultimap.<String, Entity>create() : LinkedHashMultimap.create(datacenterUsage); Optional<String> oldDcName = getKeyOfVal(mutableDatacenterUsage, member); if (!(oldDcName.isPresent() && dcName.equals(oldDcName.get()))) { mutableDatacenterUsage.values().remove(member); mutableDatacenterUsage.put(dcName, member); setAttribute(DATACENTER_USAGE, mutableDatacenterUsage); setAttribute(DATACENTERS, Sets.newLinkedHashSet(mutableDatacenterUsage.keySet())); } } } private <K,V> Optional<K> getKeyOfVal(Multimap<K,V> map, V val) { for (Map.Entry<K,V> entry : map.entries()) { if (Objects.equal(val, entry.getValue())) { return Optional.of(entry.getKey()); } } return Optional.absent(); } }); subscribe(this, DynamicGroup.MEMBER_REMOVED, new SensorEventListener<Entity>() { @Override public void onEvent(SensorEvent<Entity> event) { Entity entity = event.getSource(); Multimap<String, Entity> datacenterUsage = getAttribute(DATACENTER_USAGE); if (datacenterUsage != null && datacenterUsage.containsValue(entity)) { Multimap<String, Entity> mutableDatacenterUsage = LinkedHashMultimap.create(datacenterUsage); mutableDatacenterUsage.values().remove(entity); setAttribute(DATACENTER_USAGE, mutableDatacenterUsage); setAttribute(DATACENTERS, Sets.newLinkedHashSet(mutableDatacenterUsage.keySet())); } } }); getMutableEntityType().addEffector(EXECUTE_SCRIPT, new EffectorBody<String>() { @Override public String call(ConfigBag parameters) { return executeScript((String)parameters.getStringKey("commands")); } }); } protected Supplier<Set<Entity>> getSeedSupplier() { Supplier<Set<Entity>> seedSupplier = getConfig(SEED_SUPPLIER); return (seedSupplier == null) ? defaultSeedSupplier : seedSupplier; } protected synchronized TokenGenerator getTokenGenerator() { if (tokenGenerator!=null) return tokenGenerator; try { tokenGenerator = getConfig(TOKEN_GENERATOR_CLASS).newInstance(); BigInteger shift = getConfig(TOKEN_SHIFT); if (shift==null) shift = BigDecimal.valueOf(Math.random()).multiply( new BigDecimal(tokenGenerator.range())).toBigInteger(); tokenGenerator.setOrigin(shift); return tokenGenerator; } catch (Exception e) { throw Throwables.propagate(e); } } protected int getSeedQuorumSize() { Integer quorumSize = getConfig(INITIAL_QUORUM_SIZE); if (quorumSize!=null && quorumSize>0) return quorumSize; // default 2 is recommended, unless initial size is smaller return Math.min(Math.max(getConfig(INITIAL_SIZE), 1), DEFAULT_SEED_QUORUM); } @Override public Set<Entity> gatherPotentialSeeds() { return seedTracker.gatherPotentialSeeds(); } @Override public Set<Entity> gatherPotentialRunningSeeds() { return seedTracker.gatherPotentialRunningSeeds(); } /** * Sets the default {@link #MEMBER_SPEC} to describe the Cassandra nodes. */ @Override protected EntitySpec<?> getMemberSpec() { return getConfig(MEMBER_SPEC, EntitySpec.create(CassandraNode.class)); } @Override public String getClusterName() { return getAttribute(CLUSTER_NAME); } @Override public Collection<Entity> grow(int delta) { if (getCurrentSize() == 0) { getTokenGenerator().growingCluster(delta); } return super.grow(delta); } @Override protected Entity createNode(@Nullable Location loc, Map<?,?> flags) { Map<?,?> allflags; if (flags.containsKey(CassandraNode.TOKEN) || flags.containsKey("token")) { allflags = flags; } else { BigInteger token = getTokenGenerator().newToken(); allflags = (token == null) ? flags : MutableMap.builder().putAll(flags).put(CassandraNode.TOKEN, token).build(); } return super.createNode(loc, allflags); } @Override protected Entity replaceMember(Entity member, Location memberLoc, Map<?, ?> extraFlags) { BigInteger oldToken = ((CassandraNode) member).getToken(); BigInteger newToken = (oldToken != null) ? getTokenGenerator().getTokenForReplacementNode(oldToken) : null; return super.replaceMember(member, memberLoc, MutableMap.copyOf(extraFlags).add(CassandraNode.TOKEN, newToken)); } @Override public void start(Collection<? extends Location> locations) { Machines.warnIfLocalhost(locations, "CassandraCluster does not support multiple nodes on localhost, " + "due to assumptions Cassandra makes about the use of the same port numbers used across the cluster."); // force this to be set - even if it is using the default setAttribute(CLUSTER_NAME, getConfig(CLUSTER_NAME)); super.start(locations); connectSensors(); // TODO wait until all nodes which we think are up are consistent // i.e. all known nodes use the same schema, as reported by // SshEffectorTasks.ssh("echo \"describe cluster;\" | /bin/cassandra-cli"); // once we've done that we can revert to using 2 seed nodes. // see CassandraCluster.DEFAULT_SEED_QUORUM // (also ensure the cluster is ready if we are about to run a creation script) Time.sleep(getConfig(DELAY_BEFORE_ADVERTISING_CLUSTER)); String scriptUrl = getConfig(CassandraNode.CREATION_SCRIPT_URL); if (Strings.isNonEmpty(scriptUrl)) { executeScript(new ResourceUtils(this).getResourceAsString(scriptUrl)); } update(); } protected void connectSensors() { connectEnrichers(); policy = addPolicy(PolicySpec.create(MemberTrackingPolicy.class) .displayName("Cassandra Cluster Tracker") .configure("sensorsToTrack", ImmutableSet.of(Attributes.SERVICE_UP, Attributes.HOSTNAME, CassandraNode.THRIFT_PORT)) .configure("group", this)); } public static class MemberTrackingPolicy extends AbstractMembershipTrackingPolicy { @Override protected void onEntityChange(Entity member) { if (log.isDebugEnabled()) log.debug("Node {} updated in Cluster {}", member, this); ((CassandraDatacenterImpl)entity).update(); } @Override protected void onEntityAdded(Entity member) { if (log.isDebugEnabled()) log.debug("Node {} added to Cluster {}", member, this); ((CassandraDatacenterImpl)entity).update(); } @Override protected void onEntityRemoved(Entity member) { if (log.isDebugEnabled()) log.debug("Node {} removed from Cluster {}", member, this); ((CassandraDatacenterImpl)entity).update(); } }; @SuppressWarnings("unchecked") protected void connectEnrichers() { List<? extends List<? extends AttributeSensor<? extends Number>>> summingEnricherSetup = ImmutableList.of( ImmutableList.of(CassandraNode.READ_ACTIVE, READ_ACTIVE), ImmutableList.of(CassandraNode.READ_PENDING, READ_PENDING), ImmutableList.of(CassandraNode.WRITE_ACTIVE, WRITE_ACTIVE), ImmutableList.of(CassandraNode.WRITE_PENDING, WRITE_PENDING) ); List<? extends List<? extends AttributeSensor<? extends Number>>> averagingEnricherSetup = ImmutableList.of( ImmutableList.of(CassandraNode.READS_PER_SECOND_LAST, READS_PER_SECOND_LAST_PER_NODE), ImmutableList.of(CassandraNode.WRITES_PER_SECOND_LAST, WRITES_PER_SECOND_LAST_PER_NODE), ImmutableList.of(CassandraNode.WRITES_PER_SECOND_IN_WINDOW, WRITES_PER_SECOND_IN_WINDOW_PER_NODE), ImmutableList.of(CassandraNode.READS_PER_SECOND_IN_WINDOW, READS_PER_SECOND_IN_WINDOW_PER_NODE), ImmutableList.of(CassandraNode.THRIFT_PORT_LATENCY, THRIFT_PORT_LATENCY_PER_NODE), ImmutableList.of(CassandraNode.THRIFT_PORT_LATENCY_IN_WINDOW, THRIFT_PORT_LATENCY_IN_WINDOW_PER_NODE), ImmutableList.of(CassandraNode.PROCESS_CPU_TIME_FRACTION_LAST, PROCESS_CPU_TIME_FRACTION_LAST_PER_NODE), ImmutableList.of(CassandraNode.PROCESS_CPU_TIME_FRACTION_IN_WINDOW, PROCESS_CPU_TIME_FRACTION_IN_WINDOW_PER_NODE) ); for (List<? extends AttributeSensor<? extends Number>> es : summingEnricherSetup) { AttributeSensor<? extends Number> t = es.get(0); AttributeSensor<? extends Number> total = es.get(1); addEnricher(Enrichers.builder() .aggregating(t) .publishing(total) .fromMembers() .computingSum() .defaultValueForUnreportedSensors(null) .valueToReportIfNoSensors(null) .build()); } for (List<? extends AttributeSensor<? extends Number>> es : averagingEnricherSetup) { AttributeSensor<Number> t = (AttributeSensor<Number>) es.get(0); AttributeSensor<Double> average = (AttributeSensor<Double>) es.get(1); addEnricher(Enrichers.builder() .aggregating(t) .publishing(average) .fromMembers() .computingAverage() .defaultValueForUnreportedSensors(null) .valueToReportIfNoSensors(null) .build()); } subscribeToMembers(this, SERVICE_UP, new SensorEventListener<Boolean>() { @Override public void onEvent(SensorEvent<Boolean> event) { setAttribute(SERVICE_UP, calculateServiceUp()); } }); } @Override public void stop() { disconnectSensors(); super.stop(); } protected void disconnectSensors() { } @Override public void update() { synchronized (mutex) { // Update our seeds, as necessary seedTracker.refreshSeeds(); // Choose the first available cluster member to set host and port (and compute one-up) Optional<Entity> upNode = Iterables.tryFind(getMembers(), EntityPredicates.attributeEqualTo(SERVICE_UP, Boolean.TRUE)); if (upNode.isPresent()) { setAttribute(HOSTNAME, upNode.get().getAttribute(Attributes.HOSTNAME)); setAttribute(THRIFT_PORT, upNode.get().getAttribute(CassandraNode.THRIFT_PORT)); List<String> currentNodes = getAttribute(CASSANDRA_CLUSTER_NODES); Set<String> oldNodes = (currentNodes != null) ? ImmutableSet.copyOf(currentNodes) : ImmutableSet.<String>of(); Set<String> newNodes = MutableSet.<String>of(); for (Entity member : getMembers()) { if (member instanceof CassandraNode && Boolean.TRUE.equals(member.getAttribute(SERVICE_UP))) { String hostname = member.getAttribute(Attributes.HOSTNAME); Integer thriftPort = member.getAttribute(CassandraNode.THRIFT_PORT); if (hostname != null && thriftPort != null) { newNodes.add(HostAndPort.fromParts(hostname, thriftPort).toString()); } } } if (Sets.symmetricDifference(oldNodes, newNodes).size() > 0) { setAttribute(CASSANDRA_CLUSTER_NODES, MutableList.copyOf(newNodes)); } } else { setAttribute(HOSTNAME, null); setAttribute(THRIFT_PORT, null); setAttribute(CASSANDRA_CLUSTER_NODES, Collections.<String>emptyList()); } setAttribute(SERVICE_UP, upNode.isPresent() && calculateServiceUp()); } } @Override protected boolean calculateServiceUp() { if (!super.calculateServiceUp()) return false; List<String> nodes = getAttribute(CASSANDRA_CLUSTER_NODES); if (nodes==null || nodes.isEmpty()) return false; return true; } /** * For tracking our seeds. This gets fiddly! High-level logic is: * <ul> * <li>If we have never reached quorum (i.e. have never published seeds), then continue to wait for quorum; * because entity-startup may be blocking for this. This is handled by the seedSupplier. * <li>If we previously reached quorum (i.e. have previousy published seeds), then always update; * we never want stale/dead entities listed in our seeds. * <li>If an existing seed looks unhealthy, then replace it. * <li>If a new potential seed becomes available (and we're in need of more), then add it. * <ul> * * Also note that {@link CassandraFabric} can take over, because it know about multiple sub-clusters! * It will provide a different {@link CassandraDatacenter#SEED_SUPPLIER}. Each time we think that our seeds * need to change, we call that. The fabric will call into {@link CassandraDatacenterImpl#gatherPotentialSeeds()} * to find out what's available. * * @author aled */ protected class SeedTracker { private final Map<Entity, Boolean> memberUpness = Maps.newLinkedHashMap(); public void onMemberRemoved(Entity member) { Set<Entity> seeds = getSeeds(); boolean maybeRemove = seeds.contains(member); memberUpness.remove(member); if (maybeRemove) { refreshSeeds(); } else { if (log.isTraceEnabled()) log.trace("Seeds considered stable for cluster {} (node {} removed)", new Object[] {CassandraDatacenterImpl.this, member}); return; } } public void onHostnameChanged(Entity member, String hostname) { Set<Entity> seeds = getSeeds(); int quorum = getSeedQuorumSize(); boolean isViable = isViableSeed(member); boolean maybeAdd = isViable && seeds.size() < quorum; boolean maybeRemove = seeds.contains(member) && !isViable; if (maybeAdd || maybeRemove) { refreshSeeds(); } else { if (log.isTraceEnabled()) log.trace("Seeds considered stable for cluster {} (node {} changed hostname {})", new Object[] {CassandraDatacenterImpl.this, member, hostname}); return; } } public void onServiceUpChanged(Entity member, Boolean serviceUp) { Boolean oldVal = memberUpness.put(member, serviceUp); if (Objects.equal(oldVal, serviceUp)) { if (log.isTraceEnabled()) log.trace("Ignoring duplicate service-up in "+CassandraDatacenterImpl.this+" for "+member+", "+serviceUp); } Set<Entity> seeds = getSeeds(); int quorum = getSeedQuorumSize(); boolean isViable = isViableSeed(member); boolean maybeAdd = isViable && seeds.size() < quorum; boolean maybeRemove = seeds.contains(member) && !isViable; if (log.isDebugEnabled()) log.debug("Considering refresh of seeds for "+CassandraDatacenterImpl.this+" because "+member+" is now "+serviceUp+" ("+isViable+" / "+maybeAdd+" / "+maybeRemove+")"); if (maybeAdd || maybeRemove) { refreshSeeds(); } else { if (log.isTraceEnabled()) log.trace("Seeds considered stable for cluster {} (node {} changed serviceUp {})", new Object[] {CassandraDatacenterImpl.this, member, serviceUp}); return; } } protected Set<Entity> getSeeds() { Set<Entity> result = getAttribute(CURRENT_SEEDS); return (result == null) ? ImmutableSet.<Entity>of() : result; } public void refreshSeeds() { Set<Entity> oldseeds = getAttribute(CURRENT_SEEDS); Set<Entity> newseeds = getSeedSupplier().get(); if (Objects.equal(oldseeds, newseeds)) { if (log.isTraceEnabled()) log.debug("Seed refresh no-op for cluster {}: still={}", new Object[] {CassandraDatacenterImpl.this, oldseeds}); } else { if (log.isDebugEnabled()) log.debug("Refreshing seeds of cluster {}: now={}; old={}", new Object[] {this, newseeds, oldseeds}); setAttribute(CURRENT_SEEDS, newseeds); if (newseeds != null && newseeds.size() > 0) { setAttribute(HAS_PUBLISHED_SEEDS, true); } } } public Set<Entity> gatherPotentialSeeds() { Set<Entity> result = Sets.newLinkedHashSet(); for (Entity member : getMembers()) { if (isViableSeed(member)) { result.add(member); } } if (log.isTraceEnabled()) log.trace("Viable seeds in Cluster {}: {}", new Object[] {result}); return result; } public Set<Entity> gatherPotentialRunningSeeds() { Set<Entity> result = Sets.newLinkedHashSet(); for (Entity member : getMembers()) { if (isRunningSeed(member)) { result.add(member); } } if (log.isTraceEnabled()) log.trace("Viable running seeds in Cluster {}: {}", new Object[] {result}); return result; } public boolean isViableSeed(Entity member) { // TODO would be good to reuse the better logic in ServiceFailureDetector // (e.g. if that didn't just emit a notification but set a sensor as well?) boolean managed = Entities.isManaged(member); String hostname = member.getAttribute(Attributes.HOSTNAME); boolean serviceUp = Boolean.TRUE.equals(member.getAttribute(Attributes.SERVICE_UP)); Lifecycle serviceState = member.getAttribute(Attributes.SERVICE_STATE); boolean hasFailed = !managed || (serviceState == Lifecycle.ON_FIRE) || (serviceState == Lifecycle.RUNNING && !serviceUp) || (serviceState == Lifecycle.STOPPED); boolean result = (hostname != null && !hasFailed); if (log.isTraceEnabled()) log.trace("Node {} in Cluster {}: viableSeed={}; hostname={}; serviceUp={}; serviceState={}; hasFailed={}", new Object[] {member, this, result, hostname, serviceUp, serviceState, hasFailed}); return result; } public boolean isRunningSeed(Entity member) { boolean viableSeed = isViableSeed(member); boolean serviceUp = Boolean.TRUE.equals(member.getAttribute(Attributes.SERVICE_UP)); Lifecycle serviceState = member.getAttribute(Attributes.SERVICE_STATE); boolean result = viableSeed && serviceUp && serviceState == Lifecycle.RUNNING; if (log.isTraceEnabled()) log.trace("Node {} in Cluster {}: runningSeed={}; viableSeed={}; serviceUp={}; serviceState={}", new Object[] {member, this, result, viableSeed, serviceUp, serviceState}); return result; } } @Override public String executeScript(String commands) { Entity someChild = Iterables.getFirst(getMembers(), null); if (someChild==null) throw new IllegalStateException("No Cassandra nodes available"); // FIXME cross-etntity method-style calls such as below do not set up a queueing context (DynamicSequentialTask) // return ((CassandraNode)someChild).executeScript(commands); return Entities.invokeEffector(this, someChild, CassandraNode.EXECUTE_SCRIPT, MutableMap.of("commands", commands)).getUnchecked(); } }
package net.i2p.crypto; /* * Copyright (c) 2003, TheCrypto * 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 the TheCrypto 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. */ import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.Key; import java.security.MessageDigest; import java.security.PrivateKey; import java.security.PublicKey; import java.security.interfaces.DSAKey; import java.security.interfaces.ECKey; import java.security.interfaces.RSAKey; import net.i2p.I2PAppContext; import net.i2p.data.Hash; import net.i2p.data.Signature; import net.i2p.data.SigningPrivateKey; import net.i2p.data.SigningPublicKey; import net.i2p.data.SimpleDataStructure; import net.i2p.util.Log; import net.i2p.util.NativeBigInteger; /** * Sign and verify using DSA-SHA1. * Also contains methods to sign and verify using a SHA-256 Hash, used by Syndie only. * * The primary implementation is code from TheCryto. * As of 0.8.7, also included is an alternate implementation using java.security libraries, which * is slightly slower. This implementation could in the future be easily modified * to use a new signing algorithm from java.security when we change the signing algorithm. * * Params and rv's changed from Hash to SHA1Hash for version 0.8.1 * Hash variants of sign() and verifySignature() restored in 0.8.3, required by Syndie. * * As of 0.9.9, certain methods support RSA and ECDSA keys and signatures, i.e. all types * specified in SigType. The type is specified by the getType() method in * Signature, SigningPublicKey, and SigningPrivateKey. See Javadocs for individual * methods for the supported types. Methods encountering an unsupported type * will throw an IllegalArgumentException. */ public class DSAEngine { private final Log _log; private final I2PAppContext _context; //private static final boolean _isAndroid = System.getProperty("java.vendor").contains("Android"); private static final boolean _useJavaLibs = false; // = _isAndroid; public DSAEngine(I2PAppContext context) { _log = context.logManager().getLog(DSAEngine.class); _context = context; } public static DSAEngine getInstance() { return I2PAppContext.getGlobalContext().dsa(); } /** * Verify using DSA-SHA1 or ECDSA. * Uses TheCrypto code for DSA-SHA1 unless configured to use the java.security libraries. */ public boolean verifySignature(Signature signature, byte signedData[], SigningPublicKey verifyingKey) { return verifySignature(signature, signedData, 0, signedData.length, verifyingKey); } /** * Verify using any sig type as of 0.9.12 (DSA only prior to that) */ public boolean verifySignature(Signature signature, byte signedData[], int offset, int size, SigningPublicKey verifyingKey) { boolean rv; SigType type = signature.getType(); if (type != verifyingKey.getType()) throw new IllegalArgumentException("type mismatch sig=" + signature.getType() + " key=" + verifyingKey.getType()); if (type != SigType.DSA_SHA1) { try { rv = altVerifySig(signature, signedData, offset, size, verifyingKey); if ((!rv) && _log.shouldLog(Log.WARN)) _log.warn(type + " Sig Verify Fail"); return rv; } catch (GeneralSecurityException gse) { if (_log.shouldLog(Log.WARN)) _log.warn(type + " Sig Verify Fail", gse); return false; } } if (_useJavaLibs) { try { rv = altVerifySigSHA1(signature, signedData, offset, size, verifyingKey); if ((!rv) && _log.shouldLog(Log.WARN)) _log.warn("Lib DSA Sig Verify Fail"); return rv; } catch (GeneralSecurityException gse) { if (_log.shouldLog(Log.WARN)) _log.warn("Lib DSA Sig Verify Fail"); // now try TheCrypto } } rv = verifySignature(signature, calculateHash(signedData, offset, size), verifyingKey); if ((!rv) && _log.shouldLog(Log.WARN)) _log.warn("TheCrypto DSA Sig Verify Fail"); return rv; } /** * Verify using DSA-SHA1 ONLY */ public boolean verifySignature(Signature signature, InputStream in, SigningPublicKey verifyingKey) { return verifySignature(signature, calculateHash(in), verifyingKey); } /** * Verify using DSA-SHA1 ONLY * @param hash SHA-1 hash, NOT a SHA-256 hash */ public boolean verifySignature(Signature signature, SHA1Hash hash, SigningPublicKey verifyingKey) { return verifySig(signature, hash, verifyingKey); } /** * Nonstandard. * Used by Syndie. * @since 0.8.3 (restored, was removed in 0.8.1 and 0.8.2) */ public boolean verifySignature(Signature signature, Hash hash, SigningPublicKey verifyingKey) { return verifySig(signature, hash, verifyingKey); } /** * Generic signature type. * * @param hash SHA1Hash, Hash, Hash384, or Hash512 * @since 0.9.9 */ public boolean verifySignature(Signature signature, SimpleDataStructure hash, SigningPublicKey verifyingKey) { SigType type = signature.getType(); if (type != verifyingKey.getType()) throw new IllegalArgumentException("type mismatch sig=" + type + " key=" + verifyingKey.getType()); int hashlen = type.getHashLen(); if (hash.length() != hashlen) throw new IllegalArgumentException("type mismatch hash=" + hash.getClass() + " sig=" + type); if (type == SigType.DSA_SHA1) return verifySig(signature, hash, verifyingKey); try { return altVerifySigRaw(signature, hash, verifyingKey); } catch (GeneralSecurityException gse) { if (_log.shouldLog(Log.WARN)) _log.warn(type + " Sig Verify Fail", gse); return false; } } /** * Generic signature type. * If you have a Java pubkey, use this, so you don't lose the key parameters, * which may be different than the ones defined in SigType. * * @param hash SHA1Hash, Hash, Hash384, or Hash512 * @param pubKey Java key * @since 0.9.9 */ public boolean verifySignature(Signature signature, SimpleDataStructure hash, PublicKey pubKey) { try { return altVerifySigRaw(signature, hash, pubKey); } catch (GeneralSecurityException gse) { if (_log.shouldLog(Log.WARN)) _log.warn(signature.getType() + " Sig Verify Fail", gse); return false; } } /** * Verify using DSA-SHA1 or Syndie DSA-SHA256 ONLY. * @param hash either a Hash or a SHA1Hash * @since 0.8.3 */ private boolean verifySig(Signature signature, SimpleDataStructure hash, SigningPublicKey verifyingKey) { if (signature.getType() != SigType.DSA_SHA1) throw new IllegalArgumentException("Bad sig type " + signature.getType()); if (verifyingKey.getType() != SigType.DSA_SHA1) throw new IllegalArgumentException("Bad key type " + verifyingKey.getType()); long start = _context.clock().now(); try { byte[] sigbytes = signature.getData(); byte rbytes[] = new byte[20]; byte sbytes[] = new byte[20]; //System.arraycopy(sigbytes, 0, rbytes, 0, 20); //System.arraycopy(sigbytes, 20, sbytes, 0, 20); for (int x = 0; x < 40; x++) { if (x < 20) { rbytes[x] = sigbytes[x]; } else { sbytes[x - 20] = sigbytes[x]; } } BigInteger s = new NativeBigInteger(1, sbytes); BigInteger r = new NativeBigInteger(1, rbytes); BigInteger y = new NativeBigInteger(1, verifyingKey.getData()); BigInteger w = null; try { w = s.modInverse(CryptoConstants.dsaq); } catch (ArithmeticException ae) { _log.warn("modInverse() error", ae); return false; } byte data[] = hash.getData(); NativeBigInteger bi = new NativeBigInteger(1, data); BigInteger u1 = bi.multiply(w).mod(CryptoConstants.dsaq); BigInteger u2 = r.multiply(w).mod(CryptoConstants.dsaq); BigInteger modval = CryptoConstants.dsag.modPow(u1, CryptoConstants.dsap); BigInteger modmulval = modval.multiply(y.modPow(u2,CryptoConstants.dsap)); BigInteger v = (modmulval).mod(CryptoConstants.dsap).mod(CryptoConstants.dsaq); boolean ok = v.compareTo(r) == 0; long diff = _context.clock().now() - start; if (diff > 1000) { if (_log.shouldLog(Log.WARN)) _log.warn("Took too long to verify the signature (" + diff + "ms)"); } return ok; } catch (Exception e) { _log.log(Log.CRIT, "Error verifying the signature", e); return false; } } /** * Sign using any key type. * Uses TheCrypto code unless configured to use the java.security libraries. * * @return null on error */ public Signature sign(byte data[], SigningPrivateKey signingKey) { return sign(data, 0, data.length, signingKey); } /** * Sign using any key type as of 0.9.12 (DSA-SHA1 only prior to that) * * @return null on error */ public Signature sign(byte data[], int offset, int length, SigningPrivateKey signingKey) { if ((signingKey == null) || (data == null) || (data.length <= 0)) return null; SigType type = signingKey.getType(); if (type != SigType.DSA_SHA1) { try { return altSign(data, offset, length, signingKey); } catch (GeneralSecurityException gse) { if (_log.shouldLog(Log.WARN)) _log.warn(type + " Sign Fail", gse); return null; } } if (_useJavaLibs) { try { return altSignSHA1(data, offset, length, signingKey); } catch (GeneralSecurityException gse) { if (_log.shouldLog(Log.WARN)) _log.warn("Lib Sign Fail, privkey = " + signingKey, gse); // now try TheCrypto } } SHA1Hash h = calculateHash(data, offset, length); return sign(h, signingKey); } /** * Sign using DSA-SHA1 ONLY. * Reads the stream until EOF. Does not close the stream. * * @return null on error */ public Signature sign(InputStream in, SigningPrivateKey signingKey) { if ((signingKey == null) || (in == null) ) return null; SHA1Hash h = calculateHash(in); return sign(h, signingKey); } /** * Sign using DSA-SHA1 ONLY. * * @param hash SHA-1 hash, NOT a SHA-256 hash * @return null on error */ public Signature sign(SHA1Hash hash, SigningPrivateKey signingKey) { return signIt(hash, signingKey); } /** * Nonstandard. * Used by Syndie. * * @return null on error * @since 0.8.3 (restored, was removed in 0.8.1 and 0.8.2) */ public Signature sign(Hash hash, SigningPrivateKey signingKey) { return signIt(hash, signingKey); } /** * Generic signature type. * * @param hash SHA1Hash, Hash, Hash384, or Hash512 * @return null on error * @since 0.9.9 */ public Signature sign(SimpleDataStructure hash, SigningPrivateKey signingKey) { SigType type = signingKey.getType(); int hashlen = type.getHashLen(); if (hash.length() != hashlen) throw new IllegalArgumentException("type mismatch hash=" + hash.getClass() + " key=" + type); if (type == SigType.DSA_SHA1) return signIt(hash, signingKey); try { return altSignRaw(hash, signingKey); } catch (GeneralSecurityException gse) { if (_log.shouldLog(Log.WARN)) _log.warn(type + " Sign Fail", gse); return null; } } /** * Generic signature type. * If you have a Java privkey, use this, so you don't lose the key parameters, * which may be different than the ones defined in SigType. * * @param hash SHA1Hash, Hash, Hash384, or Hash512 * @param privKey Java key * @param type returns a Signature of this type * @return null on error * @since 0.9.9 */ public Signature sign(SimpleDataStructure hash, PrivateKey privKey, SigType type) { String algo = getRawAlgo(privKey); String talgo = getRawAlgo(type); if (!algo.equals(talgo)) throw new IllegalArgumentException("type mismatch type=" + type + " key=" + privKey.getClass().getSimpleName()); try { return altSignRaw(algo, hash, privKey, type); } catch (GeneralSecurityException gse) { if (_log.shouldLog(Log.WARN)) _log.warn(type + " Sign Fail", gse); return null; } } /** * Sign using DSA-SHA1 or Syndie DSA-SHA256 ONLY. * * @param hash either a Hash or a SHA1Hash * @return null on error * @since 0.8.3 */ private Signature signIt(SimpleDataStructure hash, SigningPrivateKey signingKey) { if ((signingKey == null) || (hash == null)) return null; if (signingKey.getType() != SigType.DSA_SHA1) throw new IllegalArgumentException("Bad key type " + signingKey.getType()); long start = _context.clock().now(); Signature sig = new Signature(); BigInteger k; boolean ok = false; do { k = new BigInteger(160, _context.random()); ok = k.compareTo(CryptoConstants.dsaq) != 1; ok = ok && !k.equals(BigInteger.ZERO); //System.out.println("K picked (ok? " + ok + "): " + k.bitLength() + ": " + k.toString()); } while (!ok); BigInteger r = CryptoConstants.dsag.modPow(k, CryptoConstants.dsap).mod(CryptoConstants.dsaq); BigInteger kinv = k.modInverse(CryptoConstants.dsaq); BigInteger M = new NativeBigInteger(1, hash.getData()); BigInteger x = new NativeBigInteger(1, signingKey.getData()); BigInteger s = (kinv.multiply(M.add(x.multiply(r)))).mod(CryptoConstants.dsaq); byte[] rbytes = r.toByteArray(); byte[] sbytes = s.toByteArray(); byte[] out = new byte[40]; // (q^random)%p is computationally random _context.random().harvester().feedEntropy("DSA.sign", rbytes, 0, rbytes.length); if (rbytes.length == 20) { //System.arraycopy(rbytes, 0, out, 0, 20); for (int i = 0; i < 20; i++) { out[i] = rbytes[i]; } } else if (rbytes.length == 21) { //System.arraycopy(rbytes, 1, out, 0, 20); for (int i = 0; i < 20; i++) { out[i] = rbytes[i + 1]; } } else if (rbytes.length > 21) { _log.error("Bad R length " + rbytes.length); return null; } else { //if (_log.shouldLog(Log.DEBUG)) _log.debug("Using short rbytes.length [" + rbytes.length + "]"); //System.arraycopy(rbytes, 0, out, 20 - rbytes.length, rbytes.length); for (int i = 0; i < rbytes.length; i++) out[i + 20 - rbytes.length] = rbytes[i]; } if (sbytes.length == 20) { //System.arraycopy(sbytes, 0, out, 20, 20); for (int i = 0; i < 20; i++) { out[i + 20] = sbytes[i]; } } else if (sbytes.length == 21) { //System.arraycopy(sbytes, 1, out, 20, 20); for (int i = 0; i < 20; i++) { out[i + 20] = sbytes[i + 1]; } } else if (sbytes.length > 21) { _log.error("Bad S length " + sbytes.length); return null; } else { //if (_log.shouldLog(Log.DEBUG)) _log.debug("Using short sbytes.length [" + sbytes.length + "]"); //System.arraycopy(sbytes, 0, out, 40 - sbytes.length, sbytes.length); for (int i = 0; i < sbytes.length; i++) out[i + 20 + 20 - sbytes.length] = sbytes[i]; } sig.setData(out); long diff = _context.clock().now() - start; if (diff > 1000) { if (_log.shouldLog(Log.WARN)) _log.warn("Took too long to sign (" + diff + "ms)"); } return sig; } /** * Reads the stream until EOF. Does not close the stream. * * @return hash SHA-1 hash, NOT a SHA-256 hash * @deprecated unused */ public SHA1Hash calculateHash(InputStream in) { MessageDigest digest = SHA1.getInstance(); byte buf[] = new byte[64]; int read = 0; try { while ( (read = in.read(buf)) != -1) { digest.update(buf, 0, read); } } catch (IOException ioe) { if (_log.shouldLog(Log.WARN)) _log.warn("Unable to hash the stream", ioe); return null; } return new SHA1Hash(digest.digest()); } /** @return hash SHA-1 hash, NOT a SHA-256 hash */ public static SHA1Hash calculateHash(byte[] source, int offset, int len) { MessageDigest h = SHA1.getInstance(); h.update(source, offset, len); byte digested[] = h.digest(); return new SHA1Hash(digested); } /** * Generic verify DSA_SHA1, ECDSA, or RSA * @throws GeneralSecurityException if algorithm unvailable or on other errors * @since 0.9.9 added off/len 0.9.12 */ private boolean altVerifySig(Signature signature, byte[] data, int offset, int len, SigningPublicKey verifyingKey) throws GeneralSecurityException { SigType type = signature.getType(); if (type != verifyingKey.getType()) throw new IllegalArgumentException("type mismatch sig=" + type + " key=" + verifyingKey.getType()); if (type == SigType.DSA_SHA1) return altVerifySigSHA1(signature, data, offset, len, verifyingKey); java.security.Signature jsig = java.security.Signature.getInstance(type.getAlgorithmName()); PublicKey pubKey = SigUtil.toJavaKey(verifyingKey); jsig.initVerify(pubKey); jsig.update(data, offset, len); boolean rv = jsig.verify(SigUtil.toJavaSig(signature)); return rv; } /** * Generic raw verify any type * @throws GeneralSecurityException if algorithm unvailable or on other errors * @since 0.9.9 */ private boolean altVerifySigRaw(Signature signature, SimpleDataStructure hash, SigningPublicKey verifyingKey) throws GeneralSecurityException { SigType type = signature.getType(); if (type != verifyingKey.getType()) throw new IllegalArgumentException("type mismatch sig=" + type + " key=" + verifyingKey.getType()); PublicKey pubKey = SigUtil.toJavaKey(verifyingKey); return verifySignature(signature, hash, pubKey); } /** * Generic raw verify any type. * If you have a Java pubkey, use this, so you don't lose the key parameters, * which may be different than the ones defined in SigType. * * @throws GeneralSecurityException if algorithm unvailable or on other errors * @param verifyingKey Java key * @since 0.9.9 */ private boolean altVerifySigRaw(Signature signature, SimpleDataStructure hash, PublicKey pubKey) throws GeneralSecurityException { SigType type = signature.getType(); int hashlen = hash.length(); if (type.getHashLen() != hashlen) throw new IllegalArgumentException("type mismatch hash=" + hash.getClass() + " key=" + type); String algo = getRawAlgo(type); java.security.Signature jsig = java.security.Signature.getInstance(algo); jsig.initVerify(pubKey); jsig.update(hash.getData()); boolean rv = jsig.verify(SigUtil.toJavaSig(signature)); return rv; } /** * Alternate to verifySignature() using java.security libraries. * @throws GeneralSecurityException if algorithm unvailable or on other errors * @since 0.8.7 added off/len 0.9.12 */ private boolean altVerifySigSHA1(Signature signature, byte[] data, int offset, int len, SigningPublicKey verifyingKey) throws GeneralSecurityException { java.security.Signature jsig = java.security.Signature.getInstance("SHA1withDSA"); PublicKey pubKey = SigUtil.toJavaDSAKey(verifyingKey); jsig.initVerify(pubKey); jsig.update(data, offset, len); boolean rv = jsig.verify(SigUtil.toJavaSig(signature)); //if (!rv) { // System.out.println("BAD SIG\n" + net.i2p.util.HexDump.dump(signature.getData())); // System.out.println("BAD SIG\n" + net.i2p.util.HexDump.dump(sigBytesToASN1(signature.getData()))); //} return rv; } /** * Generic sign DSA_SHA1, ECDSA, or RSA * @throws GeneralSecurityException if algorithm unvailable or on other errors * @since 0.9.9 added off/len 0.9.12 */ private Signature altSign(byte[] data, int offset, int len, SigningPrivateKey privateKey) throws GeneralSecurityException { SigType type = privateKey.getType(); if (type == SigType.DSA_SHA1) return altSignSHA1(data, offset, len, privateKey); java.security.Signature jsig = java.security.Signature.getInstance(type.getAlgorithmName()); PrivateKey privKey = SigUtil.toJavaKey(privateKey); jsig.initSign(privKey, _context.random()); jsig.update(data, offset, len); return SigUtil.fromJavaSig(jsig.sign(), type); } /** * Generic raw verify any type * @param hash SHA1Hash, Hash, Hash384, or Hash512 * @throws GeneralSecurityException if algorithm unvailable or on other errors * @since 0.9.9 */ private Signature altSignRaw(SimpleDataStructure hash, SigningPrivateKey privateKey) throws GeneralSecurityException { SigType type = privateKey.getType(); String algo = getRawAlgo(type); PrivateKey privKey = SigUtil.toJavaKey(privateKey); return altSignRaw(algo, hash, privKey, type); } /** * Generic raw verify any type * @param hash SHA1Hash, Hash, Hash384, or Hash512 * @param type returns a Signature of this type * @throws GeneralSecurityException if algorithm unvailable or on other errors * @since 0.9.9 */ private Signature altSignRaw(String algo, SimpleDataStructure hash, PrivateKey privKey, SigType type) throws GeneralSecurityException { int hashlen = hash.length(); if (type.getHashLen() != hashlen) throw new IllegalArgumentException("type mismatch hash=" + hash.getClass() + " key=" + type); java.security.Signature jsig = java.security.Signature.getInstance(algo); jsig.initSign(privKey, _context.random()); jsig.update(hash.getData()); return SigUtil.fromJavaSig(jsig.sign(), type); } /** * Alternate to sign() using java.security libraries. * @throws GeneralSecurityException if algorithm unvailable or on other errors * @since 0.8.7 added off/len args 0.9.12 */ private Signature altSignSHA1(byte[] data, int offset, int len, SigningPrivateKey privateKey) throws GeneralSecurityException { java.security.Signature jsig = java.security.Signature.getInstance("SHA1withDSA"); PrivateKey privKey = SigUtil.toJavaDSAKey(privateKey); jsig.initSign(privKey, _context.random()); jsig.update(data, offset, len); return SigUtil.fromJavaSig(jsig.sign(), SigType.DSA_SHA1); } /** @since 0.9.9 */ private static String getRawAlgo(SigType type) { switch (type.getBaseAlgorithm()) { case DSA: return "NONEwithDSA"; case EC: return "NONEwithECDSA"; case RSA: return "NONEwithRSA"; default: throw new IllegalArgumentException(); } } /** @since 0.9.9 */ private static String getRawAlgo(Key key) { if (key instanceof DSAKey) return "NONEwithDSA"; if (key instanceof ECKey) return "NONEwithECDSA"; if (key instanceof RSAKey) return "NONEwithRSA"; throw new IllegalArgumentException(); } //private static final int RUNS = 1000; /** * Run consistency and speed tests with both TheCrypto and java.security libraries. * * TheCrypto is about 5-15% faster than java.security. */ /**** public static void main(String args[]) { I2PAppContext ctx = I2PAppContext.getGlobalContext(); byte data[] = new byte[1024]; // warmump ctx.random().nextBytes(data); try { Thread.sleep(1000); } catch (InterruptedException ie) {} SimpleDataStructure keys[] = null; System.err.println("100 runs with new data and keys each time"); for (int i = 0; i < 100; i++) { ctx.random().nextBytes(data); keys = ctx.keyGenerator().generateSigningKeys(); Signature sig = ctx.dsa().sign(data, (SigningPrivateKey)keys[1]); Signature jsig = null; try { jsig = ctx.dsa().altSignSHA1(data, (SigningPrivateKey)keys[1]); } catch (GeneralSecurityException gse) { gse.printStackTrace(); } boolean ok = ctx.dsa().verifySignature(jsig, data, (SigningPublicKey)keys[0]); boolean usok = ctx.dsa().verifySignature(sig, data, (SigningPublicKey)keys[0]); boolean jok = false; try { jok = ctx.dsa().altVerifySigSHA1(sig, data, (SigningPublicKey)keys[0]); } catch (GeneralSecurityException gse) { gse.printStackTrace(); } boolean jjok = false;; try { jjok = ctx.dsa().altVerifySigSHA1(jsig, data, (SigningPublicKey)keys[0]); } catch (GeneralSecurityException gse) { gse.printStackTrace(); } System.err.println("TC->TC OK: " + usok + " JL->TC OK: " + ok + " TC->JK OK: " + jok + " JL->JL OK: " + jjok); if (!(ok && usok && jok && jjok)) { System.out.println("privkey\n" + net.i2p.util.HexDump.dump(keys[1].getData())); return; } } System.err.println("Starting speed test"); long start = System.currentTimeMillis(); for (int i = 0; i < RUNS; i++) { Signature sig = ctx.dsa().sign(data, (SigningPrivateKey)keys[1]); boolean ok = ctx.dsa().verifySignature(sig, data, (SigningPublicKey)keys[0]); if (!ok) { System.err.println("TheCrypto FAIL"); return; } } long time = System.currentTimeMillis() - start; System.err.println("Time for " + RUNS + " DSA sign/verifies:"); System.err.println("TheCrypto time (ms): " + time); start = System.currentTimeMillis(); for (int i = 0; i < RUNS; i++) { boolean ok = false; try { Signature jsig = ctx.dsa().altSignSHA1(data, (SigningPrivateKey)keys[1]); ok = ctx.dsa().altVerifySigSHA1(jsig, data, (SigningPublicKey)keys[0]); } catch (GeneralSecurityException gse) { gse.printStackTrace(); } if (!ok) { System.err.println("JavaLib FAIL"); return; } } time = System.currentTimeMillis() - start; System.err.println("JavaLib time (ms): " + time); ****/ /**** yes, arraycopy is slower for 20 bytes start = System.currentTimeMillis(); byte b[] = new byte[20]; for (int i = 0; i < 10000000; i++) { data[0] = data[i % 256]; System.arraycopy(data, 0, b, 0, 20); } time = System.currentTimeMillis() - start; System.err.println("arraycopy time (ms): " + time); start = System.currentTimeMillis(); for (int i = 0; i < 10000000; i++) { data[0] = data[i % 256]; for (int j = 0; j < 20; j++) { b[j] = data[j]; } } time = System.currentTimeMillis() - start; System.err.println("loop time (ms): " + time); ****/ /**** } ****/ }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.processors.standard; import org.apache.nifi.controller.AbstractControllerService; import org.apache.nifi.logging.ComponentLog; import org.apache.nifi.reporting.InitializationException; import org.apache.nifi.schema.access.SchemaNotFoundException; import org.apache.nifi.serialization.RecordSetWriter; import org.apache.nifi.serialization.RecordSetWriterFactory; import org.apache.nifi.serialization.SimpleRecordSchema; import org.apache.nifi.serialization.WriteResult; import org.apache.nifi.serialization.record.ArrayListRecordReader; import org.apache.nifi.serialization.record.ArrayListRecordWriter; import org.apache.nifi.serialization.record.MapRecord; import org.apache.nifi.serialization.record.MockRecordParser; import org.apache.nifi.serialization.record.MockRecordWriter; import org.apache.nifi.serialization.record.Record; import org.apache.nifi.serialization.record.RecordField; import org.apache.nifi.serialization.record.RecordFieldType; import org.apache.nifi.serialization.record.RecordSchema; import org.apache.nifi.serialization.record.RecordSet; import org.apache.nifi.util.MockFlowFile; import org.apache.nifi.util.TestRunner; import org.apache.nifi.util.TestRunners; import org.junit.Test; import java.io.IOException; import java.io.OutputStream; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; public class TestQueryRecord { static { System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "info"); System.setProperty("org.slf4j.simpleLogger.showDateTime", "true"); System.setProperty("org.slf4j.simpleLogger.log.nifi.io.nio", "debug"); System.setProperty("org.slf4j.simpleLogger.log.org.apache.nifi.processors.standard.SQLTransform", "debug"); } private static final String REL_NAME = "success"; public TestRunner getRunner() { TestRunner runner = TestRunners.newTestRunner(QueryRecord.class); /** * we have to disable validation of expression language because the scope of the evaluation * depends of the value of another property: if we are caching the schema/queries or not. If * we don't disable the validation, it'll throw an error saying that the scope is incorrect. */ runner.setValidateExpressionUsage(false); return runner; } @Test public void testRecordPathFunctions() throws InitializationException { final Record record = createHierarchicalRecord(); final ArrayListRecordReader recordReader = new ArrayListRecordReader(record.getSchema()); recordReader.addRecord(record); final ArrayListRecordWriter writer = new ArrayListRecordWriter(record.getSchema()); TestRunner runner = getRunner(); runner.addControllerService("reader", recordReader); runner.enableControllerService(recordReader); runner.addControllerService("writer", writer); runner.enableControllerService(writer); runner.setProperty(QueryRecord.RECORD_READER_FACTORY, "reader"); runner.setProperty(QueryRecord.RECORD_WRITER_FACTORY, "writer"); runner.setProperty(REL_NAME, "SELECT RPATH_STRING(person, '/name') AS name," + " RPATH_INT(person, '/age') AS age," + " RPATH(person, '/name') AS nameObj," + " RPATH(person, '/age') AS ageObj," + " RPATH(person, '/favoriteColors') AS colors," + " RPATH(person, '//name') AS names," + " RPATH_DATE(person, '/dob') AS dob," + " RPATH_LONG(person, '/dobTimestamp') AS dobTimestamp," + " RPATH_DATE(person, 'toDate(/joinTimestamp, \"yyyy-MM-dd\")') AS joinTime, " + " RPATH_DOUBLE(person, '/weight') AS weight" + " FROM FLOWFILE"); runner.enqueue(new byte[0]); runner.run(); runner.assertTransferCount(REL_NAME, 1); final List<Record> written = writer.getRecordsWritten(); assertEquals(1, written.size()); final Record output = written.get(0); assertEquals("John Doe", output.getValue("name")); assertEquals("John Doe", output.getValue("nameObj")); assertEquals(30, output.getValue("age")); assertEquals(30, output.getValue("ageObj")); assertArrayEquals(new String[] { "red", "green"}, (Object[]) output.getValue("colors")); assertArrayEquals(new String[] { "John Doe", "Jane Doe"}, (Object[]) output.getValue("names")); assertEquals("1517702400000", output.getAsString("joinTime")); assertEquals(Double.valueOf(180.8D), output.getAsDouble("weight")); } @Test public void testRecordPathInAggregate() throws InitializationException { final Record record = createHierarchicalRecord(); final ArrayListRecordReader recordReader = new ArrayListRecordReader(record.getSchema()); for (int i=0; i < 100; i++) { final Record toAdd = createHierarchicalRecord(); final Record person = (Record) toAdd.getValue("person"); person.setValue("name", "Person " + i); person.setValue("age", i); recordReader.addRecord(toAdd); } final ArrayListRecordWriter writer = new ArrayListRecordWriter(record.getSchema()); TestRunner runner = getRunner(); runner.addControllerService("reader", recordReader); runner.enableControllerService(recordReader); runner.addControllerService("writer", writer); runner.enableControllerService(writer); runner.setProperty(QueryRecord.RECORD_READER_FACTORY, "reader"); runner.setProperty(QueryRecord.RECORD_WRITER_FACTORY, "writer"); runner.setProperty(REL_NAME, "SELECT RPATH_STRING(person, '/name') AS name FROM FLOWFILE" + " WHERE RPATH_INT(person, '/age') > (" + " SELECT AVG( RPATH_INT(person, '/age') ) FROM FLOWFILE" + ")"); runner.enqueue(new byte[0]); runner.run(); runner.assertTransferCount(REL_NAME, 1); final List<Record> written = writer.getRecordsWritten(); assertEquals(50, written.size()); int i=50; for (final Record writtenRecord : written) { final String name = writtenRecord.getAsString("name"); assertEquals("Person " + i, name); i++; } } @Test public void testRecordPathWithArray() throws InitializationException { final Record record = createHierarchicalArrayRecord(); final ArrayListRecordReader recordReader = new ArrayListRecordReader(record.getSchema()); recordReader.addRecord(record); final ArrayListRecordWriter writer = new ArrayListRecordWriter(record.getSchema()); TestRunner runner = getRunner(); runner.addControllerService("reader", recordReader); runner.enableControllerService(recordReader); runner.addControllerService("writer", writer); runner.enableControllerService(writer); runner.setProperty(QueryRecord.RECORD_READER_FACTORY, "reader"); runner.setProperty(QueryRecord.RECORD_WRITER_FACTORY, "writer"); runner.setProperty(REL_NAME, "SELECT title, name" + " FROM FLOWFILE" + " WHERE RPATH(addresses, '/state[/label = ''home'']') <>" + " RPATH(addresses, '/state[/label = ''work'']')"); runner.enqueue(new byte[0]); runner.run(); runner.assertTransferCount(REL_NAME, 1); final List<Record> written = writer.getRecordsWritten(); assertEquals(1, written.size()); final Record output = written.get(0); assertEquals("John Doe", output.getValue("name")); assertEquals("Software Engineer", output.getValue("title")); } @Test public void testCompareResultsOfTwoRecordPathsAgainstArray() throws InitializationException { final Record record = createHierarchicalArrayRecord(); // Change the value of the 'state' field of both addresses to NY. // This allows us to use an equals operator to ensure that we do get back the same values, // whereas the unit test above tests <> and that may result in 'false confidence' if the software // were to provide the wrong values but values that were not equal. Record[] addresses = (Record[]) record.getValue("addresses"); for (final Record address : addresses) { address.setValue("state", "NY"); } final ArrayListRecordReader recordReader = new ArrayListRecordReader(record.getSchema()); recordReader.addRecord(record); final ArrayListRecordWriter writer = new ArrayListRecordWriter(record.getSchema()); TestRunner runner = getRunner(); runner.addControllerService("reader", recordReader); runner.enableControllerService(recordReader); runner.addControllerService("writer", writer); runner.enableControllerService(writer); runner.setProperty(QueryRecord.RECORD_READER_FACTORY, "reader"); runner.setProperty(QueryRecord.RECORD_WRITER_FACTORY, "writer"); runner.setProperty(REL_NAME, "SELECT title, name" + " FROM FLOWFILE" + " WHERE RPATH(addresses, '/state[/label = ''home'']') =" + " RPATH(addresses, '/state[/label = ''work'']')"); runner.enqueue(new byte[0]); runner.run(); runner.assertTransferCount(REL_NAME, 1); final List<Record> written = writer.getRecordsWritten(); assertEquals(1, written.size()); final Record output = written.get(0); assertEquals("John Doe", output.getValue("name")); assertEquals("Software Engineer", output.getValue("title")); } @Test public void testRecordPathWithArrayAndOnlyOneElementMatchingRPath() throws InitializationException { final Record record = createHierarchicalArrayRecord(); final ArrayListRecordReader recordReader = new ArrayListRecordReader(record.getSchema()); recordReader.addRecord(record); final ArrayListRecordWriter writer = new ArrayListRecordWriter(record.getSchema()); TestRunner runner = getRunner(); runner.addControllerService("reader", recordReader); runner.enableControllerService(recordReader); runner.addControllerService("writer", writer); runner.enableControllerService(writer); runner.setProperty(QueryRecord.RECORD_READER_FACTORY, "reader"); runner.setProperty(QueryRecord.RECORD_WRITER_FACTORY, "writer"); runner.setProperty(REL_NAME, "SELECT title, name" + " FROM FLOWFILE" + " WHERE RPATH(addresses, '/state[. = ''NY'']') = 'NY'"); runner.enqueue(new byte[0]); runner.run(); runner.assertTransferCount(REL_NAME, 1); final List<Record> written = writer.getRecordsWritten(); assertEquals(1, written.size()); final Record output = written.get(0); assertEquals("John Doe", output.getValue("name")); assertEquals("Software Engineer", output.getValue("title")); } @Test public void testLikeWithRecordPath() throws InitializationException { final Record record = createHierarchicalArrayRecord(); final ArrayListRecordReader recordReader = new ArrayListRecordReader(record.getSchema()); recordReader.addRecord(record); final ArrayListRecordWriter writer = new ArrayListRecordWriter(record.getSchema()); TestRunner runner = getRunner(); runner.addControllerService("reader", recordReader); runner.enableControllerService(recordReader); runner.addControllerService("writer", writer); runner.enableControllerService(writer); runner.setProperty(QueryRecord.RECORD_READER_FACTORY, "reader"); runner.setProperty(QueryRecord.RECORD_WRITER_FACTORY, "writer"); runner.setProperty(REL_NAME, "SELECT title, name" + " FROM FLOWFILE" + " WHERE RPATH_STRING(addresses, '/state[. = ''NY'']') LIKE 'N%'"); runner.enqueue(new byte[0]); runner.run(); runner.assertTransferCount(REL_NAME, 1); final List<Record> written = writer.getRecordsWritten(); assertEquals(1, written.size()); final Record output = written.get(0); assertEquals("John Doe", output.getValue("name")); assertEquals("Software Engineer", output.getValue("title")); } @Test public void testRecordPathWithMap() throws InitializationException { final Record record = createHierarchicalRecord(); final ArrayListRecordReader recordReader = new ArrayListRecordReader(record.getSchema()); recordReader.addRecord(record); final ArrayListRecordWriter writer = new ArrayListRecordWriter(record.getSchema()); TestRunner runner = getRunner(); runner.addControllerService("reader", recordReader); runner.enableControllerService(recordReader); runner.addControllerService("writer", writer); runner.enableControllerService(writer); runner.setProperty(QueryRecord.RECORD_READER_FACTORY, "reader"); runner.setProperty(QueryRecord.RECORD_WRITER_FACTORY, "writer"); runner.setProperty(REL_NAME, "SELECT RPATH(favoriteThings, '.[''sport'']') AS sport," + " RPATH_STRING(person, '/name') AS nameObj" + " FROM FLOWFILE" + " WHERE RPATH(favoriteThings, '.[''color'']') = 'green'"); runner.enqueue(new byte[0]); runner.run(); runner.assertTransferCount(REL_NAME, 1); final List<Record> written = writer.getRecordsWritten(); assertEquals(1, written.size()); final Record output = written.get(0); assertEquals("basketball", output.getValue("sport")); assertEquals("John Doe", output.getValue("nameObj")); } /** * Returns a Record that, if written in JSON, would look like: * <code><pre> * { * "person": { * "name": "John Doe", * "age": 30, * "favoriteColors": [ "red", "green" ], * "dob": 598741575825, * "dobTimestamp": 598741575825, * "joinTimestamp": "2018-02-04 10:20:55.802", * "weight": 180.8, * "mother": { * "name": "Jane Doe" * } * } * } * </pre></code> * * @return the Record */ private Record createHierarchicalRecord() { final List<RecordField> namedPersonFields = new ArrayList<>(); namedPersonFields.add(new RecordField("name", RecordFieldType.STRING.getDataType())); final RecordSchema namedPersonSchema = new SimpleRecordSchema(namedPersonFields); final List<RecordField> personFields = new ArrayList<>(); personFields.add(new RecordField("name", RecordFieldType.STRING.getDataType())); personFields.add(new RecordField("age", RecordFieldType.INT.getDataType())); personFields.add(new RecordField("favoriteColors", RecordFieldType.ARRAY.getArrayDataType(RecordFieldType.STRING.getDataType()))); personFields.add(new RecordField("dob", RecordFieldType.DATE.getDataType())); personFields.add(new RecordField("dobTimestamp", RecordFieldType.LONG.getDataType())); personFields.add(new RecordField("joinTimestamp", RecordFieldType.STRING.getDataType())); personFields.add(new RecordField("weight", RecordFieldType.DOUBLE.getDataType())); personFields.add(new RecordField("mother", RecordFieldType.RECORD.getRecordDataType(namedPersonSchema))); final RecordSchema personSchema = new SimpleRecordSchema(personFields); final List<RecordField> outerSchemaFields = new ArrayList<>(); outerSchemaFields.add(new RecordField("person", RecordFieldType.RECORD.getRecordDataType(personSchema))); outerSchemaFields.add(new RecordField("favoriteThings", RecordFieldType.MAP.getMapDataType(RecordFieldType.STRING.getDataType()))); final RecordSchema recordSchema = new SimpleRecordSchema(outerSchemaFields); final Record mother = new MapRecord(namedPersonSchema, Collections.singletonMap("name", "Jane Doe")); final Map<String, String> favorites = new HashMap<>(); favorites.put("sport", "basketball"); favorites.put("color", "green"); favorites.put("roses", "raindrops"); favorites.put("kittens", "whiskers"); final long ts = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(365 * 30); final Map<String, Object> map = new HashMap<>(); map.put("name", "John Doe"); map.put("age", 30); map.put("favoriteColors", new String[] { "red", "green" }); map.put("dob", new Date(ts)); map.put("dobTimestamp", ts); map.put("joinTimestamp", "2018-02-04 10:20:55.802"); map.put("weight", 180.8D); map.put("mother", mother); final Record person = new MapRecord(personSchema, map); final Map<String, Object> personValues = new HashMap<>(); personValues.put("person", person); personValues.put("favoriteThings", favorites); final Record record = new MapRecord(recordSchema, personValues); return record; } /** * Returns a Record that, if written in JSON, would look like: * <code><pre> * { * "name": "John Doe", * "title": "Software Engineer", * "age": 40, * "addresses": [{ * "streetNumber": 4820, * "street": "My Street", * "apartment": null, * "city": "New York", * "state": "NY", * "country": "USA", * "label": "work" * }, { * "streetNumber": 327, * "street": "Small Street", * "apartment": 309, * "city": "Los Angeles", * "state": "CA", * "country": "USA", * "label": "home" * }] * } * </pre></code> * * @return the Record */ private Record createHierarchicalArrayRecord() { final List<RecordField> addressFields = new ArrayList<>(); addressFields.add(new RecordField("streetNumber", RecordFieldType.INT.getDataType())); addressFields.add(new RecordField("street", RecordFieldType.STRING.getDataType())); addressFields.add(new RecordField("apartment", RecordFieldType.INT.getDataType())); addressFields.add(new RecordField("city", RecordFieldType.STRING.getDataType())); addressFields.add(new RecordField("state", RecordFieldType.STRING.getDataType())); addressFields.add(new RecordField("country", RecordFieldType.STRING.getDataType())); addressFields.add(new RecordField("label", RecordFieldType.STRING.getDataType())); final RecordSchema addressSchema = new SimpleRecordSchema(addressFields); final List<RecordField> personFields = new ArrayList<>(); personFields.add(new RecordField("name", RecordFieldType.STRING.getDataType())); personFields.add(new RecordField("age", RecordFieldType.INT.getDataType())); personFields.add(new RecordField("title", RecordFieldType.STRING.getDataType())); personFields.add(new RecordField("addresses", RecordFieldType.ARRAY.getArrayDataType( RecordFieldType.RECORD.getRecordDataType(addressSchema)) )); final RecordSchema personSchema = new SimpleRecordSchema(personFields); final Map<String, Object> workMap = new HashMap<>(); workMap.put("streetNumber", 4820); workMap.put("street", "My Street"); workMap.put("apartment", null); workMap.put("city", "New York City"); workMap.put("state", "NY"); workMap.put("country", "USA"); workMap.put("label", "work"); final Record workAddress = new MapRecord(addressSchema, workMap); final Map<String, Object> homeMap = new HashMap<>(); homeMap.put("streetNumber", 327); homeMap.put("street", "Small Street"); homeMap.put("apartment", 302); homeMap.put("city", "Los Angeles"); homeMap.put("state", "CA"); homeMap.put("country", "USA"); homeMap.put("label", "home"); final Record homeAddress = new MapRecord(addressSchema, homeMap); final Map<String, Object> map = new HashMap<>(); map.put("name", "John Doe"); map.put("age", 30); map.put("title", "Software Engineer"); map.put("addresses", new Record[] {homeAddress, workAddress}); final Record person = new MapRecord(personSchema, map); return person; } @Test public void testStreamClosedWhenBadData() throws InitializationException { final MockRecordParser parser = new MockRecordParser(); parser.failAfter(0); parser.addSchemaField("name", RecordFieldType.STRING); parser.addSchemaField("age", RecordFieldType.INT); parser.addRecord("Tom", 49); final MockRecordWriter writer = new MockRecordWriter("\"name\",\"points\""); TestRunner runner = getRunner(); runner.addControllerService("parser", parser); runner.enableControllerService(parser); runner.addControllerService("writer", writer); runner.enableControllerService(writer); runner.setProperty(REL_NAME, "select name, age from FLOWFILE WHERE name <> ''"); runner.setProperty(QueryRecord.RECORD_READER_FACTORY, "parser"); runner.setProperty(QueryRecord.RECORD_WRITER_FACTORY, "writer"); runner.enqueue(new byte[0]); runner.run(); runner.assertTransferCount(QueryRecord.REL_FAILURE, 1); } @Test public void testSimple() throws InitializationException, IOException, SQLException { final MockRecordParser parser = new MockRecordParser(); parser.addSchemaField("name", RecordFieldType.STRING); parser.addSchemaField("age", RecordFieldType.INT); parser.addRecord("Tom", 49); final MockRecordWriter writer = new MockRecordWriter("\"name\",\"points\""); TestRunner runner = getRunner(); runner.addControllerService("parser", parser); runner.enableControllerService(parser); runner.addControllerService("writer", writer); runner.enableControllerService(writer); runner.setProperty(REL_NAME, "select name, age from FLOWFILE WHERE name <> ''"); runner.setProperty(QueryRecord.RECORD_READER_FACTORY, "parser"); runner.setProperty(QueryRecord.RECORD_WRITER_FACTORY, "writer"); final int numIterations = 1; for (int i = 0; i < numIterations; i++) { runner.enqueue(new byte[0]); } runner.setThreadCount(4); runner.run(2 * numIterations); runner.assertTransferCount(REL_NAME, 1); final MockFlowFile out = runner.getFlowFilesForRelationship(REL_NAME).get(0); System.out.println(new String(out.toByteArray())); out.assertContentEquals("\"name\",\"points\"\n\"Tom\",\"49\"\n"); } @Test public void testNullable() throws InitializationException, IOException, SQLException { final MockRecordParser parser = new MockRecordParser(); parser.addSchemaField("name", RecordFieldType.STRING, true); parser.addSchemaField("age", RecordFieldType.INT, true); parser.addRecord("Tom", 49); parser.addRecord("Alice", null); parser.addRecord(null, 36); final MockRecordWriter writer = new MockRecordWriter("\"name\",\"points\""); TestRunner runner = getRunner(); runner.addControllerService("parser", parser); runner.enableControllerService(parser); runner.addControllerService("writer", writer); runner.enableControllerService(writer); runner.setProperty(REL_NAME, "select name, age from FLOWFILE"); runner.setProperty(QueryRecord.RECORD_READER_FACTORY, "parser"); runner.setProperty(QueryRecord.RECORD_WRITER_FACTORY, "writer"); final int numIterations = 1; for (int i = 0; i < numIterations; i++) { runner.enqueue(new byte[0]); } runner.setThreadCount(4); runner.run(2 * numIterations); runner.assertTransferCount(REL_NAME, 1); final MockFlowFile out = runner.getFlowFilesForRelationship(REL_NAME).get(0); System.out.println(new String(out.toByteArray())); out.assertContentEquals("\"name\",\"points\"\n\"Tom\",\"49\"\n\"Alice\",\n,\"36\"\n"); } @Test public void testParseFailure() throws InitializationException, IOException, SQLException { final MockRecordParser parser = new MockRecordParser(); parser.addSchemaField("name", RecordFieldType.STRING); parser.addSchemaField("age", RecordFieldType.INT); parser.addRecord("Tom", 49); final MockRecordWriter writer = new MockRecordWriter("\"name\",\"points\""); TestRunner runner = getRunner(); runner.addControllerService("parser", parser); runner.enableControllerService(parser); runner.addControllerService("writer", writer); runner.enableControllerService(writer); runner.setProperty(REL_NAME, "select name, age from FLOWFILE WHERE name <> ''"); runner.setProperty(QueryRecord.RECORD_READER_FACTORY, "parser"); runner.setProperty(QueryRecord.RECORD_WRITER_FACTORY, "writer"); final int numIterations = 1; for (int i = 0; i < numIterations; i++) { runner.enqueue(new byte[0]); } runner.setThreadCount(4); runner.run(2 * numIterations); runner.assertTransferCount(REL_NAME, 1); final MockFlowFile out = runner.getFlowFilesForRelationship(REL_NAME).get(0); System.out.println(new String(out.toByteArray())); out.assertContentEquals("\"name\",\"points\"\n\"Tom\",\"49\"\n"); } @Test public void testTransformCalc() throws InitializationException, IOException, SQLException { final MockRecordParser parser = new MockRecordParser(); parser.addSchemaField("ID", RecordFieldType.INT); parser.addSchemaField("AMOUNT1", RecordFieldType.FLOAT); parser.addSchemaField("AMOUNT2", RecordFieldType.FLOAT); parser.addSchemaField("AMOUNT3", RecordFieldType.FLOAT); parser.addRecord(8, 10.05F, 15.45F, 89.99F); parser.addRecord(100, 20.25F, 25.25F, 45.25F); parser.addRecord(105, 20.05F, 25.05F, 45.05F); parser.addRecord(200, 34.05F, 25.05F, 75.05F); final MockRecordWriter writer = new MockRecordWriter("\"NAME\",\"POINTS\""); TestRunner runner = getRunner(); runner.addControllerService("parser", parser); runner.enableControllerService(parser); runner.addControllerService("writer", writer); runner.enableControllerService(writer); runner.setProperty(REL_NAME, "select ID, AMOUNT1+AMOUNT2+AMOUNT3 as TOTAL from FLOWFILE where ID=100"); runner.setProperty(QueryRecord.RECORD_READER_FACTORY, "parser"); runner.setProperty(QueryRecord.RECORD_WRITER_FACTORY, "writer"); runner.enqueue(new byte[0]); runner.run(); runner.assertTransferCount(REL_NAME, 1); final MockFlowFile out = runner.getFlowFilesForRelationship(REL_NAME).get(0); out.assertContentEquals("\"NAME\",\"POINTS\"\n\"100\",\"90.75\"\n"); } @Test public void testHandlingWithInvalidSchema() throws InitializationException { final MockRecordParser parser = new MockRecordParser(); parser.addSchemaField("name", RecordFieldType.STRING); parser.addSchemaField("favorite_color", RecordFieldType.STRING); parser.addSchemaField("address", RecordFieldType.STRING); parser.addRecord("Tom", "blue", null); parser.addRecord("Jerry", "red", null); final MockRecordWriter writer = new MockRecordWriter("\"name\",\"points\""); TestRunner runner = getRunner(); runner.enforceReadStreamsClosed(false); runner.addControllerService("parser", parser); runner.enableControllerService(parser); runner.addControllerService("writer", writer); runner.enableControllerService(writer); runner.setProperty(QueryRecord.INCLUDE_ZERO_RECORD_FLOWFILES, "false"); runner.setProperty("rel1", "select * from FLOWFILE where address IS NOT NULL"); runner.setProperty("rel2", "select name, CAST(favorite_color AS DOUBLE) AS num from FLOWFILE"); runner.setProperty("rel3", "select * from FLOWFILE where address IS NOT NULL"); runner.setProperty(QueryRecord.RECORD_READER_FACTORY, "parser"); runner.setProperty(QueryRecord.RECORD_WRITER_FACTORY, "writer"); runner.enqueue(""); runner.run(); runner.assertAllFlowFilesTransferred(QueryRecord.REL_FAILURE, 1); } @Test public void testAggregateFunction() throws InitializationException, IOException { final MockRecordParser parser = new MockRecordParser(); parser.addSchemaField("name", RecordFieldType.STRING); parser.addSchemaField("points", RecordFieldType.INT); parser.addRecord("Tom", 1); parser.addRecord("Jerry", 2); parser.addRecord("Tom", 99); final MockRecordWriter writer = new MockRecordWriter("\"name\",\"points\""); TestRunner runner = getRunner(); runner.addControllerService("parser", parser); runner.enableControllerService(parser); runner.addControllerService("writer", writer); runner.enableControllerService(writer); runner.setProperty(REL_NAME, "select name, sum(points) as points from FLOWFILE GROUP BY name"); runner.setProperty(QueryRecord.RECORD_READER_FACTORY, "parser"); runner.setProperty(QueryRecord.RECORD_WRITER_FACTORY, "writer"); runner.enqueue(""); runner.run(); runner.assertTransferCount(REL_NAME, 1); final MockFlowFile flowFileOut = runner.getFlowFilesForRelationship(REL_NAME).get(0); flowFileOut.assertContentEquals("\"name\",\"points\"\n\"Tom\",\"100\"\n\"Jerry\",\"2\"\n"); } @Test public void testNullValueInSingleField() throws InitializationException, IOException { final MockRecordParser parser = new MockRecordParser(); parser.addSchemaField("name", RecordFieldType.STRING); parser.addSchemaField("points", RecordFieldType.INT); parser.addRecord("Tom", 1); parser.addRecord("Jerry", null); parser.addRecord("Tom", null); parser.addRecord("Jerry", 3); final MockRecordWriter writer = new MockRecordWriter(null, false); TestRunner runner = getRunner(); runner.addControllerService("parser", parser); runner.enableControllerService(parser); runner.addControllerService("writer", writer); runner.enableControllerService(writer); runner.setProperty(REL_NAME, "select points from FLOWFILE"); runner.setProperty("count", "select count(*) as c from flowfile where points is null"); runner.setProperty(QueryRecord.RECORD_READER_FACTORY, "parser"); runner.setProperty(QueryRecord.RECORD_WRITER_FACTORY, "writer"); runner.enqueue(""); runner.run(); runner.assertTransferCount(REL_NAME, 1); runner.assertTransferCount("count", 1); final MockFlowFile flowFileOut = runner.getFlowFilesForRelationship(REL_NAME).get(0); flowFileOut.assertContentEquals("1\n\n\n3\n"); final MockFlowFile countFlowFile = runner.getFlowFilesForRelationship("count").get(0); countFlowFile.assertContentEquals("2\n"); } @Test public void testColumnNames() throws InitializationException { final MockRecordParser parser = new MockRecordParser(); parser.addSchemaField("name", RecordFieldType.STRING); parser.addSchemaField("points", RecordFieldType.INT); parser.addSchemaField("greeting", RecordFieldType.STRING); parser.addRecord("Tom", 1, "Hello"); parser.addRecord("Jerry", 2, "Hi"); parser.addRecord("Tom", 99, "Howdy"); final List<String> colNames = new ArrayList<>(); colNames.add("name"); colNames.add("points"); colNames.add("greeting"); colNames.add("FAV_GREETING"); final ResultSetValidatingRecordWriter writer = new ResultSetValidatingRecordWriter(colNames); TestRunner runner = getRunner(); runner.addControllerService("parser", parser); runner.enableControllerService(parser); runner.addControllerService("writer", writer); runner.enableControllerService(writer); runner.setProperty(REL_NAME, "select *, greeting AS FAV_GREETING from FLOWFILE"); runner.setProperty(QueryRecord.RECORD_READER_FACTORY, "parser"); runner.setProperty(QueryRecord.RECORD_WRITER_FACTORY, "writer"); runner.enqueue(""); runner.run(); runner.assertTransferCount(REL_NAME, 1); } private static class ResultSetValidatingRecordWriter extends AbstractControllerService implements RecordSetWriterFactory { private final List<String> columnNames; public ResultSetValidatingRecordWriter(final List<String> colNames) { this.columnNames = new ArrayList<>(colNames); } @Override public RecordSchema getSchema(Map<String, String> variables, RecordSchema readSchema) throws SchemaNotFoundException, IOException { final List<RecordField> recordFields = columnNames.stream() .map(name -> new RecordField(name, RecordFieldType.STRING.getDataType())) .collect(Collectors.toList()); return new SimpleRecordSchema(recordFields); } @Override public RecordSetWriter createWriter(final ComponentLog logger, final RecordSchema schema, final OutputStream out, final Map<String, String> variables) { return new RecordSetWriter() { @Override public void flush() throws IOException { out.flush(); } @Override public WriteResult write(final RecordSet rs) throws IOException { final int colCount = rs.getSchema().getFieldCount(); assertEquals(columnNames.size(), colCount); final List<String> colNames = new ArrayList<>(colCount); for (int i = 0; i < colCount; i++) { colNames.add(rs.getSchema().getField(i).getFieldName()); } assertEquals(columnNames, colNames); // Iterate over the rest of the records to ensure that we read the entire stream. If we don't // do this, we won't consume all of the data and as a result we will not close the stream properly Record record; while ((record = rs.next()) != null) { System.out.println(record); } return WriteResult.of(0, Collections.emptyMap()); } @Override public String getMimeType() { return "text/plain"; } @Override public WriteResult write(Record record) throws IOException { return null; } @Override public void close() throws IOException { out.close(); } @Override public void beginRecordSet() throws IOException { } @Override public WriteResult finishRecordSet() throws IOException { return WriteResult.EMPTY; } }; } } }
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.apimgt.gateway.handlers.security.jwt; import com.nimbusds.jwt.SignedJWT; import io.swagger.parser.OpenAPIParser; import io.swagger.v3.oas.models.OpenAPI; import org.apache.axis2.Constants; import org.apache.commons.io.IOUtils; import org.apache.synapse.MessageContext; import org.apache.synapse.core.axis2.Axis2MessageContext; import org.apache.synapse.rest.RESTConstants; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo; import org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator; import org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityConstants; import org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException; import org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext; import org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.gateway.utils.GatewayUtils; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; import org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO; import org.wso2.carbon.apimgt.impl.dto.ExtendedJWTConfigurationDto; import org.wso2.carbon.apimgt.impl.jwt.JWTValidationService; import org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo; import org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.UUID; import javax.cache.Cache; @RunWith(PowerMockRunner.class) @PrepareForTest({JWTValidator.class, GatewayUtils.class, MultitenantUtils.class, PrivilegedCarbonContext.class, ServiceReferenceHolder.class}) public class JWTValidatorTest { PrivilegedCarbonContext privilegedCarbonContext; ServiceReferenceHolder serviceReferenceHolder; @Before public void setup() { System.setProperty("carbon.home", ""); PowerMockito.mockStatic(MultitenantUtils.class); PowerMockito.mockStatic(PrivilegedCarbonContext.class); PowerMockito.mockStatic(ServiceReferenceHolder.class); privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class); serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class); PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext); PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder); } @Test public void testJWTValidator() throws ParseException, APISecurityException, APIManagementException, IOException { Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("carbon.super"); SignedJWT signedJWT = SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5UZG1aak00WkRrM05qWTBZemM1T" + "W1abU9EZ3dNVEUzTVdZd05ERTVNV1JsWkRnNE56YzRaQT09In0" + ".eyJhdWQiOiJodHRwOlwvXC9vcmcud3NvMi5hcGltZ3RcL2dhdGV" + "3YXkiLCJzdWIiOiJhZG1pbkBjYXJib24uc3VwZXIiLCJhcHBsaWNhdGlvbiI6eyJvd25lciI6ImFkbWluIiwidGllclF1b3RhVHlwZ" + "SI6InJlcXVlc3RDb3VudCIsInRpZXIiOiJVbmxpbWl0ZWQiLCJuYW1lIjoiRGVmYXVsdEFwcGxpY2F0aW9uIiwiaWQiOjEsInV1aWQ" + "iOm51bGx9LCJzY29wZSI6ImFtX2FwcGxpY2F0aW9uX3Njb3BlIGRlZmF1bHQiLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0" + "NDNcL29hdXRoMlwvdG9rZW4iLCJ0aWVySW5mbyI6e30sImtleXR5cGUiOiJQUk9EVUNUSU9OIiwic3Vic2NyaWJlZEFQSXMiOltdL" + "CJjb25zdW1lcktleSI6IlhnTzM5NklIRks3ZUZZeWRycVFlNEhLR3oxa2EiLCJleHAiOjE1OTAzNDIzMTMsImlhdCI6MTU5MDMzO" + "DcxMywianRpIjoiYjg5Mzg3NjgtMjNmZC00ZGVjLThiNzAtYmVkNDVlYjdjMzNkIn0" + ".sBgeoqJn0log5EZflj_G7ADvm6B3KQ9bdfF" + "CEFVQS1U3oY9" + "-cqPwAPyOLLh95pdfjYjakkf1UtjPZjeIupwXnzg0SffIc704RoVlZocAx9Ns2XihjU6Imx2MbXq9ARmQxQkyGVkJ" + "UMTwZ8" + "-SfOnprfrhX2cMQQS8m2Lp7hcsvWFRGKxAKIeyUrbY4ihRIA5vOUrMBWYUx9Di1N7qdKA4S3e8O4KQX2VaZPBzN594c9TG" + "riiH8AuuqnrftfvidSnlRLaFJmko8-QZo8jDepwacaFhtcaPVVJFG4uYP-_" + "-N6sqfxLw3haazPN0_xU0T1zJLPRLC5HPfZMJDMGp" + "EuSe9w"); ExtendedJWTConfigurationDto jwtConfigurationDto = new ExtendedJWTConfigurationDto(); JWTValidationService jwtValidationService = Mockito.mock(JWTValidationService.class); APIKeyValidator apiKeyValidator = Mockito.mock(APIKeyValidator.class); Cache gatewayTokenCache = Mockito.mock(Cache.class); Cache invalidTokenCache = Mockito.mock(Cache.class); Cache gatewayKeyCache = Mockito.mock(Cache.class); Cache gatewayJWTTokenCache = Mockito.mock(Cache.class); JWTValidationInfo jwtValidationInfo = new JWTValidationInfo(); jwtValidationInfo.setValid(true); jwtValidationInfo.setIssuer("https://localhost"); jwtValidationInfo.setRawPayload(signedJWT.getParsedString()); jwtValidationInfo.setJti(UUID.randomUUID().toString()); jwtValidationInfo.setIssuedTime(System.currentTimeMillis()); jwtValidationInfo.setExpiryTime(System.currentTimeMillis() + 5000L); jwtValidationInfo.setConsumerKey(UUID.randomUUID().toString()); jwtValidationInfo.setUser("user1"); jwtValidationInfo.setKeyManager("Default"); SignedJWTInfo signedJWTInfo = new SignedJWTInfo(signedJWT.getParsedString(), signedJWT, signedJWT.getJWTClaimsSet()); Mockito.when(jwtValidationService.validateJWTToken(signedJWTInfo)).thenReturn(jwtValidationInfo); JWTValidatorWrapper jwtValidator = new JWTValidatorWrapper("Unlimited", true, apiKeyValidator, false, null, jwtConfigurationDto, jwtValidationService, invalidTokenCache, gatewayTokenCache, gatewayKeyCache, gatewayJWTTokenCache); MessageContext messageContext = Mockito.mock(Axis2MessageContext.class); org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class); Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET"); Map<String, String> headers = new HashMap<>(); Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)) .thenReturn(headers); Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt); Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1"); Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0"); Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/pet/findByStatus"); APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class); Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.JWT_AUTHENTICATION_SUBSCRIPTION_VALIDATION)) .thenReturn("true"); jwtValidator.setApiManagerConfiguration(apiManagerConfiguration); APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO(); apiKeyValidationInfoDTO.setApiName("api1"); apiKeyValidationInfoDTO.setApiPublisher("admin"); apiKeyValidationInfoDTO.setApiTier("Unlimited"); apiKeyValidationInfoDTO.setAuthorized(true); Mockito.when(apiKeyValidator.validateScopes(Mockito.any(TokenValidationContext.class), Mockito.anyString())) .thenReturn(true); Mockito.when(apiKeyValidator.validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(apiKeyValidationInfoDTO); AuthenticationContext authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext); Mockito.verify(apiKeyValidator) .validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); Assert.assertNotNull(authenticate); Assert.assertEquals(authenticate.getApiName(), "api1"); Assert.assertEquals(authenticate.getApiPublisher(), "admin"); Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey()); Mockito.when(gatewayTokenCache.get(signedJWT.getJWTClaimsSet().getJWTID())).thenReturn("carbon.super"); Mockito.when(gatewayKeyCache.get(signedJWT.getJWTClaimsSet().getJWTID())).thenReturn(jwtValidationInfo); authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext); Assert.assertNotNull(authenticate); Assert.assertEquals(authenticate.getApiName(), "api1"); Assert.assertEquals(authenticate.getApiPublisher(), "admin"); Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey()); Mockito.verify(jwtValidationService, Mockito.only()).validateJWTToken(signedJWTInfo); Mockito.verify(gatewayTokenCache, Mockito.atLeast(1)).get(signedJWT.getJWTClaimsSet().getJWTID()); } @Test public void testJWTValidatorForNonJTIScenario() throws ParseException, APISecurityException, APIManagementException, IOException { Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("carbon.super"); SignedJWT signedJWT = SignedJWT .parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" + ".eyJpc3MiOiJodHRwczovL2xvY2FsaG9zdCIsImlhdCI6MTU5OTU0ODE3NCwiZXhwIjoxNjMxMDg0MTc0LC" + "JhdWQiOiJ3d3cuZXhhbXBsZS5jb20iLCJzdWIiOiJqcm9ja2V0QGV4YW1wbGUuY29tIiwiR2l2ZW5OYW1l" + "IjoiSm9obm55IiwiU3VybmFtZSI6IlJvY2tldCIsIkVtYWlsIjoianJvY2tldEBleGFtcGxlLmNvbSIsIl" + "JvbGUiOlsiTWFuYWdlciIsIlByb2plY3QgQWRtaW5pc3RyYXRvciJdfQ.SSQyg_VTxF5drIogztn2SyEK" + "2wRE07wG6OW3tufD3vo"); ExtendedJWTConfigurationDto jwtConfigurationDto = new ExtendedJWTConfigurationDto(); JWTValidationService jwtValidationService = Mockito.mock(JWTValidationService.class); APIKeyValidator apiKeyValidator = Mockito.mock(APIKeyValidator.class); Cache gatewayTokenCache = Mockito.mock(Cache.class); Cache invalidTokenCache = Mockito.mock(Cache.class); Cache gatewayKeyCache = Mockito.mock(Cache.class); Cache gatewayJWTTokenCache = Mockito.mock(Cache.class); JWTValidationInfo jwtValidationInfo = new JWTValidationInfo(); jwtValidationInfo.setValid(true); jwtValidationInfo.setIssuer("https://localhost"); jwtValidationInfo.setRawPayload(signedJWT.getParsedString()); jwtValidationInfo.setJti(UUID.randomUUID().toString()); jwtValidationInfo.setIssuedTime(System.currentTimeMillis()); jwtValidationInfo.setExpiryTime(System.currentTimeMillis() + 5000L); jwtValidationInfo.setConsumerKey(UUID.randomUUID().toString()); jwtValidationInfo.setUser("user1"); jwtValidationInfo.setKeyManager("Default"); SignedJWTInfo signedJWTInfo = new SignedJWTInfo(signedJWT.getParsedString(), signedJWT, signedJWT.getJWTClaimsSet()); Mockito.when(jwtValidationService.validateJWTToken(signedJWTInfo)).thenReturn(jwtValidationInfo); JWTValidatorWrapper jwtValidator = new JWTValidatorWrapper("Unlimited", true, apiKeyValidator, false, null, jwtConfigurationDto, jwtValidationService, invalidTokenCache, gatewayTokenCache, gatewayKeyCache, gatewayJWTTokenCache); MessageContext messageContext = Mockito.mock(Axis2MessageContext.class); org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class); Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET"); Map<String, String> headers = new HashMap<>(); Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)) .thenReturn(headers); Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt); Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1"); Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0"); Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/pet/findByStatus"); APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class); Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.JWT_AUTHENTICATION_SUBSCRIPTION_VALIDATION)) .thenReturn("true"); jwtValidator.setApiManagerConfiguration(apiManagerConfiguration); APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO(); apiKeyValidationInfoDTO.setApiName("api1"); apiKeyValidationInfoDTO.setApiPublisher("admin"); apiKeyValidationInfoDTO.setApiTier("Unlimited"); apiKeyValidationInfoDTO.setAuthorized(true); Mockito.when(apiKeyValidator.validateScopes(Mockito.any(TokenValidationContext.class), Mockito.anyString())) .thenReturn(true); Mockito.when(apiKeyValidator.validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(apiKeyValidationInfoDTO); AuthenticationContext authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext); Mockito.verify(apiKeyValidator) .validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); Assert.assertNotNull(authenticate); Assert.assertEquals(authenticate.getApiName(), "api1"); Assert.assertEquals(authenticate.getApiPublisher(), "admin"); Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey()); Mockito.when(gatewayTokenCache.get(signedJWT.getSignature().toString())).thenReturn("carbon.super"); Mockito.when(gatewayKeyCache.get(signedJWT.getSignature().toString())).thenReturn(jwtValidationInfo); authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext); Assert.assertNotNull(authenticate); Assert.assertEquals(authenticate.getApiName(), "api1"); Assert.assertEquals(authenticate.getApiPublisher(), "admin"); Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey()); Mockito.verify(jwtValidationService, Mockito.only()).validateJWTToken(signedJWTInfo); Mockito.verify(gatewayTokenCache, Mockito.atLeast(1)).get(signedJWT.getSignature().toString()); } @Test public void testJWTValidatorExpiredInCache() throws ParseException, APISecurityException, APIManagementException, IOException { Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("carbon.super"); SignedJWT signedJWT = SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5UZG1aak00WkRrM05qWTBZemM1T" + "W1abU9EZ3dNVEUzTVdZd05ERTVNV1JsWkRnNE56YzRaQT09In0" + ".eyJhdWQiOiJodHRwOlwvXC9vcmcud3NvMi5hcGltZ3RcL2dhdGV" + "3YXkiLCJzdWIiOiJhZG1pbkBjYXJib24uc3VwZXIiLCJhcHBsaWNhdGlvbiI6eyJvd25lciI6ImFkbWluIiwidGllclF1b3RhVHlwZ" + "SI6InJlcXVlc3RDb3VudCIsInRpZXIiOiJVbmxpbWl0ZWQiLCJuYW1lIjoiRGVmYXVsdEFwcGxpY2F0aW9uIiwiaWQiOjEsInV1aWQ" + "iOm51bGx9LCJzY29wZSI6ImFtX2FwcGxpY2F0aW9uX3Njb3BlIGRlZmF1bHQiLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0" + "NDNcL29hdXRoMlwvdG9rZW4iLCJ0aWVySW5mbyI6e30sImtleXR5cGUiOiJQUk9EVUNUSU9OIiwic3Vic2NyaWJlZEFQSXMiOltdL" + "CJjb25zdW1lcktleSI6IlhnTzM5NklIRks3ZUZZeWRycVFlNEhLR3oxa2EiLCJleHAiOjE1OTAzNDIzMTMsImlhdCI6MTU5MDMzO" + "DcxMywianRpIjoiYjg5Mzg3NjgtMjNmZC00ZGVjLThiNzAtYmVkNDVlYjdjMzNkIn0" + ".sBgeoqJn0log5EZflj_G7ADvm6B3KQ9bdfF" + "CEFVQS1U3oY9" + "-cqPwAPyOLLh95pdfjYjakkf1UtjPZjeIupwXnzg0SffIc704RoVlZocAx9Ns2XihjU6Imx2MbXq9ARmQxQkyGVkJ" + "UMTwZ8" + "-SfOnprfrhX2cMQQS8m2Lp7hcsvWFRGKxAKIeyUrbY4ihRIA5vOUrMBWYUx9Di1N7qdKA4S3e8O4KQX2VaZPBzN594c9TG" + "riiH8AuuqnrftfvidSnlRLaFJmko8-QZo8jDepwacaFhtcaPVVJFG4uYP-_" + "-N6sqfxLw3haazPN0_xU0T1zJLPRLC5HPfZMJDMGp" + "EuSe9w"); ExtendedJWTConfigurationDto jwtConfigurationDto = new ExtendedJWTConfigurationDto(); JWTValidationService jwtValidationService = Mockito.mock(JWTValidationService.class); APIKeyValidator apiKeyValidator = Mockito.mock(APIKeyValidator.class); Cache gatewayTokenCache = Mockito.mock(Cache.class); Cache invalidTokenCache = Mockito.mock(Cache.class); Cache gatewayKeyCache = Mockito.mock(Cache.class); Cache gatewayJWTTokenCache = Mockito.mock(Cache.class); JWTValidationInfo jwtValidationInfo = new JWTValidationInfo(); jwtValidationInfo.setValid(true); jwtValidationInfo.setIssuer("https://localhost"); jwtValidationInfo.setRawPayload(signedJWT.getParsedString()); jwtValidationInfo.setJti(UUID.randomUUID().toString()); jwtValidationInfo.setIssuedTime(System.currentTimeMillis()); jwtValidationInfo.setExpiryTime(System.currentTimeMillis() + 5L); jwtValidationInfo.setConsumerKey(UUID.randomUUID().toString()); jwtValidationInfo.setUser("user1"); jwtValidationInfo.setKeyManager("Default"); SignedJWTInfo signedJWTInfo = new SignedJWTInfo(signedJWT.getParsedString(), signedJWT, signedJWT.getJWTClaimsSet()); Mockito.when(jwtValidationService.validateJWTToken(signedJWTInfo)).thenReturn(jwtValidationInfo); JWTValidatorWrapper jwtValidator = new JWTValidatorWrapper("Unlimited", true, apiKeyValidator, false, null, jwtConfigurationDto, jwtValidationService, invalidTokenCache, gatewayTokenCache, gatewayKeyCache, gatewayJWTTokenCache); MessageContext messageContext = Mockito.mock(Axis2MessageContext.class); org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class); Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET"); Map<String, String> headers = new HashMap<>(); Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)) .thenReturn(headers); Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt); Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1"); Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0"); Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/pet/findByStatus"); APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class); Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.JWT_AUTHENTICATION_SUBSCRIPTION_VALIDATION)) .thenReturn("true"); jwtValidator.setApiManagerConfiguration(apiManagerConfiguration); OpenAPIParser parser = new OpenAPIParser(); String swagger = IOUtils.toString(this.getClass().getResourceAsStream("/swaggerEntry/openapi.json")); OpenAPI openAPI = parser.readContents(swagger, null, null).getOpenAPI(); APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO(); apiKeyValidationInfoDTO.setApiName("api1"); apiKeyValidationInfoDTO.setApiPublisher("admin"); apiKeyValidationInfoDTO.setApiTier("Unlimited"); apiKeyValidationInfoDTO.setAuthorized(true); Mockito.when(apiKeyValidator.validateScopes(Mockito.any(TokenValidationContext.class), Mockito.anyString())) .thenReturn(true); Mockito.when(apiKeyValidator.validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(apiKeyValidationInfoDTO); AuthenticationContext authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext); Mockito.verify(apiKeyValidator) .validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); Assert.assertNotNull(authenticate); Assert.assertEquals(authenticate.getApiName(), "api1"); Assert.assertEquals(authenticate.getApiPublisher(), "admin"); Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey()); Mockito.when(gatewayTokenCache.get(signedJWT.getJWTClaimsSet().getJWTID())).thenReturn("carbon.super"); jwtValidationInfo.setIssuedTime(System.currentTimeMillis() - 100); jwtValidationInfo.setExpiryTime(System.currentTimeMillis()); Mockito.when(gatewayKeyCache.get(signedJWT.getJWTClaimsSet().getJWTID())).thenReturn(jwtValidationInfo); try { authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext); } catch (APISecurityException e) { Assert.assertEquals(e.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS); } Mockito.verify(jwtValidationService, Mockito.only()).validateJWTToken(signedJWTInfo); Mockito.verify(gatewayTokenCache, Mockito.atLeast(1)).get(signedJWT.getJWTClaimsSet().getJWTID()); Mockito.verify(invalidTokenCache, Mockito.times(1)).put(signedJWT.getJWTClaimsSet().getJWTID(), "carbon.super"); } @Test public void testJWTValidatorExpiredInCacheTenant() throws ParseException, APISecurityException, APIManagementException, IOException { Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("abc.com"); SignedJWT signedJWT = SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5UZG1aak00WkRrM05qWTBZemM1T" + "W1abU9EZ3dNVEUzTVdZd05ERTVNV1JsWkRnNE56YzRaQT09In0" + ".eyJhdWQiOiJodHRwOlwvXC9vcmcud3NvMi5hcGltZ3RcL2dhdGV" + "3YXkiLCJzdWIiOiJhZG1pbkBjYXJib24uc3VwZXIiLCJhcHBsaWNhdGlvbiI6eyJvd25lciI6ImFkbWluIiwidGllclF1b3RhVHlwZ" + "SI6InJlcXVlc3RDb3VudCIsInRpZXIiOiJVbmxpbWl0ZWQiLCJuYW1lIjoiRGVmYXVsdEFwcGxpY2F0aW9uIiwiaWQiOjEsInV1aWQ" + "iOm51bGx9LCJzY29wZSI6ImFtX2FwcGxpY2F0aW9uX3Njb3BlIGRlZmF1bHQiLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0" + "NDNcL29hdXRoMlwvdG9rZW4iLCJ0aWVySW5mbyI6e30sImtleXR5cGUiOiJQUk9EVUNUSU9OIiwic3Vic2NyaWJlZEFQSXMiOltdL" + "CJjb25zdW1lcktleSI6IlhnTzM5NklIRks3ZUZZeWRycVFlNEhLR3oxa2EiLCJleHAiOjE1OTAzNDIzMTMsImlhdCI6MTU5MDMzO" + "DcxMywianRpIjoiYjg5Mzg3NjgtMjNmZC00ZGVjLThiNzAtYmVkNDVlYjdjMzNkIn0" + ".sBgeoqJn0log5EZflj_G7ADvm6B3KQ9bdfF" + "CEFVQS1U3oY9" + "-cqPwAPyOLLh95pdfjYjakkf1UtjPZjeIupwXnzg0SffIc704RoVlZocAx9Ns2XihjU6Imx2MbXq9ARmQxQkyGVkJ" + "UMTwZ8" + "-SfOnprfrhX2cMQQS8m2Lp7hcsvWFRGKxAKIeyUrbY4ihRIA5vOUrMBWYUx9Di1N7qdKA4S3e8O4KQX2VaZPBzN594c9TG" + "riiH8AuuqnrftfvidSnlRLaFJmko8-QZo8jDepwacaFhtcaPVVJFG4uYP-_" + "-N6sqfxLw3haazPN0_xU0T1zJLPRLC5HPfZMJDMGp" + "EuSe9w"); ExtendedJWTConfigurationDto jwtConfigurationDto = new ExtendedJWTConfigurationDto(); JWTValidationService jwtValidationService = Mockito.mock(JWTValidationService.class); APIKeyValidator apiKeyValidator = Mockito.mock(APIKeyValidator.class); Cache gatewayTokenCache = Mockito.mock(Cache.class); Cache invalidTokenCache = Mockito.mock(Cache.class); Cache gatewayKeyCache = Mockito.mock(Cache.class); Cache gatewayJWTTokenCache = Mockito.mock(Cache.class); JWTValidationInfo jwtValidationInfo = new JWTValidationInfo(); jwtValidationInfo.setValid(true); jwtValidationInfo.setIssuer("https://localhost"); jwtValidationInfo.setRawPayload(signedJWT.getParsedString()); jwtValidationInfo.setJti(UUID.randomUUID().toString()); jwtValidationInfo.setIssuedTime(System.currentTimeMillis()); jwtValidationInfo.setExpiryTime(System.currentTimeMillis() + 5L); jwtValidationInfo.setConsumerKey(UUID.randomUUID().toString()); jwtValidationInfo.setUser("user1"); jwtValidationInfo.setKeyManager("Default"); SignedJWTInfo signedJWTInfo = new SignedJWTInfo(signedJWT.getParsedString(), signedJWT, signedJWT.getJWTClaimsSet()); Mockito.when(jwtValidationService.validateJWTToken(signedJWTInfo)).thenReturn(jwtValidationInfo); JWTValidatorWrapper jwtValidator = new JWTValidatorWrapper("Unlimited", true, apiKeyValidator, false, null, jwtConfigurationDto, jwtValidationService, invalidTokenCache, gatewayTokenCache, gatewayKeyCache, gatewayJWTTokenCache); MessageContext messageContext = Mockito.mock(Axis2MessageContext.class); org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class); Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET"); Map<String, String> headers = new HashMap<>(); Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)) .thenReturn(headers); Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt); Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1"); Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0"); Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/pet/findByStatus"); APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class); Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.JWT_AUTHENTICATION_SUBSCRIPTION_VALIDATION)) .thenReturn("true"); jwtValidator.setApiManagerConfiguration(apiManagerConfiguration); APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO(); apiKeyValidationInfoDTO.setApiName("api1"); apiKeyValidationInfoDTO.setApiPublisher("admin"); apiKeyValidationInfoDTO.setApiTier("Unlimited"); apiKeyValidationInfoDTO.setAuthorized(true); Mockito.when(apiKeyValidator.validateScopes(Mockito.any(TokenValidationContext.class), Mockito.anyString())) .thenReturn(true); Mockito.when(apiKeyValidator.validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(apiKeyValidationInfoDTO); AuthenticationContext authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext); Mockito.verify(apiKeyValidator) .validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); Assert.assertNotNull(authenticate); Assert.assertEquals(authenticate.getApiName(), "api1"); Assert.assertEquals(authenticate.getApiPublisher(), "admin"); Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey()); Mockito.when(gatewayTokenCache.get(signedJWT.getJWTClaimsSet().getJWTID())).thenReturn("abc.com"); jwtValidationInfo.setIssuedTime(System.currentTimeMillis() - 100); jwtValidationInfo.setExpiryTime(System.currentTimeMillis()); Mockito.when(gatewayKeyCache.get(signedJWT.getJWTClaimsSet().getJWTID())).thenReturn(jwtValidationInfo); try { authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext); } catch (APISecurityException e) { Assert.assertEquals(e.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS); } Mockito.verify(jwtValidationService, Mockito.only()).validateJWTToken(signedJWTInfo); Mockito.verify(gatewayTokenCache, Mockito.atLeast(1)).get(signedJWT.getJWTClaimsSet().getJWTID()); Mockito.verify(invalidTokenCache, Mockito.times(1)).put(signedJWT.getJWTClaimsSet().getJWTID(), "abc.com"); } @Test public void testJWTValidatorTenant() throws ParseException, APISecurityException, APIManagementException, IOException { Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("abc.com"); SignedJWT signedJWT = SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5UZG1aak00WkRrM05qWTBZemM1T" + "W1abU9EZ3dNVEUzTVdZd05ERTVNV1JsWkRnNE56YzRaQT09In0" + ".eyJhdWQiOiJodHRwOlwvXC9vcmcud3NvMi5hcGltZ3RcL2dhdGV" + "3YXkiLCJzdWIiOiJhZG1pbkBjYXJib24uc3VwZXIiLCJhcHBsaWNhdGlvbiI6eyJvd25lciI6ImFkbWluIiwidGllclF1b3RhVHlwZ" + "SI6InJlcXVlc3RDb3VudCIsInRpZXIiOiJVbmxpbWl0ZWQiLCJuYW1lIjoiRGVmYXVsdEFwcGxpY2F0aW9uIiwiaWQiOjEsInV1aWQ" + "iOm51bGx9LCJzY29wZSI6ImFtX2FwcGxpY2F0aW9uX3Njb3BlIGRlZmF1bHQiLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0" + "NDNcL29hdXRoMlwvdG9rZW4iLCJ0aWVySW5mbyI6e30sImtleXR5cGUiOiJQUk9EVUNUSU9OIiwic3Vic2NyaWJlZEFQSXMiOltdL" + "CJjb25zdW1lcktleSI6IlhnTzM5NklIRks3ZUZZeWRycVFlNEhLR3oxa2EiLCJleHAiOjE1OTAzNDIzMTMsImlhdCI6MTU5MDMzO" + "DcxMywianRpIjoiYjg5Mzg3NjgtMjNmZC00ZGVjLThiNzAtYmVkNDVlYjdjMzNkIn0" + ".sBgeoqJn0log5EZflj_G7ADvm6B3KQ9bdfF" + "CEFVQS1U3oY9" + "-cqPwAPyOLLh95pdfjYjakkf1UtjPZjeIupwXnzg0SffIc704RoVlZocAx9Ns2XihjU6Imx2MbXq9ARmQxQkyGVkJ" + "UMTwZ8" + "-SfOnprfrhX2cMQQS8m2Lp7hcsvWFRGKxAKIeyUrbY4ihRIA5vOUrMBWYUx9Di1N7qdKA4S3e8O4KQX2VaZPBzN594c9TG" + "riiH8AuuqnrftfvidSnlRLaFJmko8-QZo8jDepwacaFhtcaPVVJFG4uYP-_" + "-N6sqfxLw3haazPN0_xU0T1zJLPRLC5HPfZMJDMGp" + "EuSe9w"); SignedJWTInfo signedJWTInfo = new SignedJWTInfo(signedJWT.getParsedString(), signedJWT, signedJWT.getJWTClaimsSet()); ExtendedJWTConfigurationDto jwtConfigurationDto = new ExtendedJWTConfigurationDto(); JWTValidationService jwtValidationService = Mockito.mock(JWTValidationService.class); APIKeyValidator apiKeyValidator = Mockito.mock(APIKeyValidator.class); Cache gatewayTokenCache = Mockito.mock(Cache.class); Cache invalidTokenCache = Mockito.mock(Cache.class); Cache gatewayKeyCache = Mockito.mock(Cache.class); Cache gatewayJWTTokenCache = Mockito.mock(Cache.class); JWTValidationInfo jwtValidationInfo = new JWTValidationInfo(); jwtValidationInfo.setValid(true); jwtValidationInfo.setIssuer("https://localhost"); jwtValidationInfo.setRawPayload(signedJWT.getParsedString()); jwtValidationInfo.setJti(UUID.randomUUID().toString()); jwtValidationInfo.setIssuedTime(System.currentTimeMillis()); jwtValidationInfo.setExpiryTime(System.currentTimeMillis() + 5000L); jwtValidationInfo.setConsumerKey(UUID.randomUUID().toString()); jwtValidationInfo.setUser("user1"); jwtValidationInfo.setKeyManager("Default"); Mockito.when(jwtValidationService.validateJWTToken(signedJWTInfo)).thenReturn(jwtValidationInfo); JWTValidatorWrapper jwtValidator = new JWTValidatorWrapper("Unlimited", true, apiKeyValidator, false, null, jwtConfigurationDto, jwtValidationService, invalidTokenCache, gatewayTokenCache, gatewayKeyCache, gatewayJWTTokenCache); MessageContext messageContext = Mockito.mock(Axis2MessageContext.class); org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class); Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET"); Map<String, String> headers = new HashMap<>(); Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)) .thenReturn(headers); Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt); Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1"); Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0"); Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/pet/findByStatus"); APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class); Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.JWT_AUTHENTICATION_SUBSCRIPTION_VALIDATION)) .thenReturn("true"); jwtValidator.setApiManagerConfiguration(apiManagerConfiguration); APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO(); apiKeyValidationInfoDTO.setApiName("api1"); apiKeyValidationInfoDTO.setApiPublisher("admin"); apiKeyValidationInfoDTO.setApiTier("Unlimited"); apiKeyValidationInfoDTO.setAuthorized(true); Mockito.when(apiKeyValidator.validateScopes(Mockito.any(TokenValidationContext.class), Mockito.anyString())) .thenReturn(true); Mockito.when(apiKeyValidator.validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(apiKeyValidationInfoDTO); AuthenticationContext authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext); Mockito.verify(apiKeyValidator) .validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); Assert.assertNotNull(authenticate); Assert.assertEquals(authenticate.getApiName(), "api1"); Assert.assertEquals(authenticate.getApiPublisher(), "admin"); Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey()); Mockito.when(gatewayTokenCache.get(signedJWT.getJWTClaimsSet().getJWTID())).thenReturn("carbon.super"); Mockito.when(gatewayKeyCache.get(signedJWT.getJWTClaimsSet().getJWTID())).thenReturn(jwtValidationInfo); authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext); Assert.assertNotNull(authenticate); Assert.assertEquals(authenticate.getApiName(), "api1"); Assert.assertEquals(authenticate.getApiPublisher(), "admin"); Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey()); Mockito.verify(jwtValidationService, Mockito.only()).validateJWTToken(signedJWTInfo); Mockito.verify(gatewayTokenCache, Mockito.atLeast(1)).get(signedJWT.getJWTClaimsSet().getJWTID()); } @Test public void testJWTValidatorInvalid() throws ParseException, APIManagementException, IOException, APISecurityException { Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("abc.com"); SignedJWT signedJWT = SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5UZG1aak00WkRrM05qWTBZemM1T" + "W1abU9EZ3dNVEUzTVdZd05ERTVNV1JsWkRnNE56YzRaQT09In0" + ".eyJhdWQiOiJodHRwOlwvXC9vcmcud3NvMi5hcGltZ3RcL2dhdGV" + "3YXkiLCJzdWIiOiJhZG1pbkBjYXJib24uc3VwZXIiLCJhcHBsaWNhdGlvbiI6eyJvd25lciI6ImFkbWluIiwidGllclF1b3RhVHlwZ" + "SI6InJlcXVlc3RDb3VudCIsInRpZXIiOiJVbmxpbWl0ZWQiLCJuYW1lIjoiRGVmYXVsdEFwcGxpY2F0aW9uIiwiaWQiOjEsInV1aWQ" + "iOm51bGx9LCJzY29wZSI6ImFtX2FwcGxpY2F0aW9uX3Njb3BlIGRlZmF1bHQiLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0" + "NDNcL29hdXRoMlwvdG9rZW4iLCJ0aWVySW5mbyI6e30sImtleXR5cGUiOiJQUk9EVUNUSU9OIiwic3Vic2NyaWJlZEFQSXMiOltdL" + "CJjb25zdW1lcktleSI6IlhnTzM5NklIRks3ZUZZeWRycVFlNEhLR3oxa2EiLCJleHAiOjE1OTAzNDIzMTMsImlhdCI6MTU5MDMzO" + "DcxMywianRpIjoiYjg5Mzg3NjgtMjNmZC00ZGVjLThiNzAtYmVkNDVlYjdjMzNkIn0" + ".sBgeoqJn0log5EZflj_G7ADvm6B3KQ9bdfF" + "CEFVQS1U3oY9" + "-cqPwAPyOLLh95pdfjYjakkf1UtjPZjeIupwXnzg0SffIc704RoVlZocAx9Ns2XihjU6Imx2MbXq9ARmQxQkyGVkJ" + "UMTwZ8" + "-SfOnprfrhX2cMQQS8m2Lp7hcsvWFRGKxAKIeyUrbY4ihRIA5vOUrMBWYUx9Di1N7qdKA4S3e8O4KQX2VaZPBzN594c9TG" + "riiH8AuuqnrftfvidSnlRLaFJmko8-QZo8jDepwacaFhtcaPVVJFG4uYP-_" + "-N6sqfxLw3haazPN0_xU0T1zJLPRLC5HPfZMJDMGp" + "EuSe9w"); SignedJWTInfo signedJWTInfo = new SignedJWTInfo(signedJWT.getParsedString(), signedJWT, signedJWT.getJWTClaimsSet()); ExtendedJWTConfigurationDto jwtConfigurationDto = new ExtendedJWTConfigurationDto(); JWTValidationService jwtValidationService = Mockito.mock(JWTValidationService.class); APIKeyValidator apiKeyValidator = Mockito.mock(APIKeyValidator.class); Cache gatewayTokenCache = Mockito.mock(Cache.class); Cache invalidTokenCache = Mockito.mock(Cache.class); Cache gatewayKeyCache = Mockito.mock(Cache.class); Cache gatewayJWTTokenCache = Mockito.mock(Cache.class); JWTValidationInfo jwtValidationInfo = new JWTValidationInfo(); jwtValidationInfo.setValid(false); jwtValidationInfo.setIssuer("https://localhost"); jwtValidationInfo.setRawPayload(signedJWT.getParsedString()); jwtValidationInfo.setJti(UUID.randomUUID().toString()); jwtValidationInfo.setConsumerKey(UUID.randomUUID().toString()); jwtValidationInfo.setValidationCode(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS); jwtValidationInfo.setUser("user1"); jwtValidationInfo.setKeyManager("Default"); Mockito.when(jwtValidationService.validateJWTToken(signedJWTInfo)).thenReturn(jwtValidationInfo); JWTValidatorWrapper jwtValidator = new JWTValidatorWrapper("Unlimited", true, apiKeyValidator, false, null, jwtConfigurationDto, jwtValidationService, invalidTokenCache, gatewayTokenCache, gatewayKeyCache, gatewayJWTTokenCache); MessageContext messageContext = Mockito.mock(Axis2MessageContext.class); org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class); Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET"); Map<String, String> headers = new HashMap<>(); Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)) .thenReturn(headers); Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt); Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1"); Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0"); Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/pet/findByStatus"); APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class); Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.JWT_AUTHENTICATION_SUBSCRIPTION_VALIDATION)) .thenReturn("true"); jwtValidator.setApiManagerConfiguration(apiManagerConfiguration); OpenAPIParser parser = new OpenAPIParser(); String swagger = IOUtils.toString(this.getClass().getResourceAsStream("/swaggerEntry/openapi.json")); OpenAPI openAPI = parser.readContents(swagger, null, null).getOpenAPI(); APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO(); apiKeyValidationInfoDTO.setApiName("api1"); apiKeyValidationInfoDTO.setApiPublisher("admin"); apiKeyValidationInfoDTO.setApiTier("Unlimited"); apiKeyValidationInfoDTO.setAuthorized(true); try { AuthenticationContext authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext); Assert.fail("JWT get Authenticated"); } catch (APISecurityException e) { Assert.assertEquals(e.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS); } Mockito.when(invalidTokenCache.get(signedJWT.getJWTClaimsSet().getJWTID())).thenReturn("carbon.super"); String cacheKey = GatewayUtils .getAccessTokenCacheKey(signedJWT.getJWTClaimsSet().getJWTID(), "/api1", "1.0", "/pet/findByStatus", "GET"); try { jwtValidator.authenticate(signedJWTInfo, messageContext); } catch (APISecurityException e) { Assert.assertEquals(e.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS); } Mockito.verify(apiKeyValidator, Mockito.never()) .validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); Mockito.verify(gatewayTokenCache, Mockito.atLeast(1)).get(signedJWT.getJWTClaimsSet().getJWTID()); Mockito.verify(gatewayKeyCache, Mockito.never()).get(cacheKey); } @Test public void testJWTValidatorInvalidConsumerKey() throws ParseException, APIManagementException, IOException, APISecurityException { Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("carbon.super"); SignedJWT signedJWT = SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5UZG1aak00WkRrM05qWTBZemM1T" + "W1abU9EZ3dNVEUzTVdZd05ERTVNV1JsWkRnNE56YzRaQT09In0" + ".eyJhdWQiOiJodHRwOlwvXC9vcmcud3NvMi5hcGltZ3RcL2dhdGV" + "3YXkiLCJzdWIiOiJhZG1pbkBjYXJib24uc3VwZXIiLCJhcHBsaWNhdGlvbiI6eyJvd25lciI6ImFkbWluIiwidGllclF1b3RhVHlwZ" + "SI6InJlcXVlc3RDb3VudCIsInRpZXIiOiJVbmxpbWl0ZWQiLCJuYW1lIjoiRGVmYXVsdEFwcGxpY2F0aW9uIiwiaWQiOjEsInV1aWQ" + "iOm51bGx9LCJzY29wZSI6ImFtX2FwcGxpY2F0aW9uX3Njb3BlIGRlZmF1bHQiLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0" + "NDNcL29hdXRoMlwvdG9rZW4iLCJ0aWVySW5mbyI6e30sImtleXR5cGUiOiJQUk9EVUNUSU9OIiwic3Vic2NyaWJlZEFQSXMiOltdL" + "CJjb25zdW1lcktleSI6IlhnTzM5NklIRks3ZUZZeWRycVFlNEhLR3oxa2EiLCJleHAiOjE1OTAzNDIzMTMsImlhdCI6MTU5MDMzO" + "DcxMywianRpIjoiYjg5Mzg3NjgtMjNmZC00ZGVjLThiNzAtYmVkNDVlYjdjMzNkIn0" + ".sBgeoqJn0log5EZflj_G7ADvm6B3KQ9bdfF" + "CEFVQS1U3oY9" + "-cqPwAPyOLLh95pdfjYjakkf1UtjPZjeIupwXnzg0SffIc704RoVlZocAx9Ns2XihjU6Imx2MbXq9ARmQxQkyGVkJ" + "UMTwZ8" + "-SfOnprfrhX2cMQQS8m2Lp7hcsvWFRGKxAKIeyUrbY4ihRIA5vOUrMBWYUx9Di1N7qdKA4S3e8O4KQX2VaZPBzN594c9TG" + "riiH8AuuqnrftfvidSnlRLaFJmko8-QZo8jDepwacaFhtcaPVVJFG4uYP-_" + "-N6sqfxLw3haazPN0_xU0T1zJLPRLC5HPfZMJDMGp" + "EuSe9w"); SignedJWTInfo signedJWTInfo = new SignedJWTInfo(signedJWT.getParsedString(), signedJWT, signedJWT.getJWTClaimsSet()); ExtendedJWTConfigurationDto jwtConfigurationDto = new ExtendedJWTConfigurationDto(); JWTValidationService jwtValidationService = Mockito.mock(JWTValidationService.class); APIKeyValidator apiKeyValidator = Mockito.mock(APIKeyValidator.class); Cache gatewayTokenCache = Mockito.mock(Cache.class); Cache invalidTokenCache = Mockito.mock(Cache.class); Cache gatewayKeyCache = Mockito.mock(Cache.class); Cache gatewayJWTTokenCache = Mockito.mock(Cache.class); JWTValidationInfo jwtValidationInfo = new JWTValidationInfo(); jwtValidationInfo.setValid(true); jwtValidationInfo.setIssuer("https://localhost"); jwtValidationInfo.setRawPayload(signedJWT.getParsedString()); jwtValidationInfo.setJti(UUID.randomUUID().toString()); jwtValidationInfo.setConsumerKey(UUID.randomUUID().toString()); jwtValidationInfo.setUser("user1"); jwtValidationInfo.setKeyManager("Default"); Mockito.when(jwtValidationService.validateJWTToken(signedJWTInfo)).thenReturn(jwtValidationInfo); JWTValidatorWrapper jwtValidator = new JWTValidatorWrapper("Unlimited", true, apiKeyValidator, false, null, jwtConfigurationDto, jwtValidationService, invalidTokenCache, gatewayTokenCache, gatewayKeyCache, gatewayJWTTokenCache); MessageContext messageContext = Mockito.mock(Axis2MessageContext.class); org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class); Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET"); Map<String, String> headers = new HashMap<>(); Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)) .thenReturn(headers); Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt); Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1"); Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0"); Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/pet/findByStatus"); APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class); Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.JWT_AUTHENTICATION_SUBSCRIPTION_VALIDATION)) .thenReturn("true"); jwtValidator.setApiManagerConfiguration(apiManagerConfiguration); OpenAPIParser parser = new OpenAPIParser(); String swagger = IOUtils.toString(this.getClass().getResourceAsStream("/swaggerEntry/openapi.json")); OpenAPI openAPI = parser.readContents(swagger, null, null).getOpenAPI(); APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO(); apiKeyValidationInfoDTO.setAuthorized(false); apiKeyValidationInfoDTO.setValidationStatus( APIConstants.KeyValidationStatus.API_AUTH_RESOURCE_FORBIDDEN); Mockito.when(apiKeyValidator.validateScopes(Mockito.any(TokenValidationContext.class), Mockito.anyString())) .thenReturn(true); Mockito.when(apiKeyValidator.validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString() , Mockito.anyString(), Mockito.anyString())).thenReturn(apiKeyValidationInfoDTO); try { jwtValidator.authenticate(signedJWTInfo, messageContext); Assert.fail("JWT get Authenticated"); } catch (APISecurityException e) { Assert.assertEquals(e.getErrorCode(), APISecurityConstants.API_AUTH_FORBIDDEN); } } @Test public void testJWTValidatorForTamperedPayload() throws ParseException, APISecurityException, APIManagementException, IOException { Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("carbon.super"); SignedJWT signedJWT = SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5UZG1aak00WkRrM05qWTBZemM1T" + "W1abU9EZ3dNVEUzTVdZd05ERTVNV1JsWkRnNE56YzRaQT09In0" + ".eyJhdWQiOiJodHRwOlwvXC9vcmcud3NvMi5hcGltZ3RcL2dhdGV" + "3YXkiLCJzdWIiOiJhZG1pbkBjYXJib24uc3VwZXIiLCJhcHBsaWNhdGlvbiI6eyJvd25lciI6ImFkbWluIiwidGllclF1b3RhVHlwZ" + "SI6InJlcXVlc3RDb3VudCIsInRpZXIiOiJVbmxpbWl0ZWQiLCJuYW1lIjoiRGVmYXVsdEFwcGxpY2F0aW9uIiwiaWQiOjEsInV1aWQ" + "iOm51bGx9LCJzY29wZSI6ImFtX2FwcGxpY2F0aW9uX3Njb3BlIGRlZmF1bHQiLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0" + "NDNcL29hdXRoMlwvdG9rZW4iLCJ0aWVySW5mbyI6e30sImtleXR5cGUiOiJQUk9EVUNUSU9OIiwic3Vic2NyaWJlZEFQSXMiOltdL" + "CJjb25zdW1lcktleSI6IlhnTzM5NklIRks3ZUZZeWRycVFlNEhLR3oxa2EiLCJleHAiOjE1OTAzNDIzMTMsImlhdCI6MTU5MDMzO" + "DcxMywianRpIjoiYjg5Mzg3NjgtMjNmZC00ZGVjLThiNzAtYmVkNDVlYjdjMzNkIn0" + ".sBgeoqJn0log5EZflj_G7ADvm6B3KQ9bdfF" + "CEFVQS1U3oY9" + "-cqPwAPyOLLh95pdfjYjakkf1UtjPZjeIupwXnzg0SffIc704RoVlZocAx9Ns2XihjU6Imx2MbXq9ARmQxQkyGVkJ" + "UMTwZ8" + "-SfOnprfrhX2cMQQS8m2Lp7hcsvWFRGKxAKIeyUrbY4ihRIA5vOUrMBWYUx9Di1N7qdKA4S3e8O4KQX2VaZPBzN594c9TG" + "riiH8AuuqnrftfvidSnlRLaFJmko8-QZo8jDepwacaFhtcaPVVJFG4uYP-_" + "-N6sqfxLw3haazPN0_xU0T1zJLPRLC5HPfZMJDMGp" + "EuSe9w"); SignedJWT signedJWTTampered = SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5UZG1aak00WkRrM05qWTBZemM1T" + "W1abU9EZ3dNVEUzTVdZd05ERTVNV1JsWkRnNE56YzRaQT09In0" + ".ewogICJhdWQiOiAiaHR0cDovL29yZy53c28yLmFwaW1ndC9nYXRld2F5IiwKICAic3ViIjogImFkbWluQGNhcm" + "Jvbi5zdXBlciIsCiAgImFwcGxpY2F0aW9uIjogewogICAgIm93bmVyIjogImFkbWluIiwKICAgICJ0aWVyUXVvd" + "GFUeXBlIjogInJlcXVlc3RDb3VudCIsCiAgICAidGllciI6ICJVbmxpbWl0ZWQiLAogICAgIm5hbWUiOiAiRGVm" + "YXVsdEFwcGxpY2F0aW9uMiIsCiAgICAiaWQiOiAyLAogICAgInV1aWQiOiBudWxsCiAgfSwKICAic2NvcGUiOiA" + "iYW1fYXBwbGljYXRpb25fc2NvcGUgZGVmYXVsdCIsCiAgImlzcyI6ICJodHRwczovL2xvY2FsaG9zdDo5NDQzL2" + "9hdXRoMi90b2tlbiIsCiAgInRpZXJJbmZvIjoge30sCiAgImtleXR5cGUiOiAiUFJPRFVDVElPTiIsCiAgInN1Y" + "nNjcmliZWRBUElzIjogW10sCiAgImNvbnN1bWVyS2V5IjogIlhnTzM5NklIRks3ZUZZeWRycVFlNEhLR3oxa2Ei" + "LAogICJleHAiOiAxNTkwMzQyMzEzLAogICJpYXQiOiAxNTkwMzM4NzEzLAogICJqdGkiOiAiYjg5Mzg3NjgtMjN" + "mZC00ZGVjLThiNzAtYmVkNDVlYjdjMzNkIgp9" + ".sBgeoqJn0log5EZflj_G7ADvm6B3KQ9bdfF" + "CEFVQS1U3oY9" + "-cqPwAPyOLLh95pdfjYjakkf1UtjPZjeIupwXnzg0SffIc704RoVlZocAx9Ns2XihjU6Imx2MbXq9ARmQxQkyGVkJ" + "UMTwZ8" + "-SfOnprfrhX2cMQQS8m2Lp7hcsvWFRGKxAKIeyUrbY4ihRIA5vOUrMBWYUx9Di1N7qdKA4S3e8O4KQX2VaZPBzN594c9TG" + "riiH8AuuqnrftfvidSnlRLaFJmko8-QZo8jDepwacaFhtcaPVVJFG4uYP-_" + "-N6sqfxLw3haazPN0_xU0T1zJLPRLC5HPfZMJDMGp" + "EuSe9w"); testTamperedTokens(signedJWT, signedJWTTampered); } @Test public void testJWTValidatorForTamperedSignature() throws ParseException, APISecurityException, APIManagementException, IOException { Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("carbon.super"); SignedJWT signedJWT = SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5UZG1aak00WkRrM05qWTBZemM1T" + "W1abU9EZ3dNVEUzTVdZd05ERTVNV1JsWkRnNE56YzRaQT09In0" + ".eyJhdWQiOiJodHRwOlwvXC9vcmcud3NvMi5hcGltZ3RcL2dhdGV" + "3YXkiLCJzdWIiOiJhZG1pbkBjYXJib24uc3VwZXIiLCJhcHBsaWNhdGlvbiI6eyJvd25lciI6ImFkbWluIiwidGllclF1b3RhVHlwZ" + "SI6InJlcXVlc3RDb3VudCIsInRpZXIiOiJVbmxpbWl0ZWQiLCJuYW1lIjoiRGVmYXVsdEFwcGxpY2F0aW9uIiwiaWQiOjEsInV1aWQ" + "iOm51bGx9LCJzY29wZSI6ImFtX2FwcGxpY2F0aW9uX3Njb3BlIGRlZmF1bHQiLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0" + "NDNcL29hdXRoMlwvdG9rZW4iLCJ0aWVySW5mbyI6e30sImtleXR5cGUiOiJQUk9EVUNUSU9OIiwic3Vic2NyaWJlZEFQSXMiOltdL" + "CJjb25zdW1lcktleSI6IlhnTzM5NklIRks3ZUZZeWRycVFlNEhLR3oxa2EiLCJleHAiOjE1OTAzNDIzMTMsImlhdCI6MTU5MDMzO" + "DcxMywianRpIjoiYjg5Mzg3NjgtMjNmZC00ZGVjLThiNzAtYmVkNDVlYjdjMzNkIn0" + ".sBgeoqJn0log5EZflj_G7ADvm6B3KQ9bdfF" + "CEFVQS1U3oY9" + "-cqPwAPyOLLh95pdfjYjakkf1UtjPZjeIupwXnzg0SffIc704RoVlZocAx9Ns2XihjU6Imx2MbXq9ARmQxQkyGVkJ" + "UMTwZ8" + "-SfOnprfrhX2cMQQS8m2Lp7hcsvWFRGKxAKIeyUrbY4ihRIA5vOUrMBWYUx9Di1N7qdKA4S3e8O4KQX2VaZPBzN594c9TG" + "riiH8AuuqnrftfvidSnlRLaFJmko8-QZo8jDepwacaFhtcaPVVJFG4uYP-_" + "-N6sqfxLw3haazPN0_xU0T1zJLPRLC5HPfZMJDMGp" + "EuSe9w"); SignedJWT signedJWTTampered = SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5UZG1aak00WkRrM05qWTBZemM1T" + "W1abU9EZ3dNVEUzTVdZd05ERTVNV1JsWkRnNE56YzRaQT09In0" + ".eyJhdWQiOiJodHRwOlwvXC9vcmcud3NvMi5hcGltZ3RcL2dhdGV" + "3YXkiLCJzdWIiOiJhZG1pbkBjYXJib24uc3VwZXIiLCJhcHBsaWNhdGlvbiI6eyJvd25lciI6ImFkbWluIiwidGllclF1b3RhVHlwZ" + "SI6InJlcXVlc3RDb3VudCIsInRpZXIiOiJVbmxpbWl0ZWQiLCJuYW1lIjoiRGVmYXVsdEFwcGxpY2F0aW9uIiwiaWQiOjEsInV1aWQ" + "iOm51bGx9LCJzY29wZSI6ImFtX2FwcGxpY2F0aW9uX3Njb3BlIGRlZmF1bHQiLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0" + "NDNcL29hdXRoMlwvdG9rZW4iLCJ0aWVySW5mbyI6e30sImtleXR5cGUiOiJQUk9EVUNUSU9OIiwic3Vic2NyaWJlZEFQSXMiOltdL" + "CJjb25zdW1lcktleSI6IlhnTzM5NklIRks3ZUZZeWRycVFlNEhLR3oxa2EiLCJleHAiOjE1OTAzNDIzMTMsImlhdCI6MTU5MDMzO" + "DcxMywianRpIjoiYjg5Mzg3NjgtMjNmZC00ZGVjLThiNzAtYmVkNDVlYjdjMzNkIn0" + ".sBgeoqJn0log5EZflj_G7ADvm6B3KQ9bdfF" + "CEFVQS1U3oY9" + "-cqPwAPyOLLh95pdfjYjakkf1UtjPZjeIupwXnzg0SffIc704RoVlZocAx9Ns2XihjU6Imx2MbXq9ARmQxQkyGVkJ" + "UMTwZ8" + "-SfOnprfrhX2cMQQS8m2Lp7hcsvWFRGKxAKIeyUrbY4ihRIA5vOUrMBWYUx9Di1N7qdKA4S3e8O4KQX2VaZPBzN594c9TG" + "riiH8AuuqnrftfvidSnlRLaFJmko8-QZo8jDepwacaFhtcaPVVJFG4uYP-_" + "-N6sqfxLw3haazPN0_xU0T1zJLPRLC5HPfZMJDMGp" + "XXXXX"); testTamperedTokens(signedJWT, signedJWTTampered); } private void testTamperedTokens(SignedJWT originalToken, SignedJWT tamperedToken) throws ParseException, APIManagementException, APISecurityException { ExtendedJWTConfigurationDto jwtConfigurationDto = new ExtendedJWTConfigurationDto(); JWTValidationService jwtValidationService = Mockito.mock(JWTValidationService.class); APIKeyValidator apiKeyValidator = Mockito.mock(APIKeyValidator.class); Cache gatewayTokenCache = Mockito.mock(Cache.class); Cache invalidTokenCache = Mockito.mock(Cache.class); Cache gatewayKeyCache = Mockito.mock(Cache.class); Cache gatewayJWTTokenCache = Mockito.mock(Cache.class); JWTValidationInfo jwtValidationInfo = new JWTValidationInfo(); jwtValidationInfo.setValid(true); jwtValidationInfo.setIssuer("https://localhost"); jwtValidationInfo.setRawPayload(originalToken.getParsedString()); jwtValidationInfo.setJti(UUID.randomUUID().toString()); jwtValidationInfo.setIssuedTime(System.currentTimeMillis()); jwtValidationInfo.setExpiryTime(System.currentTimeMillis() + 5000000L); jwtValidationInfo.setConsumerKey(UUID.randomUUID().toString()); jwtValidationInfo.setUser("user1"); jwtValidationInfo.setKeyManager("Default"); SignedJWTInfo signedJWTInfo = new SignedJWTInfo(originalToken.getParsedString(), originalToken, originalToken.getJWTClaimsSet()); SignedJWTInfo signedJWTInfoTampered = new SignedJWTInfo(tamperedToken.getParsedString(), tamperedToken, tamperedToken.getJWTClaimsSet()); Mockito.when(jwtValidationService.validateJWTToken(signedJWTInfo)).thenReturn(jwtValidationInfo); JWTValidatorWrapper jwtValidator = new JWTValidatorWrapper("Unlimited", true, apiKeyValidator, false, null, jwtConfigurationDto, jwtValidationService, invalidTokenCache, gatewayTokenCache, gatewayKeyCache, gatewayJWTTokenCache); MessageContext messageContext = Mockito.mock(Axis2MessageContext.class); org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class); Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET"); Map<String, String> headers = new HashMap<>(); Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)) .thenReturn(headers); Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt); Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1"); Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0"); Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/pet/findByStatus"); APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class); Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.JWT_AUTHENTICATION_SUBSCRIPTION_VALIDATION)) .thenReturn("true"); jwtValidator.setApiManagerConfiguration(apiManagerConfiguration); APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO(); apiKeyValidationInfoDTO.setApiName("api1"); apiKeyValidationInfoDTO.setApiPublisher("admin"); apiKeyValidationInfoDTO.setApiTier("Unlimited"); apiKeyValidationInfoDTO.setAuthorized(true); Mockito.when(apiKeyValidator.validateScopes(Mockito.any(TokenValidationContext.class), Mockito.anyString())) .thenReturn(true); Mockito.when(apiKeyValidator.validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(apiKeyValidationInfoDTO); AuthenticationContext authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext); Mockito.verify(apiKeyValidator) .validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); Assert.assertNotNull(authenticate); Assert.assertEquals(authenticate.getApiName(), "api1"); Assert.assertEquals(authenticate.getApiPublisher(), "admin"); Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey()); Mockito.when(gatewayTokenCache.get(originalToken.getJWTClaimsSet().getJWTID())).thenReturn("carbon.super"); Mockito.when(gatewayKeyCache.get(originalToken.getJWTClaimsSet().getJWTID())).thenReturn(jwtValidationInfo); authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext); Assert.assertNotNull(authenticate); Assert.assertEquals(authenticate.getApiName(), "api1"); Assert.assertEquals(authenticate.getApiPublisher(), "admin"); Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey()); JWTValidationInfo jwtValidationInfoInvalid = new JWTValidationInfo(); jwtValidationInfoInvalid.setValid(false); jwtValidationInfoInvalid.setValidationCode(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS); Mockito.when(jwtValidationService.validateJWTToken(signedJWTInfoTampered)).thenReturn(jwtValidationInfoInvalid); try { jwtValidator.authenticate(signedJWTInfoTampered, messageContext); } catch (APISecurityException e) { Assert.assertEquals(e.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS); } Mockito.verify(jwtValidationService).validateJWTToken(signedJWTInfo); Mockito.verify(gatewayTokenCache, Mockito.atLeast(1)).get(originalToken.getJWTClaimsSet().getJWTID()); } @Test public void testAuthenticateForGraphQLSubscription() throws Exception { Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("carbon.super"); SignedJWT signedJWT = SignedJWT.parse("eyJ4NXQiOiJNell4TW1Ga09HWXdNV0kwWldObU5EY3hOR1l3WW1NNFp" + "UQTNNV0kyTkRBelpHUXpOR00wWkdSbE5qSmtPREZrWkRSaU9URmtNV0ZoTXpVMlpHVmxOZyIsImtpZCI6Ik16WXhNbUZrT0" + "dZd01XSTBaV05tTkRjeE5HWXdZbU00WlRBM01XSTJOREF6WkdRek5HTTBaR1JsTmpKa09ERmtaRFJpT1RGa01XRmhNelUyW" + "kdWbE5nX1JTMjU2IiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJhZG1pbiIsImF1dCI6IkFQUExJQ0FUSU9OIiwiYXVkIjoidT" + "ljaTNDRmRRUDZJNG9DNU84VFcwZklBRXRnYSIsIm5iZiI6MTYzNjkxNTk4OCwiYXpwIjoidTljaTNDRmRRUDZJNG9DNU84VFc" + "wZklBRXRnYSIsInNjb3BlIjoic2NvcGUxIiwiaXNzIjoiaHR0cHM6XC9cL2xvY2FsaG9zdDo5NDQzXC9vYXV0aDJcL3Rva2Vu" + "IiwiZXhwIjoxNjM2OTE5NTg4LCJpYXQiOjE2MzY5MTU5ODgsImp0aSI6IjJiM2FmYTkxLTBjNDItNGUzNC1iYTliLTc3ZmVkND" + "dkMGNmZCJ9.J8VkCSDUMCUNdJrpbRJy_cj5YazIrdRyNKTJ-9Lv1EabUgwENX1XQcUioSqF686ESI_PvUxYZIwViybVIIGVRuxM" + "Tp9vCMQDWhxXPCuehahul7Ebn0mQtrM7K2fwL0DpyKpI0ER_UYH-PgNvnHS0f3zmJdUBNao2QwuWorXMuwzSw3oPcdHcYmF9" + "Jn024J8Dv3ipHtzEgSc26ULVRaO9bDzJZochzQzqdkxjLMDMBYmKizXOCXEcXJYrEnQpTRHQGOuRN9stXePvO9_gFGVTenun" + "9pBT7Yw7D3Sd-qg-r_AnExOjQu8QwZRjTh_l09YwBYIrMdhSbtXpeAy0GNrc0w"); SignedJWTInfo signedJWTInfo = new SignedJWTInfo(signedJWT.getParsedString(), signedJWT, signedJWT.getJWTClaimsSet()); String apiContext = "/graphql"; String apiVersion = "1.0.0"; ExtendedJWTConfigurationDto jwtConfigurationDto = new ExtendedJWTConfigurationDto(); JWTValidationService jwtValidationService = Mockito.mock(JWTValidationService.class); APIKeyValidator apiKeyValidator = Mockito.mock(APIKeyValidator.class); Cache gatewayTokenCache = Mockito.mock(Cache.class); Cache invalidTokenCache = Mockito.mock(Cache.class); Cache gatewayKeyCache = Mockito.mock(Cache.class); Cache gatewayJWTTokenCache = Mockito.mock(Cache.class); JWTValidationInfo jwtValidationInfo = new JWTValidationInfo(); jwtValidationInfo.setValid(true); jwtValidationInfo.setIssuer("https://localhost"); jwtValidationInfo.setRawPayload(signedJWT.getParsedString()); jwtValidationInfo.setJti(UUID.randomUUID().toString()); jwtValidationInfo.setIssuedTime(System.currentTimeMillis()); jwtValidationInfo.setExpiryTime(System.currentTimeMillis() + 5000L); jwtValidationInfo.setConsumerKey(UUID.randomUUID().toString()); jwtValidationInfo.setUser("user1"); jwtValidationInfo.setKeyManager("Resident Key Manager"); APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO(); apiKeyValidationInfoDTO.setApiName("GraphQLAPI"); apiKeyValidationInfoDTO.setApiPublisher("admin"); apiKeyValidationInfoDTO.setApiTier("Unlimited"); apiKeyValidationInfoDTO.setAuthorized(true); apiKeyValidationInfoDTO.setGraphQLMaxDepth(3); apiKeyValidationInfoDTO.setGraphQLMaxComplexity(4); // testing happy path Mockito.when(jwtValidationService.validateJWTToken(signedJWTInfo)).thenReturn(jwtValidationInfo); JWTValidatorWrapper jwtValidator = new JWTValidatorWrapper("Unlimited", true, apiKeyValidator, false, null, jwtConfigurationDto, jwtValidationService, invalidTokenCache, gatewayTokenCache, gatewayKeyCache, gatewayJWTTokenCache); Mockito.when(apiKeyValidator.validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(apiKeyValidationInfoDTO); AuthenticationContext authenticate = jwtValidator .authenticateForGraphQLSubscription(signedJWTInfo, apiContext, apiVersion); Assert.assertNotNull(authenticate); Assert.assertEquals(authenticate.getApiName(), "GraphQLAPI"); Assert.assertEquals(authenticate.getApiPublisher(), "admin"); Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey()); Assert.assertEquals(authenticate.getRequestTokenScopes(), jwtValidationInfo.getScopes()); Assert.assertEquals(authenticate.getGraphQLMaxComplexity(), apiKeyValidationInfoDTO.getGraphQLMaxComplexity()); Assert.assertEquals(authenticate.getGraphQLMaxDepth(), apiKeyValidationInfoDTO.getGraphQLMaxDepth()); //testing token validation failure jwtValidationInfo.setValid(false); Mockito.when(jwtValidationService.validateJWTToken(signedJWTInfo)).thenReturn(jwtValidationInfo); APISecurityException apiSecurityException = null; try { jwtValidator.authenticateForGraphQLSubscription(signedJWTInfo, apiContext, apiVersion); } catch (APISecurityException exception) { apiSecurityException = exception; Assert.assertEquals(exception.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS); Assert.assertEquals(exception.getMessage(), "Invalid JWT token"); } if (apiSecurityException == null) { Assert.fail(); } //testing subscription validation failure jwtValidationInfo.setValid(true); apiKeyValidationInfoDTO.setAuthorized(false); apiKeyValidationInfoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_RESOURCE_FORBIDDEN); try { jwtValidator.authenticateForGraphQLSubscription(signedJWTInfo, apiContext, apiVersion); } catch (APISecurityException exception) { Assert.assertEquals(exception.getErrorCode(), apiKeyValidationInfoDTO.getValidationStatus()); Assert.assertEquals(exception.getMessage(), "User is NOT authorized to access the Resource. API Subscription validation failed."); } } @Test public void testValidateScopesForGraphQLSubscriptions() throws ParseException { String apiContext = "/graphql"; String apiVersion = "1.0.0"; String matchingResource = "/subresource"; SignedJWT signedJWT = SignedJWT.parse("eyJ4NXQiOiJNell4TW1Ga09HWXdNV0kwWldObU5EY3hOR1l3WW1NNFp" + "UQTNNV0kyTkRBelpHUXpOR00wWkdSbE5qSmtPREZrWkRSaU9URmtNV0ZoTXpVMlpHVmxOZyIsImtpZCI6Ik16WXhNbUZrT0" + "dZd01XSTBaV05tTkRjeE5HWXdZbU00WlRBM01XSTJOREF6WkdRek5HTTBaR1JsTmpKa09ERmtaRFJpT1RGa01XRmhNelUyW" + "kdWbE5nX1JTMjU2IiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJhZG1pbiIsImF1dCI6IkFQUExJQ0FUSU9OIiwiYXVkIjoidT" + "ljaTNDRmRRUDZJNG9DNU84VFcwZklBRXRnYSIsIm5iZiI6MTYzNjkxNTk4OCwiYXpwIjoidTljaTNDRmRRUDZJNG9DNU84VFc" + "wZklBRXRnYSIsInNjb3BlIjoic2NvcGUxIiwiaXNzIjoiaHR0cHM6XC9cL2xvY2FsaG9zdDo5NDQzXC9vYXV0aDJcL3Rva2Vu" + "IiwiZXhwIjoxNjM2OTE5NTg4LCJpYXQiOjE2MzY5MTU5ODgsImp0aSI6IjJiM2FmYTkxLTBjNDItNGUzNC1iYTliLTc3ZmVkND" + "dkMGNmZCJ9.J8VkCSDUMCUNdJrpbRJy_cj5YazIrdRyNKTJ-9Lv1EabUgwENX1XQcUioSqF686ESI_PvUxYZIwViybVIIGVRuxM" + "Tp9vCMQDWhxXPCuehahul7Ebn0mQtrM7K2fwL0DpyKpI0ER_UYH-PgNvnHS0f3zmJdUBNao2QwuWorXMuwzSw3oPcdHcYmF9" + "Jn024J8Dv3ipHtzEgSc26ULVRaO9bDzJZochzQzqdkxjLMDMBYmKizXOCXEcXJYrEnQpTRHQGOuRN9stXePvO9_gFGVTenun" + "9pBT7Yw7D3Sd-qg-r_AnExOjQu8QwZRjTh_l09YwBYIrMdhSbtXpeAy0GNrc0w"); SignedJWTInfo signedJWTInfo = new SignedJWTInfo(signedJWT.getParsedString(), signedJWT, signedJWT.getJWTClaimsSet()); AuthenticationContext authenticationContext = new AuthenticationContext(); authenticationContext.setRequestTokenScopes(new ArrayList<String>() { { add("scope1"); } }); APIKeyValidator apiKeyValidator = Mockito.mock(APIKeyValidator.class); ExtendedJWTConfigurationDto jwtConfigurationDto = new ExtendedJWTConfigurationDto(); JWTValidationService jwtValidationService = Mockito.mock(JWTValidationService.class); Cache gatewayTokenCache = Mockito.mock(Cache.class); Cache invalidTokenCache = Mockito.mock(Cache.class); Cache gatewayKeyCache = Mockito.mock(Cache.class); Cache gatewayJWTTokenCache = Mockito.mock(Cache.class); JWTValidatorWrapper jwtValidator = new JWTValidatorWrapper("Unlimited", true, apiKeyValidator, false, null, jwtConfigurationDto, jwtValidationService, invalidTokenCache, gatewayTokenCache, gatewayKeyCache, gatewayJWTTokenCache); try { Mockito.when(apiKeyValidator.validateScopes(Mockito.any(TokenValidationContext.class), Mockito.anyString())).thenReturn(true); jwtValidator.validateScopesForGraphQLSubscriptions(apiContext, apiVersion, matchingResource, signedJWTInfo, authenticationContext); } catch (APISecurityException e) { Assert.fail(); } try { Mockito.when(apiKeyValidator.validateScopes(Mockito.any(TokenValidationContext.class), Mockito.anyString())).thenReturn(false); jwtValidator.validateScopesForGraphQLSubscriptions(apiContext, apiVersion, matchingResource, signedJWTInfo, authenticationContext); } catch (APISecurityException e) { Assert.assertEquals(e.getErrorCode(), APISecurityConstants.INVALID_SCOPE); String message = "User is NOT authorized to access the Resource: " + matchingResource + ". Scope validation failed."; Assert.assertEquals(e.getMessage(), message); } } }
/******************************************************************************* * Copyright (c) 2010 Haifeng Li * * 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 ch.zhaw.facerecognition.SVMLib; import java.io.Serializable; /** * A resizeable, array-backed list of double primitives. * * @author Haifeng Li */ public final class DoubleArrayList implements Serializable { private static final long serialVersionUID = 1L; /** * The data of the list. */ private double[] data; /** * The index after the last entry in the list. */ private int size; /** * Constructs an empty list. */ public DoubleArrayList() { this(10); } /** * Constructs an empty list with the specified initial capacity. * * @param capacity the initial size of array list. */ public DoubleArrayList(int capacity) { data = new double[capacity]; size = 0; } /** * Constructs a list containing the values of the specified array. * * @param values the initial values of array list. */ public DoubleArrayList(double[] values) { this(Math.max(values.length, 10)); add(values); } /** * Increases the capacity, if necessary, to ensure that it can hold * at least the number of values specified by the minimum capacity * argument. * * @param capacity the desired minimum capacity. */ public void ensureCapacity(int capacity) { if (capacity > data.length) { int newCap = Math.max(data.length << 1, capacity); double[] tmp = new double[newCap]; System.arraycopy(data, 0, tmp, 0, data.length); data = tmp; } } /** * Returns the number of values in the list. * * @return the number of values in the list */ public int size() { return size; } /** * Returns true if this list contains no values. * * @return true if the list is empty */ public boolean isEmpty() { return size == 0; } /** * Trims the capacity to be the list's current size. */ public void trimToSize() { if (data.length > size()) { double[] tmp = toArray(); data = tmp; } } /** * Appends the specified value to the end of this list. * * @param val a value to be appended to this list. */ public void add(double val) { ensureCapacity(size + 1); data[size++] = val; } /** * Appends an array to the end of this list. * * @param vals an array to be appended to this list. */ public void add(double[] vals) { ensureCapacity(size + vals.length); System.arraycopy(vals, 0, data, size, vals.length); size += vals.length; } /** * Returns the value at the specified position in this list. * * @param index index of the value to return * @return the value at the specified position in this list */ public double get(int index) { return data[index]; } /** * Replaces the value at the specified position in this list with the * specified value. * * @param index index of the value to replace * @param val value to be stored at the specified position * @throws IndexOutOfBoundsException if the index is out of range (index &lt; 0 || index &ge; size()) */ public DoubleArrayList set(int index, double val) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(String.valueOf(index)); } data[index] = val; return this; } /** * Removes all of the values from this list. The list will * be empty after this call returns. */ public void clear() { size = 0; } /** * Removes the value at specified index from the list. * * @param index index of the value to remove. * @return the value previously stored at specified index * @throws IndexOutOfBoundsException if the index is out of range (index &lt; 0 || index &ge; size()) */ public double remove(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(String.valueOf(index)); } double old = get(index); if (index == 0) { // data at the front System.arraycopy(data, 1, data, 0, size - 1); } else if (size - 1 == index) { // no copy to make, decrementing pos "deletes" values at // the end } else { // data in the middle System.arraycopy(data, index + 1, data, index, size - (index + 1)); } size--; return old; } /** * Returns an array containing all of the values in this list in * proper sequence (from first to last value). * The caller is thus free to modify the returned array. */ public double[] toArray() { return toArray(null); } /** * Returns an array containing all of the values in this list in * proper sequence (from first to last value). If the list fits * in the specified array, it is returned therein. Otherwise, a new * array is allocated with the size of this list. * * @param dest the array into which the values of the list are to * be stored, if it is big enough; otherwise, a new array is allocated * for this purpose. * @return an array containing the values of the list */ public double[] toArray(double[] dest) { if (dest == null || dest.length < size()) { dest = new double[size]; } System.arraycopy(data, 0, dest, 0, size); return dest; } }
/* * Copyright 2014 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 net.kuujo.vertigo.instance.impl; import io.vertx.core.*; import io.vertx.core.eventbus.DeliveryOptions; import io.vertx.core.eventbus.EventBus; import io.vertx.core.eventbus.Message; import io.vertx.core.http.CaseInsensitiveHeaders; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import net.kuujo.vertigo.instance.OutputConnection; import net.kuujo.vertigo.context.OutputConnectionContext; import java.util.TreeMap; import java.util.UUID; /** * Default output connection implementation. * * @author <a href="http://github.com/kuujo">Jordan Halterman</a> */ public class ControlledOutputConnection<T> implements OutputConnection<T>, Handler<Message<T>> { protected static final String ACTION_HEADER = "action"; protected static final String PORT_HEADER = "port"; protected static final String SOURCE_HEADER = "source"; protected static final String ID_HEADER = "name"; protected static final String INDEX_HEADER = "index"; protected static final String MESSAGE_ACTION = "message"; protected static final String ACK_ACTION = "ack"; protected static final String FAIL_ACTION = "fail"; protected static final String PAUSE_ACTION = "pause"; protected static final String RESUME_ACTION = "resume"; protected static final int DEFAULT_MAX_QUEUE_SIZE = 1000; private final Logger log; protected final Vertx vertx; protected final EventBus eventBus; protected final OutputConnectionContext context; private int maxQueueSize = DEFAULT_MAX_QUEUE_SIZE; private Handler<Void> drainHandler; private long currentMessage = 1; private final TreeMap<Long, JsonObject> messages = new TreeMap<>(); //protected final TreeMap<Long, Handler<AsyncResult<Void>>> ackHandlers = new TreeMap<>(); private boolean full; private boolean paused; public ControlledOutputConnection(Vertx vertx, OutputConnectionContext context) { this.vertx = vertx; this.eventBus = vertx.eventBus(); this.context = context; this.log = LoggerFactory.getLogger(String.format("%s-%s", ControlledOutputConnection.class.getName(), context.port().output().component().address())); } @Override public void handle(Message<T> message) { String action = message.headers().get(ACTION_HEADER); Long id = Long.valueOf(message.headers().get(INDEX_HEADER)); switch (action) { case ACK_ACTION: doAck(id); break; case FAIL_ACTION: doFail(id); break; case PAUSE_ACTION: doPause(id); break; case RESUME_ACTION: doResume(id); break; } } @Override public OutputConnection<T> setSendQueueMaxSize(int maxSize) { this.maxQueueSize = maxSize; return this; } @Override public int getSendQueueMaxSize() { return maxQueueSize; } @Override public int size() { return messages.size(); } @Override public boolean sendQueueFull() { return paused || messages.size() >= maxQueueSize; } @Override public OutputConnection<T> drainedHandler(Handler<Void> handler) { this.drainHandler = handler; return this; } /** * Checks whether the connection is full. */ protected void checkFull() { if (!full && messages.size() >= maxQueueSize) { full = true; log.debug("{} - Connection to {} is full", this, context.target()); } } /** * Checks whether the connection has been drained. */ protected void checkDrain() { if (full && !paused && messages.size() < maxQueueSize / 2) { full = false; log.debug("{} - Connection to {} is drained", this, context.target()); if (drainHandler != null) { drainHandler.handle((Void)null); } } } /** * Handles a batch ack. */ protected void doAck(long id) { // The other side of the connection has sent a message indicating which // messages it has seen. We can clear any messages before the indicated ID. if (log.isDebugEnabled()) { log.debug("{} - Received ack for messages up to {}, removing all previous messages from memory", this, id); } if (messages.containsKey(id)) { messages.headMap(id, true).clear(); } else { messages.clear(); } checkDrain(); } /** * Handles a batch fail. */ protected void doFail(long id) { if (log.isDebugEnabled()) { log.debug("{} - Received resend request for messages starting at {}", this, id); } // Ack all the entries before the given ID. doAck(id); // Now that all the entries before the given ID have been removed, // just iterate over the messages map and resend all the messages. for (JsonObject message : messages.values()) { eventBus.send(context.target().address(), message); } } /** * Handles a connection pause. */ protected void doPause(long id) { log.debug("{} - Paused connection to {}", this, context.target()); paused = true; } /** * Handles a connection resume. */ protected void doResume(long id) { if (paused) { log.debug("{} - Resumed connection to {}", this, context.target()); paused = false; checkDrain(); } } /** * Sends a message. */ protected OutputConnection<T> doSend(Object message, MultiMap headers, Handler<AsyncResult<Void>> ackHandler) { if (!paused) { // Generate a unique ID and monotonically increasing index for the message. String id = UUID.randomUUID().toString(); long index = currentMessage++; /* Commented out tracking of ackHandlers. Presumably these need to be kept around so new handlers can be created if messages are resent. // if (ackHandler != null) { // ackHandlers.put(index, ackHandler); // } */ // Set up the message headers. DeliveryOptions options = new DeliveryOptions(); if (headers == null) { headers = new CaseInsensitiveHeaders(); } headers.add(ACTION_HEADER, MESSAGE_ACTION) .add(ID_HEADER, id) .add(INDEX_HEADER, String.valueOf(index)) .add(PORT_HEADER, context.target().port()) .add(SOURCE_HEADER, context.target().address()) // TODO: header is called source, but takes the address... .add(ID_HEADER, id) .add(INDEX_HEADER, String.valueOf(index)); options.setHeaders(headers); if (context.sendTimeout() > 0) { options.setSendTimeout(context.sendTimeout()); } if (log.isDebugEnabled()) { log.debug("{} - Send: Message[name={}, message={}]", this, id, message); } if (ackHandler != null) { eventBus.send(context.target().address(), message, options, r -> { if (r.succeeded()) { ackHandler.handle(Future.<Void>succeededFuture()); } else { ackHandler.handle(Future.<Void>failedFuture(r.cause())); } }); } else { eventBus.send(context.target().address(), message, options); } checkFull(); } return this; } @Override public OutputConnection<T> send(T message) { return doSend(message, null, null); } @Override public OutputConnection<T> send(T message, MultiMap headers) { return doSend(message, headers, null); } @Override public OutputConnection<T> send(T message, Handler<AsyncResult<Void>> ackHandler) { return doSend(message, null, ackHandler); } @Override public OutputConnection<T> send(T message, MultiMap headers, Handler<AsyncResult<Void>> ackHandler) { return doSend(message, headers, ackHandler); } @Override public String toString() { return context.toString(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.rest.protocols.tcp; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.Date; import java.util.UUID; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.internal.client.marshaller.GridClientMarshaller; import org.apache.ignite.internal.processors.rest.client.message.GridClientHandshakeRequest; import org.apache.ignite.internal.processors.rest.client.message.GridClientHandshakeResponse; import org.apache.ignite.internal.processors.rest.client.message.GridClientMessage; import org.apache.ignite.internal.processors.rest.client.message.GridClientPingPacket; import org.apache.ignite.internal.processors.rest.client.message.GridRouterRequest; import org.apache.ignite.internal.processors.rest.client.message.GridRouterResponse; import org.apache.ignite.internal.processors.rest.protocols.tcp.redis.GridRedisMessage; import org.apache.ignite.internal.processors.rest.protocols.tcp.redis.GridRedisProtocolParser; import org.apache.ignite.internal.util.GridByteArrayList; import org.apache.ignite.internal.util.GridClientByteUtils; import org.apache.ignite.internal.util.nio.GridNioParser; import org.apache.ignite.internal.util.nio.GridNioSession; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.marshaller.Marshaller; import org.apache.ignite.marshaller.jdk.JdkMarshaller; import org.jetbrains.annotations.Nullable; import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.BOOLEAN_FLAG; import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.BYTE_ARR_FLAG; import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.BYTE_FLAG; import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.DATE_FLAG; import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.DOUBLE_FLAG; import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.FLAGS_LENGTH; import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.FLOAT_FLAG; import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.HDR_LEN; import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.IGNITE_HANDSHAKE_FLAG; import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.IGNITE_HANDSHAKE_RES_FLAG; import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.IGNITE_REQ_FLAG; import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.INT_FLAG; import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.LONG_FLAG; import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.MEMCACHE_REQ_FLAG; import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.MEMCACHE_RES_FLAG; import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.SERIALIZED_FLAG; import static org.apache.ignite.internal.processors.rest.protocols.tcp.redis.GridRedisMessage.RESP_REQ_FLAG; import static org.apache.ignite.internal.util.nio.GridNioSessionMetaKey.MARSHALLER; import static org.apache.ignite.internal.util.nio.GridNioSessionMetaKey.PARSER_STATE; /** * Parser for extended memcache protocol. Handles parsing and encoding activity. */ public class GridTcpRestParser implements GridNioParser { /** UTF-8 charset. */ private static final Charset UTF_8 = Charset.forName("UTF-8"); /** JDK marshaller. */ private final Marshaller marsh; /** Router client flag. */ private final boolean routerClient; /** * @param routerClient Router client flag. */ public GridTcpRestParser(boolean routerClient) { this(routerClient, new JdkMarshaller()); } /** * @param routerClient Router client flag. * @param marsh Marshaller. */ public GridTcpRestParser(boolean routerClient, Marshaller marsh) { this.routerClient = routerClient; this.marsh = marsh; } /** {@inheritDoc} */ @Nullable @Override public GridClientMessage decode(GridNioSession ses, ByteBuffer buf) throws IOException, IgniteCheckedException { ParserState state = ses.removeMeta(PARSER_STATE.ordinal()); if (state == null) state = new ParserState(); GridClientPacketType type = state.packetType(); if (type == null) { byte hdr = buf.get(buf.position()); switch (hdr) { case MEMCACHE_REQ_FLAG: state.packet(new GridMemcachedMessage()); state.packetType(GridClientPacketType.MEMCACHE); break; case RESP_REQ_FLAG: state.packetType(GridClientPacketType.REDIS); break; case IGNITE_REQ_FLAG: // Skip header. buf.get(); state.packetType(GridClientPacketType.IGNITE); break; case IGNITE_HANDSHAKE_FLAG: // Skip header. buf.get(); state.packetType(GridClientPacketType.IGNITE_HANDSHAKE); break; case IGNITE_HANDSHAKE_RES_FLAG: buf.get(); state.packetType(GridClientPacketType.IGNITE_HANDSHAKE_RES); break; default: throw new IOException("Failed to parse incoming packet (invalid packet start) [ses=" + ses + ", b=" + Integer.toHexString(hdr & 0xFF) + ']'); } } GridClientMessage res = null; switch (state.packetType()) { case MEMCACHE: res = parseMemcachePacket(ses, buf, state); break; case REDIS: res = GridRedisProtocolParser.readArray(buf); break; case IGNITE_HANDSHAKE: res = parseHandshake(buf, state); break; case IGNITE_HANDSHAKE_RES: if (buf.hasRemaining()) res = new GridClientHandshakeResponse(buf.get()); break; case IGNITE: res = parseCustomPacket(ses, buf, state); break; } if (res == null) // Packet was not fully parsed yet. ses.addMeta(PARSER_STATE.ordinal(), state); return res; } /** {@inheritDoc} */ @Override public ByteBuffer encode(GridNioSession ses, Object msg0) throws IOException, IgniteCheckedException { assert msg0 != null; GridClientMessage msg = (GridClientMessage)msg0; if (msg instanceof GridMemcachedMessage) return encodeMemcache((GridMemcachedMessage)msg); else if (msg instanceof GridRedisMessage) return ((GridRedisMessage)msg).getResponse(); else if (msg instanceof GridClientPingPacket) return ByteBuffer.wrap(GridClientPingPacket.PING_PACKET); else if (msg instanceof GridClientHandshakeRequest) { byte[] bytes = ((GridClientHandshakeRequest)msg).rawBytes(); ByteBuffer buf = ByteBuffer.allocate(bytes.length + 1); buf.put(IGNITE_HANDSHAKE_FLAG); buf.put(bytes); buf.flip(); return buf; } else if (msg instanceof GridClientHandshakeResponse) return ByteBuffer.wrap(new byte[] { IGNITE_HANDSHAKE_RES_FLAG, ((GridClientHandshakeResponse)msg).resultCode() }); else if (msg instanceof GridRouterRequest) { byte[] body = ((GridRouterRequest)msg).body(); ByteBuffer buf = ByteBuffer.allocate(45 + body.length); buf.put(IGNITE_REQ_FLAG); buf.putInt(40 + body.length); buf.putLong(msg.requestId()); buf.put(U.uuidToBytes(msg.clientId())); buf.put(U.uuidToBytes(msg.destinationId())); buf.put(body); buf.flip(); return buf; } else { GridClientMarshaller marsh = marshaller(ses); ByteBuffer res = marsh.marshal(msg, 45); ByteBuffer slice = res.slice(); slice.put(IGNITE_REQ_FLAG); slice.putInt(res.remaining() - 5); slice.putLong(msg.requestId()); slice.put(U.uuidToBytes(msg.clientId())); slice.put(U.uuidToBytes(msg.destinationId())); return res; } } /** * Parses memcache protocol message. * * @param ses Session. * @param buf Buffer containing not parsed bytes. * @param state Current parser state. * @return Parsed packet.s * @throws IOException If packet cannot be parsed. * @throws IgniteCheckedException If deserialization error occurred. */ @Nullable private GridClientMessage parseMemcachePacket(GridNioSession ses, ByteBuffer buf, ParserState state) throws IOException, IgniteCheckedException { assert state.packetType() == GridClientPacketType.MEMCACHE; assert state.packet() != null; assert state.packet() instanceof GridMemcachedMessage; GridMemcachedMessage req = (GridMemcachedMessage)state.packet(); ByteArrayOutputStream tmp = state.buffer(); int i = state.index(); while (buf.remaining() > 0) { byte b = buf.get(); if (i == 0) req.requestFlag(b); else if (i == 1) req.operationCode(b); else if (i == 2 || i == 3) { tmp.write(b); if (i == 3) { req.keyLength(U.bytesToShort(tmp.toByteArray(), 0)); tmp.reset(); } } else if (i == 4) req.extrasLength(b); else if (i >= 8 && i <= 11) { tmp.write(b); if (i == 11) { req.totalLength(U.bytesToInt(tmp.toByteArray(), 0)); tmp.reset(); } } else if (i >= 12 && i <= 15) { tmp.write(b); if (i == 15) { req.opaque(tmp.toByteArray()); tmp.reset(); } } else if (i >= HDR_LEN && i < HDR_LEN + req.extrasLength()) { tmp.write(b); if (i == HDR_LEN + req.extrasLength() - 1) { req.extras(tmp.toByteArray()); tmp.reset(); } } else if (i >= HDR_LEN + req.extrasLength() && i < HDR_LEN + req.extrasLength() + req.keyLength()) { tmp.write(b); if (i == HDR_LEN + req.extrasLength() + req.keyLength() - 1) { req.key(tmp.toByteArray()); tmp.reset(); } } else if (i >= HDR_LEN + req.extrasLength() + req.keyLength() && i < HDR_LEN + req.totalLength()) { tmp.write(b); if (i == HDR_LEN + req.totalLength() - 1) { req.value(tmp.toByteArray()); tmp.reset(); } } if (i == HDR_LEN + req.totalLength() - 1) // Assembled the packet. return assemble(ses, req); i++; } state.index(i); return null; } /** * Parses a client handshake, checking a client version and * reading the marshaller protocol ID. * * @param buf Message bytes. * @param state Parser state. * @return True if a hint was parsed, false if still need more bytes to parse. */ @Nullable private GridClientMessage parseHandshake(ByteBuffer buf, ParserState state) { assert state.packetType() == GridClientPacketType.IGNITE_HANDSHAKE; int idx = state.index(); GridClientHandshakeRequest packet = (GridClientHandshakeRequest)state.packet(); if (packet == null) { packet = new GridClientHandshakeRequest(); state.packet(packet); } int rem = buf.remaining(); if (rem > 0) { byte[] bbuf = new byte[5]; // Buffer to read data to. int nRead = Math.min(rem, bbuf.length); // Number of bytes to read. buf.get(bbuf, 0, nRead); // Batch read from buffer. int nAvailable = nRead; // Number of available bytes. if (idx < 4) { // Need to read version bytes. int len = Math.min(nRead, 4 - idx); // Number of version bytes available in buffer. packet.putBytes(bbuf, idx, len); idx += len; state.index(idx); nAvailable -= len; } assert idx <= 4 : "Wrong idx: " + idx; assert nAvailable == 0 || nAvailable == 1 : "Wrong nav: " + nAvailable; if (idx == 4 && nAvailable > 0) return packet; } return null; // Wait for more data. } /** * Parses custom packet serialized by Ignite marshaller. * * @param ses Session. * @param buf Buffer containing not parsed bytes. * @param state Parser state. * @return Parsed message. * @throws IOException If packet parsing or deserialization failed. * @throws IgniteCheckedException If failed. */ @Nullable private GridClientMessage parseCustomPacket(GridNioSession ses, ByteBuffer buf, ParserState state) throws IOException, IgniteCheckedException { assert state.packetType() == GridClientPacketType.IGNITE; assert state.packet() == null; ByteArrayOutputStream tmp = state.buffer(); int len = state.index(); if (buf.remaining() > 0) { if (len == 0) { // Don't know the size yet. byte[] lenBytes = statefulRead(buf, tmp, 4); if (lenBytes != null) { len = U.bytesToInt(lenBytes, 0); if (len == 0) return GridClientPingPacket.PING_MESSAGE; else if (len < 0) throw new IOException("Failed to parse incoming packet (invalid packet length) [ses=" + ses + ", len=" + len + ']'); state.index(len); } } if (len > 0 && state.header() == null) { byte[] hdrBytes = statefulRead(buf, tmp, 40); if (hdrBytes != null) { long reqId = GridClientByteUtils.bytesToLong(hdrBytes, 0); UUID clientId = GridClientByteUtils.bytesToUuid(hdrBytes, 8); UUID destId = GridClientByteUtils.bytesToUuid(hdrBytes, 24); state.header(new HeaderData(reqId, clientId, destId)); } } if (len > 0 && state.header() != null) { final int packetSize = len - 40; if (tmp.size() + buf.remaining() >= packetSize) { if (buf.remaining() > 0) { byte[] bodyBytes = new byte[packetSize - tmp.size()]; buf.get(bodyBytes); tmp.write(bodyBytes); } return parseClientMessage(ses, state); } else copyRemaining(buf, tmp); } } return null; } /** * Tries to read the specified amount of bytes using intermediate buffer. Stores * the bytes to intermediate buffer, if size requirement is not met. * * @param buf Byte buffer to read from. * @param intBuf Intermediate buffer to read bytes from and to save remaining bytes to. * @param size Number of bytes to read. * @return Resulting byte array or {@code null}, if both buffers contain less bytes * than required. In case of non-null result, the intermediate buffer is empty. * In case of {@code null} result, the input buffer is empty (read fully). * @throws IOException If IO error occurs. */ @Nullable private byte[] statefulRead(ByteBuffer buf, ByteArrayOutputStream intBuf, int size) throws IOException { if (intBuf.size() + buf.remaining() >= size) { int off = 0; byte[] bytes = new byte[size]; if (intBuf.size() > 0) { assert intBuf.size() < size; byte[] tmpBytes = intBuf.toByteArray(); System.arraycopy(tmpBytes, 0, bytes, 0, tmpBytes.length); off = intBuf.size(); intBuf.reset(); } buf.get(bytes, off, size - off); return bytes; } else { copyRemaining(buf, intBuf); return null; } } /** * Copies remaining bytes from byte buffer to output stream. * * @param src Source buffer. * @param dest Destination stream. * @throws IOException If IO error occurs. */ private void copyRemaining(ByteBuffer src, OutputStream dest) throws IOException { byte[] b = new byte[src.remaining()]; src.get(b); dest.write(b); } /** * Parses {@link GridClientMessage} from raw bytes. * * @param ses Session. * @param state Parser state. * @return A parsed client message. * @throws IOException On marshaller error. * @throws IgniteCheckedException If no marshaller was defined for the session. */ protected GridClientMessage parseClientMessage(GridNioSession ses, ParserState state) throws IOException, IgniteCheckedException { GridClientMessage msg; if (routerClient) { msg = new GridRouterResponse( state.buffer().toByteArray(), state.header().reqId(), state.header().clientId(), state.header().destinationId()); } else { GridClientMarshaller marsh = marshaller(ses); msg = marsh.unmarshal(state.buffer().toByteArray()); msg.requestId(state.header().reqId()); msg.clientId(state.header().clientId()); msg.destinationId(state.header().destinationId()); } return msg; } /** * Encodes memcache message to a raw byte array. * * @param msg Message being serialized. * @return Serialized message. * @throws IgniteCheckedException If serialization failed. */ private ByteBuffer encodeMemcache(GridMemcachedMessage msg) throws IgniteCheckedException { GridByteArrayList res = new GridByteArrayList(HDR_LEN); int keyLen = 0; int keyFlags = 0; if (msg.key() != null) { ByteArrayOutputStream rawKey = new ByteArrayOutputStream(); keyFlags = encodeObj(msg.key(), rawKey); msg.key(rawKey.toByteArray()); keyLen = rawKey.size(); } int dataLen = 0; int valFlags = 0; if (msg.value() != null) { ByteArrayOutputStream rawVal = new ByteArrayOutputStream(); valFlags = encodeObj(msg.value(), rawVal); msg.value(rawVal.toByteArray()); dataLen = rawVal.size(); } int flagsLen = 0; if (msg.addFlags())// || keyFlags > 0 || valFlags > 0) flagsLen = FLAGS_LENGTH; res.add(MEMCACHE_RES_FLAG); res.add(msg.operationCode()); // Cast is required due to packet layout. res.add((short)keyLen); // Cast is required due to packet layout. res.add((byte)flagsLen); // Data type is always 0x00. res.add((byte)0x00); res.add((short)msg.status()); res.add(keyLen + flagsLen + dataLen); res.add(msg.opaque(), 0, msg.opaque().length); // CAS, unused. res.add(0L); assert res.size() == HDR_LEN; if (flagsLen > 0) { res.add((short)keyFlags); res.add((short)valFlags); } assert msg.key() == null || msg.key() instanceof byte[]; assert msg.value() == null || msg.value() instanceof byte[]; if (keyLen > 0) res.add((byte[])msg.key(), 0, ((byte[])msg.key()).length); if (dataLen > 0) res.add((byte[])msg.value(), 0, ((byte[])msg.value()).length); return ByteBuffer.wrap(res.entireArray()); } /** * Validates incoming packet and deserializes all fields that need to be deserialized. * * @param ses Session on which packet is being parsed. * @param req Raw packet. * @return Same packet with fields deserialized. * @throws IOException If parsing failed. * @throws IgniteCheckedException If deserialization failed. */ private GridClientMessage assemble(GridNioSession ses, GridMemcachedMessage req) throws IOException, IgniteCheckedException { byte[] extras = req.extras(); // First, decode key and value, if any if (req.key() != null || req.value() != null) { short keyFlags = 0; short valFlags = 0; if (req.hasFlags()) { if (extras == null || extras.length < FLAGS_LENGTH) throw new IOException("Failed to parse incoming packet (flags required for command) [ses=" + ses + ", opCode=" + Integer.toHexString(req.operationCode() & 0xFF) + ']'); keyFlags = U.bytesToShort(extras, 0); valFlags = U.bytesToShort(extras, 2); } if (req.key() != null) { assert req.key() instanceof byte[]; byte[] rawKey = (byte[])req.key(); // Only values can be hessian-encoded. req.key(decodeObj(keyFlags, rawKey)); } if (req.value() != null) { assert req.value() instanceof byte[]; byte[] rawVal = (byte[])req.value(); req.value(decodeObj(valFlags, rawVal)); } } if (req.hasExpiration()) { if (extras == null || extras.length < 8) throw new IOException("Failed to parse incoming packet (expiration value required for command) [ses=" + ses + ", opCode=" + Integer.toHexString(req.operationCode() & 0xFF) + ']'); req.expiration(U.bytesToInt(extras, 4) & 0xFFFFFFFFL); } if (req.hasInitial()) { if (extras == null || extras.length < 16) throw new IOException("Failed to parse incoming packet (initial value required for command) [ses=" + ses + ", opCode=" + Integer.toHexString(req.operationCode() & 0xFF) + ']'); req.initial(U.bytesToLong(extras, 8)); } if (req.hasDelta()) { if (extras == null || extras.length < 8) throw new IOException("Failed to parse incoming packet (delta value required for command) [ses=" + ses + ", opCode=" + Integer.toHexString(req.operationCode() & 0xFF) + ']'); req.delta(U.bytesToLong(extras, 0)); } if (extras != null) { // Clients that include cache name must always include flags. int len = 4; if (req.hasExpiration()) len += 4; if (req.hasDelta()) len += 8; if (req.hasInitial()) len += 8; if (extras.length - len > 0) { byte[] cacheName = new byte[extras.length - len]; U.arrayCopy(extras, len, cacheName, 0, extras.length - len); req.cacheName(new String(cacheName, UTF_8)); } } return req; } /** * Decodes value from a given byte array to the object according to the flags given. * * @param flags Flags. * @param bytes Byte array to decode. * @return Decoded value. * @throws IgniteCheckedException If deserialization failed. */ private Object decodeObj(short flags, byte[] bytes) throws IgniteCheckedException { assert bytes != null; if ((flags & SERIALIZED_FLAG) != 0) return U.unmarshal(marsh, bytes, null); int masked = flags & 0xff00; switch (masked) { case BOOLEAN_FLAG: return bytes[0] == '1'; case INT_FLAG: return U.bytesToInt(bytes, 0); case LONG_FLAG: return U.bytesToLong(bytes, 0); case DATE_FLAG: return new Date(U.bytesToLong(bytes, 0)); case BYTE_FLAG: return bytes[0]; case FLOAT_FLAG: return Float.intBitsToFloat(U.bytesToInt(bytes, 0)); case DOUBLE_FLAG: return Double.longBitsToDouble(U.bytesToLong(bytes, 0)); case BYTE_ARR_FLAG: return bytes; default: return new String(bytes, UTF_8); } } /** * Encodes given object to a byte array and returns flags that describe the type of serialized object. * * @param obj Object to serialize. * @param out Output stream to which object should be written. * @return Serialization flags. * @throws IgniteCheckedException If JDK serialization failed. */ private int encodeObj(Object obj, ByteArrayOutputStream out) throws IgniteCheckedException { int flags = 0; byte[] data = null; if (obj instanceof String) data = ((String)obj).getBytes(UTF_8); else if (obj instanceof Boolean) { data = new byte[] {(byte)((Boolean)obj ? '1' : '0')}; flags |= BOOLEAN_FLAG; } else if (obj instanceof Integer) { data = U.intToBytes((Integer)obj); flags |= INT_FLAG; } else if (obj instanceof Long) { data = U.longToBytes((Long)obj); flags |= LONG_FLAG; } else if (obj instanceof Date) { data = U.longToBytes(((Date)obj).getTime()); flags |= DATE_FLAG; } else if (obj instanceof Byte) { data = new byte[] {(Byte)obj}; flags |= BYTE_FLAG; } else if (obj instanceof Float) { data = U.intToBytes(Float.floatToIntBits((Float)obj)); flags |= FLOAT_FLAG; } else if (obj instanceof Double) { data = U.longToBytes(Double.doubleToLongBits((Double)obj)); flags |= DOUBLE_FLAG; } else if (obj instanceof byte[]) { data = (byte[])obj; flags |= BYTE_ARR_FLAG; } else { U.marshal(marsh, obj, out); flags |= SERIALIZED_FLAG; } if (data != null) out.write(data, 0, data.length); return flags; } /** * Returns marshaller. * * @return Marshaller. */ protected GridClientMarshaller marshaller(GridNioSession ses) { GridClientMarshaller marsh = ses.meta(MARSHALLER.ordinal()); assert marsh != null; return marsh; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridTcpRestParser.class, this); } /** * Holder for parser state and temporary buffer. */ protected static class ParserState { /** Parser index. */ private int idx; /** Temporary data buffer. */ private ByteArrayOutputStream buf = new ByteArrayOutputStream(); /** Packet being assembled. */ private GridClientMessage packet; /** Packet type. */ private GridClientPacketType packetType; /** Header data. */ private HeaderData hdr; /** * @return Stored parser index. */ public int index() { return idx; } /** * @param idx Index to store. */ public void index(int idx) { this.idx = idx; } /** * @return Temporary data buffer. */ public ByteArrayOutputStream buffer() { return buf; } /** * @return Pending packet. */ @Nullable public GridClientMessage packet() { return packet; } /** * @param packet Pending packet. */ public void packet(GridClientMessage packet) { assert this.packet == null; this.packet = packet; } /** * @return Pending packet type. */ public GridClientPacketType packetType() { return packetType; } /** * @param packetType Pending packet type. */ public void packetType(GridClientPacketType packetType) { this.packetType = packetType; } /** * @return Header. */ public HeaderData header() { return hdr; } /** * @param hdr Header. */ public void header(HeaderData hdr) { this.hdr = hdr; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(ParserState.class, this); } } /** * Header. */ protected static class HeaderData { /** Request Id. */ private final long reqId; /** Request Id. */ private final UUID clientId; /** Request Id. */ private final UUID destId; /** * @param reqId Request Id. * @param clientId Client Id. * @param destId Destination Id. */ private HeaderData(long reqId, UUID clientId, UUID destId) { this.reqId = reqId; this.clientId = clientId; this.destId = destId; } /** * @return Request Id. */ public long reqId() { return reqId; } /** * @return Client Id. */ public UUID clientId() { return clientId; } /** * @return Destination Id. */ public UUID destinationId() { return destId; } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rs.fon.eklub.boot; import java.util.EnumSet; import java.util.List; import java.util.Properties; import javax.servlet.DispatcherType; import javax.servlet.Filter; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.sql.DataSource; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.Conventions; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import rs.fon.eklub.constants.ConfigKeys; import rs.fon.eklub.core.interactors.AdminInteractor; import rs.fon.eklub.core.interactors.CategoryInteractor; import rs.fon.eklub.core.interactors.GroupInteractor; import rs.fon.eklub.core.interactors.MemberInteractor; import rs.fon.eklub.core.interactors.MembershipFeeInteractor; import rs.fon.eklub.core.interactors.PaymentInteractor; import rs.fon.eklub.core.interactors.StatInteractor; import rs.fon.eklub.core.interactors.TrainingInteractor; import rs.fon.eklub.core.services.CategoryService; import rs.fon.eklub.core.validators.GroupValidator; import rs.fon.eklub.core.validators.MemberValidator; import rs.fon.eklub.core.validators.PaymentValidator; import rs.fon.eklub.core.validators.TrainingValidator; import rs.fon.eklub.dao.implementation.CategoryDao; import rs.fon.eklub.dao.implementation.EmployeeDao; import rs.fon.eklub.dao.implementation.GroupDao; import rs.fon.eklub.dao.implementation.MemberDao; import rs.fon.eklub.dao.implementation.MembershipFeeDao; import rs.fon.eklub.dao.implementation.PaymentDao; import rs.fon.eklub.dao.implementation.StatDao; import rs.fon.eklub.dao.implementation.TrainingDao; import rs.fon.eklub.filters.CORSFilter; import rs.fon.eklub.util.Config; import rs.fon.eklub.json.converters.JsonHttpConverter; import rs.fon.eklub.security.MethodSecurityConfig; import rs.fon.eklub.security.OAuth2ResourceConfig; /** * * @author milos */ @EnableAutoConfiguration @Configuration @Import({OAuth2ResourceConfig.class, MethodSecurityConfig.class}) @ComponentScan(basePackages = "rs.fon.eklub") public class Main extends WebMvcConfigurationSupport implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { registerServletFilter(servletContext, new CORSFilter()); } protected FilterRegistration.Dynamic registerServletFilter(ServletContext servletContext, Filter filter) { String filterName = Conventions.getVariableName(filter); FilterRegistration.Dynamic registration = servletContext.addFilter(filterName, filter); registration.setAsyncSupported(true); registration.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*"); return registration; } @Bean protected ServletContextListener listener() { return new ServletContextListener() { @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("ServletContext initialized"); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("ServletContext destroyed"); } }; } @Autowired @Bean public CategoryService getCategoryInteractor(SessionFactory sessionFactory) { return new CategoryInteractor(new CategoryDao(sessionFactory)); } @Autowired @Bean public GroupInteractor getGroupInteractor(SessionFactory sessionFactory) { return new GroupInteractor(new GroupDao(sessionFactory), new GroupValidator()); } @Autowired @Bean public MemberInteractor getMemberInteractor(SessionFactory sessionFactory) { return new MemberInteractor(new MemberDao(sessionFactory), new MemberValidator()); } @Autowired @Bean public TrainingInteractor getTrainingInteractor(SessionFactory sessionFactory) { return new TrainingInteractor(new TrainingDao(sessionFactory), new TrainingValidator()); } @Autowired @Bean public MembershipFeeInteractor getMembershipFeeInteractor(SessionFactory sessionFactory) { return new MembershipFeeInteractor(new MembershipFeeDao(sessionFactory)); } @Autowired @Bean public PaymentInteractor getPaymentInteractor(SessionFactory sessionFactory) { return new PaymentInteractor(new PaymentDao(sessionFactory), new PaymentValidator()); } @Autowired @Bean public AdminInteractor getAdminInteractor(SessionFactory sessionFactory) { return new AdminInteractor(new EmployeeDao(sessionFactory)); } @Autowired @Bean public StatInteractor getStatInteractor(SessionFactory sessionFactory) { return new StatInteractor(new StatDao(sessionFactory)); } @Bean(name = "dataSource") public DataSource getDataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(Config.getInstance().getValue(ConfigKeys.DatabaseConfigKeys.DB_DRIVER)); dataSource.setUrl(Config.getInstance().getValue(ConfigKeys.DatabaseConfigKeys.DB_CONNECTION_STRING)); dataSource.setUsername(Config.getInstance().getValue(ConfigKeys.DatabaseConfigKeys.DB_USER)); dataSource.setPassword(Config.getInstance().getValue(ConfigKeys.DatabaseConfigKeys.DB_PASSWORD)); return dataSource; } @Autowired @Bean(name = "sessionFactory") public SessionFactory getSessionFactory(DataSource dataSource) { LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource); sessionBuilder.addProperties(getHibernateProperties()); sessionBuilder.addResource("mappings/Category.hbm.xml"); sessionBuilder.addResource("mappings/Member.hbm.xml"); sessionBuilder.addResource("mappings/Group.hbm.xml"); sessionBuilder.addResource("mappings/MembershipFee.hbm.xml"); sessionBuilder.addResource("mappings/Training.hbm.xml"); sessionBuilder.addResource("mappings/Payment.hbm.xml"); sessionBuilder.addResource("mappings/Attendance.hbm.xml"); sessionBuilder.addResource("mappings/Employee.hbm.xml"); sessionBuilder.addResource("mappings/EmployeeEngagement.hbm.xml"); return sessionBuilder.buildSessionFactory(); } // @Autowired // @Bean(name = "transactionManager") // public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) { // HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory); // return transactionManager; // } private Properties getHibernateProperties() { Properties properties = new Properties(); properties.put("hibernate.show_sql", "true"); properties.put("hibernate.format_sql", "true"); properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); properties.put("hibernate.globally_quoted_identifiers", "true"); return properties; } // @Bean // public MappingJackson2HttpMessageConverter json2HttpMapper() { // MappingJackson2HttpMessageConverter jsonConverter = new JsonHttpConverter(); // return jsonConverter; // } @Override protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new JsonHttpConverter()); } public static void main(String[] args) { SpringApplication.run(Main.class, args); } }
package org.kb10uy.tencocoa; import android.app.Notification; import android.app.NotificationManager; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Binder; import android.os.IBinder; import android.preference.PreferenceManager; import org.kb10uy.tencocoa.model.TencocoaUserStreamLister; import org.kb10uy.tencocoa.model.TencocoaUserStreamObject; import org.kb10uy.tencocoa.model.TwitterAccountInformation; import java.util.ArrayList; import java.util.List; import twitter4j.DirectMessage; import twitter4j.StallWarning; import twitter4j.Status; import twitter4j.StatusDeletionNotice; import twitter4j.Twitter; import twitter4j.User; import twitter4j.UserList; import twitter4j.UserStreamAdapter; import twitter4j.UserStreamListener; public class TencocoaStreamingService extends Service { private static final int TENCOCOA_STREAMING_NOTIFICATION_ID = 0xC0C0A; private NotificationManager mNotificationManager; private TencocoaStreamingServiceBinder mBinder = new TencocoaStreamingServiceBinder(); private String mConsumerKey, mConsumerSecret; private TencocoaUserStreamObject mUserStream; private TencocoaUserStreamPassiveAdapterManager mPassiveAdapterManager = new TencocoaUserStreamPassiveAdapterManager(); //helper methods //general private void showNotification(int tickerStringId, int descriptionStringId) { Notification.Builder builder = new Notification.Builder(getApplicationContext()) .setSmallIcon(R.drawable.tencocoa_notify) .setTicker(getString(tickerStringId)) .setContentTitle(getString(R.string.app_name)) .setContentText(getString(descriptionStringId)); mNotificationManager.cancelAll(); mNotificationManager.notify(TENCOCOA_STREAMING_NOTIFICATION_ID, builder.build()); } //service methods @Override public void onCreate() { super.onCreate(); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); mConsumerKey = pref.getString(getString(R.string.preference_twitter_consumer_key), ""); mConsumerSecret = pref.getString(getString(R.string.preference_twitter_consumer_secret), ""); mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mUserStream = new TencocoaUserStreamObject(mConsumerKey, mConsumerSecret); } @Override public void onDestroy() { super.onDestroy(); if (mUserStream.isRunning()) stopCurrentUserStream(); } @Override public IBinder onBind(Intent intent) { return mBinder; } //action methods public void setTargetUser(TwitterAccountInformation info) { mUserStream.setNewAccount(info); } public TwitterAccountInformation getTargetUserInformation() { return mUserStream.getAccountInformation(); } public Twitter getTargetUserTwitterInstance() { return mUserStream.getTwitterInstance(); } public void startCurrentUserStream(TencocoaUserStreamLister listener) { AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { listener.addAdapter(mPassiveAdapterManager); mUserStream.start(listener); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); mPassiveAdapterManager.onUserStreamReset(mUserStream.getAccountInformation()); showNotification(R.string.notification_streaming_userstream_started_ticker, R.string.notification_streaming_userstream_started_text); } }; task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } public void stopCurrentUserStream() { if (mUserStream == null) return; AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { mUserStream.stop(); return null; } @Override protected void onPostExecute(Void aVoid) { showNotification(R.string.notification_streaming_userstream_finished_ticker, R.string.notification_streaming_userstream_finished_text); } }; task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); //mUserStream.shutdown(); //mUserStream.removeListener(mUserStreamListener); } public boolean isUserStreamRunning() { return mUserStream.isRunning(); } public void addUserStreamPassiveAdapter(TencocoaUserStreamPassiveAdapter adapter) { mPassiveAdapterManager.addAdapter(adapter); } public void removeUserStreamPassiveAdapter(TencocoaUserStreamPassiveAdapter adapter) { mPassiveAdapterManager.removeAdapter(adapter); } public class TencocoaStreamingServiceBinder extends Binder { public TencocoaStreamingService getService() { return TencocoaStreamingService.this; } } public static class TencocoaUserStreamPassiveAdapter extends UserStreamAdapter { public void onUserStreamReset(TwitterAccountInformation info) { } } public static class TencocoaUserStreamPassiveAdapterManager extends UserStreamAdapter { protected List<TencocoaUserStreamPassiveAdapter> mAdapters; public void onUserStreamReset(TwitterAccountInformation info) { for (TencocoaUserStreamPassiveAdapter i : mAdapters) i.onUserStreamReset(info); } public TencocoaUserStreamPassiveAdapterManager() { mAdapters = new ArrayList<>(); } public void addAdapter(TencocoaUserStreamPassiveAdapter adapter) { mAdapters.add(adapter); } public void removeAdapter(TencocoaUserStreamPassiveAdapter adapter) { mAdapters.remove(adapter); } public void clearAdapter() { mAdapters.clear(); } @Override public void onDeletionNotice(long directMessageId, long userId) { for (UserStreamAdapter i : mAdapters) i.onDeletionNotice(directMessageId, userId); } @Override public void onFriendList(long[] friendIds) { for (UserStreamAdapter i : mAdapters) i.onFriendList(friendIds); } @Override public void onFavorite(User source, User target, Status favoritedStatus) { for (UserStreamAdapter i : mAdapters) i.onFavorite(source, target, favoritedStatus); } @Override public void onUnfavorite(User source, User target, Status unfavoritedStatus) { for (UserStreamAdapter i : mAdapters) i.onUnfavorite(source, target, unfavoritedStatus); } @Override public void onFollow(User source, User followedUser) { for (UserStreamAdapter i : mAdapters) i.onFollow(source, followedUser); } @Override public void onUnfollow(User source, User unfollowedUser) { for (UserStreamAdapter i : mAdapters) i.onUnfollow(source, unfollowedUser); } @Override public void onDirectMessage(DirectMessage directMessage) { for (UserStreamAdapter i : mAdapters) i.onDirectMessage(directMessage); } @Override public void onUserListMemberAddition(User addedMember, User listOwner, UserList list) { for (UserStreamAdapter i : mAdapters) onUserListMemberAddition(addedMember, listOwner, list); } @Override public void onUserListMemberDeletion(User deletedMember, User listOwner, UserList list) { for (UserStreamAdapter i : mAdapters) i.onUserListMemberDeletion(deletedMember, listOwner, list); } @Override public void onUserListSubscription(User subscriber, User listOwner, UserList list) { for (UserStreamAdapter i : mAdapters) i.onUserListSubscription(subscriber, listOwner, list); } @Override public void onUserListUnsubscription(User subscriber, User listOwner, UserList list) { for (UserStreamAdapter i : mAdapters) i.onUserListUnsubscription(subscriber, listOwner, list); } @Override public void onUserListCreation(User listOwner, UserList list) { for (UserStreamAdapter i : mAdapters) i.onUserListCreation(listOwner, list); } @Override public void onUserListUpdate(User listOwner, UserList list) { for (UserStreamAdapter i : mAdapters) i.onUserListUpdate(listOwner, list); } @Override public void onUserListDeletion(User listOwner, UserList list) { for (UserStreamAdapter i : mAdapters) i.onUserListDeletion(listOwner, list); } @Override public void onUserProfileUpdate(User updatedUser) { for (UserStreamAdapter i : mAdapters) i.onUserProfileUpdate(updatedUser); } @Override public void onUserSuspension(long suspendedUser) { for (UserStreamAdapter i : mAdapters) i.onUserSuspension(suspendedUser); } @Override public void onUserDeletion(long deletedUser) { for (UserStreamAdapter i : mAdapters) i.onUserDeletion(deletedUser); } @Override public void onBlock(User source, User blockedUser) { for (UserStreamAdapter i : mAdapters) i.onBlock(source, blockedUser); } @Override public void onUnblock(User source, User unblockedUser) { for (UserStreamAdapter i : mAdapters) i.onUnblock(source, unblockedUser); } @Override public void onRetweetedRetweet(User source, User target, Status retweetedStatus) { for (UserStreamAdapter i : mAdapters) i.onRetweetedRetweet(source, target, retweetedStatus); } @Override public void onFavoritedRetweet(User source, User target, Status favoritedRetweet) { for (UserStreamAdapter i : mAdapters) i.onFavoritedRetweet(source, target, favoritedRetweet); } @Override public void onQuotedTweet(User source, User target, Status quotingTweet) { for (UserStreamAdapter i : mAdapters) i.onRetweetedRetweet(source, target, quotingTweet); } @Override public void onStatus(Status status) { for (UserStreamAdapter i : mAdapters) i.onStatus(status); } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { for (UserStreamAdapter i : mAdapters) i.onDeletionNotice(statusDeletionNotice); } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { for (UserStreamAdapter i : mAdapters) i.onTrackLimitationNotice(numberOfLimitedStatuses); } @Override public void onScrubGeo(long userId, long upToStatusId) { for (UserStreamAdapter i : mAdapters) i.onScrubGeo(userId, upToStatusId); } @Override public void onStallWarning(StallWarning warning) { for (UserStreamAdapter i : mAdapters) i.onStallWarning(warning); } @Override public void onException(Exception ex) { for (UserStreamAdapter i : mAdapters) i.onException(ex); } } }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.trans.steps.insertupdate; import static org.junit.Assert.assertArrayEquals; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.pentaho.di.core.KettleEnvironment; import org.pentaho.di.core.RowMetaAndData; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.plugins.PluginRegistry; import org.pentaho.di.core.plugins.StepPluginType; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.trans.RowProducer; import org.pentaho.di.trans.RowStepCollector; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransHopMeta; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.steps.injector.InjectorMeta; public class InsertUpdateTest extends TestCase { public static final String[] databasesXML = { "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<connection>" + "<name>db</name>" + "<server>127.0.0.1</server>" + "<type>H2</type>" + "<access>Native</access>" + "<database>mem:db</database>" + "<port></port>" + "<username>sa</username>" + "<password></password>" + "</connection>", }; public static final String TARGET_TABLE = "insertupdate_step_test_case_table"; private static String[] insertStatement = { // New rows for the source "INSERT INTO " + TARGET_TABLE + "(ID, CODE, VALUE, ROW_ORDER) " + "VALUES (NULL, NULL, 'null_id_code', 1)", "INSERT INTO " + TARGET_TABLE + "(ID, CODE, VALUE, ROW_ORDER) " + "VALUES (NULL, 1, 'null_id', 3)", "INSERT INTO " + TARGET_TABLE + "(ID, CODE, VALUE, ROW_ORDER) " + "VALUES (1, NULL, 'null_code', 5)", "INSERT INTO " + TARGET_TABLE + "(ID, CODE, VALUE, ROW_ORDER) " + "VALUES (2, 2, 'non_null_keys', 7)", }; // this points to the transformation Trans trans; // this points to the update step being tested public InsertUpdateMeta insupd; // these are used to write and read rows in the test transformation public RowStepCollector rc; public RowProducer rp; // the database used for the transformation run public Database db; // returns the structure of the target table public RowMetaInterface getTargetTableRowMeta() { RowMetaInterface rm = new RowMeta(); ValueMetaInterface[] valuesMeta = { new ValueMeta( "ID", ValueMeta.TYPE_INTEGER, 8, 0 ), new ValueMeta( "CODE", ValueMeta.TYPE_INTEGER, 8, 0 ), new ValueMeta( "VALUE", ValueMeta.TYPE_STRING, 255, 0 ), new ValueMeta( "ROW_ORDER", ValueMeta.TYPE_INTEGER, 8, 0 ), }; for ( int i = 0; i < valuesMeta.length; i++ ) { rm.addValueMeta( valuesMeta[i] ); } return rm; } // adds lookup key line definition to the update step // input is in format {key, condition, stream, stream2} public void addLookup( String[] def ) { // make sure to initialize the step if ( insupd.getKeyLookup() == null ) { insupd.setKeyLookup( new String[0] ); insupd.setKeyCondition( new String[0] ); insupd.setKeyStream( new String[0] ); insupd.setKeyStream2( new String[0] ); } int newLength = insupd.getKeyLookup().length + 1; ArrayList<String> newKeyLookup = new ArrayList<String>( newLength ); newKeyLookup.addAll( Arrays.asList( insupd.getKeyLookup() ) ); newKeyLookup.add( def[0] ); insupd.setKeyLookup( newKeyLookup.toArray( new String[0] ) ); ArrayList<String> newKeyCondition = new ArrayList<String>( newLength ); newKeyCondition.addAll( Arrays.asList( insupd.getKeyCondition() ) ); newKeyCondition.add( def[1] ); insupd.setKeyCondition( newKeyCondition.toArray( new String[0] ) ); ArrayList<String> newKeyStream = new ArrayList<String>( newLength ); newKeyStream.addAll( Arrays.asList( insupd.getKeyStream() ) ); newKeyStream.add( def[2] ); insupd.setKeyStream( newKeyStream.toArray( new String[0] ) ); ArrayList<String> newKeyStream2 = new ArrayList<String>( newLength ); newKeyStream2.addAll( Arrays.asList( insupd.getKeyStream2() ) ); newKeyStream2.add( def[3] ); insupd.setKeyStream2( newKeyStream2.toArray( new String[0] ) ); } @Before public void setUp() throws Exception { KettleEnvironment.init(); /* SET UP TRANSFORMATION */ // Create a new transformation... TransMeta transMeta = new TransMeta(); transMeta.setName( "insert/update test" ); // Add the database connections for ( int i = 0; i < databasesXML.length; i++ ) { DatabaseMeta databaseMeta = new DatabaseMeta( databasesXML[i] ); transMeta.addDatabase( databaseMeta ); } DatabaseMeta dbInfo = transMeta.findDatabase( "db" ); /* SET UP DATABASE */ // Create target table db = new Database( transMeta, dbInfo ); db.connect(); String source = db.getCreateTableStatement( TARGET_TABLE, getTargetTableRowMeta(), null, false, null, true ); db.execStatement( source ); // populate target table for ( String sql : insertStatement ) { db.execStatement( sql ); } /* SET UP TRANSFORMATION STEPS */ PluginRegistry registry = PluginRegistry.getInstance(); // create an injector step... String injectorStepName = "injector step"; InjectorMeta im = new InjectorMeta(); // Set the information of the injector. String injectorPid = registry.getPluginId( StepPluginType.class, im ); StepMeta injectorStep = new StepMeta( injectorPid, injectorStepName, im ); transMeta.addStep( injectorStep ); // create the update step... String updateStepName = "insert/update [" + TARGET_TABLE + "]"; insupd = new InsertUpdateMeta(); insupd.setDatabaseMeta( transMeta.findDatabase( "db" ) ); insupd.setTableName( TARGET_TABLE ); insupd.setUpdateLookup( new String[] { "VALUE", "ROW_ORDER" } ); insupd.setUpdateStream( new String[] { "VALUE", "ROW_ORDER" } ); insupd.setUpdate( new Boolean[] { true, false } ); String fromid = registry.getPluginId( StepPluginType.class, insupd ); StepMeta updateStep = new StepMeta( fromid, updateStepName, insupd ); updateStep.setDescription( "insert/update data in table [" + TARGET_TABLE + "] on database [" + dbInfo + "]" ); transMeta.addStep( updateStep ); TransHopMeta hi = new TransHopMeta( injectorStep, updateStep ); transMeta.addTransHop( hi ); /* PREPARE TRANSFORMATION EXECUTION */ trans = new Trans( transMeta ); trans.prepareExecution( null ); StepInterface si = trans.getStepInterface( updateStepName, 0 ); rc = new RowStepCollector(); si.addRowListener( rc ); rp = trans.addRowProducer( injectorStepName, 0 ); } @After public void tearDown() throws Exception { /* DROP THE TEST TABLE */ if ( db != null ) { db.execStatement( "DROP TABLE " + TARGET_TABLE + ";" ); db.disconnect(); } db = null; insupd = null; trans = null; rc = null; rp = null; } public List<RowMetaAndData> createMatchingDataRows() { RowMetaInterface rm = getTargetTableRowMeta(); List<RowMetaAndData> list = new ArrayList<RowMetaAndData>(); list.add( new RowMetaAndData( rm, new Object[] { null, null, "null_id_code_insupd", 2L } ) ); list.add( new RowMetaAndData( rm, new Object[] { null, 1L, "null_id_insupd", 4L } ) ); list.add( new RowMetaAndData( rm, new Object[] { 1L, null, "null_code_insupd", 6L } ) ); list.add( new RowMetaAndData( rm, new Object[] { 2L, 2L, "updated", 8L } ) ); return list; } // this method pumps rows to the update step; public void pumpMatchingRows() throws Exception { pumpRows( createMatchingDataRows() ); } public void pumpRows( List<RowMetaAndData> inputList ) throws Exception { trans.startThreads(); // add rows for ( RowMetaAndData rm : inputList ) { rp.putRow( rm.getRowMeta(), rm.getData() ); } rp.finished(); trans.waitUntilFinished(); if ( trans.getErrors() > 0 ) { fail( "test transformation failed, check logs!" ); } } public String[] getDbRows() throws Exception { ResultSet rs = db.openQuery( "SELECT VALUE FROM " + TARGET_TABLE + " ORDER BY ROW_ORDER ASC;" ); ArrayList<String> rows = new ArrayList<String>(); while ( rs.next() ) { rows.add( rs.getString( "VALUE" ) ); } return rows.toArray( new String[0] ); } public void testUpdateEquals() throws Exception { addLookup( new String[] { "ID", "=", "ID", "" } ); pumpMatchingRows(); String[] rows = getDbRows(); // now the 1,null and 2,2 record should have been updated // the others got inserted String[] expected = { "null_id_code", "null_id_code_insupd", "null_id", "null_id_insupd", "null_code_insupd", "updated" }; assertArrayEquals( "Unexpected changes by insert/update step", expected, rows ); } public void testUpdateEqualsTwoKeys() throws Exception { addLookup( new String[] { "ID", "=", "ID", "" } ); addLookup( new String[] { "CODE", "=", "CODE", "" } ); pumpMatchingRows(); String[] rows = getDbRows(); // now the 2,2 record should have been updated String[] expected = { "null_id_code", "null_id_code_insupd", "null_id", "null_id_insupd", "null_code", "null_code_insupd", "updated" }; assertArrayEquals( "Unexpected changes by insert/update step", expected, rows ); } public void testUpdateEqualsSupportsNull() throws Exception { addLookup( new String[] { "ID", "= ~NULL", "ID", "" } ); pumpMatchingRows(); String[] rows = getDbRows(); // now all records should have been updated, the later matching records taking precedence String[] expected = { "null_id_insupd", "null_id_insupd", "null_code_insupd", "updated" }; assertArrayEquals( "Unexpected changes by insert/update step", expected, rows ); } public void testUpdateEqualsSupportsNullTwoKeys() throws Exception { addLookup( new String[] { "ID", "= ~NULL", "ID", "" } ); addLookup( new String[] { "CODE", "= ~NULL", "CODE", "" } ); pumpMatchingRows(); String[] rows = getDbRows(); // now all records should have been updated String[] expected = { "null_id_code_insupd", "null_id_insupd", "null_code_insupd", "updated" }; assertArrayEquals( "Unexpected changes by insert/update step", expected, rows ); } public void testUpdateEqualsSupportsNullTwoKeysMixed() throws Exception { addLookup( new String[] { "ID", "= ~NULL", "ID", "" } ); addLookup( new String[] { "CODE", "=", "CODE", "" } ); pumpMatchingRows(); String[] rows = getDbRows(); // now [null,1], [2,2] records should have been updated, rest inserted String[] expected = { "null_id_code", "null_id_code_insupd", "null_id_insupd", "null_code", "null_code_insupd", "updated" }; assertArrayEquals( "Unexpected changes by insert/update step", expected, rows ); } public void testUpdateIsNull() throws Exception { addLookup( new String[] { "CODE", "IS NULL", "", "" } ); pumpMatchingRows(); String[] rows = getDbRows(); // now [null, null], [1,null] records should have been updated, last record taking precedence String[] expected = { "updated", "null_id", "updated", "non_null_keys" }; assertArrayEquals( "Unexpected changes by insert/update step", expected, rows ); } public void testUpdateIsNotNull() throws Exception { addLookup( new String[] { "CODE", "IS NOT NULL", "", "" } ); pumpMatchingRows(); String[] rows = getDbRows(); // now [null, 1], [2,2] records should have been updated, last record taking precedence String[] expected = { "null_id_code", "updated", "null_code", "updated" }; assertArrayEquals( "Unexpected changes by insert/update step", expected, rows ); } public void testUpdateBetween() throws Exception { addLookup( new String[] { "ID", "BETWEEN", "ID", "CODE" } ); pumpMatchingRows(); String[] rows = getDbRows(); // now [2,2] record should have been updated, rest is inserted String[] expected = { "null_id_code", "null_id_code_insupd", "null_id", "null_id_insupd", "null_code", "null_code_insupd", "updated" }; assertArrayEquals( "Unexpected changes by insert/update step", expected, rows ); } public void testUpdateEqualsSupportsNullTwoKeysMixed2() throws Exception { addLookup( new String[] { "ID", "=", "ID", "" } ); addLookup( new String[] { "CODE", "= ~NULL", "CODE", "" } ); pumpMatchingRows(); String[] rows = getDbRows(); // now [1,null], [2,2] records should have been updated, rest inserted String[] expected = { "null_id_code", "null_id_code_insupd", "null_id", "null_id_insupd", "null_code_insupd", "updated" }; assertArrayEquals( "Unexpected changes by insert/update step", expected, rows ); } }
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.action.support; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionRunnable; import org.elasticsearch.common.Randomness; import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException; import org.elasticsearch.core.TimeValue; import org.elasticsearch.threadpool.Scheduler; import org.elasticsearch.threadpool.ThreadPool; import java.util.ArrayDeque; import java.util.concurrent.atomic.AtomicBoolean; /** * A action that will be retried on failure if {@link RetryableAction#shouldRetry(Exception)} returns true. * The executor the action will be executed on can be defined in the constructor. Otherwise, SAME is the * default. The action will be retried with exponentially increasing delay periods until the timeout period * has been reached. */ public abstract class RetryableAction<Response> { private final Logger logger; private final AtomicBoolean isDone = new AtomicBoolean(false); private final ThreadPool threadPool; private final long initialDelayMillis; private final long timeoutMillis; private final long startMillis; private final ActionListener<Response> finalListener; private final String executor; private volatile Scheduler.ScheduledCancellable retryTask; public RetryableAction( Logger logger, ThreadPool threadPool, TimeValue initialDelay, TimeValue timeoutValue, ActionListener<Response> listener ) { this(logger, threadPool, initialDelay, timeoutValue, listener, ThreadPool.Names.SAME); } public RetryableAction( Logger logger, ThreadPool threadPool, TimeValue initialDelay, TimeValue timeoutValue, ActionListener<Response> listener, String executor ) { this.logger = logger; this.threadPool = threadPool; this.initialDelayMillis = initialDelay.getMillis(); if (initialDelayMillis < 1) { throw new IllegalArgumentException("Initial delay was less than 1 millisecond: " + initialDelay); } this.timeoutMillis = timeoutValue.getMillis(); this.startMillis = threadPool.relativeTimeInMillis(); this.finalListener = listener; this.executor = executor; } public void run() { final RetryingListener retryingListener = new RetryingListener(initialDelayMillis, null); final Runnable runnable = createRunnable(retryingListener); threadPool.executor(executor).execute(runnable); } public void cancel(Exception e) { if (isDone.compareAndSet(false, true)) { Scheduler.ScheduledCancellable localRetryTask = this.retryTask; if (localRetryTask != null) { localRetryTask.cancel(); } onFinished(); finalListener.onFailure(e); } } private Runnable createRunnable(RetryingListener retryingListener) { return new ActionRunnable<>(retryingListener) { @Override protected void doRun() { retryTask = null; // It is possible that the task was cancelled in between the retry being dispatched and now if (isDone.get() == false) { tryAction(listener); } } @Override public void onRejection(Exception e) { retryTask = null; // TODO: The only implementations of this class use SAME which means the execution will not be // rejected. Future implementations can adjust this functionality as needed. onFailure(e); } }; } public abstract void tryAction(ActionListener<Response> listener); public abstract boolean shouldRetry(Exception e); protected long calculateDelayBound(long previousDelayBound) { return Math.min(previousDelayBound * 2, Integer.MAX_VALUE); } protected long minimumDelayMillis() { return 0L; } public void onFinished() {} private class RetryingListener implements ActionListener<Response> { private static final int MAX_EXCEPTIONS = 4; private final long delayMillisBound; private ArrayDeque<Exception> caughtExceptions; private RetryingListener(long delayMillisBound, ArrayDeque<Exception> caughtExceptions) { this.delayMillisBound = delayMillisBound; this.caughtExceptions = caughtExceptions; } @Override public void onResponse(Response response) { if (isDone.compareAndSet(false, true)) { onFinished(); finalListener.onResponse(response); } } @Override public void onFailure(Exception e) { if (shouldRetry(e)) { final long elapsedMillis = threadPool.relativeTimeInMillis() - startMillis; if (elapsedMillis >= timeoutMillis) { logger.debug( () -> new ParameterizedMessage("retryable action timed out after {}", TimeValue.timeValueMillis(elapsedMillis)), e ); onFinalFailure(e); } else { addException(e); final long nextDelayMillisBound = calculateDelayBound(delayMillisBound); final RetryingListener retryingListener = new RetryingListener(nextDelayMillisBound, caughtExceptions); final Runnable runnable = createRunnable(retryingListener); int range = Math.toIntExact((delayMillisBound + 1) / 2); final long delayMillis = Randomness.get().nextInt(range) + delayMillisBound - range + 1L; assert delayMillis > 0; if (isDone.get() == false) { final TimeValue delay = TimeValue.timeValueMillis(delayMillis); logger.debug(() -> new ParameterizedMessage("retrying action that failed in {}", delay), e); try { retryTask = threadPool.schedule(runnable, delay, executor); } catch (EsRejectedExecutionException ree) { onFinalFailure(ree); } } } } else { onFinalFailure(e); } } private void onFinalFailure(Exception e) { addException(e); if (isDone.compareAndSet(false, true)) { onFinished(); finalListener.onFailure(buildFinalException()); } } private Exception buildFinalException() { final Exception topLevel = caughtExceptions.removeFirst(); Exception suppressed; while ((suppressed = caughtExceptions.pollFirst()) != null) { topLevel.addSuppressed(suppressed); } return topLevel; } private void addException(Exception e) { if (caughtExceptions != null) { if (caughtExceptions.size() == MAX_EXCEPTIONS) { caughtExceptions.removeLast(); } } else { caughtExceptions = new ArrayDeque<>(MAX_EXCEPTIONS); } caughtExceptions.addFirst(e); } } }
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.component.factory.master; import java.util.LinkedHashMap; import java.util.Map; import org.joda.beans.Bean; import org.joda.beans.BeanBuilder; import org.joda.beans.BeanDefinition; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaProperty; import org.joda.beans.Property; import org.joda.beans.PropertyDefinition; import org.joda.beans.impl.direct.DirectBeanBuilder; import org.joda.beans.impl.direct.DirectMetaProperty; import org.joda.beans.impl.direct.DirectMetaPropertyMap; import com.opengamma.component.ComponentInfo; import com.opengamma.component.ComponentRepository; import com.opengamma.component.factory.AbstractComponentFactory; import com.opengamma.component.factory.ComponentInfoAttributes; import com.opengamma.master.position.PositionMaster; import com.opengamma.master.position.impl.DataPositionMasterResource; import com.opengamma.master.position.impl.EHCachingPositionMaster; import com.opengamma.master.position.impl.RemotePositionMaster; import net.sf.ehcache.CacheManager; /** * Component factory for the combined position master. * <p> * This factory creates a combined position master from an underlying and user master. */ @BeanDefinition public class EHCachingPositionMasterComponentFactory extends AbstractComponentFactory { /** * The classifier that the factory should publish under. */ @PropertyDefinition(validate = "notNull") private String _classifier; /** * The flag determining whether the component should be published by REST (default true). */ @PropertyDefinition private boolean _publishRest = true; /** * The underlying position master. */ @PropertyDefinition(validate = "notNull") private PositionMaster _underlying; /** * The cache manager. */ @PropertyDefinition private CacheManager _cacheManager; //------------------------------------------------------------------------- @Override public void init(final ComponentRepository repo, final LinkedHashMap<String, String> configuration) { final PositionMaster master = new EHCachingPositionMaster(getClassifier(), getUnderlying(), getCacheManager()); // register final ComponentInfo info = new ComponentInfo(PositionMaster.class, getClassifier()); info.addAttribute(ComponentInfoAttributes.LEVEL, 2); if (isPublishRest()) { info.addAttribute(ComponentInfoAttributes.REMOTE_CLIENT_JAVA, RemotePositionMaster.class); } repo.registerComponent(info, master); if (isPublishRest()) { repo.getRestComponents().publish(info, new DataPositionMasterResource(master)); } } //------------------------- AUTOGENERATED START ------------------------- ///CLOVER:OFF /** * The meta-bean for {@code EHCachingPositionMasterComponentFactory}. * @return the meta-bean, not null */ public static EHCachingPositionMasterComponentFactory.Meta meta() { return EHCachingPositionMasterComponentFactory.Meta.INSTANCE; } static { JodaBeanUtils.registerMetaBean(EHCachingPositionMasterComponentFactory.Meta.INSTANCE); } @Override public EHCachingPositionMasterComponentFactory.Meta metaBean() { return EHCachingPositionMasterComponentFactory.Meta.INSTANCE; } //----------------------------------------------------------------------- /** * Gets the classifier that the factory should publish under. * @return the value of the property, not null */ public String getClassifier() { return _classifier; } /** * Sets the classifier that the factory should publish under. * @param classifier the new value of the property, not null */ public void setClassifier(String classifier) { JodaBeanUtils.notNull(classifier, "classifier"); this._classifier = classifier; } /** * Gets the the {@code classifier} property. * @return the property, not null */ public final Property<String> classifier() { return metaBean().classifier().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the flag determining whether the component should be published by REST (default true). * @return the value of the property */ public boolean isPublishRest() { return _publishRest; } /** * Sets the flag determining whether the component should be published by REST (default true). * @param publishRest the new value of the property */ public void setPublishRest(boolean publishRest) { this._publishRest = publishRest; } /** * Gets the the {@code publishRest} property. * @return the property, not null */ public final Property<Boolean> publishRest() { return metaBean().publishRest().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the underlying position master. * @return the value of the property, not null */ public PositionMaster getUnderlying() { return _underlying; } /** * Sets the underlying position master. * @param underlying the new value of the property, not null */ public void setUnderlying(PositionMaster underlying) { JodaBeanUtils.notNull(underlying, "underlying"); this._underlying = underlying; } /** * Gets the the {@code underlying} property. * @return the property, not null */ public final Property<PositionMaster> underlying() { return metaBean().underlying().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the cache manager. * @return the value of the property */ public CacheManager getCacheManager() { return _cacheManager; } /** * Sets the cache manager. * @param cacheManager the new value of the property */ public void setCacheManager(CacheManager cacheManager) { this._cacheManager = cacheManager; } /** * Gets the the {@code cacheManager} property. * @return the property, not null */ public final Property<CacheManager> cacheManager() { return metaBean().cacheManager().createProperty(this); } //----------------------------------------------------------------------- @Override public EHCachingPositionMasterComponentFactory clone() { return JodaBeanUtils.cloneAlways(this); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { EHCachingPositionMasterComponentFactory other = (EHCachingPositionMasterComponentFactory) obj; return JodaBeanUtils.equal(getClassifier(), other.getClassifier()) && (isPublishRest() == other.isPublishRest()) && JodaBeanUtils.equal(getUnderlying(), other.getUnderlying()) && JodaBeanUtils.equal(getCacheManager(), other.getCacheManager()) && super.equals(obj); } return false; } @Override public int hashCode() { int hash = 7; hash = hash * 31 + JodaBeanUtils.hashCode(getClassifier()); hash = hash * 31 + JodaBeanUtils.hashCode(isPublishRest()); hash = hash * 31 + JodaBeanUtils.hashCode(getUnderlying()); hash = hash * 31 + JodaBeanUtils.hashCode(getCacheManager()); return hash ^ super.hashCode(); } @Override public String toString() { StringBuilder buf = new StringBuilder(160); buf.append("EHCachingPositionMasterComponentFactory{"); int len = buf.length(); toString(buf); if (buf.length() > len) { buf.setLength(buf.length() - 2); } buf.append('}'); return buf.toString(); } @Override protected void toString(StringBuilder buf) { super.toString(buf); buf.append("classifier").append('=').append(JodaBeanUtils.toString(getClassifier())).append(',').append(' '); buf.append("publishRest").append('=').append(JodaBeanUtils.toString(isPublishRest())).append(',').append(' '); buf.append("underlying").append('=').append(JodaBeanUtils.toString(getUnderlying())).append(',').append(' '); buf.append("cacheManager").append('=').append(JodaBeanUtils.toString(getCacheManager())).append(',').append(' '); } //----------------------------------------------------------------------- /** * The meta-bean for {@code EHCachingPositionMasterComponentFactory}. */ public static class Meta extends AbstractComponentFactory.Meta { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code classifier} property. */ private final MetaProperty<String> _classifier = DirectMetaProperty.ofReadWrite( this, "classifier", EHCachingPositionMasterComponentFactory.class, String.class); /** * The meta-property for the {@code publishRest} property. */ private final MetaProperty<Boolean> _publishRest = DirectMetaProperty.ofReadWrite( this, "publishRest", EHCachingPositionMasterComponentFactory.class, Boolean.TYPE); /** * The meta-property for the {@code underlying} property. */ private final MetaProperty<PositionMaster> _underlying = DirectMetaProperty.ofReadWrite( this, "underlying", EHCachingPositionMasterComponentFactory.class, PositionMaster.class); /** * The meta-property for the {@code cacheManager} property. */ private final MetaProperty<CacheManager> _cacheManager = DirectMetaProperty.ofReadWrite( this, "cacheManager", EHCachingPositionMasterComponentFactory.class, CacheManager.class); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap( this, (DirectMetaPropertyMap) super.metaPropertyMap(), "classifier", "publishRest", "underlying", "cacheManager"); /** * Restricted constructor. */ protected Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case -281470431: // classifier return _classifier; case -614707837: // publishRest return _publishRest; case -1770633379: // underlying return _underlying; case -1452875317: // cacheManager return _cacheManager; } return super.metaPropertyGet(propertyName); } @Override public BeanBuilder<? extends EHCachingPositionMasterComponentFactory> builder() { return new DirectBeanBuilder<EHCachingPositionMasterComponentFactory>(new EHCachingPositionMasterComponentFactory()); } @Override public Class<? extends EHCachingPositionMasterComponentFactory> beanType() { return EHCachingPositionMasterComponentFactory.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return _metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code classifier} property. * @return the meta-property, not null */ public final MetaProperty<String> classifier() { return _classifier; } /** * The meta-property for the {@code publishRest} property. * @return the meta-property, not null */ public final MetaProperty<Boolean> publishRest() { return _publishRest; } /** * The meta-property for the {@code underlying} property. * @return the meta-property, not null */ public final MetaProperty<PositionMaster> underlying() { return _underlying; } /** * The meta-property for the {@code cacheManager} property. * @return the meta-property, not null */ public final MetaProperty<CacheManager> cacheManager() { return _cacheManager; } //----------------------------------------------------------------------- @Override protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case -281470431: // classifier return ((EHCachingPositionMasterComponentFactory) bean).getClassifier(); case -614707837: // publishRest return ((EHCachingPositionMasterComponentFactory) bean).isPublishRest(); case -1770633379: // underlying return ((EHCachingPositionMasterComponentFactory) bean).getUnderlying(); case -1452875317: // cacheManager return ((EHCachingPositionMasterComponentFactory) bean).getCacheManager(); } return super.propertyGet(bean, propertyName, quiet); } @Override protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) { switch (propertyName.hashCode()) { case -281470431: // classifier ((EHCachingPositionMasterComponentFactory) bean).setClassifier((String) newValue); return; case -614707837: // publishRest ((EHCachingPositionMasterComponentFactory) bean).setPublishRest((Boolean) newValue); return; case -1770633379: // underlying ((EHCachingPositionMasterComponentFactory) bean).setUnderlying((PositionMaster) newValue); return; case -1452875317: // cacheManager ((EHCachingPositionMasterComponentFactory) bean).setCacheManager((CacheManager) newValue); return; } super.propertySet(bean, propertyName, newValue, quiet); } @Override protected void validate(Bean bean) { JodaBeanUtils.notNull(((EHCachingPositionMasterComponentFactory) bean)._classifier, "classifier"); JodaBeanUtils.notNull(((EHCachingPositionMasterComponentFactory) bean)._underlying, "underlying"); super.validate(bean); } } ///CLOVER:ON //-------------------------- AUTOGENERATED END -------------------------- }
/* * Copyright 2005 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.core.reteoo; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import org.drools.core.RuleBaseConfiguration; import org.drools.core.base.ClassObjectType; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.common.Memory; import org.drools.core.common.MemoryFactory; import org.drools.core.common.RuleBasePartitionId; import org.drools.core.common.TupleSets; import org.drools.core.common.UpdateContext; import org.drools.core.phreak.SegmentUtilities; import org.drools.core.reteoo.ObjectTypeNode.Id; import org.drools.core.reteoo.builder.BuildContext; import org.drools.core.rule.Pattern; import org.drools.core.spi.Activation; import org.drools.core.spi.ClassWireable; import org.drools.core.spi.ObjectType; import org.drools.core.spi.PropagationContext; import org.drools.core.spi.Tuple; import org.drools.core.util.AbstractBaseLinkedListNode; import org.drools.core.util.bitmask.AllSetBitMask; import org.drools.core.util.bitmask.BitMask; import org.kie.api.definition.rule.Rule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.drools.core.phreak.AddRemoveRule.flushLeftTupleIfNecessary; import static org.drools.core.reteoo.PropertySpecificUtil.isPropertyReactive; /** * All asserting Facts must propagated into the right <code>ObjectSink</code> side of a BetaNode, if this is the first Pattern * then there are no BetaNodes to propagate to. <code>LeftInputAdapter</code> is used to adapt an ObjectSink propagation into a * <code>TupleSource</code> which propagates a <code>ReteTuple</code> suitable fot the right <code>ReteTuple</code> side * of a <code>BetaNode</code>. */ public class LeftInputAdapterNode extends LeftTupleSource implements ObjectSinkNode, MemoryFactory<LeftInputAdapterNode.LiaNodeMemory> { protected static final transient Logger log = LoggerFactory.getLogger(LeftInputAdapterNode.class); private static final long serialVersionUID = 510L; private ObjectSource objectSource; private ObjectSinkNode previousRightTupleSinkNode; private ObjectSinkNode nextRightTupleSinkNode; private boolean leftTupleMemoryEnabled; protected BitMask sinkMask; public LeftInputAdapterNode() { } /** * Constructus a LeftInputAdapterNode with a unique id that receives <code>FactHandle</code> from a * parent <code>ObjectSource</code> and adds it to a given pattern in the resulting Tuples. * * @param id * The unique id of this node in the current Rete network * @param source * The parent node, where Facts are propagated from */ public LeftInputAdapterNode(final int id, final ObjectSource source, final BuildContext context) { super(id, context); this.objectSource = source; this.leftTupleMemoryEnabled = context.isTupleMemoryEnabled(); ObjectSource current = source; while (current.getType() != NodeTypeEnums.ObjectTypeNode) { current = current.getParentObjectSource(); } setStreamMode( context.isStreamMode() && context.getRootObjectTypeNode().getObjectType().isEvent() ); sinkMask = calculateSinkMask(context); hashcode = calculateHashCode(); } private BitMask calculateSinkMask(BuildContext context) { Pattern pattern = context.getLastBuiltPatterns() != null ? context.getLastBuiltPatterns()[0] : null; if (pattern == null) { return AllSetBitMask.get(); } ObjectType objectType = pattern.getObjectType(); if ( !(objectType instanceof ClassObjectType) ) { // Only ClassObjectType can use property specific return AllSetBitMask.get(); } Class objectClass = ((ClassWireable) objectType).getClassType(); return isPropertyReactive( context, objectClass ) ? pattern.getPositiveWatchMask( pattern.getAccessibleProperties( context.getKnowledgeBase() ) ) : AllSetBitMask.get(); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); objectSource = (ObjectSource) in.readObject(); leftTupleMemoryEnabled = in.readBoolean(); sinkMask = (BitMask) in.readObject(); } public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeObject(objectSource); out.writeBoolean(leftTupleMemoryEnabled); out.writeObject(sinkMask); } public ObjectSource getObjectSource() { return this.objectSource; } public short getType() { return NodeTypeEnums.LeftInputAdapterNode; } @Override public boolean isLeftTupleMemoryEnabled() { return leftTupleMemoryEnabled; } public ObjectSource getParentObjectSource() { return this.objectSource; } public void attach( BuildContext context ) { this.objectSource.addObjectSink( this ); } public void networkUpdated(UpdateContext updateContext) { this.objectSource.networkUpdated(updateContext); } public void assertObject(final InternalFactHandle factHandle, final PropagationContext context, final InternalWorkingMemory workingMemory) { LiaNodeMemory lm = workingMemory.getNodeMemory( this ); doInsertObject( factHandle, context, this, workingMemory, lm, true, // queries are handled directly, and not through here true ); } public static void doInsertObject(final InternalFactHandle factHandle, final PropagationContext context, final LeftInputAdapterNode liaNode, final InternalWorkingMemory wm, final LiaNodeMemory lm, boolean linkOrNotify, boolean useLeftMemory) { SegmentMemory sm = lm.getOrCreateSegmentMemory( liaNode, wm ); if ( sm.getTipNode() == liaNode) { // liaNode in it's own segment and child segments not yet created if ( sm.isEmpty() ) { SegmentUtilities.createChildSegments( wm, sm, liaNode.getSinkPropagator() ); } sm = sm.getFirst(); // repoint to the child sm } int counter = lm.getAndIncreaseCounter(); // node is not linked, so notify will happen when we link the node boolean notifySegment = linkOrNotify && counter != 0; if ( counter == 0) { // if there is no left mempry, then there is no linking or notification if ( linkOrNotify ) { // link and notify lm.linkNode( wm ); } else { // link without notify, when driven by a query, as we don't want it, placed on the agenda lm.linkNodeWithoutRuleNotify(); } } LeftTupleSink sink = liaNode.getSinkPropagator().getFirstLeftTupleSink(); LeftTuple leftTuple = sink.createLeftTuple( factHandle, useLeftMemory ); leftTuple.setPropagationContext( context ); doInsertSegmentMemory( wm, notifySegment, lm, sm, leftTuple, liaNode.isStreamMode() ); if ( sm.getRootNode() != liaNode ) { // sm points to lia child sm, so iterate for all remaining children for ( sm = sm.getNext(); sm != null; sm = sm.getNext() ) { sink = sm.getSinkFactory(); leftTuple = sink.createPeer( leftTuple ); // pctx is set during peer cloning doInsertSegmentMemory( wm, notifySegment, lm, sm, leftTuple, liaNode.isStreamMode() ); } } } public static void doInsertSegmentMemory( InternalWorkingMemory wm, boolean linkOrNotify, final LiaNodeMemory lm, SegmentMemory sm, LeftTuple leftTuple, boolean streamMode ) { if ( flushLeftTupleIfNecessary( wm, sm, leftTuple, streamMode, Tuple.INSERT ) ) { if ( linkOrNotify ) { lm.setNodeDirty( wm ); } return; } // mask check is necessary if insert is a result of a modify boolean stagedInsertWasEmpty = sm.getStagedLeftTuples().addInsert( leftTuple ); if ( stagedInsertWasEmpty && linkOrNotify ) { // staged is empty, so notify rule, to force re-evaluation. lm.setNodeDirty(wm); } } public static void doDeleteObject(LeftTuple leftTuple, PropagationContext context, SegmentMemory sm, final InternalWorkingMemory wm, final LeftInputAdapterNode liaNode, final boolean linkOrNotify, final LiaNodeMemory lm) { if ( sm.getTipNode() == liaNode ) { // liaNode in it's own segment and child segments not yet created if ( sm.isEmpty() ) { SegmentUtilities.createChildSegments( wm, sm, liaNode.getSinkPropagator() ); } sm = sm.getFirst(); // repoint to the child sm } doDeleteSegmentMemory(leftTuple, context, lm, sm, wm, linkOrNotify, liaNode.isStreamMode()); if ( sm.getNext() != null) { // sm points to lia child sm, so iterate for all remaining children for ( sm = sm.getNext(); sm != null; sm = sm.getNext() ) { // iterate for peers segment memory leftTuple = leftTuple.getPeer(); if (leftTuple == null) { break; } doDeleteSegmentMemory(leftTuple, context, lm, sm, wm, linkOrNotify, liaNode.isStreamMode()); } } if ( lm.getAndDecreaseCounter() == 1 ) { if ( linkOrNotify ) { lm.unlinkNode( wm ); } else { lm.unlinkNodeWithoutRuleNotify(); } } } private static void doDeleteSegmentMemory(LeftTuple leftTuple, PropagationContext pctx, final LiaNodeMemory lm, SegmentMemory sm, InternalWorkingMemory wm, boolean linkOrNotify, boolean streamMode) { leftTuple.setPropagationContext( pctx ); if ( flushLeftTupleIfNecessary( wm, sm, leftTuple, streamMode, Tuple.DELETE ) ) { if ( linkOrNotify ) { lm.setNodeDirty( wm ); } return; } TupleSets<LeftTuple> leftTuples = sm.getStagedLeftTuples(); boolean stagedDeleteWasEmpty = leftTuples.addDelete(leftTuple); if ( stagedDeleteWasEmpty && linkOrNotify ) { // staged is empty, so notify rule, to force re-evaluation lm.setNodeDirty(wm); } } public static void doUpdateObject(LeftTuple leftTuple, PropagationContext context, final InternalWorkingMemory wm, final LeftInputAdapterNode liaNode, final boolean linkOrNotify, final LiaNodeMemory lm, SegmentMemory sm) { if ( sm.getTipNode() == liaNode) { // liaNode in it's own segment and child segments not yet created if ( sm.isEmpty() ) { SegmentUtilities.createChildSegments( wm, sm, liaNode.getSinkPropagator() ); } sm = sm.getFirst(); // repoint to the child sm } TupleSets<LeftTuple> leftTuples = sm.getStagedLeftTuples(); doUpdateSegmentMemory(leftTuple, context, wm, linkOrNotify, lm, leftTuples, sm, liaNode.isStreamMode() ); if ( sm.getNext() != null ) { // sm points to lia child sm, so iterate for all remaining children for ( sm = sm.getNext(); sm != null; sm = sm.getNext() ) { // iterate for peers segment memory leftTuple = leftTuple.getPeer(); leftTuples = sm.getStagedLeftTuples(); doUpdateSegmentMemory(leftTuple, context, wm, linkOrNotify, lm, leftTuples, sm, liaNode.isStreamMode() ); } } } private static void doUpdateSegmentMemory( LeftTuple leftTuple, PropagationContext pctx, InternalWorkingMemory wm, boolean linkOrNotify, final LiaNodeMemory lm, TupleSets<LeftTuple> leftTuples, SegmentMemory sm, boolean streamMode ) { leftTuple.setPropagationContext( pctx ); if ( leftTuple.getStagedType() == LeftTuple.NONE ) { if ( flushLeftTupleIfNecessary( wm, sm, leftTuple, streamMode, Tuple.UPDATE ) ) { if ( linkOrNotify ) { lm.setNodeDirty( wm ); } return; } // if LeftTuple is already staged, leave it there boolean stagedUpdateWasEmpty = leftTuples.addUpdate(leftTuple); if ( stagedUpdateWasEmpty && linkOrNotify ) { // staged is empty, so notify rule, to force re-evaluation lm.setNodeDirty(wm); } } } public void retractLeftTuple(LeftTuple leftTuple, PropagationContext context, InternalWorkingMemory workingMemory) { LiaNodeMemory lm = workingMemory.getNodeMemory( this ); SegmentMemory smem = lm.getSegmentMemory(); if ( smem.getTipNode() == this ) { // segment with only a single LiaNode in it, skip to next segment // as a liaNode only segment has no staging smem = smem.getFirst(); } doDeleteObject( leftTuple, context, smem, workingMemory, this, true, lm ); } public void modifyObject(InternalFactHandle factHandle, final ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory workingMemory) { ObjectTypeNode.Id otnId = this.sink.getFirstLeftTupleSink().getLeftInputOtnId(); LeftTuple leftTuple = processDeletesFromModify(modifyPreviousTuples, context, workingMemory, otnId); LiaNodeMemory lm = workingMemory.getNodeMemory( this ); LeftTupleSink sink = getSinkPropagator().getFirstLeftTupleSink(); BitMask mask = sink.getLeftInferredMask(); if ( leftTuple != null && leftTuple.getInputOtnId().equals( otnId ) ) { modifyPreviousTuples.removeLeftTuple(partitionId); leftTuple.reAdd(); if ( context.getModificationMask().intersects( mask) ) { doUpdateObject(leftTuple, context, workingMemory, leftTuple.getTupleSource(), true, lm, lm.getOrCreateSegmentMemory(this, workingMemory ) ); if (leftTuple instanceof Activation) { ((Activation)leftTuple).setActive(true); } } } else { if ( context.getModificationMask().intersects( mask) ) { doInsertObject(factHandle, context, this, workingMemory, lm, true, true); } } } protected LeftTuple processDeletesFromModify(ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory workingMemory, Id otnId) { LeftTuple leftTuple = modifyPreviousTuples.peekLeftTuple(partitionId); while ( leftTuple != null && leftTuple.getInputOtnId().before( otnId ) ) { modifyPreviousTuples.removeLeftTuple(partitionId); modifyPreviousTuples.doDeleteObject(context, workingMemory, leftTuple); leftTuple = modifyPreviousTuples.peekLeftTuple(partitionId); } return leftTuple; } public void byPassModifyToBetaNode(InternalFactHandle factHandle, ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory workingMemory) { modifyObject(factHandle, modifyPreviousTuples, context, workingMemory ); } protected boolean doRemove(final RuleRemovalContext context, final ReteooBuilder builder) { if (!isInUse()) { objectSource.removeObjectSink(this); return true; } return false; } public LeftTuple createPeer(LeftTuple original) { return null; } /** * Returns the next node * @return * The next ObjectSinkNode */ public ObjectSinkNode getNextObjectSinkNode() { return this.nextRightTupleSinkNode; } /** * Sets the next node * @param next * The next ObjectSinkNode */ public void setNextObjectSinkNode(final ObjectSinkNode next) { this.nextRightTupleSinkNode = next; } /** * Returns the previous node * @return * The previous ObjectSinkNode */ public ObjectSinkNode getPreviousObjectSinkNode() { return this.previousRightTupleSinkNode; } /** * Sets the previous node * @param previous * The previous ObjectSinkNode */ public void setPreviousObjectSinkNode(final ObjectSinkNode previous) { this.previousRightTupleSinkNode = previous; } private int calculateHashCode() { return 31 * this.objectSource.hashCode() + 37 * sinkMask.hashCode(); } @Override public boolean equals(final Object object) { if (this == object) { return true; } if ( object.getClass() != LeftInputAdapterNode.class || this.hashCode() != object.hashCode() ) { return false; } return this.objectSource.getId() == ((LeftInputAdapterNode)object).objectSource.getId() && this.sinkMask.equals( ((LeftInputAdapterNode) object).sinkMask ); } @Override public ObjectTypeNode getObjectTypeNode() { ObjectSource source = this.objectSource; while ( source != null ) { if ( source instanceof ObjectTypeNode ) { return (ObjectTypeNode) source; } source = source.source; } return null; } public LiaNodeMemory createMemory(RuleBaseConfiguration config, InternalWorkingMemory wm) { return new LiaNodeMemory(); } public static class LiaNodeMemory extends AbstractBaseLinkedListNode<Memory> implements SegmentNodeMemory { private int counter; private SegmentMemory segmentMemory; private long nodePosMaskBit; public LiaNodeMemory() { } public int getCounter() { return counter; } public int getAndIncreaseCounter() { return this.counter++; } public int getAndDecreaseCounter() { return this.counter--; } public void setCounter(int counter) { this.counter = counter; } public SegmentMemory getSegmentMemory() { return segmentMemory; } public void setSegmentMemory(SegmentMemory segmentNodes) { this.segmentMemory = segmentNodes; } public long getNodePosMaskBit() { return nodePosMaskBit; } public void setNodePosMaskBit(long nodePosMask) { nodePosMaskBit = nodePosMask; } public void setNodeDirtyWithoutNotify() { } public void setNodeCleanWithoutNotify() { } public void linkNodeWithoutRuleNotify() { segmentMemory.linkNodeWithoutRuleNotify(nodePosMaskBit); } public void linkNode(InternalWorkingMemory wm) { segmentMemory.linkNode(nodePosMaskBit, wm); } public boolean unlinkNode(InternalWorkingMemory wm) { return segmentMemory.unlinkNode(nodePosMaskBit, wm); } public void unlinkNodeWithoutRuleNotify() { segmentMemory.unlinkNodeWithoutRuleNotify(nodePosMaskBit); } public short getNodeType() { return NodeTypeEnums.LeftInputAdapterNode; } public void setNodeDirty(InternalWorkingMemory wm) { segmentMemory.notifyRuleLinkSegment(wm, nodePosMaskBit); } public void reset() { counter = 0; } } /** * Used with the updateSink method, so that the parent ObjectSource * can update the TupleSink */ public static class RightTupleSinkAdapter implements ObjectSink { private LeftTupleSink sink; private LeftInputAdapterNode liaNode; public RightTupleSinkAdapter(LeftInputAdapterNode liaNode) { this.liaNode = liaNode; } /** * Do not use this constructor. It should be used just by deserialization. */ public RightTupleSinkAdapter() { } public void assertObject(final InternalFactHandle factHandle, final PropagationContext context, final InternalWorkingMemory workingMemory) { liaNode.assertObject(factHandle, context, workingMemory); } public void modifyObject(InternalFactHandle factHandle, ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory workingMemory) { throw new UnsupportedOperationException( "ObjectSinkAdapter onlys supports assertObject method calls" ); } public int getId() { return 0; } public RuleBasePartitionId getPartitionId() { return sink.getPartitionId(); } public void writeExternal(ObjectOutput out) throws IOException { // this is a short living adapter class used only during an update operation, and // as so, no need for serialization code } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // this is a short living adapter class used only during an update operation, and // as so, no need for serialization code } public void byPassModifyToBetaNode(InternalFactHandle factHandle, ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory workingMemory) { throw new UnsupportedOperationException(); } public short getType() { return NodeTypeEnums.LeftInputAdapterNode; } public int getAssociationsSize() { return sink.getAssociationsSize(); } public int getAssociatedRuleSize() { return sink.getAssociatedRuleSize(); } public int getAssociationsSize(Rule rule) { return sink.getAssociationsSize(rule); } public boolean isAssociatedWith( Rule rule ) { return sink.isAssociatedWith( rule ); } } @Override public void setSourcePartitionId(BuildContext context, RuleBasePartitionId partitionId) { setSourcePartitionId(objectSource, context, partitionId); } @Override public void setPartitionId(BuildContext context, RuleBasePartitionId partitionId) { if (this.partitionId != null && this.partitionId != partitionId) { objectSource.sink.changeSinkPartition(this, this.partitionId, partitionId, objectSource.alphaNodeHashingThreshold, objectSource.alphaNodeRangeIndexThreshold ); } this.partitionId = partitionId; } public boolean isTerminal() { return false; } }
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.item.inventory.adapter.impl.slots; import com.google.common.collect.ImmutableList; import net.minecraft.inventory.IInventory; import org.spongepowered.api.item.ItemType; import org.spongepowered.api.item.ItemTypes; import org.spongepowered.api.item.inventory.Inventory; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.Slot; import org.spongepowered.api.item.inventory.transaction.InventoryTransactionResult; import org.spongepowered.api.item.inventory.transaction.InventoryTransactionResult.Type; import org.spongepowered.common.interfaces.inventory.IMixinSlot; import org.spongepowered.common.item.inventory.adapter.InventoryAdapter; import org.spongepowered.common.item.inventory.adapter.impl.Adapter; import org.spongepowered.common.item.inventory.lens.Fabric; import org.spongepowered.common.item.inventory.lens.impl.MinecraftFabric; import org.spongepowered.common.item.inventory.lens.impl.slots.FakeSlotLensImpl; import org.spongepowered.common.item.inventory.lens.impl.slots.SlotLensImpl; import org.spongepowered.common.item.inventory.lens.slots.SlotLens; import org.spongepowered.common.item.inventory.util.ItemStackUtil; import java.util.Optional; public class SlotAdapter extends Adapter implements Slot { private final SlotLens<IInventory, net.minecraft.item.ItemStack> slot; private final int ordinal; private SlotAdapter nextSlot; private final ImmutableList<Inventory> slots; // Internal use for events, will be removed soon! public int slotNumber = -1; public SlotAdapter(net.minecraft.inventory.Slot slot) { this(MinecraftFabric.of(slot), getLens(slot), slot.inventory instanceof Inventory ? (Inventory) slot.inventory : null); this.slotNumber = slot.slotNumber; } @SuppressWarnings({"unchecked", "rawtypes"}) private static SlotLens<IInventory, net.minecraft.item.ItemStack> getLens(net.minecraft.inventory.Slot slot) { if (((IMixinSlot) slot).getSlotIndex() >= 0) { // Normal Slot? if (slot.inventory instanceof InventoryAdapter) { // If the inventory is an adapter we can get the existing SlotLens return ((InventoryAdapter) slot.inventory).getSlotProvider().getSlot(((IMixinSlot) slot).getSlotIndex()); } // otherwise fallback to a new SlotLens return new SlotLensImpl(((IMixinSlot) slot).getSlotIndex()); } return new FakeSlotLensImpl(slot); } public SlotAdapter(Fabric<IInventory> inventory, SlotLens<IInventory, net.minecraft.item.ItemStack> lens, Inventory parent) { super(inventory, lens, parent); this.slot = lens; this.ordinal = lens.getOrdinal(inventory); this.slots = ImmutableList.of(this); this.slotNumber = this.ordinal; // TODO this is used in events } public int getOrdinal() { return this.ordinal; } @Override public int getStackSize() { return this.slot.getStack(this.inventory).getCount(); } @SuppressWarnings("unchecked") @Override public <T extends Inventory> Iterable<T> slots() { return (Iterable<T>) this.slots; } @SuppressWarnings("unchecked") @Override public <T extends Inventory> T first() { return (T) this; } @Override public Optional<ItemStack> poll() { net.minecraft.item.ItemStack stack = this.inventory.getStack(this.ordinal); if (stack.isEmpty()) { return Optional.<ItemStack>empty(); } this.inventory.setStack(this.ordinal, net.minecraft.item.ItemStack.EMPTY); return Optional.<ItemStack>of(ItemStackUtil.fromNative(stack)); } @Override public Optional<ItemStack> poll(int limit) { return super.poll(limit); } @Override public Optional<ItemStack> peek() { net.minecraft.item.ItemStack stack = this.slot.getStack(this.inventory); if (stack.isEmpty()) { return Optional.empty(); } return ItemStackUtil.cloneDefensiveOptional(stack); } @Override public Optional<ItemStack> peek(int limit) { return super.peek(limit); } @Override public InventoryTransactionResult offer(ItemStack stack) { // // TODO Correct the transaction based on how offer goes // final net.minecraft.item.ItemStack old = this.inventory.getStack(this.ordinal); // if (!ItemStackUtil.compare(old, stack)) { // return InventoryTransactionResult.failNoTransactions(); // } // boolean canIncrease = getMaxStackSize() != old.stackSize; // if (!canIncrease) { // return InventoryTransactionResult.failNoTransactions(); // } // int remaining = getMaxStackSize() - old.stackSize; // int toBeOffered = stack.getQuantity(); // if (toBeOffered > remaining) { // old.stackSize += toBeOffered - remaining; // stack.setQuantity(toBeOffered - remaining); // } else { // old.stackSize += remaining; // // TODO Quantity being set 0 could be a problem... // stack.setQuantity(0); // } // this.inventory.markDirty(); // return InventoryTransactionResult.successNoTransactions(); InventoryTransactionResult.Builder result = InventoryTransactionResult.builder().type(Type.SUCCESS); net.minecraft.item.ItemStack nativeStack = ItemStackUtil.toNative(stack); int maxStackSize = this.slot.getMaxStackSize(this.inventory); int remaining = stack.getQuantity(); net.minecraft.item.ItemStack old = this.slot.getStack(this.inventory); int push = Math.min(remaining, maxStackSize); if (old.isEmpty() && this.slot.setStack(this.inventory, ItemStackUtil.cloneDefensiveNative(nativeStack, push))) { remaining -= push; } else if (!old.isEmpty() && ItemStackUtil.compareIgnoreQuantity(old, stack)) { push = Math.max(Math.min(maxStackSize - old.getCount(), remaining), 0); // max() accounts for oversized stacks old.setCount(old.getCount() + push); remaining -= push; } if (remaining == stack.getQuantity()) { // No items were consumed result.reject(ItemStackUtil.cloneDefensive(nativeStack)); } else { stack.setQuantity(remaining); } return result.build(); } @Override public InventoryTransactionResult set(ItemStack stack) { InventoryTransactionResult.Builder result = InventoryTransactionResult.builder().type(Type.SUCCESS); net.minecraft.item.ItemStack nativeStack = ItemStackUtil.toNative(stack); net.minecraft.item.ItemStack old = this.slot.getStack(this.inventory); if (stack.getItem() == ItemTypes.NONE) { clear(); // NONE item will clear the slot return result.replace(ItemStackUtil.fromNative(old)).build(); } int remaining = stack.getQuantity(); int push = Math.min(remaining, this.slot.getMaxStackSize(this.inventory)); if (this.slot.setStack(this.inventory, ItemStackUtil.cloneDefensiveNative(nativeStack, push))) { result.replace(ItemStackUtil.fromNative(old)); remaining -= push; } if (remaining > 0) { result.reject(ItemStackUtil.cloneDefensive(nativeStack, remaining)); } return result.build(); } @Override public void clear() { this.slot.setStack(this.inventory, net.minecraft.item.ItemStack.EMPTY); } @Override public int size() { return !this.slot.getStack(this.inventory).isEmpty()? 1 : 0; } @Override public int totalItems() { return this.slot.getStack(this.inventory).getCount(); } @Override public int capacity() { return 1; } @Override public boolean hasChildren() { return false; } @Override public boolean contains(ItemStack stack) { net.minecraft.item.ItemStack slotStack = this.slot.getStack(this.inventory); return slotStack.isEmpty() ? ItemStackUtil.toNative(stack).isEmpty() : ItemStackUtil.compareIgnoreQuantity(slotStack, stack) && slotStack.getCount() >= stack.getQuantity(); } @Override public boolean containsAny(ItemStack stack) { net.minecraft.item.ItemStack slotStack = this.slot.getStack(this.inventory); return slotStack.isEmpty() ? ItemStackUtil.toNative(stack).isEmpty() : ItemStackUtil.compareIgnoreQuantity(slotStack, stack); } @Override public boolean contains(ItemType type) { net.minecraft.item.ItemStack slotStack = this.slot.getStack(this.inventory); return slotStack.isEmpty() ? (type == null || type == ItemTypes.AIR) : slotStack.getItem().equals(type); } @Override public int getMaxStackSize() { return super.getMaxStackSize(); } // @Override // public Iterator<Inventory> iterator() { // // TODO // return super.iterator(); // } }
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.provider.calculator.generic; import static org.testng.AssertJUnit.assertEquals; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import org.testng.annotations.Test; import org.threeten.bp.Period; import com.opengamma.analytics.financial.forex.method.FXMatrix; import com.opengamma.analytics.financial.instrument.index.IborIndex; import com.opengamma.analytics.financial.instrument.index.IndexON; import com.opengamma.analytics.financial.interestrate.annuity.derivative.Annuity; import com.opengamma.analytics.financial.interestrate.payments.derivative.CouponFixed; import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve; import com.opengamma.analytics.financial.model.interestrate.curve.YieldCurve; import com.opengamma.analytics.financial.provider.calculator.discounting.PresentValueCurveSensitivityDiscountingCalculator; import com.opengamma.analytics.financial.provider.calculator.discounting.PresentValueDiscountingCalculator; import com.opengamma.analytics.financial.provider.description.interestrate.MulticurveProviderDiscount; import com.opengamma.analytics.financial.provider.description.interestrate.MulticurveProviderInterface; import com.opengamma.analytics.financial.provider.sensitivity.multicurve.MultipleCurrencyMulticurveSensitivity; import com.opengamma.analytics.math.curve.ConstantDoublesCurve; import com.opengamma.analytics.math.curve.InterpolatedDoublesCurve; import com.opengamma.analytics.math.interpolation.Interpolator1D; import com.opengamma.analytics.math.interpolation.factory.DoubleQuadraticInterpolator1dAdapter; import com.opengamma.analytics.math.interpolation.factory.LinearExtrapolator1dAdapter; import com.opengamma.analytics.math.interpolation.factory.NamedInterpolator1dFactory; import com.opengamma.financial.convention.businessday.BusinessDayConventions; import com.opengamma.financial.convention.daycount.DayCounts; import com.opengamma.util.money.Currency; import com.opengamma.util.test.TestGroup; import com.opengamma.util.tuple.DoublesPair; /** * Test. */ @Test(groups = TestGroup.UNIT) public class ZSpreadCalculatorTest { private static final String CURVE_NAME = "Discounting"; private static final PresentValueDiscountingCalculator PV_CALCULATOR = PresentValueDiscountingCalculator.getInstance(); private static final PresentValueCurveSensitivityDiscountingCalculator PVS_CALCULATOR = PresentValueCurveSensitivityDiscountingCalculator .getInstance(); private static final double[] T; private static final double[] R1; private static final double[] R2; private static final double[] R3; private static final double[] R4; private static final MulticurveProviderDiscount CONSTANT_CURVES; private static final MulticurveProviderDiscount MULTI_CURVES; private static final YieldCurve EUR_DISCOUNTING; private static final Annuity<CouponFixed> PAYMENTS; private static final double YIELD = 0.04; private static final Currency CUR = Currency.EUR; private static final ZSpreadCalculator<MulticurveProviderInterface> CALCULATOR = new ZSpreadCalculator<>( PV_CALCULATOR, PVS_CALCULATOR); private static final Interpolator1D INTERPOLATOR = NamedInterpolator1dFactory.of(DoubleQuadraticInterpolator1dAdapter.NAME, LinearExtrapolator1dAdapter.NAME, LinearExtrapolator1dAdapter.NAME); static { int n = 5; final CouponFixed[] rateAtYield = new CouponFixed[n]; EUR_DISCOUNTING = YieldCurve.from(ConstantDoublesCurve.from(YIELD, CURVE_NAME)); final Map<Currency, YieldAndDiscountCurve> constantDiscounting = Collections .<Currency, YieldAndDiscountCurve> singletonMap(Currency.EUR, EUR_DISCOUNTING); final Map<IborIndex, YieldAndDiscountCurve> emptyForwardIbor = Collections.emptyMap(); final Map<IndexON, YieldAndDiscountCurve> emptyForwardON = Collections.emptyMap(); final FXMatrix fxMatrix = new FXMatrix(); fxMatrix.addCurrency(Currency.EUR, Currency.USD, 1.2); CONSTANT_CURVES = new MulticurveProviderDiscount(constantDiscounting, emptyForwardIbor, emptyForwardON, fxMatrix); for (int i = 0; i < n; i++) { rateAtYield[i] = new CouponFixed(CUR, 0.5 * (i + 1), 0.5, YIELD); } n = 10; T = new double[n]; R1 = new double[n]; R2 = new double[n]; R3 = new double[n]; R4 = new double[n]; final Random random = new Random(12983); for (int i = 0; i < n; i++) { final double time = 0.5 * (i + 1); T[i] = time + Math.max(0, (0.5 - random.nextDouble()) / 10); R1[i] = 0.02 + time * random.nextGaussian() / 10; R2[i] = 0.03 + time * random.nextGaussian() / 10; R3[i] = 0.04 + time * random.nextGaussian() / 10; R4[i] = 0.04 + time * random.nextGaussian() / 10; } final Map<Currency, YieldAndDiscountCurve> discounting = new HashMap<>(); discounting.put(Currency.EUR, YieldCurve.from(InterpolatedDoublesCurve.from(T, R1, INTERPOLATOR))); discounting.put(Currency.USD, YieldCurve.from(InterpolatedDoublesCurve.from(T, R2, INTERPOLATOR))); final Map<IborIndex, YieldAndDiscountCurve> forwardIbor = new HashMap<>(); forwardIbor.put(new IborIndex(Currency.EUR, Period.ofMonths(6), n, DayCounts.ACT_360, BusinessDayConventions.NONE, false, "Ibor"), YieldCurve.from(InterpolatedDoublesCurve.from(T, R3, INTERPOLATOR))); final Map<IndexON, YieldAndDiscountCurve> forwardON = new HashMap<>(); forwardON.put(new IndexON("ON", Currency.EUR, DayCounts.ACT_360, 0), YieldCurve.from(InterpolatedDoublesCurve.from(T, R4, INTERPOLATOR))); MULTI_CURVES = new MulticurveProviderDiscount(discounting, forwardIbor, forwardON, fxMatrix); PAYMENTS = new Annuity<>(rateAtYield); } /** * */ @Test(expectedExceptions = IllegalArgumentException.class) public void testNullPVCalculator() { new ZSpreadCalculator<>(null, PVS_CALCULATOR); } /** * */ @Test(expectedExceptions = IllegalArgumentException.class) public void testNullPVSCalculator() { new ZSpreadCalculator<>(PV_CALCULATOR, null); } /** * */ @Test(expectedExceptions = IllegalArgumentException.class) public void testNullAnnuity1() { CALCULATOR.calculatePriceForZSpread(null, MULTI_CURVES, 0.04); } /** * */ @Test(expectedExceptions = IllegalArgumentException.class) public void testNullAnnuity2() { CALCULATOR.calculatePriceSensitivityToCurve(null, MULTI_CURVES, 0.04); } /** * */ @Test(expectedExceptions = IllegalArgumentException.class) public void testNullAnnuity3() { CALCULATOR.calculatePriceSensitivityToZSpread(null, MULTI_CURVES, 0.04); } /** * */ @Test(expectedExceptions = IllegalArgumentException.class) public void testNullAnnuity4() { CALCULATOR.calculateZSpread(null, MULTI_CURVES, 0.04); } /** * */ @Test(expectedExceptions = IllegalArgumentException.class) public void testNullAnnuity5() { CALCULATOR.calculateZSpreadSensitivityToCurve(null, MULTI_CURVES, 0.04); } /** * */ @Test(expectedExceptions = IllegalArgumentException.class) public void testNullCurves1() { CALCULATOR.calculatePriceForZSpread(PAYMENTS, null, 0.04); } /** * */ @Test(expectedExceptions = IllegalArgumentException.class) public void testNullCurves2() { CALCULATOR.calculatePriceSensitivityToCurve(PAYMENTS, null, 0.04); } /** * */ @Test(expectedExceptions = IllegalArgumentException.class) public void testNullCurves3() { CALCULATOR.calculatePriceSensitivityToZSpread(PAYMENTS, null, 0.04); } /** * */ @Test(expectedExceptions = IllegalArgumentException.class) public void testNullCurves4() { CALCULATOR.calculateZSpread(PAYMENTS, null, 0.04); } /** * */ @Test(expectedExceptions = IllegalArgumentException.class) public void testNullCurves5() { CALCULATOR.calculateZSpreadSensitivityToCurve(PAYMENTS, null, 0.04); } /** * */ @Test public void testZeroSpread() { double price = 0; for (int i = 0; i < 5; i++) { price += EUR_DISCOUNTING.getDiscountFactor(0.5 * (i + 1)); } price *= YIELD / 2; assertEquals(0, CALCULATOR.calculateZSpread(PAYMENTS, CONSTANT_CURVES, price), 1e-12); assertEquals(CALCULATOR.calculatePriceForZSpread(PAYMENTS, CONSTANT_CURVES, 0), price, 1e-12); } /** * */ @Test public void testZSpread() { final double price = PAYMENTS.accept(PV_CALCULATOR, CONSTANT_CURVES).getAmount(Currency.EUR); final double zSpread = CALCULATOR.calculateZSpread(PAYMENTS, MULTI_CURVES, price); final double[] rSpread = new double[R1.length]; for (int i = 0; i < rSpread.length; i++) { rSpread[i] = R1[i] + zSpread; } final MulticurveProviderDiscount multicurves = new MulticurveProviderDiscount(MULTI_CURVES.copy()); multicurves.replaceCurve(Currency.EUR, YieldCurve.from(InterpolatedDoublesCurve.from(T, rSpread, INTERPOLATOR))); assertEquals(price, PAYMENTS.accept(PV_CALCULATOR, multicurves).getAmount(Currency.EUR), 1e-12); assertEquals(price, CALCULATOR.calculatePriceForZSpread(PAYMENTS, MULTI_CURVES, zSpread), 1e-12); } /** * */ @Test public void testPriceSensitivityToZSpread() { final double price = PAYMENTS.accept(PV_CALCULATOR, CONSTANT_CURVES).getAmount(Currency.EUR); final double zSpread = CALCULATOR.calculateZSpread(PAYMENTS, MULTI_CURVES, price); final double eps = 1e-3; final double[] rSpread = new double[R1.length]; for (int i = 0; i < rSpread.length; i++) { rSpread[i] = R1[i] + zSpread + eps; } final MulticurveProviderDiscount multicurves = new MulticurveProviderDiscount(MULTI_CURVES.copy()); multicurves.replaceCurve(Currency.EUR, YieldCurve.from(InterpolatedDoublesCurve.from(T, rSpread, INTERPOLATOR))); final double newPrice = PAYMENTS.accept(PV_CALCULATOR, multicurves).getAmount(Currency.EUR); assertEquals((newPrice - price) / eps, CALCULATOR.calculatePriceSensitivityToZSpread(PAYMENTS, MULTI_CURVES, zSpread), eps); } /** * */ @Test public void testSensitivities() { double zSpread = 0.06; final double dPdZ = CALCULATOR.calculatePriceSensitivityToZSpread(PAYMENTS, CONSTANT_CURVES, zSpread); final Map<String, List<DoublesPair>> dZdC = CALCULATOR.calculateZSpreadSensitivityToCurve(PAYMENTS, CONSTANT_CURVES, zSpread); Map<String, List<DoublesPair>> dPdC = CALCULATOR.calculatePriceSensitivityToCurve(PAYMENTS, CONSTANT_CURVES, zSpread); assertEquals(dZdC.size(), dPdC.size()); Iterator<Entry<String, List<DoublesPair>>> iter1 = dZdC.entrySet().iterator(); Iterator<Entry<String, List<DoublesPair>>> iter2 = dPdC.entrySet().iterator(); while (iter1.hasNext()) { final Entry<String, List<DoublesPair>> e1 = iter1.next(); final Entry<String, List<DoublesPair>> e2 = iter2.next(); assertEquals(e1.getKey(), CURVE_NAME); assertEquals(e2.getKey(), CURVE_NAME); final List<DoublesPair> pairs1 = e1.getValue(); final List<DoublesPair> pairs2 = e2.getValue(); assertEquals(pairs1.size(), 5); assertEquals(pairs2.size(), 5); for (int i = 0; i < 5; i++) { assertEquals(pairs1.get(i).first, pairs2.get(i).first, 1e-15); assertEquals(-pairs2.get(i).second / pairs1.get(i).second, dPdZ, 1e-15); } } zSpread = 0.0; dPdC = CALCULATOR.calculatePriceSensitivityToCurve(PAYMENTS, CONSTANT_CURVES, zSpread); final MultipleCurrencyMulticurveSensitivity mcms = PAYMENTS.accept(PVS_CALCULATOR, CONSTANT_CURVES); assertEquals(mcms.getCurrencies().size(), 1); final Map<String, List<DoublesPair>> pvSensitivity = mcms.getSensitivity(CUR).getYieldDiscountingSensitivities(); iter1 = dPdC.entrySet().iterator(); iter2 = pvSensitivity.entrySet().iterator(); while (iter1.hasNext()) { final Entry<String, List<DoublesPair>> e1 = iter1.next(); final Entry<String, List<DoublesPair>> e2 = iter2.next(); assertEquals(e1.getKey(), CURVE_NAME); assertEquals(e2.getKey(), CURVE_NAME); final List<DoublesPair> pairs1 = e1.getValue(); final List<DoublesPair> pairs2 = e2.getValue(); assertEquals(pairs1.size(), 5); assertEquals(pairs2.size(), 5); for (int i = 0; i < 5; i++) { assertEquals(pairs1.get(i).first, pairs2.get(i).first, 1e-15); assertEquals(pairs2.get(i).second, pairs1.get(i).second, 1e-15); } } } /** * */ @Test public void testZSpreadSensitivityToCurve() { } /** * */ @Test public void testPriceSensitivityToCurve() { } }
/* * 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.connectors.jdbc.internal.cli; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.Serializable; import java.util.Collections; import org.apache.commons.lang3.SerializationUtils; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.apache.geode.cache.AttributesMutator; import org.apache.geode.cache.CacheLoader; import org.apache.geode.cache.CacheWriter; import org.apache.geode.cache.Region; import org.apache.geode.cache.RegionAttributes; import org.apache.geode.cache.asyncqueue.internal.InternalAsyncEventQueue; import org.apache.geode.cache.execute.FunctionContext; import org.apache.geode.cache.execute.ResultSender; import org.apache.geode.connectors.jdbc.JdbcLoader; import org.apache.geode.connectors.jdbc.JdbcWriter; import org.apache.geode.connectors.jdbc.internal.JdbcConnectorService; import org.apache.geode.connectors.jdbc.internal.configuration.RegionMapping; import org.apache.geode.distributed.DistributedMember; import org.apache.geode.distributed.DistributedSystem; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.management.internal.functions.CliFunctionResult; public class DestroyMappingCommandFunctionTest { private static final String regionName = "testRegion"; private DestroyMappingFunction function; private FunctionContext<String> context; private ResultSender<Object> resultSender; private RegionMapping mapping; private JdbcConnectorService service; private InternalCache cache; private RegionAttributes<Object, Object> regionAttributes; private AttributesMutator<Object, Object> regionMutator; @SuppressWarnings("unchecked") @Before public void setUp() { cache = mock(InternalCache.class); Region<Object, Object> region = mock(Region.class); when(region.getName()).thenReturn(regionName); regionAttributes = mock(RegionAttributes.class); regionMutator = mock(AttributesMutator.class); when(region.getAttributes()).thenReturn(regionAttributes); when(region.getAttributesMutator()).thenReturn(regionMutator); when(cache.getRegion(regionName)).thenReturn(region); context = mock(FunctionContext.class); when(context.getMemberName()).thenReturn("myMemberName"); DistributedMember member = mock(DistributedMember.class); resultSender = mock(ResultSender.class); service = mock(JdbcConnectorService.class); DistributedSystem system = mock(DistributedSystem.class); when(context.getResultSender()).thenReturn(resultSender); when(context.getCache()).thenReturn(cache); when(cache.getDistributedSystem()).thenReturn(system); when(system.getDistributedMember()).thenReturn(member); when(context.getArguments()).thenReturn(regionName); when(cache.getService(eq(JdbcConnectorService.class))).thenReturn(service); mapping = new RegionMapping(); function = new DestroyMappingFunction(); } @Test public void isHAReturnsFalse() { assertThat(function.isHA()).isFalse(); } @Test public void getIdReturnsNameOfClass() { assertThat(function.getId()).isEqualTo(function.getClass().getName()); } @Test public void serializes() { Serializable original = function; Object copy = SerializationUtils.clone(original); assertThat(copy).isNotSameAs(original).isInstanceOf(DestroyMappingFunction.class); } @Test public void executeFunctionGivenExistingMappingReturnsTrue() { when(service.getMappingForRegion(eq(regionName))).thenReturn(mapping); CliFunctionResult result = function.executeFunction(context); assertThat(result.isSuccessful()).isTrue(); assertThat(result.toString()) .contains("Destroyed JDBC mapping for region " + regionName + " on myMemberName"); } @Test public void executeFunctionGivenNoExistingMappingReturnsFalse() { CliFunctionResult result = function.executeFunction(context); assertThat(result.isSuccessful()).isFalse(); assertThat(result.toString()) .contains("JDBC mapping for region \"" + regionName + "\" not found"); } @Test public void executeFunctionGivenARegionWithJdbcLoaderRemovesTheLoader() { @SuppressWarnings("unchecked") final JdbcLoader<Object, Object> mockJdbcLoader = mock(JdbcLoader.class); when(regionAttributes.getCacheLoader()).thenReturn(mockJdbcLoader); when(service.getMappingForRegion(eq(regionName))).thenReturn(mapping); function.executeFunction(context); verify(regionMutator, times(1)).setCacheLoader(null); } @Test public void executeFunctionGivenARegionWithNonJdbcLoaderDoesNotRemoveTheLoader() { @SuppressWarnings("unchecked") final CacheLoader<Object, Object> mockCacheLoader = mock(CacheLoader.class); when(regionAttributes.getCacheLoader()).thenReturn(mockCacheLoader); when(service.getMappingForRegion(eq(regionName))).thenReturn(mapping); function.executeFunction(context); verify(regionMutator, never()).setCacheLoader(null); } @Test public void executeFunctionGivenARegionWithJdbcWriterRemovesTheWriter() { @SuppressWarnings("unchecked") final JdbcWriter<Object, Object> mock = mock(JdbcWriter.class); when(regionAttributes.getCacheWriter()).thenReturn(mock); when(service.getMappingForRegion(eq(regionName))).thenReturn(mapping); function.executeFunction(context); verify(regionMutator, times(1)).setCacheWriter(null); } @Test public void executeFunctionGivenARegionWithNonJdbcWriterDoesNotRemoveTheWriter() { @SuppressWarnings("unchecked") final CacheWriter<Object, Object> mock = mock(CacheWriter.class); when(regionAttributes.getCacheWriter()).thenReturn(mock); when(service.getMappingForRegion(eq(regionName))).thenReturn(mapping); function.executeFunction(context); verify(regionMutator, never()).setCacheWriter(null); } @Test public void executeFunctionGivenARegionWithJdbcAsyncEventQueueRemovesTheQueueName() { String queueName = MappingCommandUtils.createAsyncEventQueueName(regionName); when(regionAttributes.getAsyncEventQueueIds()).thenReturn(Collections.singleton(queueName)); when(service.getMappingForRegion(eq(regionName))).thenReturn(mapping); function.executeFunction(context); verify(regionMutator, times(1)).removeAsyncEventQueueId(queueName); } @Test public void executeFunctionGivenARegionWithNonJdbcAsyncEventQueueDoesNotRemoveTheQueueName() { when(regionAttributes.getAsyncEventQueueIds()) .thenReturn(Collections.singleton("nonJdbcQueue")); when(service.getMappingForRegion(eq(regionName))).thenReturn(mapping); function.executeFunction(context); verify(regionMutator, never()).removeAsyncEventQueueId(any()); } @Test public void executeFunctionGivenAJdbcAsyncWriterQueueRemovesTheQueue() { String queueName = MappingCommandUtils.createAsyncEventQueueName(regionName); InternalAsyncEventQueue myQueue = mock(InternalAsyncEventQueue.class); when(cache.getAsyncEventQueue(queueName)).thenReturn(myQueue); when(service.getMappingForRegion(eq(regionName))).thenReturn(mapping); function.executeFunction(context); verify(myQueue, times(1)).stop(); verify(myQueue, times(1)).destroy(); } @Test public void executeFunctionGivenExistingMappingCallsDestroyRegionMapping() { when(service.getMappingForRegion(eq(regionName))).thenReturn(mapping); function.executeFunction(context); verify(service, times(1)).destroyRegionMapping(eq(regionName)); } @Test public void executeReportsErrorIfMappingNotFound() { function.execute(context); ArgumentCaptor<CliFunctionResult> argument = ArgumentCaptor.forClass(CliFunctionResult.class); verify(resultSender, times(1)).lastResult(argument.capture()); assertThat(argument.getValue().getStatusMessage()) .contains("JDBC mapping for region \"" + regionName + "\" not found"); } }
package org.apereo.cas.web.flow; /** * This is {@link CasWebflowConstants}. * * @author Misagh Moayyed * @since 5.0.0 */ public interface CasWebflowConstants { /** * Base path for webflow configuration files. */ String BASE_CLASSPATH_WEBFLOW = "classpath*:/webflow"; /* **************************************** * Transitions. **************************************** */ /** * The transition state 'authenticationFailure'. */ String TRANSITION_ID_AUTHENTICATION_FAILURE = "authenticationFailure"; /** * The transition state 'yes'. */ String TRANSITION_ID_YES = "yes"; /** * The transition state 'finalize'. */ String TRANSITION_ID_FINALIZE = "finalize"; /** * The transition state 'warn'. */ String TRANSITION_ID_WARN = "warn"; /** * The transition state 'no'. */ String TRANSITION_ID_NO = "no"; /** * The transition state 'submit'. */ String TRANSITION_ID_SUBMIT = "submit"; /** * The transition state 'error'. */ String TRANSITION_ID_ERROR = "error"; /** * The transition state 'resume'. */ String TRANSITION_ID_RESUME = "resume"; /** * The transition state 'gateway'. */ String TRANSITION_ID_GATEWAY = "gateway"; /** * The transition state 'stop'. */ String TRANSITION_ID_STOP = "stop"; /** * TGT does not exist event ID={@value}. **/ String TRANSITION_ID_TGT_NOT_EXISTS = "notExists"; /** * TGT invalid event ID={@value}. **/ String TRANSITION_ID_TGT_INVALID = "invalid"; /** * TGT valid event ID={@value}. **/ String TRANSITION_ID_TGT_VALID = "valid"; /** * The transition state 'interruptSkipped'. */ String TRANSITION_ID_INTERRUPT_SKIPPED = "interruptSkipped"; /** * The transition state 'interruptRequired'. */ String TRANSITION_ID_INTERRUPT_REQUIRED = "interruptRequired"; /** * Provider service is unavailable. */ String TRANSITION_ID_UNAVAILABLE = "unavailable"; /** * User allowed to bypass auth by provider. */ String TRANSITION_ID_BYPASS = "bypass"; /** * User was denied access by provider. */ String TRANSITION_ID_DENY = "deny"; /** * The transition state 'success'. */ String TRANSITION_ID_SUCCESS = "success"; /** * Transition id 'redirect' . */ String TRANSITION_ID_REDIRECT = "redirect"; /** * Propagate transition id. */ String TRANSITION_ID_PROPAGATE = "propagate"; /** * Finish transition id. */ String TRANSITION_ID_FINISH = "finish"; /** * Front transition id. */ String TRANSITION_ID_FRONT = "front"; /** * Proceed transition id. */ String TRANSITION_ID_PROCEED = "proceed"; /** * Confirm transition id. */ String TRANSITION_ID_CONFIRM = "confirm"; /** * Cancel transition id. */ String TRANSITION_ID_CANCEL = "cancel"; /** * Enroll transition id. */ String TRANSITION_ID_ENROLL = "enroll"; /** * Renew transition id. */ String TRANSITION_ID_RENEW = "renew"; /** * The transition state 'successWithWarnings'. */ String TRANSITION_ID_SUCCESS_WITH_WARNINGS = "successWithWarnings"; /** * Transition id 'resetPassword'. */ String TRANSITION_ID_RESET_PASSWORD = "resetPassword"; /** * Transition id 'forgotUsername'. */ String TRANSITION_ID_FORGOT_USERNAME = "forgotUsername"; /** * Transition id 'mustAcceptUsagePolicy'. */ String TRANSITION_ID_AUP_MUST_ACCEPT = "mustAcceptUsagePolicy"; /** * Transition id 'acceptedUsagePolicy'. */ String TRANSITION_ID_AUP_ACCEPTED = "acceptedUsagePolicy"; /** * State to determine the MFA failure mode and what action to take. */ String TRANSITION_ID_MFA_FAILURE = "mfaFailure"; /* **************************************** * States. **************************************** */ /** * The state id 'success'. */ String STATE_ID_SUCCESS = "success"; /** * The state id 'stopWebflow'. */ String STATE_ID_STOP_WEBFLOW = "stopWebflow"; /** * The state id 'verifyTrustedDevice'. */ String STATE_ID_VERIFY_TRUSTED_DEVICE = "verifyTrustedDevice"; /** * The state id 'registerTrustedDevice'. */ String STATE_ID_REGISTER_TRUSTED_DEVICE = "registerTrustedDevice"; /** * The state 'realSubmit'. */ String STATE_ID_REAL_SUBMIT = "realSubmit"; /** * 'gateway' state id. */ String STATE_ID_GATEWAY = "gateway"; /** * 'finishMfaTrustedAuth' state id. */ String STATE_ID_FINISH_MFA_TRUSTED_AUTH = "finishMfaTrustedAuth"; /** * The transition state 'initialAuthenticationRequestValidationCheck'. */ String STATE_ID_INITIAL_AUTHN_REQUEST_VALIDATION_CHECK = "initialAuthenticationRequestValidationCheck"; /** * The state id 'sendTicketGrantingTicket'. */ String STATE_ID_SEND_TICKET_GRANTING_TICKET = "sendTicketGrantingTicket"; /** * The state id 'ticketGrantingTicketCheck'. */ String STATE_ID_TICKET_GRANTING_TICKET_CHECK = "ticketGrantingTicketCheck"; /** * The state id 'createTicketGrantingTicket'. */ String STATE_ID_CREATE_TICKET_GRANTING_TICKET = "createTicketGrantingTicket"; /** * The state 'initializeLoginForm'. */ String STATE_ID_INIT_LOGIN_FORM = "initializeLoginForm"; /** * The state 'viewLoginForm'. */ String STATE_ID_VIEW_LOGIN_FORM = "viewLoginForm"; /** * The state 'serviceAuthorizationCheck'. */ String STATE_ID_SERVICE_AUTHZ_CHECK = "serviceAuthorizationCheck"; /** * The state 'terminateSession'. */ String STATE_ID_TERMINATE_SESSION = "terminateSession"; /** * The state 'gatewayRequestCheck'. */ String STATE_ID_GATEWAY_REQUEST_CHECK = "gatewayRequestCheck"; /** * The state 'gatewayRequestCheck'. */ String STATE_ID_GENERATE_SERVICE_TICKET = "generateServiceTicket"; /** * The state 'gatewayServicesManagementCheck'. */ String STATE_ID_GATEWAY_SERVICES_MGMT_CHECK = "gatewayServicesManagementCheck"; /** * The state 'postView'. */ String STATE_ID_POST_VIEW = "postView"; /** * The state 'headerView'. */ String STATE_ID_HEADER_VIEW = "headerView"; /** * The state 'showWarningView'. */ String STATE_ID_SHOW_WARNING_VIEW = "showWarningView"; /** * The state 'redirectView'. */ String STATE_ID_REDIRECT_VIEW = "redirectView"; /** * The state id 'endWebflowExecution'. */ String STATE_ID_END_WEBFLOW = "endWebflowExecution"; /** * The state 'viewRedirectToUnauthorizedUrlView'. */ String STATE_ID_VIEW_REDIR_UNAUTHZ_URL = "viewRedirectToUnauthorizedUrlView"; /** * The state 'serviceUnauthorizedCheck'. */ String STATE_ID_SERVICE_UNAUTHZ_CHECK = "serviceUnauthorizedCheck"; /** * The state 'viewGenericLoginSuccess'. */ String STATE_ID_VIEW_GENERIC_LOGIN_SUCCESS = "viewGenericLoginSuccess"; /** * The state 'serviceCheck'. */ String STATE_ID_SERVICE_CHECK = "serviceCheck"; /** * The state 'viewServiceErrorView'. */ String STATE_ID_VIEW_SERVICE_ERROR = "viewServiceErrorView"; /** * The state id 'warn'. */ String STATE_ID_WARN = "warn"; /** * The state id 'renewRequestCheck'. */ String STATE_ID_RENEW_REQUEST_CHECK = "renewRequestCheck"; /** * The state id 'hasServiceCheck'. */ String STATE_ID_HAS_SERVICE_CHECK = "hasServiceCheck"; /** * The state id 'redirect'. */ String STATE_ID_REDIRECT = "redirect"; /** * State id when MFA provider has been detected as unavailable and failureMode is closed. */ String STATE_ID_MFA_UNAVAILABLE = "mfaUnavailable"; /** * State id when MFA provider has denied access to a user because of account lockout. */ String STATE_ID_MFA_DENIED = "mfaDenied"; /** * State id 'doLogout'. */ String STATE_ID_DO_LOGOUT = "doLogout"; /** * State id 'propagateLogoutRequests'. */ String STATE_ID_PROPAGATE_LOGOUT_REQUESTS = "propagateLogoutRequests"; /** * State id 'logoutView'. */ String STATE_ID_LOGOUT_VIEW = "logoutView"; /** * State id 'finishLogout'. */ String STATE_ID_FINISH_LOGOUT = "finishLogout"; /** * Delegated authentication state id. */ String STATE_ID_DELEGATED_AUTHENTICATION = "delegatedAuthenticationAction"; /** * State id 'frontLogout'. */ String STATE_ID_FRONT_LOGOUT = "frontLogout"; /** * State id 'confirmLogoutView'. */ String STATE_ID_CONFIRM_LOGOUT_VIEW = "confirmLogoutView"; /** * State id 'casPasswordUpdateSuccess'. */ String STATE_ID_PASSWORD_UPDATE_SUCCESS = "casPasswordUpdateSuccess"; /** * State id 'handleAuthenticationFailure'. */ String STATE_ID_HANDLE_AUTHN_FAILURE = "handleAuthenticationFailure"; /** * State for password reset subflow "pswdResetSubflow". */ String STATE_ID_PASSWORD_RESET_SUBFLOW = "pswdResetSubflow"; /** * State id 'proceedFromAuthenticationWarningView'. */ String STATE_ID_PROCEED_FROM_AUTHENTICATION_WARNINGS_VIEW = "proceedFromAuthenticationWarningView"; /** * Login flow state indicating the password reset subflow is complete "pswdResetComplete". */ String STATE_ID_PASSWORD_RESET_FLOW_COMPLETE = "pswdResetComplete"; /** * State to restart the login flow fresh "redirectToLogin". */ String STATE_ID_REDIRECT_TO_LOGIN = "redirectToLogin"; /** * State to check where the password change should go after completion (post or pre-login) "postLoginPswdChangeCheck". */ String STATE_ID_POST_LOGIN_PASSWORD_CHANGE_CHECK = "postLoginPswdChangeCheck"; /** * State id to check for do change password manual flag "checkDoChangePassword". */ String STATE_ID_CHECK_DO_CHANGE_PASSWORD = "checkDoChangePassword"; /** * State to check if the MFA provider is available. */ String STATE_ID_MFA_CHECK_AVAILABLE = "mfaCheckAvailable"; /** * State to check if the MFA provider should be bypassed. */ String STATE_ID_MFA_CHECK_BYPASS = "mfaCheckBypass"; /** * State that can be used by MFA providers that offer preAuth endpoints. */ String STATE_ID_MFA_PRE_AUTH = "mfaPreAuth"; /** * The view state 'showAuthenticationWarningMessages'. */ String STATE_ID_SHOW_AUTHN_WARNING_MSGS = "showAuthenticationWarningMessages"; /* **************************************** * Views. **************************************** */ /** * The view id 'registerDeviceView'. */ String VIEW_ID_REGISTER_DEVICE = "registerDeviceView"; /** * The view state 'casPac4jStopWebflow'. */ String VIEW_ID_PAC4J_STOP_WEBFLOW = "casPac4jStopWebflow"; /** * The view state 'casWsFedStopWebflow'. */ String VIEW_ID_WSFED_STOP_WEBFLOW = "casWsFedStopWebflow"; /** * The view state 'error'. */ String VIEW_ID_ERROR = "error"; /** * View id when MFA provider has been detected as unavailable and failureMode is closed. */ String VIEW_ID_MFA_UNAVAILABLE = "casMfaUnavailableView"; /** * View id when MFA provider has denied access to a user because of account lockout. */ String VIEW_ID_MFA_DENIED = "casMfaDeniedView"; /** * The view id 'casPostResponseView'. */ String VIEW_ID_POST_RESPONSE = "casPostResponseView"; /** * The view id 'casGenericSuccessView'. */ String VIEW_ID_GENERIC_SUCCESS = "casGenericSuccessView"; /** * The view id 'casConfirmView'. */ String VIEW_ID_CONFIRM = "casConfirmView"; /** * The view id 'casServiceErrorView'. */ String VIEW_ID_SERVICE_ERROR = "casServiceErrorView"; /** * View id 'casResetPasswordSendInstructions'. */ String VIEW_ID_SEND_RESET_PASSWORD_ACCT_INFO = "casResetPasswordSendInstructionsView"; /** * View id 'casForgotUsernameSentInfoView'. */ String VIEW_ID_SENT_FORGOT_USERNAME_ACCT_INFO = "casForgotUsernameSentInfoView"; /** * View id 'casForgotUsernameSendInfoView'. */ String VIEW_ID_FORGOT_USERNAME_ACCT_INFO = "casForgotUsernameSendInfoView"; /** * View id 'casBadHoursView'. */ String VIEW_ID_INVALID_AUTHENTICATION_HOURS = "casBadHoursView"; /** * View id 'casPasswordUpdateSuccessView'. */ String VIEW_ID_PASSWORD_UPDATE_SUCCESS = "casPasswordUpdateSuccessView"; /** * View id 'casAuthenticationBlockedView'. */ String VIEW_ID_AUTHENTICATION_BLOCKED = "casAuthenticationBlockedView"; /** * View id 'casResetPasswordErrorView'. */ String VIEW_ID_PASSWORD_RESET_ERROR = "casResetPasswordErrorView"; /** * View id 'casBadWorkstationView'. */ String VIEW_ID_INVALID_WORKSTATION = "casBadWorkstationView"; /** * View id 'casAccountDisabledView'. */ String VIEW_ID_ACCOUNT_DISABLED = "casAccountDisabledView"; /** * View id 'casAccountLockedView'. */ String VIEW_ID_ACCOUNT_LOCKED = "casAccountLockedView"; /** * View id 'casMustChangePassView'. */ String VIEW_ID_MUST_CHANGE_PASSWORD = "casMustChangePassView"; /** * View id 'casExpiredPassView'. */ String VIEW_ID_EXPIRED_PASSWORD = "casExpiredPassView"; /** * View id 'casResetPasswordSentInstructions'. */ String VIEW_ID_SENT_RESET_PASSWORD_ACCT_INFO = "casResetPasswordSentInstructionsView"; /** * View name used for form-login into admin/actuator endpoints. */ String VIEW_ID_ENDPOINT_ADMIN_LOGIN_VIEW = "casAdminLoginView"; /* **************************************** * Decisions. **************************************** */ /** * The decision state 'checkRegistrationRequired'. */ String DECISION_STATE_REQUIRE_REGISTRATION = "checkRegistrationRequired"; /** * The decision state 'finishLogout'. */ String DECISION_STATE_FINISH_LOGOUT = "finishLogout"; /** * Action to check if login should redirect to password reset subflow. */ String DECISION_STATE_CHECK_FOR_PASSWORD_RESET_TOKEN_ACTION = "checkForPswdResetToken"; /* **************************************** * Variables & Attributes. **************************************** */ /** * The flow var id 'credential'. */ String VAR_ID_CREDENTIAL = "credential"; /** * The flow var id 'providerId'. */ String VAR_ID_MFA_PROVIDER_ID = "mfaProviderId"; /** * Event attribute id 'authenticationWarnings'. */ String ATTRIBUTE_ID_AUTHENTICATION_WARNINGS = "authenticationWarnings"; /* **************************************** * Actions. **************************************** */ /** * Action id 'renderLoginFormAction'. */ String ACTION_ID_RENDER_LOGIN_FORM = "renderLoginFormAction"; /** * Action id 'authenticationViaFormAction'. */ String ACTION_ID_AUTHENTICATION_VIA_FORM_ACTION = "authenticationViaFormAction"; /** * Action id 'compositeMfaProviderSelectedAction'. */ String ACTION_ID_MFA_PROVIDER_SELECTED = "compositeMfaProviderSelectedAction"; /** * Action id 'initialFlowSetupAction'. */ String ACTION_ID_INIT_FLOW_SETUP = "initialFlowSetupAction"; /** * Action id 'verifyRequiredServiceAction'. */ String ACTION_ID_VERIFY_REQUIRED_SERVICE = "verifyRequiredServiceAction"; /** * Action id 'ticketGrantingTicketCheckAction'. */ String ACTION_ID_TICKET_GRANTING_TICKET_CHECK = "ticketGrantingTicketCheckAction"; /** * Action id 'initialAuthenticationRequestValidationAction'. */ String ACTION_ID_INITIAL_AUTHN_REQUEST_VALIDATION = "initialAuthenticationRequestValidationAction"; /** * Action id 'remoteAuthenticate'. */ String ACTION_ID_REMOTE_TRUSTED_AUTHENTICATION = "remoteAuthenticate"; /** * Action id 'clearWebflowCredentialsAction'. */ String ACTION_ID_CLEAR_WEBFLOW_CREDENTIALS = "clearWebflowCredentialsAction"; /** * Action id 'generateServiceTicketAction'. */ String ACTION_ID_GENERATE_SERVICE_TICKET = "generateServiceTicketAction"; /** * Action id 'redirectToServiceAction'. */ String ACTION_ID_REDIRECT_TO_SERVICE = "redirectToServiceAction"; /** * Action id 'redirectToServiceAction'. */ String ACTION_ID_TERMINATE_SESSION = "terminateSessionAction"; /** * Action id 'logoutViewSetupAction'. */ String ACTION_ID_LOGOUT_VIEW_SETUP = "logoutViewSetupAction"; /** * Action id 'authenticationExceptionHandler'. */ String ACTION_ID_AUTHENTICATION_EXCEPTION_HANDLER = "authenticationExceptionHandler"; /** * Action id 'sendTicketGrantingTicketAction'. */ String ACTION_ID_SEND_TICKET_GRANTING_TICKET = "sendTicketGrantingTicketAction"; /** * Action id 'createTicketGrantingTicketAction'. */ String ACTION_ID_CREATE_TICKET_GRANTING_TICKET = "createTicketGrantingTicketAction"; /** * Action id `delegatedAuthenticationAction`. */ String ACTION_ID_DELEGATED_AUTHENTICATION = "delegatedAuthenticationAction"; /** * Action id `renewAuthenticationRequestCheckAction`. */ String ACTION_ID_RENEW_AUTHN_REQUEST = "renewAuthenticationRequestCheckAction"; }
/* * 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.phoenix.execute; import static org.apache.phoenix.util.LogUtil.addCustomAnnotations; import java.sql.SQLException; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.phoenix.cache.ServerCacheClient.ServerCache; import org.apache.phoenix.compile.ColumnProjector; import org.apache.phoenix.compile.ExplainPlan; import org.apache.phoenix.compile.FromCompiler; import org.apache.phoenix.compile.QueryPlan; import org.apache.phoenix.compile.RowProjector; import org.apache.phoenix.compile.ScanRanges; import org.apache.phoenix.compile.StatementContext; import org.apache.phoenix.compile.WhereCompiler; import org.apache.phoenix.exception.SQLExceptionCode; import org.apache.phoenix.exception.SQLExceptionInfo; import org.apache.phoenix.expression.Determinism; import org.apache.phoenix.expression.Expression; import org.apache.phoenix.expression.InListExpression; import org.apache.phoenix.expression.LiteralExpression; import org.apache.phoenix.expression.RowValueConstructorExpression; import org.apache.phoenix.iterate.FilterResultIterator; import org.apache.phoenix.iterate.ResultIterator; import org.apache.phoenix.jdbc.PhoenixConnection; import org.apache.phoenix.job.JobManager.JobCallable; import org.apache.phoenix.join.HashCacheClient; import org.apache.phoenix.join.HashJoinInfo; import org.apache.phoenix.parse.FilterableStatement; import org.apache.phoenix.parse.ParseNode; import org.apache.phoenix.parse.SQLParser; import org.apache.phoenix.parse.SelectStatement; import org.apache.phoenix.query.ConnectionQueryServices; import org.apache.phoenix.query.QueryServices; import org.apache.phoenix.query.QueryServicesOptions; import org.apache.phoenix.schema.PTable; import org.apache.phoenix.schema.tuple.Tuple; import org.apache.phoenix.schema.types.PArrayDataType; import org.apache.phoenix.schema.types.PBoolean; import org.apache.phoenix.schema.types.PDataType; import org.apache.phoenix.schema.types.PVarbinary; import org.apache.phoenix.util.SQLCloseable; import org.apache.phoenix.util.SQLCloseables; import com.google.common.collect.Lists; public class HashJoinPlan extends DelegateQueryPlan { private static final Log LOG = LogFactory.getLog(HashJoinPlan.class); private final SelectStatement statement; private final HashJoinInfo joinInfo; private final SubPlan[] subPlans; private final boolean recompileWhereClause; private List<SQLCloseable> dependencies; private HashCacheClient hashClient; private int maxServerCacheTimeToLive; private AtomicLong firstJobEndTime; private List<Expression> keyRangeExpressions; public static HashJoinPlan create(SelectStatement statement, QueryPlan plan, HashJoinInfo joinInfo, SubPlan[] subPlans) { if (!(plan instanceof HashJoinPlan)) return new HashJoinPlan(statement, plan, joinInfo, subPlans, joinInfo == null); HashJoinPlan hashJoinPlan = (HashJoinPlan) plan; assert (hashJoinPlan.joinInfo == null && hashJoinPlan.delegate instanceof BaseQueryPlan); SubPlan[] mergedSubPlans = new SubPlan[hashJoinPlan.subPlans.length + subPlans.length]; int i = 0; for (SubPlan subPlan : hashJoinPlan.subPlans) { mergedSubPlans[i++] = subPlan; } for (SubPlan subPlan : subPlans) { mergedSubPlans[i++] = subPlan; } return new HashJoinPlan(statement, hashJoinPlan.delegate, joinInfo, mergedSubPlans, true); } private HashJoinPlan(SelectStatement statement, QueryPlan plan, HashJoinInfo joinInfo, SubPlan[] subPlans, boolean recompileWhereClause) { super(plan); this.statement = statement; this.joinInfo = joinInfo; this.subPlans = subPlans; this.recompileWhereClause = recompileWhereClause; } @Override public ResultIterator iterator() throws SQLException { int count = subPlans.length; PhoenixConnection connection = getContext().getConnection(); ConnectionQueryServices services = connection.getQueryServices(); ExecutorService executor = services.getExecutor(); List<Future<Object>> futures = Lists.<Future<Object>>newArrayListWithExpectedSize(count); dependencies = Lists.newArrayList(); if (joinInfo != null) { hashClient = new HashCacheClient(delegate.getContext().getConnection()); maxServerCacheTimeToLive = services.getProps().getInt(QueryServices.MAX_SERVER_CACHE_TIME_TO_LIVE_MS_ATTRIB, QueryServicesOptions.DEFAULT_MAX_SERVER_CACHE_TIME_TO_LIVE_MS); firstJobEndTime = new AtomicLong(0); keyRangeExpressions = new CopyOnWriteArrayList<Expression>(); } for (int i = 0; i < count; i++) { final int index = i; futures.add(executor.submit(new JobCallable<Object>() { @Override public Object call() throws Exception { return subPlans[index].execute(HashJoinPlan.this); } @Override public Object getJobId() { return HashJoinPlan.this; } })); } SQLException firstException = null; for (int i = 0; i < count; i++) { try { Object result = futures.get(i).get(); subPlans[i].postProcess(result, this); } catch (InterruptedException e) { if (firstException == null) { firstException = new SQLException("Sub plan [" + i + "] execution interrupted.", e); } } catch (ExecutionException e) { if (firstException == null) { firstException = new SQLException("Encountered exception in sub plan [" + i + "] execution.", e.getCause()); } } } if (firstException != null) { SQLCloseables.closeAllQuietly(dependencies); throw firstException; } Expression postFilter = null; boolean hasKeyRangeExpressions = keyRangeExpressions != null && !keyRangeExpressions.isEmpty(); if (recompileWhereClause || hasKeyRangeExpressions) { StatementContext context = delegate.getContext(); PTable table = context.getCurrentTable().getTable(); ParseNode viewWhere = table.getViewStatement() == null ? null : new SQLParser(table.getViewStatement()).parseQuery().getWhere(); context.setResolver(FromCompiler.getResolverForQuery((SelectStatement) (delegate.getStatement()), delegate.getContext().getConnection())); if (recompileWhereClause) { postFilter = WhereCompiler.compile(delegate.getContext(), delegate.getStatement(), viewWhere, null); } if (hasKeyRangeExpressions) { WhereCompiler.compile(delegate.getContext(), delegate.getStatement(), viewWhere, keyRangeExpressions, true, null); } } if (joinInfo != null) { Scan scan = delegate.getContext().getScan(); HashJoinInfo.serializeHashJoinIntoScan(scan, joinInfo); } ResultIterator iterator = joinInfo == null ? delegate.iterator() : ((BaseQueryPlan) delegate).iterator(dependencies); if (statement.getInnerSelectStatement() != null && postFilter != null) { iterator = new FilterResultIterator(iterator, postFilter); } return iterator; } private Expression createKeyRangeExpression(Expression lhsExpression, Expression rhsExpression, List<Expression> rhsValues, ImmutableBytesWritable ptr) throws SQLException { if (rhsValues.isEmpty()) return LiteralExpression.newConstant(false, PBoolean.INSTANCE, Determinism.ALWAYS); rhsValues.add(0, lhsExpression); return InListExpression.create(rhsValues, false, ptr); } @Override public ExplainPlan getExplainPlan() throws SQLException { List<String> planSteps = Lists.newArrayList(delegate.getExplainPlan().getPlanSteps()); int count = subPlans.length; for (int i = 0; i < count; i++) { planSteps.addAll(subPlans[i].getPreSteps(this)); } for (int i = 0; i < count; i++) { planSteps.addAll(subPlans[i].getPostSteps(this)); } if (joinInfo != null && joinInfo.getPostJoinFilterExpression() != null) { planSteps.add(" AFTER-JOIN SERVER FILTER BY " + joinInfo.getPostJoinFilterExpression().toString()); } if (joinInfo != null && joinInfo.getLimit() != null) { planSteps.add(" JOIN-SCANNER " + joinInfo.getLimit() + " ROW LIMIT"); } return new ExplainPlan(planSteps); } @Override public FilterableStatement getStatement() { return statement; } protected interface SubPlan { public Object execute(HashJoinPlan parent) throws SQLException; public void postProcess(Object result, HashJoinPlan parent) throws SQLException; public List<String> getPreSteps(HashJoinPlan parent) throws SQLException; public List<String> getPostSteps(HashJoinPlan parent) throws SQLException; } public static class WhereClauseSubPlan implements SubPlan { private final QueryPlan plan; private final SelectStatement select; private final boolean expectSingleRow; public WhereClauseSubPlan(QueryPlan plan, SelectStatement select, boolean expectSingleRow) { this.plan = plan; this.select = select; this.expectSingleRow = expectSingleRow; } @Override public Object execute(HashJoinPlan parent) throws SQLException { List<Object> values = Lists.<Object> newArrayList(); ResultIterator iterator = plan.iterator(); RowProjector projector = plan.getProjector(); ImmutableBytesWritable ptr = new ImmutableBytesWritable(); int columnCount = projector.getColumnCount(); int rowCount = 0; PDataType baseType = PVarbinary.INSTANCE; for (Tuple tuple = iterator.next(); tuple != null; tuple = iterator.next()) { if (expectSingleRow && rowCount >= 1) throw new SQLExceptionInfo.Builder(SQLExceptionCode.SINGLE_ROW_SUBQUERY_RETURNS_MULTIPLE_ROWS).build().buildException(); if (columnCount == 1) { ColumnProjector columnProjector = projector.getColumnProjector(0); baseType = columnProjector.getExpression().getDataType(); Object value = columnProjector.getValue(tuple, baseType, ptr); values.add(value); } else { List<Expression> expressions = Lists.<Expression>newArrayListWithExpectedSize(columnCount); for (int i = 0; i < columnCount; i++) { ColumnProjector columnProjector = projector.getColumnProjector(i); PDataType type = columnProjector.getExpression().getDataType(); Object value = columnProjector.getValue(tuple, type, ptr); expressions.add(LiteralExpression.newConstant(value, type)); } Expression expression = new RowValueConstructorExpression(expressions, true); baseType = expression.getDataType(); expression.evaluate(null, ptr); values.add(baseType.toObject(ptr)); } rowCount++; } Object result = expectSingleRow ? (values.isEmpty() ? null : values.get(0)) : PArrayDataType.instantiatePhoenixArray(baseType, values.toArray()); parent.getContext().setSubqueryResult(select, result); return null; } @Override public void postProcess(Object result, HashJoinPlan parent) throws SQLException { } @Override public List<String> getPreSteps(HashJoinPlan parent) throws SQLException { List<String> steps = Lists.newArrayList(); steps.add(" EXECUTE " + (expectSingleRow ? "SINGLE" : "MULTIPLE") + "-ROW SUBQUERY"); for (String step : plan.getExplainPlan().getPlanSteps()) { steps.add(" " + step); } return steps; } @Override public List<String> getPostSteps(HashJoinPlan parent) throws SQLException { return Collections.<String>emptyList(); } } public static class HashSubPlan implements SubPlan { private final int index; private final QueryPlan plan; private final List<Expression> hashExpressions; private final boolean singleValueOnly; private final Expression keyRangeLhsExpression; private final Expression keyRangeRhsExpression; public HashSubPlan(int index, QueryPlan subPlan, List<Expression> hashExpressions, boolean singleValueOnly, Expression keyRangeLhsExpression, Expression keyRangeRhsExpression) { this.index = index; this.plan = subPlan; this.hashExpressions = hashExpressions; this.singleValueOnly = singleValueOnly; this.keyRangeLhsExpression = keyRangeLhsExpression; this.keyRangeRhsExpression = keyRangeRhsExpression; } @Override public Object execute(HashJoinPlan parent) throws SQLException { ScanRanges ranges = parent.delegate.getContext().getScanRanges(); List<Expression> keyRangeRhsValues = null; if (keyRangeRhsExpression != null) { keyRangeRhsValues = Lists.<Expression>newArrayList(); } ServerCache cache = null; if (hashExpressions != null) { cache = parent.hashClient.addHashCache(ranges, plan.iterator(), plan.getEstimatedSize(), hashExpressions, singleValueOnly, parent.delegate.getTableRef(), keyRangeRhsExpression, keyRangeRhsValues); long endTime = System.currentTimeMillis(); boolean isSet = parent.firstJobEndTime.compareAndSet(0, endTime); if (!isSet && (endTime - parent.firstJobEndTime.get()) > parent.maxServerCacheTimeToLive) { LOG.warn(addCustomAnnotations("Hash plan [" + index + "] execution seems too slow. Earlier hash cache(s) might have expired on servers.", parent.delegate.getContext().getConnection())); } } else { assert(keyRangeRhsExpression != null); ResultIterator iterator = plan.iterator(); for (Tuple result = iterator.next(); result != null; result = iterator.next()) { // Evaluate key expressions for hash join key range optimization. keyRangeRhsValues.add(HashCacheClient.evaluateKeyExpression(keyRangeRhsExpression, result, plan.getContext().getTempPtr())); } } if (keyRangeRhsValues != null) { parent.keyRangeExpressions.add(parent.createKeyRangeExpression(keyRangeLhsExpression, keyRangeRhsExpression, keyRangeRhsValues, plan.getContext().getTempPtr())); } return cache; } @Override public void postProcess(Object result, HashJoinPlan parent) throws SQLException { ServerCache cache = (ServerCache) result; if (cache != null) { parent.joinInfo.getJoinIds()[index].set(cache.getId()); parent.dependencies.add(cache); } } @Override public List<String> getPreSteps(HashJoinPlan parent) throws SQLException { List<String> steps = Lists.newArrayList(); boolean earlyEvaluation = parent.joinInfo.earlyEvaluation()[index]; boolean skipMerge = parent.joinInfo.getSchemas()[index].getFieldCount() == 0; if (hashExpressions != null) { steps.add(" PARALLEL " + parent.joinInfo.getJoinTypes()[index].toString().toUpperCase() + "-JOIN TABLE " + index + (earlyEvaluation ? "" : "(DELAYED EVALUATION)") + (skipMerge ? " (SKIP MERGE)" : "")); } else { steps.add(" SKIP-SCAN-JOIN TABLE " + index); } for (String step : plan.getExplainPlan().getPlanSteps()) { steps.add(" " + step); } return steps; } @Override public List<String> getPostSteps(HashJoinPlan parent) throws SQLException { if (keyRangeLhsExpression == null) return Collections.<String> emptyList(); String step = " DYNAMIC SERVER FILTER BY " + keyRangeLhsExpression.toString() + " IN (" + keyRangeRhsExpression.toString() + ")"; return Collections.<String> singletonList(step); } } }
package org.hisp.dhis.common; /* * Copyright (c) 2004-2018, University of Oslo * 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 the HISP project 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. */ import com.google.common.collect.Lists; import org.hisp.dhis.attribute.Attribute; import org.hisp.dhis.attribute.AttributeValue; import org.hisp.dhis.category.CategoryOptionCombo; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.dataelement.DataElementOperand; import org.hisp.dhis.program.Program; import org.hisp.dhis.program.ProgramDataElementDimensionItem; import org.junit.Test; import java.util.List; import java.util.Map; import static org.junit.Assert.*; /** * @author Lars Helge Overland */ public class DimensionalObjectUtilsTest { @Test public void testGetPrettyFilter() { assertEquals( "< 5, = Discharged", DimensionalObjectUtils.getPrettyFilter( "LT:5:EQ:Discharged" ) ); assertEquals( ">= 10, Female", DimensionalObjectUtils.getPrettyFilter( "GE:10:LIKE:Female" ) ); assertEquals( "> 20, Discharged, Transferred", DimensionalObjectUtils.getPrettyFilter( "GT:20:IN:Discharged;Transferred" ) ); assertEquals( null, DimensionalObjectUtils.getPrettyFilter( null ) ); assertEquals( null, DimensionalObjectUtils.getPrettyFilter( "uid" ) ); } @Test public void testIsCompositeDimensionObject() { assertTrue( DimensionalObjectUtils.isCompositeDimensionalObject( "d4HjsAHkj42.G142kJ2k3Gj" ) ); assertTrue( DimensionalObjectUtils.isCompositeDimensionalObject( "d4HjsAHkj42.G142kJ2k3Gj.BoaSg2GopVn" ) ); assertTrue( DimensionalObjectUtils.isCompositeDimensionalObject( "d4HjsAHkj42.*.BoaSg2GopVn" ) ); assertTrue( DimensionalObjectUtils.isCompositeDimensionalObject( "d4HjsAHkj42.G142kJ2k3Gj.*" ) ); assertTrue( DimensionalObjectUtils.isCompositeDimensionalObject( "d4HjsAHkj42.*" ) ); assertTrue( DimensionalObjectUtils.isCompositeDimensionalObject( "d4HjsAHkj42.*.*" ) ); assertTrue( DimensionalObjectUtils.isCompositeDimensionalObject( "codeA.codeB" ) ); assertFalse( DimensionalObjectUtils.isCompositeDimensionalObject( "d4HjsAHkj42" ) ); assertFalse( DimensionalObjectUtils.isCompositeDimensionalObject( "14HjsAHkj42-G142kJ2k3Gj" ) ); } @Test public void testGetUidMapIsSchemeCode() { DataElement deA = new DataElement( "NameA" ); DataElement deB = new DataElement( "NameB" ); DataElement deC = new DataElement( "NameC" ); deA.setUid( "A123456789A" ); deB.setUid( "A123456789B" ); deC.setUid( "A123456789C" ); deA.setCode( "CodeA" ); deB.setCode( "CodeB" ); deC.setCode( null ); List<DataElement> elements = Lists.newArrayList( deA, deB, deC ); Map<String, String> map = DimensionalObjectUtils.getDimensionItemIdSchemeMap( elements, IdScheme.CODE ); assertEquals( 3, map.size() ); assertEquals( "CodeA", map.get( "A123456789A" ) ); assertEquals( "CodeB", map.get( "A123456789B" ) ); assertEquals( null, map.get( "A123456789C" ) ); } @Test public void testGetUidMapIsSchemeCodeCompositeObject() { Program prA = new Program(); prA.setUid( "P123456789A" ); prA.setCode( "PCodeA" ); DataElement deA = new DataElement( "NameA" ); DataElement deB = new DataElement( "NameB" ); deA.setUid( "D123456789A" ); deB.setUid( "D123456789B" ); deA.setCode( "DCodeA" ); deB.setCode( "DCodeB" ); ProgramDataElementDimensionItem pdeA = new ProgramDataElementDimensionItem( prA, deA ); ProgramDataElementDimensionItem pdeB = new ProgramDataElementDimensionItem( prA, deB ); List<ProgramDataElementDimensionItem> elements = Lists.newArrayList( pdeA, pdeB ); Map<String, String> map = DimensionalObjectUtils.getDimensionItemIdSchemeMap( elements, IdScheme.CODE ); assertEquals( 2, map.size() ); assertEquals( "PCodeA.DCodeA", map.get( "P123456789A.D123456789A" ) ); assertEquals( "PCodeA.DCodeB", map.get( "P123456789A.D123456789B" ) ); } @Test public void testGetUidMapIsSchemeAttribute() { DataElement deA = new DataElement( "DataElementA" ); DataElement deB = new DataElement( "DataElementB" ); DataElement deC = new DataElement( "DataElementC" ); deA.setUid( "A123456789A" ); deB.setUid( "A123456789B" ); deC.setUid( "A123456789C" ); Attribute atA = new Attribute( "AttributeA", ValueType.INTEGER ); atA.setUid( "ATTR123456A" ); AttributeValue avA = new AttributeValue( "AttributeValueA", atA ); AttributeValue avB = new AttributeValue( "AttributeValueB", atA ); deA.getAttributeValues().add( avA ); deB.getAttributeValues().add( avB ); List<DataElement> elements = Lists.newArrayList( deA, deB, deC ); String scheme = IdScheme.ATTR_ID_SCHEME_PREFIX + atA.getUid(); IdScheme idScheme = IdScheme.from( scheme ); Map<String, String> map = DimensionalObjectUtils.getDimensionItemIdSchemeMap( elements, idScheme ); assertEquals( 3, map.size() ); assertEquals( "AttributeValueA", map.get( "A123456789A" ) ); assertEquals( "AttributeValueB", map.get( "A123456789B" ) ); assertEquals( null, map.get( "A123456789C" ) ); } @Test public void testGetDataElementOperandIdSchemeCodeMap() { DataElement deA = new DataElement( "NameA" ); DataElement deB = new DataElement( "NameB" ); deA.setUid( "D123456789A" ); deB.setUid( "D123456789B" ); deA.setCode( "DCodeA" ); deB.setCode( "DCodeB" ); CategoryOptionCombo ocA = new CategoryOptionCombo(); ocA.setUid( "C123456789A" ); ocA.setCode( "CCodeA" ); DataElementOperand opA = new DataElementOperand( deA, ocA ); DataElementOperand opB = new DataElementOperand( deB, ocA ); List<DataElementOperand> operands = Lists.newArrayList( opA, opB ); Map<String, String> map = DimensionalObjectUtils.getDataElementOperandIdSchemeMap( operands, IdScheme.CODE ); assertEquals( 3, map.size() ); assertEquals( "DCodeA", map.get( "D123456789A" ) ); assertEquals( "DCodeB", map.get( "D123456789B" ) ); assertEquals( "CCodeA", map.get( "C123456789A" ) ); } @Test public void testGetFirstSecondIdentifier() { assertEquals( "A123456789A", DimensionalObjectUtils.getFirstIdentifer( "A123456789A.P123456789A" ) ); assertNull( DimensionalObjectUtils.getFirstIdentifer( "A123456789A" ) ); } @Test public void testGetSecondIdentifier() { assertEquals( "P123456789A", DimensionalObjectUtils.getSecondIdentifer( "A123456789A.P123456789A" ) ); assertNull( DimensionalObjectUtils.getSecondIdentifer( "A123456789A" ) ); } @Test public void testReplaceOperandTotalsWithDataElements() { DataElement deA = new DataElement( "NameA" ); DataElement deB = new DataElement( "NameB" ); deA.setAutoFields(); deB.setAutoFields(); CategoryOptionCombo cocA = new CategoryOptionCombo(); cocA.setAutoFields(); DataElementOperand opA = new DataElementOperand( deA ); DataElementOperand opB = new DataElementOperand( deA, cocA ); DataElementOperand opC = new DataElementOperand( deB, cocA ); List<DimensionalItemObject> items = Lists.newArrayList( deB, opA, opB, opC ); assertEquals( 4, items.size() ); assertTrue( items.contains( deB ) ); assertTrue( items.contains( opA ) ); assertTrue( items.contains( opB ) ); assertTrue( items.contains( opC ) ); assertFalse( items.contains( deA ) ); items = DimensionalObjectUtils.replaceOperandTotalsWithDataElements( items ); assertEquals( 4, items.size() ); assertTrue( items.contains( deB ) ); assertFalse( items.contains( opA ) ); assertTrue( items.contains( opB ) ); assertTrue( items.contains( opC ) ); assertTrue( items.contains( deA ) ); } }
package org.cfeclipse.cfml.dialogs; import java.util.Iterator; import java.util.Set; import org.cfeclipse.cfml.dictionary.Parameter; import org.cfeclipse.cfml.dictionary.Tag; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; public class EditCustomTagDialog extends Dialog { private String title; private Tag tag; private Set attributes; private Shell dialogShell; private Label tagNameLabel; private Button removeAttribute; private Button addAttribute; private Composite attributesButtons; private Group TagInfo; private Composite attributeProperties; private Group attrubutesGroup; private Label attributeName; private Button addAtrib; private Text attribName; private Button isXMLcheck; private Button isSingleCheck; private List attributesList; private Text tagName; public EditCustomTagDialog(Shell parentShell){ super(parentShell); this.title = "New Custom Tag"; this.tag = new Tag("cf_newtag", true); } public EditCustomTagDialog(Shell parentShell, Tag tag){ super(parentShell); this.tag = tag; this.title = tag.getName(); Set attribs = tag.getParameters(); this.attributes = attribs; } public Control createDialogArea(Composite parent) { Composite container = new Composite(parent, SWT.NULL); FillLayout fl = new FillLayout(); container.setLayout(fl); TabFolder tabFolder = new TabFolder(container, SWT.HORIZONTAL); //Here we addd the main tabFolder = createMainLayout(tabFolder); //Create the help Tab TabItem tabHelp = new TabItem(tabFolder, SWT.NONE); tabHelp.setText("Help"); GridLayout gl = new GridLayout(); gl.numColumns = 1; Composite helpContents = new Composite(tabFolder, SWT.NONE); helpContents.setLayout(gl); Text helpDesc = new Text(helpContents, SWT.READ_ONLY | SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.RESIZE); helpDesc.setLayoutData(new GridData(GridData.FILL_BOTH)); helpDesc.setBackground(new Color(Display.getCurrent(), 255, 255, 255)); if(this.tag != null){ helpDesc.setText(this.tag.getHelp()); } else { helpDesc.setText("help to go here"); } tabHelp.setControl(helpContents); return container; } private void addAttributeMouseDoubleClick(MouseEvent evt) { System.out.println("addAttribute.mouseDoubleClick, event=" + evt); //TODO add your code for addAttribute.mouseDoubleClick } private TabFolder createMainLayout(TabFolder tabFolder){ TabItem mainTab = new TabItem(tabFolder, SWT.NONE); mainTab.setText("Tag"); GridLayout gl = new GridLayout(); //gl.numColumns = 2; Composite mainContents = new Composite(tabFolder, SWT.NONE); mainContents.setLayout(gl); //Set the tag name displayTagName(mainContents); displayTagInfo(mainContents); displayAttributes(mainContents); mainTab.setControl(mainContents); return tabFolder; } /** * @param mainContents */ private void displayAttributes(Composite mainContents) { { Composite attribGroup = new Composite(mainContents, SWT.NONE); GridLayout attribGroupLayout = new GridLayout(); attribGroupLayout.makeColumnsEqualWidth = true; attribGroupLayout.numColumns = 2; GridData attribGroupLData = new GridData(); attribGroupLData.verticalAlignment = GridData.FILL; attribGroupLData.widthHint = 264; attribGroupLData.horizontalSpan = 2; attribGroup.setLayoutData(attribGroupLData); attribGroup.setLayout(attribGroupLayout); } { attrubutesGroup = new Group(mainContents, SWT.NONE); GridLayout attrubutesGroupLayout = new GridLayout(); attrubutesGroupLayout.makeColumnsEqualWidth = true; attrubutesGroupLayout.numColumns = 2; attrubutesGroup.setLayout(attrubutesGroupLayout); GridData attrubutesGroupLData = new GridData(); attrubutesGroupLData.widthHint = 490; attrubutesGroupLData.verticalAlignment = GridData.FILL; attrubutesGroup.setLayoutData(attrubutesGroupLData); attrubutesGroup.setText("Attributes:"); { GridData attributesListLData = new GridData(); attributesListLData.widthHint = 170; attributesListLData.heightHint = 100; attributesListLData.verticalAlignment = GridData.FILL; attributesList = new List(attrubutesGroup, SWT.NONE|SWT.BORDER|SWT.V_SCROLL); attributesList.setLayoutData(attributesListLData); Iterator iter = this.tag.getParameters().iterator(); while(iter.hasNext()){ Parameter param = (Parameter)iter.next(); attributesList.add(param.getName()); } attributesList.addMouseListener(new MouseAdapter() { public void mouseDown(MouseEvent evt) { attributesListMouseDown(evt); } }); } { attributeProperties = new Composite( attrubutesGroup, SWT.NONE); { attributeName = new Label(attributeProperties, SWT.NONE); attributeName.setText("Attribute Name:"); } { attribName = new Text(attributeProperties, SWT.NONE|SWT.BORDER); attribName.setText("Attribute Name"); } GridLayout attributePropertiesLayout = new GridLayout(); attributePropertiesLayout.makeColumnsEqualWidth = true; attributePropertiesLayout.numColumns = 2; GridData attributePropertiesLData = new GridData(); attributePropertiesLData.widthHint = 202; attributePropertiesLData.verticalAlignment = GridData.FILL; attributeProperties.setLayoutData(attributePropertiesLData); attributeProperties.setLayout(attributePropertiesLayout); } { attributesButtons = new Composite(attrubutesGroup, SWT.NONE); GridLayout attributesButtonsLayout = new GridLayout(); attributesButtonsLayout.makeColumnsEqualWidth = true; attributesButtonsLayout.numColumns = 2; attributesButtons.setLayout(attributesButtonsLayout); { addAttribute = new Button(attributesButtons, SWT.PUSH | SWT.CENTER); addAttribute.setText(" + "); addAttribute.addMouseListener(new MouseAdapter() { public void mouseDoubleClick(MouseEvent evt) { addAttributeMouseDoubleClick(evt); } }); } { removeAttribute = new Button( attributesButtons, SWT.PUSH | SWT.CENTER); removeAttribute.setText(" - "); } } } } /** * @param mainContents */ private void displayTagInfo(Composite mainContents) { { TagInfo = new Group(mainContents, SWT.NONE); GridLayout TagInfoLayout = new GridLayout(); TagInfoLayout.makeColumnsEqualWidth = true; TagInfoLayout.numColumns = 2; TagInfo.setLayout(TagInfoLayout); GridData TagInfoLData = new GridData(); TagInfo.setLayoutData(TagInfoLData); TagInfo.setText("Tag Info:"); { isXMLcheck = new Button(TagInfo, SWT.CHECK | SWT.LEFT); isXMLcheck.setText("Is XML Style?"); isXMLcheck.setSelection(this.tag.isXMLStyle()); } { isSingleCheck = new Button(TagInfo, SWT.CHECK | SWT.LEFT); isSingleCheck.setText("Is Single?"); isSingleCheck.setSelection(this.tag.isSingle()); } } } /** * @param mainContents */ private void displayTagName(Composite mainContents) { { // tagNameLabel = new Label(mainContents, SWT.NONE); // tagNameLabel.setText("Tag Name:"); } { tagName = new Text(mainContents, SWT.NONE|SWT.BORDER); GridData tagNameLData = new GridData(); tagNameLData.widthHint = 200; tagName.setLayoutData(tagNameLData); tagName.setText(this.tag.getName()); } } protected void configureShell(Shell newShell){ super.configureShell(newShell); newShell.setText(this.title); } protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, "OK", true); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } protected void buttonPressed(int buttonId) { if (buttonId == IDialogConstants.OK_ID) { // Grab the values from all the text fields and stick them in the fieldStore this.close(); } super.buttonPressed(buttonId); } private void attributesListMouseDown(MouseEvent evt) { System.out.println("attributesList.mouseDown, event=" + evt + " " + attributesList.getItem(attributesList.getSelectionIndex())); //TODO add your code for attributesList.mouseDown } }
/** * Copyright 2000-2013 Geometria Contributors * http://geocentral.net/geometria * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License * http://www.gnu.org/licenses */ package net.geocentral.geometria.evaluator; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import net.geocentral.geometria.evaluator.function.GAcos; import net.geocentral.geometria.evaluator.function.GAsin; import net.geocentral.geometria.evaluator.function.GAtan; import net.geocentral.geometria.evaluator.function.GCos; import net.geocentral.geometria.evaluator.function.GSin; import net.geocentral.geometria.evaluator.function.GSqrt; import net.geocentral.geometria.evaluator.function.GTan; import net.geocentral.geometria.evaluator.operator.GAdd; import net.geocentral.geometria.evaluator.operator.GDivide; import net.geocentral.geometria.evaluator.operator.GNegate; import net.geocentral.geometria.evaluator.operator.GPower; import net.geocentral.geometria.evaluator.operator.GSubtract; import net.geocentral.geometria.evaluator.operator.GTimes; import net.geocentral.geometria.evaluator.token.GConstant; import net.geocentral.geometria.evaluator.token.GDecimal; import net.geocentral.geometria.evaluator.token.GFunction; import net.geocentral.geometria.evaluator.token.GLeftParanthesis; import net.geocentral.geometria.evaluator.token.GOperator; import net.geocentral.geometria.evaluator.token.GPi; import net.geocentral.geometria.evaluator.token.GRightParanthesis; import net.geocentral.geometria.evaluator.token.GToken; import net.geocentral.geometria.evaluator.token.GTokenBounds; import net.geocentral.geometria.evaluator.token.GValueToken; import net.geocentral.geometria.evaluator.token.GVariable; import net.geocentral.geometria.model.GLabelFactory; import net.geocentral.geometria.util.GDictionary; import org.apache.log4j.Logger; public class GTokenizer { public static final String CHARSET = "[0-9\\." + GLabelFactory.VARIABLE_CHARSET + "]"; private Map<String, GConstant> constants; private Map<String, GVariable> variables; private GTokenBounds errorTokenBounds; private static Logger logger = Logger.getLogger("net.geocentral.geometria"); public <T extends GVariable> GTokenizer(Collection<T> variableList) { logger.info(variableList); makeConstants(); variables = new LinkedHashMap<String, GVariable>(); if (variableList != null) { for (GVariable variable : variableList) { variables.put(variable.getName(), variable); } } } private void makeConstants() { logger.info(""); constants = new LinkedHashMap<String, GConstant>(); GPi pi = new GPi(); constants.put(pi.getName().toLowerCase(), pi); } public Map<GToken, GTokenBounds> tokenize(String input) throws Exception { logger.info(input); List<GToken> tokenList = new ArrayList<GToken>(); List<GTokenBounds> tokenBoundsList = new ArrayList<GTokenBounds>(); StringBuffer buf = new StringBuffer(); for (int pos = 0; pos < input.length(); pos++) { char ch = input.charAt(pos); if (String.valueOf(ch).matches(CHARSET)) { buf.append(ch); if (pos == input.length() - 1) { GTokenBounds tokenBounds = new GTokenBounds(pos - buf.length() + 1, buf.length()); GToken token; try { token = makeAlphaNumericToken(buf); } catch (Exception exception) { errorTokenBounds = tokenBounds; throw exception; } tokenList.add(token); tokenBoundsList.add(tokenBounds); } continue; } else if (buf.length() > 0) { GTokenBounds tokenBounds = new GTokenBounds(pos - buf.length(), buf.length()); GToken token; try { token = makeAlphaNumericToken(buf); } catch (Exception exception) { errorTokenBounds = tokenBounds; throw exception; } tokenList.add(token); tokenBoundsList.add(tokenBounds); buf = new StringBuffer(); } if (ch == ' ') { continue; } else if (ch == '(') { tokenList.add(new GLeftParanthesis()); tokenBoundsList.add(new GTokenBounds(pos, 1)); } else if (ch == ')') { tokenList.add(new GRightParanthesis()); tokenBoundsList.add(new GTokenBounds(pos, 1)); } else { GToken prevToken = tokenList.isEmpty() ? null : tokenList.get(tokenList.size() - 1); GTokenBounds tokenBounds = new GTokenBounds(pos, 1); GToken token; try { token = makeOperator(ch, prevToken); } catch (Exception exception) { errorTokenBounds = tokenBounds; throw exception; } tokenList.add(token); tokenBoundsList.add(tokenBounds); } } Iterator<GToken> tokenIterator = tokenList.iterator(); Iterator<GTokenBounds> tokenBoundsIterator = tokenBoundsList.iterator(); Map<GToken, GTokenBounds> tokenMap = new LinkedHashMap<GToken, GTokenBounds>(); while (tokenIterator.hasNext()) { GToken token = tokenIterator.next(); GTokenBounds tokenBounds = tokenBoundsIterator.next(); tokenMap.put(token, tokenBounds); } return tokenMap; } private GToken makeAlphaNumericToken(StringBuffer buf) throws Exception { logger.info(""); String bufValue = String.valueOf(buf); if (bufValue.equalsIgnoreCase("acos")) { return new GAcos(); } else if (bufValue.equalsIgnoreCase("asin")) { return new GAsin(); } else if (bufValue.equalsIgnoreCase("atan")) { return new GAtan(); } else if (bufValue.equalsIgnoreCase("cos")) { return new GCos(); } else if (bufValue.equalsIgnoreCase("sin")) { return new GSin(); } else if (bufValue.equalsIgnoreCase("sqrt")) { return new GSqrt(); } else if (bufValue.equalsIgnoreCase("tan")) { return new GTan(); } else { GConstant constant = constants.get(bufValue.toLowerCase()); if (constant != null) { return copyOf(constant); } GVariable variable = variables.get(bufValue); if (variable != null) { return copyOf(variable); } double value; try { value = Double.parseDouble(bufValue); } catch (Exception exception) { logger.info("Bad token: " + bufValue); throw new Exception(GDictionary.get("BadToken", bufValue)); } return new GDecimal(value); } } private GToken copyOf(final GVariable variable) { logger.info(variable); GVariable v = new GVariable() { public String getName() { return variable.getName(); } public double getValue() { return variable.getValue(); } public String toString() { return variable.toString(); } }; return v; } private GToken copyOf(final GConstant constant) { logger.info(constant); GConstant c = new GConstant() { public String getName() { return constant.getName(); } public double getValue() { return constant.getValue(); } public String toString() { return constant.toString(); } }; return c; } private GOperator makeOperator(char ch, GToken prevToken) throws Exception { logger.info(ch + " " + prevToken); if (ch == '+') { return new GAdd(); } else if (ch == '*') { return new GTimes(); } else if (ch == '/') { return new GDivide(); } else if (ch == '^') { return new GPower(); } else if (ch == '-') { if (prevToken == null) { return new GNegate(); } else if (prevToken instanceof GValueToken) { return new GSubtract(); } else if (prevToken instanceof GRightParanthesis) { return new GSubtract(); } else if (prevToken instanceof GFunction) { logger.info("Misplaced operator -"); throw new Exception(GDictionary.get("MisplacedOperator", "-")); } else { return new GNegate(); } } else { logger.info("Bad token: " + ch); throw new Exception(GDictionary.get("BadToken", String.valueOf(ch))); } } public Map<String, GConstant> getConstants() { return constants; } public Map<String, GVariable> getVariables() { return variables; } public GTokenBounds getErrorTokenBounds() { return errorTokenBounds; } }
/* * Copyright 2016 Analytical Graphics, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.keycloak.authentication.authenticators.x509; import java.security.cert.X509Certificate; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import org.keycloak.authentication.AuthenticationFlowContext; import org.keycloak.authentication.authenticators.browser.AbstractUsernameFormAuthenticator; import org.keycloak.events.Details; import org.keycloak.events.Errors; import org.keycloak.forms.login.LoginFormsProvider; import org.keycloak.models.ModelDuplicateException; import org.keycloak.models.UserModel; import org.keycloak.models.utils.FormMessage; /** * @author <a href="mailto:pnalyvayko@agi.com">Peter Nalyvayko</a> * @version $Revision: 1 $ * */ public class X509ClientCertificateAuthenticator extends AbstractX509ClientCertificateAuthenticator { @Override public void close() { } @Override public void authenticate(AuthenticationFlowContext context) { try { dumpContainerAttributes(context); X509Certificate[] certs = getCertificateChain(context); if (certs == null || certs.length == 0) { // No x509 client cert, fall through and // continue processing the rest of the authentication flow logger.debug("[X509ClientCertificateAuthenticator:authenticate] x509 client certificate is not available for mutual SSL."); context.attempted(); return; } saveX509CertificateAuditDataToAuthSession(context, certs[0]); recordX509CertificateAuditDataViaContextEvent(context); X509AuthenticatorConfigModel config = null; if (context.getAuthenticatorConfig() != null && context.getAuthenticatorConfig().getConfig() != null) { config = new X509AuthenticatorConfigModel(context.getAuthenticatorConfig()); } if (config == null) { logger.warn("[X509ClientCertificateAuthenticator:authenticate] x509 Client Certificate Authentication configuration is not available."); context.challenge(createInfoResponse(context, "X509 client authentication has not been configured yet")); context.attempted(); return; } // Validate X509 client certificate try { CertificateValidator.CertificateValidatorBuilder builder = certificateValidationParameters(context.getSession(), config); CertificateValidator validator = builder.build(certs); validator.checkRevocationStatus() .validateKeyUsage() .validateExtendedKeyUsage() .validateTimestamps(config.isCertValidationEnabled()); } catch(Exception e) { logger.error(e.getMessage(), e); // TODO use specific locale to load error messages String errorMessage = "Certificate validation's failed."; // TODO is calling form().setErrors enough to show errors on login screen? context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(), errorMessage, e.getMessage())); context.attempted(); return; } Object userIdentity = getUserIdentityExtractor(config).extractUserIdentity(certs); if (userIdentity == null) { context.getEvent().error(Errors.INVALID_USER_CREDENTIALS); logger.warnf("[X509ClientCertificateAuthenticator:authenticate] Unable to extract user identity from certificate."); // TODO use specific locale to load error messages String errorMessage = "Unable to extract user identity from specified certificate"; // TODO is calling form().setErrors enough to show errors on login screen? context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(), errorMessage)); context.attempted(); return; } UserModel user; try { context.getEvent().detail(Details.USERNAME, userIdentity.toString()); context.getAuthenticationSession().setAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, userIdentity.toString()); user = getUserIdentityToModelMapper(config).find(context, userIdentity); } catch(ModelDuplicateException e) { logger.modelDuplicateException(e); String errorMessage = "X509 certificate authentication's failed."; // TODO is calling form().setErrors enough to show errors on login screen? context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(), errorMessage, e.getMessage())); context.attempted(); return; } if (invalidUser(context, user)) { // TODO use specific locale to load error messages String errorMessage = "X509 certificate authentication's failed."; // TODO is calling form().setErrors enough to show errors on login screen? context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(), errorMessage, "Invalid user")); context.attempted(); return; } if (!userEnabled(context, user)) { // TODO use specific locale to load error messages String errorMessage = "X509 certificate authentication's failed."; // TODO is calling form().setErrors enough to show errors on login screen? context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(), errorMessage, "User is disabled")); context.attempted(); return; } if (context.getRealm().isBruteForceProtected()) { if (context.getProtector().isTemporarilyDisabled(context.getSession(), context.getRealm(), user)) { context.getEvent().user(user); context.getEvent().error(Errors.USER_TEMPORARILY_DISABLED); // TODO use specific locale to load error messages String errorMessage = "X509 certificate authentication's failed."; // TODO is calling form().setErrors enough to show errors on login screen? context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(), errorMessage, "User is temporarily disabled. Contact administrator.")); context.attempted(); return; } } context.setUser(user); // Check whether to display the identity confirmation if (!config.getConfirmationPageDisallowed()) { // FIXME calling forceChallenge was the only way to display // a form to let users either choose the user identity from certificate // or to ignore it and proceed to a normal login screen. Attempting // to call the method "challenge" results in a wrong/unexpected behavior. // The question is whether calling "forceChallenge" here is ok from // the design viewpoint? context.forceChallenge(createSuccessResponse(context, certs[0].getSubjectDN().getName())); // Do not set the flow status yet, we want to display a form to let users // choose whether to accept the identity from certificate or to specify username/password explicitly } else { // Bypass the confirmation page and log the user in context.success(); } } catch(Exception e) { logger.errorf("[X509ClientCertificateAuthenticator:authenticate] Exception: %s", e.getMessage()); context.attempted(); } } private Response createErrorResponse(AuthenticationFlowContext context, String subjectDN, String errorMessage, String ... errorParameters) { return createResponse(context, subjectDN, false, errorMessage, errorParameters); } private Response createSuccessResponse(AuthenticationFlowContext context, String subjectDN) { return createResponse(context, subjectDN, true, null, null); } private Response createResponse(AuthenticationFlowContext context, String subjectDN, boolean isUserEnabled, String errorMessage, Object[] errorParameters) { LoginFormsProvider form = context.form(); if (errorMessage != null && errorMessage.trim().length() > 0) { List<FormMessage> errors = new LinkedList<>(); errors.add(new FormMessage(errorMessage)); if (errorParameters != null) { for (Object errorParameter : errorParameters) { if (errorParameter == null) continue; for (String part : errorParameter.toString().split("\n")) { errors.add(new FormMessage(part)); } } } form.setErrors(errors); } MultivaluedMap<String,String> formData = new MultivaluedHashMap<>(); formData.add("username", context.getUser() != null ? context.getUser().getUsername() : "unknown user"); formData.add("subjectDN", subjectDN); formData.add("isUserEnabled", String.valueOf(isUserEnabled)); form.setFormData(formData); return form.createX509ConfirmPage(); } private void dumpContainerAttributes(AuthenticationFlowContext context) { Enumeration<String> attributeNames = context.getHttpRequest().getAttributeNames(); while(attributeNames.hasMoreElements()) { String a = attributeNames.nextElement(); logger.tracef("[X509ClientCertificateAuthenticator:dumpContainerAttributes] \"%s\"", a); } } private boolean userEnabled(AuthenticationFlowContext context, UserModel user) { if (!user.isEnabled()) { context.getEvent().user(user); context.getEvent().error(Errors.USER_DISABLED); return false; } return true; } private boolean invalidUser(AuthenticationFlowContext context, UserModel user) { if (user == null) { context.getEvent().error(Errors.USER_NOT_FOUND); return true; } return false; } @Override public void action(AuthenticationFlowContext context) { MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters(); if (formData.containsKey("cancel")) { context.clearUser(); context.attempted(); return; } if (context.getUser() != null) { recordX509CertificateAuditDataViaContextEvent(context); context.success(); return; } context.attempted(); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package servlet; import java.io.IOException; import java.net.URISyntaxException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import objects.User; import org.json.JSONArray; import org.json.JSONObject; import static servlet.Login.COMPLETED_TASKS_DB; import static servlet.Login.DB_PASS; import static servlet.Login.DB_URL; import static servlet.Login.DB_USER; import static servlet.Login.TASKS_DB; /** * * @author Bryan Siebert */ @WebServlet(name = "GetUserTasks", urlPatterns = {"/bubbles"}) public class BubblesView extends HttpServlet { private HttpSession session; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, URISyntaxException { response.setContentType("text/html;charset=UTF-8"); updatePriority(request, response); request.getRequestDispatcher("home.jsp").forward(request, response); } public void updatePriority(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, URISyntaxException { String dbUser = DB_USER; String dbPass = DB_PASS; String dbURL = DB_URL; User user = null; Connection connection = null; try{ session = request.getSession(false); int ownerID = ((User)session.getAttribute("loggedin")).getId(); Class.forName("org.postgresql.Driver").newInstance(); connection = DriverManager.getConnection(dbURL, dbUser, dbPass); String sql = "select * from "+TASKS_DB+" where owner = ? "; PreparedStatement verifyStatement = connection.prepareStatement(sql); verifyStatement.setInt(1, ownerID); ResultSet result = verifyStatement.executeQuery(); JSONObject obj; JSONArray arr = new JSONArray(); int numResults = 0; int numPast = 0; int numToday = 0; int numTomorrow = 0; int numThisWeek = 0; int numNextWeek = 0; int numFar = 0; while(result.next()){ numResults++; obj = new JSONObject(); obj.put("id", result.getInt("id")); obj.put("title", result.getString("title")); obj.put("description", result.getString("description")); obj.put("date", result.getDate("due")); obj.put("difficulty", result.getInt("difficulty")); obj.put("priority", result.getDouble("priority")); obj.put("timeuntil", result.getString("timeuntil")); arr.put(obj); //Count how many of each type if(result.getString("timeuntil").equals("past")) numPast++; else if(result.getString("timeuntil").equals("today")) numToday++; else if(result.getString("timeuntil").equals("tomorrow")) numTomorrow++; else if(result.getString("timeuntil").equals("thisweek")) numThisWeek++; else if(result.getString("timeuntil").equals("nextweek")) numNextWeek++; else if(result.getString("timeuntil").equals("far")) numFar++; } if(numPast > 0){ if(numPast == 1) session.setAttribute("stats", "You have 1 task past due"); else session.setAttribute("stats", "You have "+numPast+" tasks past due"); } else if(numToday > 0){ if(numToday == 1) session.setAttribute("stats", "You have 1 task due today"); else session.setAttribute("stats", "You have "+numToday+" tasks due today"); } else if(numTomorrow > 0){ if(numTomorrow == 1) session.setAttribute("stats", "You have 1 task due tomorrow"); else session.setAttribute("stats", "You have "+numTomorrow+" tasks due tomorrow"); } else if(numThisWeek > 0){ if(numThisWeek == 1) session.setAttribute("stats", "You have 1 task due this week"); else session.setAttribute("stats", "You have "+numThisWeek+" tasks due this week"); } else if(numNextWeek > 0){ if(numNextWeek == 1) session.setAttribute("stats", "You have 1 task due this next week"); else session.setAttribute("stats", "You have "+numNextWeek+" tasks due this next week"); } else if(numFar > 0){ if(numFar == 1) session.setAttribute("stats", "You have 1 task due weeks from now"); else session.setAttribute("stats", "You have "+numFar+" tasks due weeks from now"); } else session.removeAttribute("stats"); sql = "select * from "+COMPLETED_TASKS_DB+" where owner = ? and popped = 'false'"; verifyStatement = connection.prepareStatement(sql); verifyStatement.setInt(1, ownerID); result = verifyStatement.executeQuery(); while(result.next()){ numResults++; obj = new JSONObject(); obj.put("id", result.getInt("taskid")); obj.put("title", "Pop!"); obj.put("description", result.getString("description")); obj.put("date", result.getDate("due")); obj.put("difficulty", result.getInt("difficulty")); obj.put("priority", result.getInt("priority")); obj.put("timeuntil", result.getString("timeuntil")+" completed"); arr.put(obj); //Statement stmnt = connection.createStatement(); //stmnt.execute("UPDATE "+COMPLETED_TASKS_DB+" SET popped = 'true' WHERE taskid = "+result.getInt("taskid")); } if(numResults>0){ obj = new JSONObject(); obj.put("children", arr); session.setAttribute("tasklist", obj.toString()); } else session.removeAttribute("tasklist"); }catch(SQLException se){ System.out.println(se.getMessage()); }catch(java.lang.Exception ex){ } if(connection != null && !connection.isClosed()){ connection.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (SQLException ex) { Logger.getLogger(BubblesView.class.getName()).log(Level.SEVERE, null, ex); } catch (URISyntaxException ex) { Logger.getLogger(BubblesView.class.getName()).log(Level.SEVERE, null, ex); } } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (SQLException ex) { Logger.getLogger(BubblesView.class.getName()).log(Level.SEVERE, null, ex); } catch (URISyntaxException ex) { Logger.getLogger(BubblesView.class.getName()).log(Level.SEVERE, null, ex); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.pubsub.deprecated; import com.google.cloud.GrpcServiceOptions.ExecutorFactory; import com.google.cloud.pubsub.deprecated.PubSub.MessageConsumer; import com.google.cloud.pubsub.deprecated.PubSub.MessageProcessor; import com.google.cloud.pubsub.deprecated.spi.PubSubRpc; import com.google.cloud.pubsub.deprecated.spi.PubSubRpc.PullCallback; import com.google.cloud.pubsub.deprecated.spi.PubSubRpc.PullFuture; import com.google.common.util.concurrent.ForwardingListenableFuture; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.pubsub.v1.PullRequest; import com.google.pubsub.v1.PullResponse; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import org.easymock.EasyMock; import org.easymock.IAnswer; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; public class MessageConsumerImplTest { private static final String PROJECT = "project"; private static final String SUBSCRIPTION = "subscription"; private static final String SUBSCRIPTION_PB = "projects/project/subscriptions/subscription"; private static final int MAX_QUEUED_CALLBACKS = 42; private static final Message MESSAGE1 = Message.of("payload1"); private static final Message MESSAGE2 = Message.of("payload2"); private static final String ACK_ID1 = "ack-id1"; private static final String ACK_ID2 = "ack-id2"; private static final com.google.pubsub.v1.ReceivedMessage MESSAGE1_PB = com.google.pubsub.v1.ReceivedMessage.newBuilder() .setAckId(ACK_ID1) .setMessage(MESSAGE1.toPb()) .build(); private static final com.google.pubsub.v1.ReceivedMessage MESSAGE2_PB = com.google.pubsub.v1.ReceivedMessage.newBuilder() .setAckId(ACK_ID2) .setMessage(MESSAGE2.toPb()) .build(); private static final PullResponse PULL_RESPONSE = PullResponse.newBuilder() .addReceivedMessages(MESSAGE1_PB) .addReceivedMessages(MESSAGE2_PB) .build(); private static final MessageProcessor DO_NOTHING_PROCESSOR = new MessageProcessor() { @Override public void process(Message message) throws Exception { // do nothing } }; private static final MessageProcessor THROW_PROCESSOR = new MessageProcessor() { @Override public void process(Message message) throws Exception { throw new RuntimeException(); } }; private static final PullResponse EMPTY_RESPONSE = PullResponse.getDefaultInstance(); private PubSubRpc pubsubRpc; private PubSub pubsub; private PubSubOptions options; private AckDeadlineRenewer renewer; @Rule public Timeout globalTimeout = Timeout.seconds(60); static final class TestPullFuture extends ForwardingListenableFuture.SimpleForwardingListenableFuture<PullResponse> implements PullFuture { TestPullFuture(PullResponse response) { super(Futures.immediateFuture(response)); } @Override public void addCallback(final PullCallback callback) { Futures.addCallback(delegate(), new FutureCallback<PullResponse>() { @Override public void onSuccess(PullResponse result) { callback.success(result); } @Override public void onFailure(Throwable error) { callback.failure(error); } }); } } @Before public void setUp() { pubsubRpc = EasyMock.createStrictMock(PubSubRpc.class); pubsub = EasyMock.createMock(PubSub.class); options = EasyMock.createStrictMock(PubSubOptions.class); renewer = EasyMock.createMock(AckDeadlineRenewer.class); } @After public void tearDown() { EasyMock.verify(pubsubRpc); EasyMock.verify(pubsub); EasyMock.verify(options); EasyMock.verify(renewer); } private static PullRequest pullRequest(int maxQueuedCallbacks) { return PullRequest.newBuilder() .setMaxMessages(maxQueuedCallbacks) .setSubscription(SUBSCRIPTION_PB) .setReturnImmediately(false) .build(); } private static IAnswer<Void> createAnswer(final CountDownLatch latch) { return new IAnswer<Void>() { @Override public Void answer() throws Throwable { latch.countDown(); return null; } }; } @Test public void testMessageConsumerAck() throws Exception { PullRequest request = pullRequest(MAX_QUEUED_CALLBACKS); EasyMock.expect(options.getRpc()).andReturn(pubsubRpc); EasyMock.expect(options.getService()).andReturn(pubsub); EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); EasyMock.expect(pubsub.getOptions()).andReturn(options).times(2); final CountDownLatch latch = new CountDownLatch(2); EasyMock.expect(pubsub.ackAsync(SUBSCRIPTION, ACK_ID1)).andReturn(null); EasyMock.expect(pubsub.ackAsync(SUBSCRIPTION, ACK_ID2)).andReturn(null); EasyMock.replay(pubsub); EasyMock.expect(pubsubRpc.pull(request)).andReturn(new TestPullFuture(PULL_RESPONSE)); EasyMock.expect(pubsubRpc.pull(EasyMock.<PullRequest>anyObject())) .andReturn(new TestPullFuture(EMPTY_RESPONSE)).anyTimes(); renewer.add(SUBSCRIPTION, ACK_ID1); EasyMock.expectLastCall(); renewer.add(SUBSCRIPTION, ACK_ID2); EasyMock.expectLastCall(); renewer.remove(SUBSCRIPTION, ACK_ID1); EasyMock.expectLastCall().andAnswer(createAnswer(latch)); renewer.remove(SUBSCRIPTION, ACK_ID2); EasyMock.expectLastCall().andAnswer(createAnswer(latch)); EasyMock.replay(pubsubRpc, options, renewer); try (MessageConsumer consumer = MessageConsumerImpl.builder(options, SUBSCRIPTION, renewer, DO_NOTHING_PROCESSOR) .maxQueuedCallbacks(MAX_QUEUED_CALLBACKS) .build()) { latch.await(); } } @Test public void testMessageConsumerNack() throws Exception { PullRequest request = pullRequest(MAX_QUEUED_CALLBACKS); EasyMock.expect(options.getRpc()).andReturn(pubsubRpc); EasyMock.expect(options.getService()).andReturn(pubsub); EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); EasyMock.expect(pubsub.getOptions()).andReturn(options).times(2); final CountDownLatch latch = new CountDownLatch(2); EasyMock.expect(pubsub.nackAsync(SUBSCRIPTION, ACK_ID1)).andReturn(null); EasyMock.expect(pubsub.nackAsync(SUBSCRIPTION, ACK_ID2)).andReturn(null); EasyMock.replay(pubsub); EasyMock.expect(pubsubRpc.pull(request)).andReturn(new TestPullFuture(PULL_RESPONSE)); EasyMock.expect(pubsubRpc.pull(EasyMock.<PullRequest>anyObject())) .andReturn(new TestPullFuture(EMPTY_RESPONSE)).anyTimes(); renewer.add(SUBSCRIPTION, ACK_ID1); EasyMock.expectLastCall(); renewer.add(SUBSCRIPTION, ACK_ID2); EasyMock.expectLastCall(); renewer.remove(SUBSCRIPTION, ACK_ID1); EasyMock.expectLastCall().andAnswer(createAnswer(latch)); renewer.remove(SUBSCRIPTION, ACK_ID2); EasyMock.expectLastCall().andAnswer(createAnswer(latch)); EasyMock.replay(pubsubRpc, options, renewer); try (MessageConsumer consumer = MessageConsumerImpl.builder(options, SUBSCRIPTION, renewer, THROW_PROCESSOR) .maxQueuedCallbacks(MAX_QUEUED_CALLBACKS) .build()) { latch.await(); } } @Test public void testMessageConsumerMultipleCallsAck() throws Exception { PullRequest request1 = pullRequest(MAX_QUEUED_CALLBACKS); PullRequest request2 = pullRequest(MAX_QUEUED_CALLBACKS - 1); PullResponse response1 = PullResponse.newBuilder() .addReceivedMessages(MESSAGE1_PB) .build(); final PullResponse response2 = PullResponse.newBuilder() .addReceivedMessages(MESSAGE2_PB) .build(); EasyMock.expect(options.getRpc()).andReturn(pubsubRpc); EasyMock.expect(options.getService()).andReturn(pubsub); EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); final CountDownLatch nextPullLatch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(2); EasyMock.expect(pubsub.getOptions()).andReturn(options); EasyMock.expect(pubsub.ackAsync(SUBSCRIPTION, ACK_ID1)).andAnswer(new IAnswer<Future<Void>>() { @Override public Future<Void> answer() throws Throwable { nextPullLatch.await(); return null; } }); EasyMock.expect(pubsub.getOptions()).andReturn(options); EasyMock.expect(pubsub.ackAsync(SUBSCRIPTION, ACK_ID2)).andReturn(null); EasyMock.replay(pubsub); EasyMock.expect(pubsubRpc.pull(request1)).andReturn(new TestPullFuture(response1)); EasyMock.expect(pubsubRpc.pull(request2)).andAnswer(new IAnswer<PullFuture>() { @Override public PullFuture answer() throws Throwable { nextPullLatch.countDown(); return new TestPullFuture(response2); } }); EasyMock.expect(pubsubRpc.pull(EasyMock.<PullRequest>anyObject())) .andReturn(new TestPullFuture(EMPTY_RESPONSE)).anyTimes(); renewer.add(SUBSCRIPTION, ACK_ID1); EasyMock.expectLastCall(); renewer.remove(SUBSCRIPTION, ACK_ID1); EasyMock.expectLastCall().andAnswer(createAnswer(latch)); renewer.add(SUBSCRIPTION, ACK_ID2); EasyMock.expectLastCall(); renewer.remove(SUBSCRIPTION, ACK_ID2); EasyMock.expectLastCall().andAnswer(createAnswer(latch)); EasyMock.replay(pubsubRpc, options, renewer); try (MessageConsumer consumer = MessageConsumerImpl.builder(options, SUBSCRIPTION, renewer, DO_NOTHING_PROCESSOR) .maxQueuedCallbacks(MAX_QUEUED_CALLBACKS) .build()) { latch.await(); } } @Test public void testMessageConsumerMultipleCallsNack() throws Exception { PullRequest request1 = pullRequest(MAX_QUEUED_CALLBACKS); PullRequest request2 = pullRequest(MAX_QUEUED_CALLBACKS - 1); PullResponse response1 = PullResponse.newBuilder() .addReceivedMessages(MESSAGE1_PB) .build(); final PullResponse response2 = PullResponse.newBuilder() .addReceivedMessages(MESSAGE2_PB) .build(); EasyMock.expect(options.getRpc()).andReturn(pubsubRpc); EasyMock.expect(options.getService()).andReturn(pubsub); EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); final CountDownLatch nextPullLatch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(2); EasyMock.expect(pubsub.getOptions()).andReturn(options); EasyMock.expect(pubsub.nackAsync(SUBSCRIPTION, ACK_ID1)).andAnswer(new IAnswer<Future<Void>>() { @Override public Future<Void> answer() throws Throwable { nextPullLatch.await(); return null; } }); EasyMock.expect(pubsub.getOptions()).andReturn(options); EasyMock.expect(pubsub.nackAsync(SUBSCRIPTION, ACK_ID2)).andReturn(null); EasyMock.replay(pubsub); EasyMock.expect(pubsubRpc.pull(request1)).andReturn(new TestPullFuture(response1)); EasyMock.expect(pubsubRpc.pull(request2)).andAnswer(new IAnswer<PullFuture>() { @Override public PullFuture answer() throws Throwable { nextPullLatch.countDown(); return new TestPullFuture(response2); } }); EasyMock.expect(pubsubRpc.pull(EasyMock.<PullRequest>anyObject())) .andReturn(new TestPullFuture(EMPTY_RESPONSE)).anyTimes(); renewer.add(SUBSCRIPTION, ACK_ID1); EasyMock.expectLastCall(); renewer.remove(SUBSCRIPTION, ACK_ID1); EasyMock.expectLastCall().andAnswer(createAnswer(latch)); renewer.add(SUBSCRIPTION, ACK_ID2); EasyMock.expectLastCall(); renewer.remove(SUBSCRIPTION, ACK_ID2); EasyMock.expectLastCall().andAnswer(createAnswer(latch)); EasyMock.replay(pubsubRpc, options, renewer); try (MessageConsumer consumer = MessageConsumerImpl.builder(options, SUBSCRIPTION, renewer, THROW_PROCESSOR) .maxQueuedCallbacks(MAX_QUEUED_CALLBACKS) .build()) { latch.await(); } } @Test public void testMessageConsumerMaxCallbacksAck() throws Exception { PullRequest request1 = pullRequest(2); PullRequest request2 = pullRequest(1); final PullResponse otherPullResponse = PullResponse.newBuilder() .addReceivedMessages(MESSAGE1_PB) .build(); EasyMock.expect(options.getRpc()).andReturn(pubsubRpc); EasyMock.expect(options.getService()).andReturn(pubsub); EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); EasyMock.expect(pubsub.getOptions()).andReturn(options).times(2); final CountDownLatch nextPullLatch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(3); EasyMock.expect(pubsub.ackAsync(SUBSCRIPTION, ACK_ID1)).andReturn(null); EasyMock.expect(pubsub.ackAsync(SUBSCRIPTION, ACK_ID2)).andAnswer(new IAnswer<Future<Void>>() { @Override public Future<Void> answer() throws Throwable { nextPullLatch.await(); return null; } }); EasyMock.expect(pubsub.getOptions()).andReturn(options); EasyMock.expect(pubsub.ackAsync(SUBSCRIPTION, ACK_ID1)).andReturn(null); EasyMock.replay(pubsub); EasyMock.expect(pubsubRpc.pull(request1)).andReturn(new TestPullFuture(PULL_RESPONSE)); EasyMock.expect(pubsubRpc.pull(request2)).andAnswer(new IAnswer<PullFuture>() { @Override public PullFuture answer() throws Throwable { nextPullLatch.countDown(); return new TestPullFuture(otherPullResponse); } }); EasyMock.expect(pubsubRpc.pull(EasyMock.<PullRequest>anyObject())) .andReturn(new TestPullFuture(EMPTY_RESPONSE)).anyTimes(); renewer.add(SUBSCRIPTION, ACK_ID1); EasyMock.expectLastCall(); renewer.add(SUBSCRIPTION, ACK_ID2); EasyMock.expectLastCall(); renewer.remove(SUBSCRIPTION, ACK_ID1); EasyMock.expectLastCall().andAnswer(createAnswer(latch)); renewer.remove(SUBSCRIPTION, ACK_ID2); EasyMock.expectLastCall().andAnswer(createAnswer(latch)); renewer.add(SUBSCRIPTION, ACK_ID1); EasyMock.expectLastCall(); renewer.remove(SUBSCRIPTION, ACK_ID1); EasyMock.expectLastCall().andAnswer(createAnswer(latch)); EasyMock.replay(pubsubRpc, options, renewer); try (MessageConsumer consumer = MessageConsumerImpl.builder(options, SUBSCRIPTION, renewer, DO_NOTHING_PROCESSOR) .maxQueuedCallbacks(2) .build()) { latch.await(); } } @Test public void testMessageConsumerMaxCallbacksNack() throws Exception { PullRequest request1 = pullRequest(2); PullRequest request2 = pullRequest(1); final PullResponse otherPullResponse = PullResponse.newBuilder() .addReceivedMessages(MESSAGE1_PB) .build(); EasyMock.expect(options.getRpc()).andReturn(pubsubRpc); EasyMock.expect(options.getService()).andReturn(pubsub); EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); EasyMock.expect(pubsub.getOptions()).andReturn(options).times(2); final CountDownLatch nextPullLatch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(3); EasyMock.expect(pubsub.nackAsync(SUBSCRIPTION, ACK_ID1)).andReturn(null); EasyMock.expect(pubsub.nackAsync(SUBSCRIPTION, ACK_ID2)).andAnswer(new IAnswer<Future<Void>>() { @Override public Future<Void> answer() throws Throwable { nextPullLatch.await(); return null; } }); EasyMock.expect(pubsub.getOptions()).andReturn(options); EasyMock.expect(pubsub.nackAsync(SUBSCRIPTION, ACK_ID1)).andReturn(null); EasyMock.replay(pubsub); EasyMock.expect(pubsubRpc.pull(request1)).andReturn(new TestPullFuture(PULL_RESPONSE)); EasyMock.expect(pubsubRpc.pull(request2)).andAnswer(new IAnswer<PullFuture>() { @Override public PullFuture answer() throws Throwable { nextPullLatch.countDown(); return new TestPullFuture(otherPullResponse); } }); EasyMock.expect(pubsubRpc.pull(EasyMock.<PullRequest>anyObject())) .andReturn(new TestPullFuture(EMPTY_RESPONSE)).anyTimes(); renewer.add(SUBSCRIPTION, ACK_ID1); EasyMock.expectLastCall(); renewer.add(SUBSCRIPTION, ACK_ID2); EasyMock.expectLastCall(); renewer.remove(SUBSCRIPTION, ACK_ID1); EasyMock.expectLastCall().andAnswer(createAnswer(latch)); renewer.remove(SUBSCRIPTION, ACK_ID2); EasyMock.expectLastCall().andAnswer(createAnswer(latch)); renewer.add(SUBSCRIPTION, ACK_ID1); EasyMock.expectLastCall(); renewer.remove(SUBSCRIPTION, ACK_ID1); EasyMock.expectLastCall().andAnswer(createAnswer(latch)); EasyMock.replay(pubsubRpc, options, renewer); try (MessageConsumer consumer = MessageConsumerImpl.builder(options, SUBSCRIPTION, renewer, THROW_PROCESSOR) .maxQueuedCallbacks(2) .build()) { latch.await(); } } @Test public void testClose() throws Exception { EasyMock.expect(options.getRpc()).andReturn(pubsubRpc); EasyMock.expect(options.getService()).andReturn(pubsub); final ExecutorService executor = EasyMock.createStrictMock(ExecutorService.class); executor.shutdown(); EasyMock.expectLastCall(); EasyMock.replay(pubsubRpc, pubsub, options, executor, renewer); MessageConsumer consumer = MessageConsumerImpl.builder(options, SUBSCRIPTION, renewer, DO_NOTHING_PROCESSOR) .maxQueuedCallbacks(MAX_QUEUED_CALLBACKS) .executorFactory(new ExecutorFactory<ExecutorService>() { @Override public ExecutorService get() { return executor; } @Override public void release(ExecutorService executor) { executor.shutdown(); } }).build(); consumer.close(); // closing again should do nothing consumer.close(); EasyMock.verify(executor); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator; import com.facebook.presto.memory.LocalMemoryContext; import com.facebook.presto.operator.aggregation.Accumulator; import com.facebook.presto.operator.aggregation.AccumulatorFactory; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.PageBuilder; import com.facebook.presto.spi.block.BlockBuilder; import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.planner.plan.AggregationNode.Step; import com.facebook.presto.sql.planner.plan.PlanNodeId; import com.google.common.collect.ImmutableList; import java.util.List; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.ImmutableList.toImmutableList; import static java.util.Objects.requireNonNull; /** * Group input data and produce a single block for each sequence of identical values. */ public class AggregationOperator implements Operator { private final boolean partial; public static class AggregationOperatorFactory implements OperatorFactory { private final int operatorId; private final PlanNodeId planNodeId; private final Step step; private final List<AccumulatorFactory> accumulatorFactories; private final List<Type> types; private boolean closed; public AggregationOperatorFactory(int operatorId, PlanNodeId planNodeId, Step step, List<AccumulatorFactory> accumulatorFactories) { this.operatorId = operatorId; this.planNodeId = requireNonNull(planNodeId, "planNodeId is null"); this.step = step; this.accumulatorFactories = ImmutableList.copyOf(accumulatorFactories); this.types = toTypes(step, accumulatorFactories); } @Override public List<Type> getTypes() { return types; } @Override public Operator createOperator(DriverContext driverContext) { checkState(!closed, "Factory is already closed"); OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, planNodeId, AggregationOperator.class.getSimpleName()); return new AggregationOperator(operatorContext, step, accumulatorFactories); } @Override public void close() { closed = true; } @Override public OperatorFactory duplicate() { return new AggregationOperatorFactory(operatorId, planNodeId, step, accumulatorFactories); } } private enum State { NEEDS_INPUT, HAS_OUTPUT, FINISHED } private final OperatorContext operatorContext; private final LocalMemoryContext systemMemoryContext; private final List<Type> types; private final List<Aggregator> aggregates; private State state = State.NEEDS_INPUT; public AggregationOperator(OperatorContext operatorContext, Step step, List<AccumulatorFactory> accumulatorFactories) { this.operatorContext = requireNonNull(operatorContext, "operatorContext is null"); this.systemMemoryContext = operatorContext.getSystemMemoryContext().newLocalMemoryContext(); requireNonNull(step, "step is null"); this.partial = step.isOutputPartial(); requireNonNull(accumulatorFactories, "accumulatorFactories is null"); this.types = toTypes(step, accumulatorFactories); // wrapper each function with an aggregator ImmutableList.Builder<Aggregator> builder = ImmutableList.builder(); for (AccumulatorFactory accumulatorFactory : accumulatorFactories) { builder.add(new Aggregator(accumulatorFactory, step)); } aggregates = builder.build(); } @Override public OperatorContext getOperatorContext() { return operatorContext; } @Override public List<Type> getTypes() { return types; } @Override public void finish() { if (state == State.NEEDS_INPUT) { state = State.HAS_OUTPUT; } } @Override public boolean isFinished() { return state == State.FINISHED; } @Override public boolean needsInput() { return state == State.NEEDS_INPUT; } @Override public void addInput(Page page) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); long memorySize = 0; for (Aggregator aggregate : aggregates) { aggregate.processPage(page); memorySize += aggregate.getEstimatedSize(); } if (partial) { systemMemoryContext.setBytes(memorySize); } else { operatorContext.setMemoryReservation(memorySize); } } @Override public Page getOutput() { if (state != State.HAS_OUTPUT) { return null; } // project results into output blocks List<Type> types = aggregates.stream().map(Aggregator::getType).collect(toImmutableList()); PageBuilder pageBuilder = new PageBuilder(types); pageBuilder.declarePosition(); for (int i = 0; i < aggregates.size(); i++) { Aggregator aggregator = aggregates.get(i); BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(i); aggregator.evaluate(blockBuilder); } state = State.FINISHED; return pageBuilder.build(); } private static List<Type> toTypes(Step step, List<AccumulatorFactory> accumulatorFactories) { ImmutableList.Builder<Type> types = ImmutableList.builder(); for (AccumulatorFactory accumulatorFactory : accumulatorFactories) { types.add(new Aggregator(accumulatorFactory, step).getType()); } return types.build(); } private static class Aggregator { private final Accumulator aggregation; private final Step step; private final int intermediateChannel; private Aggregator(AccumulatorFactory accumulatorFactory, Step step) { if (step.isInputRaw()) { intermediateChannel = -1; aggregation = accumulatorFactory.createAccumulator(); } else { checkArgument(accumulatorFactory.getInputChannels().size() == 1, "expected 1 input channel for intermediate aggregation"); intermediateChannel = accumulatorFactory.getInputChannels().get(0); aggregation = accumulatorFactory.createIntermediateAccumulator(); } this.step = step; } public Type getType() { if (step.isOutputPartial()) { return aggregation.getIntermediateType(); } else { return aggregation.getFinalType(); } } public void processPage(Page page) { if (step.isInputRaw()) { aggregation.addInput(page); } else { aggregation.addIntermediate(page.getBlock(intermediateChannel)); } } public void evaluate(BlockBuilder blockBuilder) { if (step.isOutputPartial()) { aggregation.evaluateIntermediate(blockBuilder); } else { aggregation.evaluateFinal(blockBuilder); } } public long getEstimatedSize() { return aggregation.getEstimatedSize(); } } }
/* * 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.zeppelin.python; import org.apache.zeppelin.interpreter.Interpreter; import org.apache.zeppelin.interpreter.InterpreterContext; import org.apache.zeppelin.interpreter.InterpreterException; import org.apache.zeppelin.interpreter.InterpreterGroup; import org.apache.zeppelin.interpreter.InterpreterResult; import org.apache.zeppelin.interpreter.InterpreterResultMessage; import org.apache.zeppelin.interpreter.LazyOpenInterpreter; import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertEquals; public class IPythonInterpreterTest extends BasePythonInterpreterTest { protected Properties initIntpProperties() { Properties properties = new Properties(); properties.setProperty("zeppelin.python.maxResult", "3"); properties.setProperty("zeppelin.python.gatewayserver_address", "127.0.0.1"); return properties; } protected void startInterpreter(Properties properties) throws InterpreterException { interpreter = new LazyOpenInterpreter(new IPythonInterpreter(properties)); intpGroup = new InterpreterGroup(); intpGroup.put("session_1", new ArrayList<Interpreter>()); intpGroup.get("session_1").add(interpreter); interpreter.setInterpreterGroup(intpGroup); interpreter.open(); } @Override public void setUp() throws InterpreterException { Properties properties = initIntpProperties(); startInterpreter(properties); } @Override public void tearDown() throws InterpreterException { intpGroup.close(); } @Test public void testIPythonAdvancedFeatures() throws InterpreterException, InterruptedException, IOException { // ipython help InterpreterContext context = getInterpreterContext(); InterpreterResult result = interpreter.interpret("range?", context); Thread.sleep(100); assertEquals(InterpreterResult.Code.SUCCESS, result.code()); List<InterpreterResultMessage> interpreterResultMessages = context.out.toInterpreterResultMessage(); assertTrue(interpreterResultMessages.get(0).getData().contains("range(stop)")); // timeit context = getInterpreterContext(); result = interpreter.interpret("%timeit range(100)", context); Thread.sleep(100); assertEquals(InterpreterResult.Code.SUCCESS, result.code()); interpreterResultMessages = context.out.toInterpreterResultMessage(); assertTrue(interpreterResultMessages.get(0).getData().contains("loops")); // cancel final InterpreterContext context2 = getInterpreterContext(); new Thread() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } try { interpreter.cancel(context2); } catch (InterpreterException e) { e.printStackTrace(); } } }.start(); result = interpreter.interpret("import time\ntime.sleep(10)", context2); Thread.sleep(100); assertEquals(InterpreterResult.Code.ERROR, result.code()); interpreterResultMessages = context2.out.toInterpreterResultMessage(); assertTrue(interpreterResultMessages.get(0).getData().contains("KeyboardInterrupt")); } @Test public void testIPythonPlotting() throws InterpreterException, InterruptedException, IOException { // matplotlib InterpreterContext context = getInterpreterContext(); InterpreterResult result = interpreter.interpret("%matplotlib inline\n" + "import matplotlib.pyplot as plt\ndata=[1,1,2,3,4]\nplt.figure()\nplt.plot(data)", context); Thread.sleep(100); assertEquals(InterpreterResult.Code.SUCCESS, result.code()); List<InterpreterResultMessage> interpreterResultMessages = context.out.toInterpreterResultMessage(); // the order of IMAGE and TEXT is not determined // check there must be one IMAGE output boolean hasImageOutput = false; boolean hasLineText = false; boolean hasFigureText = false; for (InterpreterResultMessage msg : interpreterResultMessages) { if (msg.getType() == InterpreterResult.Type.IMG) { hasImageOutput = true; } if (msg.getType() == InterpreterResult.Type.TEXT && msg.getData().contains("matplotlib.lines.Line2D")) { hasLineText = true; } if (msg.getType() == InterpreterResult.Type.TEXT && msg.getData().contains("matplotlib.figure.Figure")) { hasFigureText = true; } } assertTrue("No Image Output", hasImageOutput); assertTrue("No Line Text", hasLineText); assertTrue("No Figure Text", hasFigureText); // bokeh // bokeh initialization context = getInterpreterContext(); result = interpreter.interpret("from bokeh.io import output_notebook, show\n" + "from bokeh.plotting import figure\n" + "import bkzep\n" + "output_notebook(notebook_type='zeppelin')", context); Thread.sleep(100); assertEquals(InterpreterResult.Code.SUCCESS, result.code()); interpreterResultMessages = context.out.toInterpreterResultMessage(); assertEquals(2, interpreterResultMessages.size()); assertEquals(InterpreterResult.Type.HTML, interpreterResultMessages.get(0).getType()); assertTrue(interpreterResultMessages.get(0).getData().contains("Loading BokehJS")); assertEquals(InterpreterResult.Type.HTML, interpreterResultMessages.get(1).getType()); assertTrue(interpreterResultMessages.get(1).getData().contains("BokehJS is being loaded")); // bokeh plotting context = getInterpreterContext(); result = interpreter.interpret("from bokeh.plotting import figure, output_file, show\n" + "x = [1, 2, 3, 4, 5]\n" + "y = [6, 7, 2, 4, 5]\n" + "p = figure(title=\"simple line example\", x_axis_label='x', y_axis_label='y')\n" + "p.line(x, y, legend=\"Temp.\", line_width=2)\n" + "show(p)", context); Thread.sleep(100); assertEquals(InterpreterResult.Code.SUCCESS, result.code()); interpreterResultMessages = context.out.toInterpreterResultMessage(); assertEquals(2, interpreterResultMessages.size()); assertEquals(InterpreterResult.Type.HTML, interpreterResultMessages.get(0).getType()); assertEquals(InterpreterResult.Type.HTML, interpreterResultMessages.get(1).getType()); // docs_json is the source data of plotting which bokeh would use to render the plotting. assertTrue(interpreterResultMessages.get(1).getData().contains("docs_json")); // ggplot context = getInterpreterContext(); result = interpreter.interpret("from ggplot import *\n" + "ggplot(diamonds, aes(x='price', fill='cut')) +\\\n" + " geom_density(alpha=0.25) +\\\n" + " facet_wrap(\"clarity\")", context); Thread.sleep(100); assertEquals(InterpreterResult.Code.SUCCESS, result.code()); interpreterResultMessages = context.out.toInterpreterResultMessage(); // the order of IMAGE and TEXT is not determined // check there must be one IMAGE output hasImageOutput = false; for (InterpreterResultMessage msg : interpreterResultMessages) { if (msg.getType() == InterpreterResult.Type.IMG) { hasImageOutput = true; } } assertTrue("No Image Output", hasImageOutput); } @Test public void testGrpcFrameSize() throws InterpreterException, IOException { tearDown(); Properties properties = initIntpProperties(); properties.setProperty("zeppelin.ipython.grpc.message_size", "3000"); startInterpreter(properties); // to make this test can run under both python2 and python3 InterpreterResult result = interpreter.interpret("from __future__ import print_function", getInterpreterContext()); assertEquals(InterpreterResult.Code.SUCCESS, result.code()); InterpreterContext context = getInterpreterContext(); result = interpreter.interpret("print('1'*3000)", context); assertEquals(InterpreterResult.Code.ERROR, result.code()); List<InterpreterResultMessage> interpreterResultMessages = context.out.toInterpreterResultMessage(); assertEquals(1, interpreterResultMessages.size()); assertTrue(interpreterResultMessages.get(0).getData().contains("exceeds maximum size 3000")); // next call continue work result = interpreter.interpret("print(1)", context); assertEquals(InterpreterResult.Code.SUCCESS, result.code()); tearDown(); // increase framesize to make it work properties.setProperty("zeppelin.ipython.grpc.message_size", "5000"); startInterpreter(properties); // to make this test can run under both python2 and python3 result = interpreter.interpret("from __future__ import print_function", getInterpreterContext()); assertEquals(InterpreterResult.Code.SUCCESS, result.code()); context = getInterpreterContext(); result = interpreter.interpret("print('1'*3000)", context); assertEquals(InterpreterResult.Code.SUCCESS, result.code()); } }
package com.taco.tutorial1; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.omg.CORBA_2_3.portable.OutputStream; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; public class Player implements java.io.Serializable { @SuppressWarnings("unused") private static final long serialVersionUID = 1L; Vector2 position; String textureLoc; private static final int col = 4; private static final int row = 6; Animation animation; Texture playerTexture; TextureRegion[] frames; float stateTime; TextureRegion currentFrame; Rectangle bounds; public Vector2 getPreviousPosition() { return previousPosition; } public void setPreviousPosition(Vector2 previousPosition) { this.previousPosition = previousPosition; } String direction; Vector2 previousPosition; public Player(Vector2 position, String textureLoc){ this.position = position; previousPosition = new Vector2(0,0); playerTexture = new Texture(Gdx.files.internal("data/boo.png")); TextureRegion[][] tmp = TextureRegion.split(playerTexture, playerTexture.getWidth() / col, playerTexture.getHeight() / row); frames = new TextureRegion[col * row]; int index = 0; for (int i=0; i< row; i++){ for (int j=0; j<col; j++){ frames[index++] = tmp[i][j]; } } animation = new Animation(1, frames); stateTime = 0f; currentFrame = animation.getKeyFrame(0); bounds = new Rectangle(position.x, position.y, currentFrame.getRegionWidth(), currentFrame.getRegionHeight()); } public void update(){ stateTime += Gdx.graphics.getDeltaTime(); //BEGIN MOVEMENT LOGIC// if(Gdx.input.isKeyPressed(Keys.W)){ position.y+=1f; currentFrame = animation.getKeyFrame(16 + stateTime%4); } if(Gdx.input.isKeyPressed(Keys.A)){ position.x-=1f; currentFrame = animation.getKeyFrame(8 + stateTime%4); } if(Gdx.input.isKeyPressed(Keys.S)){ position.y-=1f; currentFrame = animation.getKeyFrame(20 + stateTime % 4); } if(Gdx.input.isKeyPressed(Keys.D)){ position.x+=1f; currentFrame = animation.getKeyFrame(0 + stateTime % 4); } float accelX = Gdx.input.getAccelerometerX(); float accelY = Gdx.input.getAccelerometerY(); float accelZ = Gdx.input.getAccelerometerZ(); position.x+=accelY ; position.y-=accelX; if(accelY>1){//D stateTime += Gdx.graphics.getDeltaTime(); currentFrame = animation.getKeyFrame(0); } if(accelY<-1){//A stateTime += Gdx.graphics.getDeltaTime(); currentFrame = animation.getKeyFrame(8); } if(accelX>1){//S stateTime += Gdx.graphics.getDeltaTime(); currentFrame = animation.getKeyFrame(20); } if(accelX<-1){//W stateTime += Gdx.graphics.getDeltaTime(); currentFrame = animation.getKeyFrame(16); } bounds = new Rectangle(position.x, position.y, currentFrame.getRegionWidth(), currentFrame.getRegionHeight()); //END MOVEMENT LOGIC// } public void setPosition(Vector2 position) { this.position = position; } public static void savePlayer(Vector2 position) throws IOException{ FileHandle file = Gdx.files.local("player.dat"); OutputStream out = null; try{ file.writeBytes(serialize(position), false); } catch(Exception ex){ System.out.println(ex.toString()); }finally{ if(out!= null) try{ out.close(); }catch(Exception ex){} } System.out.println("Saving Player"); } public static Vector2 readPlayer() throws IOException, ClassNotFoundException{ Vector2 position = null; FileHandle file = Gdx.files.local("player.dat"); position = (Vector2) deserialize(file.readBytes()); return position; } private static byte[] serialize(Object obj) throws IOException{ ByteArrayOutputStream b = new ByteArrayOutputStream(); ObjectOutputStream o = new ObjectOutputStream(b); o.writeObject(obj); return b.toByteArray(); } public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException { ByteArrayInputStream b = new ByteArrayInputStream(bytes); ObjectInputStream o = new ObjectInputStream(b); return o.readObject(); } public Rectangle getBounds() { return bounds; } public void setBounds(Rectangle bounds) { this.bounds = bounds; } public float getStateTime() { return stateTime; } public void setStateTime(float stateTime) { this.stateTime = stateTime; } public Animation getAnimation() { return animation; } public void setAnimation(Animation animation) { this.animation = animation; } public TextureRegion[] getFrames() { return frames; } public void setFrames(TextureRegion[] frames) { this.frames = frames; } public TextureRegion getCurrentFrame() { return currentFrame; } public void setCurrentFrame(TextureRegion currentFrame) { this.currentFrame = currentFrame; } public String getTextureLoc(){ return textureLoc; } public Vector2 getPosition(){ return position; } public String getDirection() { return direction; } public void setDirection(String direction) { this.direction = direction; } }
package us.kbase.mobu.initializer.test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import junit.framework.Assert; import us.kbase.mobu.initializer.ModuleInitializer; public class InitializerTest { private static File tempDir = null; private static final String SIMPLE_MODULE_NAME = "a_simple_module_for_unit_testing"; private static final String EXAMPLE_OLD_METHOD_NAME = "count_contigs_in_set"; private static final String EXAMPLE_METHOD_NAME = "filter_contigs"; private static final String USER_NAME = "kbasedev"; private static final String[] EXPECTED_PATHS = { "docs", "scripts", "test", "ui", "lib", "ui/narrative", "ui/narrative/methods/", "ui/widgets", "lib/README.md", "docs/README.md", "test/README.md", "data/README.md", "scripts/entrypoint.sh", "LICENSE", "README.md", ".travis.yml", "Dockerfile", "Makefile" }; private static final String[] EXPECTED_DEFAULT_PATHS = { "ui/narrative/methods/example_method/img", "ui/narrative/methods/example_method/spec.json", "ui/narrative/methods/example_method/display.yaml" }; private static List<String> allExpectedDefaultPaths; private static List<String> allExpectedExamplePaths; private static List<String> perlPaths; private static List<String> pythonPaths; private static List<String> javaPaths; private static List<String> rPaths; @After public void tearDownModule() throws IOException { File module = Paths.get(tempDir.getAbsolutePath(), SIMPLE_MODULE_NAME).toFile(); if (module.exists() && module.isDirectory()) { FileUtils.deleteDirectory(module); } } @AfterClass public static void cleanupClass() throws Exception { FileUtils.deleteQuietly(tempDir); } public boolean checkPaths(List<String> pathList, String moduleName) { for (String p : pathList) { File f = Paths.get(tempDir.getAbsolutePath(), moduleName, p).toFile(); if (!f.exists()) { System.out.println("Unable to find path: " + f.toString()); return false; } } return true; } /** * Checks that all directories and files are present as expected. * @param moduleName * @return */ public boolean examineModule(String moduleName, boolean useExample, String language) { List<String> expectedPaths = allExpectedDefaultPaths; if (useExample) expectedPaths = allExpectedExamplePaths; if (!checkPaths(expectedPaths, moduleName)) return false; if (useExample) { List<String> langPaths; switch(language) { case "python": langPaths = pythonPaths; break; case "perl": langPaths = perlPaths; break; case "java": langPaths = javaPaths; break; case "r": langPaths = rPaths; break; default: langPaths = pythonPaths; break; } if (!checkPaths(langPaths, moduleName)) return false; } return true; } @BeforeClass public static void prepPathsToCheck() throws IOException { allExpectedDefaultPaths = new ArrayList<String>(Arrays.asList(EXPECTED_PATHS)); allExpectedDefaultPaths.addAll(Arrays.asList(EXPECTED_DEFAULT_PATHS)); allExpectedDefaultPaths.add(SIMPLE_MODULE_NAME + ".spec"); allExpectedExamplePaths = new ArrayList<String>(Arrays.asList(EXPECTED_PATHS)); allExpectedExamplePaths.add(SIMPLE_MODULE_NAME + ".spec"); allExpectedExamplePaths.add("scripts/entrypoint.sh"); allExpectedExamplePaths.add("scripts/run_async.sh"); perlPaths = new ArrayList<String>(); perlPaths.add("lib/" + SIMPLE_MODULE_NAME + "/" + SIMPLE_MODULE_NAME + "Impl.pm"); perlPaths.add("ui/narrative/methods/" + EXAMPLE_METHOD_NAME); perlPaths.add("ui/narrative/methods/" + EXAMPLE_METHOD_NAME + "/img"); perlPaths.add("ui/narrative/methods/" + EXAMPLE_METHOD_NAME + "/spec.json"); perlPaths.add("ui/narrative/methods/" + EXAMPLE_METHOD_NAME + "/display.yaml"); pythonPaths = new ArrayList<String>(); pythonPaths.add("lib/" + SIMPLE_MODULE_NAME + "/" + SIMPLE_MODULE_NAME + "Impl.py"); pythonPaths.add("ui/narrative/methods/" + EXAMPLE_METHOD_NAME); pythonPaths.add("ui/narrative/methods/" + EXAMPLE_METHOD_NAME + "/img"); pythonPaths.add("ui/narrative/methods/" + EXAMPLE_METHOD_NAME + "/spec.json"); pythonPaths.add("ui/narrative/methods/" + EXAMPLE_METHOD_NAME + "/display.yaml"); javaPaths = new ArrayList<String>(); javaPaths.add("lib/src/asimplemoduleforunittesting/ASimpleModuleForUnitTestingServer.java"); javaPaths.add("ui/narrative/methods/" + EXAMPLE_METHOD_NAME); javaPaths.add("ui/narrative/methods/" + EXAMPLE_METHOD_NAME + "/img"); javaPaths.add("ui/narrative/methods/" + EXAMPLE_METHOD_NAME + "/spec.json"); javaPaths.add("ui/narrative/methods/" + EXAMPLE_METHOD_NAME + "/display.yaml"); rPaths = new ArrayList<String>(); rPaths.add("lib/" + SIMPLE_MODULE_NAME + "/" + SIMPLE_MODULE_NAME + "Impl.r"); rPaths.add("ui/narrative/methods/" + EXAMPLE_OLD_METHOD_NAME); rPaths.add("ui/narrative/methods/" + EXAMPLE_OLD_METHOD_NAME + "/img"); rPaths.add("ui/narrative/methods/" + EXAMPLE_OLD_METHOD_NAME + "/spec.json"); rPaths.add("ui/narrative/methods/" + EXAMPLE_OLD_METHOD_NAME + "/display.yaml"); File rootTemp = new File("temp_test"); if (!rootTemp.exists()) { rootTemp.mkdir(); } tempDir = Files.createTempDirectory(rootTemp.toPath(), "init_test_").toFile(); } @Test public void testSimpleModule() throws Exception { boolean useExample = false; ModuleInitializer initer = new ModuleInitializer(SIMPLE_MODULE_NAME, USER_NAME, null, false, tempDir); initer.initialize(useExample); Assert.assertTrue(examineModule(SIMPLE_MODULE_NAME, useExample, ModuleInitializer.DEFAULT_LANGUAGE)); } @Test public void testModuleWithUser() throws Exception { boolean useExample = false; String language = "python"; ModuleInitializer initer = new ModuleInitializer(SIMPLE_MODULE_NAME, USER_NAME, language, false, tempDir); initer.initialize(false); Assert.assertTrue(examineModule(SIMPLE_MODULE_NAME, useExample, language)); } @Test(expected=IOException.class) public void testModuleAlreadyExists() throws Exception { File f = Paths.get(tempDir.getAbsolutePath(), SIMPLE_MODULE_NAME).toFile(); if (!f.exists()) f.mkdir(); ModuleInitializer initer = new ModuleInitializer(SIMPLE_MODULE_NAME, USER_NAME, null, false, tempDir); initer.initialize(false); } @Test(expected=Exception.class) public void testNoNameModule() throws Exception { ModuleInitializer initer = new ModuleInitializer(null, null, null, false, tempDir); initer.initialize(false); } @Test public void testPerlModuleExample() throws Exception { boolean useExample = true; String lang = "perl"; ModuleInitializer initer = new ModuleInitializer(SIMPLE_MODULE_NAME, USER_NAME, lang, false, tempDir); initer.initialize(useExample); Assert.assertTrue(examineModule(SIMPLE_MODULE_NAME, useExample, lang)); } @Test public void testPythonModuleExample() throws Exception { boolean useExample = true; String lang = "python"; ModuleInitializer initer = new ModuleInitializer(SIMPLE_MODULE_NAME, USER_NAME, lang, false, tempDir); initer.initialize(useExample); Assert.assertTrue(examineModule(SIMPLE_MODULE_NAME, useExample, lang)); } @Test public void testJavaModuleExample() throws Exception { boolean useExample = true; String lang = "java"; ModuleInitializer initer = new ModuleInitializer(SIMPLE_MODULE_NAME, USER_NAME, lang, false, tempDir); initer.initialize(useExample); Assert.assertTrue(examineModule(SIMPLE_MODULE_NAME, useExample, lang)); } @Test public void testRModuleExample() throws Exception { boolean useExample = true; String lang = "r"; ModuleInitializer initer = new ModuleInitializer(SIMPLE_MODULE_NAME, USER_NAME, lang, false, tempDir); initer.initialize(useExample); Assert.assertTrue(examineModule(SIMPLE_MODULE_NAME, useExample, lang)); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.osconfig.v1.model; /** * Common Vulnerability Scoring System version 3. For details, see https://www.first.org/cvss * /specification-document * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the OS Config API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class CVSSv3 extends com.google.api.client.json.GenericJson { /** * This metric describes the conditions beyond the attacker's control that must exist in order to * exploit the vulnerability. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String attackComplexity; /** * This metric reflects the context by which vulnerability exploitation is possible. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String attackVector; /** * This metric measures the impact to the availability of the impacted component resulting from a * successfully exploited vulnerability. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String availabilityImpact; /** * The base score is a function of the base metric scores. https://www.first.org/cvss * /specification-document#Base-Metrics * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Float baseScore; /** * This metric measures the impact to the confidentiality of the information resources managed by * a software component due to a successfully exploited vulnerability. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String confidentialityImpact; /** * The Exploitability sub-score equation is derived from the Base Exploitability metrics. * https://www.first.org/cvss/specification-document#2-1-Exploitability-Metrics * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Float exploitabilityScore; /** * The Impact sub-score equation is derived from the Base Impact metrics. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Float impactScore; /** * This metric measures the impact to integrity of a successfully exploited vulnerability. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String integrityImpact; /** * This metric describes the level of privileges an attacker must possess before successfully * exploiting the vulnerability. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String privilegesRequired; /** * The Scope metric captures whether a vulnerability in one vulnerable component impacts resources * in components beyond its security scope. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String scope; /** * This metric captures the requirement for a human user, other than the attacker, to participate * in the successful compromise of the vulnerable component. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String userInteraction; /** * This metric describes the conditions beyond the attacker's control that must exist in order to * exploit the vulnerability. * @return value or {@code null} for none */ public java.lang.String getAttackComplexity() { return attackComplexity; } /** * This metric describes the conditions beyond the attacker's control that must exist in order to * exploit the vulnerability. * @param attackComplexity attackComplexity or {@code null} for none */ public CVSSv3 setAttackComplexity(java.lang.String attackComplexity) { this.attackComplexity = attackComplexity; return this; } /** * This metric reflects the context by which vulnerability exploitation is possible. * @return value or {@code null} for none */ public java.lang.String getAttackVector() { return attackVector; } /** * This metric reflects the context by which vulnerability exploitation is possible. * @param attackVector attackVector or {@code null} for none */ public CVSSv3 setAttackVector(java.lang.String attackVector) { this.attackVector = attackVector; return this; } /** * This metric measures the impact to the availability of the impacted component resulting from a * successfully exploited vulnerability. * @return value or {@code null} for none */ public java.lang.String getAvailabilityImpact() { return availabilityImpact; } /** * This metric measures the impact to the availability of the impacted component resulting from a * successfully exploited vulnerability. * @param availabilityImpact availabilityImpact or {@code null} for none */ public CVSSv3 setAvailabilityImpact(java.lang.String availabilityImpact) { this.availabilityImpact = availabilityImpact; return this; } /** * The base score is a function of the base metric scores. https://www.first.org/cvss * /specification-document#Base-Metrics * @return value or {@code null} for none */ public java.lang.Float getBaseScore() { return baseScore; } /** * The base score is a function of the base metric scores. https://www.first.org/cvss * /specification-document#Base-Metrics * @param baseScore baseScore or {@code null} for none */ public CVSSv3 setBaseScore(java.lang.Float baseScore) { this.baseScore = baseScore; return this; } /** * This metric measures the impact to the confidentiality of the information resources managed by * a software component due to a successfully exploited vulnerability. * @return value or {@code null} for none */ public java.lang.String getConfidentialityImpact() { return confidentialityImpact; } /** * This metric measures the impact to the confidentiality of the information resources managed by * a software component due to a successfully exploited vulnerability. * @param confidentialityImpact confidentialityImpact or {@code null} for none */ public CVSSv3 setConfidentialityImpact(java.lang.String confidentialityImpact) { this.confidentialityImpact = confidentialityImpact; return this; } /** * The Exploitability sub-score equation is derived from the Base Exploitability metrics. * https://www.first.org/cvss/specification-document#2-1-Exploitability-Metrics * @return value or {@code null} for none */ public java.lang.Float getExploitabilityScore() { return exploitabilityScore; } /** * The Exploitability sub-score equation is derived from the Base Exploitability metrics. * https://www.first.org/cvss/specification-document#2-1-Exploitability-Metrics * @param exploitabilityScore exploitabilityScore or {@code null} for none */ public CVSSv3 setExploitabilityScore(java.lang.Float exploitabilityScore) { this.exploitabilityScore = exploitabilityScore; return this; } /** * The Impact sub-score equation is derived from the Base Impact metrics. * @return value or {@code null} for none */ public java.lang.Float getImpactScore() { return impactScore; } /** * The Impact sub-score equation is derived from the Base Impact metrics. * @param impactScore impactScore or {@code null} for none */ public CVSSv3 setImpactScore(java.lang.Float impactScore) { this.impactScore = impactScore; return this; } /** * This metric measures the impact to integrity of a successfully exploited vulnerability. * @return value or {@code null} for none */ public java.lang.String getIntegrityImpact() { return integrityImpact; } /** * This metric measures the impact to integrity of a successfully exploited vulnerability. * @param integrityImpact integrityImpact or {@code null} for none */ public CVSSv3 setIntegrityImpact(java.lang.String integrityImpact) { this.integrityImpact = integrityImpact; return this; } /** * This metric describes the level of privileges an attacker must possess before successfully * exploiting the vulnerability. * @return value or {@code null} for none */ public java.lang.String getPrivilegesRequired() { return privilegesRequired; } /** * This metric describes the level of privileges an attacker must possess before successfully * exploiting the vulnerability. * @param privilegesRequired privilegesRequired or {@code null} for none */ public CVSSv3 setPrivilegesRequired(java.lang.String privilegesRequired) { this.privilegesRequired = privilegesRequired; return this; } /** * The Scope metric captures whether a vulnerability in one vulnerable component impacts resources * in components beyond its security scope. * @return value or {@code null} for none */ public java.lang.String getScope() { return scope; } /** * The Scope metric captures whether a vulnerability in one vulnerable component impacts resources * in components beyond its security scope. * @param scope scope or {@code null} for none */ public CVSSv3 setScope(java.lang.String scope) { this.scope = scope; return this; } /** * This metric captures the requirement for a human user, other than the attacker, to participate * in the successful compromise of the vulnerable component. * @return value or {@code null} for none */ public java.lang.String getUserInteraction() { return userInteraction; } /** * This metric captures the requirement for a human user, other than the attacker, to participate * in the successful compromise of the vulnerable component. * @param userInteraction userInteraction or {@code null} for none */ public CVSSv3 setUserInteraction(java.lang.String userInteraction) { this.userInteraction = userInteraction; return this; } @Override public CVSSv3 set(String fieldName, Object value) { return (CVSSv3) super.set(fieldName, value); } @Override public CVSSv3 clone() { return (CVSSv3) super.clone(); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.admin.indices.settings.get; import com.carrotsearch.hppc.cursors.ObjectObjectCursor; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.common.Strings; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParserUtils; import org.elasticsearch.common.xcontent.json.JsonXContent; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class GetSettingsResponse extends ActionResponse implements ToXContentObject { private final ImmutableOpenMap<String, Settings> indexToSettings; private final ImmutableOpenMap<String, Settings> indexToDefaultSettings; public GetSettingsResponse(ImmutableOpenMap<String, Settings> indexToSettings, ImmutableOpenMap<String, Settings> indexToDefaultSettings) { this.indexToSettings = indexToSettings; this.indexToDefaultSettings = indexToDefaultSettings; } public GetSettingsResponse(StreamInput in) throws IOException { super(in); indexToSettings = in.readImmutableMap(StreamInput::readString, Settings::readSettingsFromStream); indexToDefaultSettings = in.readImmutableMap(StreamInput::readString, Settings::readSettingsFromStream); } /** * Returns a map of index name to {@link Settings} object. The returned {@link Settings} * objects contain only those settings explicitly set on a given index. Any settings * taking effect as defaults must be accessed via {@link #getIndexToDefaultSettings()}. */ public ImmutableOpenMap<String, Settings> getIndexToSettings() { return indexToSettings; } /** * If the originating {@link GetSettingsRequest} object was configured to include * defaults, this will contain a mapping of index name to {@link Settings} objects. * The returned {@link Settings} objects will contain only those settings taking * effect as defaults. Any settings explicitly set on the index will be available * via {@link #getIndexToSettings()}. * See also {@link GetSettingsRequest#includeDefaults(boolean)} */ public ImmutableOpenMap<String, Settings> getIndexToDefaultSettings() { return indexToDefaultSettings; } /** * Returns the string value for the specified index and setting. If the includeDefaults * flag was not set or set to false on the GetSettingsRequest, this method will only * return a value where the setting was explicitly set on the index. If the includeDefaults * flag was set to true on the GetSettingsRequest, this method will fall back to return the default * value if the setting was not explicitly set. */ public String getSetting(String index, String setting) { Settings settings = indexToSettings.get(index); if (setting != null) { if (settings != null && settings.hasValue(setting)) { return settings.get(setting); } else { Settings defaultSettings = indexToDefaultSettings.get(index); if (defaultSettings != null) { return defaultSettings.get(setting); } else { return null; } } } else { return null; } } @Override public void writeTo(StreamOutput out) throws IOException { out.writeMap(indexToSettings, StreamOutput::writeString, (o, s) -> Settings.writeSettingsToStream(s, o)); out.writeMap(indexToDefaultSettings, StreamOutput::writeString, (o, s) -> Settings.writeSettingsToStream(s, o)); } private static void parseSettingsField(XContentParser parser, String currentIndexName, Map<String, Settings> indexToSettings, Map<String, Settings> indexToDefaultSettings) throws IOException { if (parser.currentToken() == XContentParser.Token.START_OBJECT) { switch (parser.currentName()) { case "settings": indexToSettings.put(currentIndexName, Settings.fromXContent(parser)); break; case "defaults": indexToDefaultSettings.put(currentIndexName, Settings.fromXContent(parser)); break; default: parser.skipChildren(); } } else if (parser.currentToken() == XContentParser.Token.START_ARRAY) { parser.skipChildren(); } parser.nextToken(); } private static void parseIndexEntry(XContentParser parser, Map<String, Settings> indexToSettings, Map<String, Settings> indexToDefaultSettings) throws IOException { String indexName = parser.currentName(); parser.nextToken(); while (!parser.isClosed() && parser.currentToken() != XContentParser.Token.END_OBJECT) { parseSettingsField(parser, indexName, indexToSettings, indexToDefaultSettings); } } public static GetSettingsResponse fromXContent(XContentParser parser) throws IOException { HashMap<String, Settings> indexToSettings = new HashMap<>(); HashMap<String, Settings> indexToDefaultSettings = new HashMap<>(); if (parser.currentToken() == null) { parser.nextToken(); } XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser::getTokenLocation); parser.nextToken(); while (!parser.isClosed()) { if (parser.currentToken() == XContentParser.Token.START_OBJECT) { //we must assume this is an index entry parseIndexEntry(parser, indexToSettings, indexToDefaultSettings); } else if (parser.currentToken() == XContentParser.Token.START_ARRAY) { parser.skipChildren(); } else { parser.nextToken(); } } ImmutableOpenMap<String, Settings> settingsMap = ImmutableOpenMap.<String, Settings>builder().putAll(indexToSettings).build(); ImmutableOpenMap<String, Settings> defaultSettingsMap = ImmutableOpenMap.<String, Settings>builder().putAll(indexToDefaultSettings).build(); return new GetSettingsResponse(settingsMap, defaultSettingsMap); } @Override public String toString() { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); XContentBuilder builder = new XContentBuilder(JsonXContent.jsonXContent, baos); toXContent(builder, ToXContent.EMPTY_PARAMS, false); return Strings.toString(builder); } catch (IOException e) { throw new IllegalStateException(e); //should not be possible here } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return toXContent(builder, params, indexToDefaultSettings.isEmpty()); } private XContentBuilder toXContent(XContentBuilder builder, Params params, boolean omitEmptySettings) throws IOException { builder.startObject(); for (ObjectObjectCursor<String, Settings> cursor : getIndexToSettings()) { // no settings, jump over it to shorten the response data if (omitEmptySettings && cursor.value.isEmpty()) { continue; } builder.startObject(cursor.key); builder.startObject("settings"); cursor.value.toXContent(builder, params); builder.endObject(); if (indexToDefaultSettings.isEmpty() == false) { builder.startObject("defaults"); indexToDefaultSettings.get(cursor.key).toXContent(builder, params); builder.endObject(); } builder.endObject(); } builder.endObject(); return builder; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GetSettingsResponse that = (GetSettingsResponse) o; return Objects.equals(indexToSettings, that.indexToSettings) && Objects.equals(indexToDefaultSettings, that.indexToDefaultSettings); } @Override public int hashCode() { return Objects.hash(indexToSettings, indexToDefaultSettings); } }
/* * Copyright 2013-2021 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.cloudfoundry.client.v3; import org.cloudfoundry.AbstractIntegrationTest; import org.cloudfoundry.CloudFoundryVersion; import org.cloudfoundry.IfCloudFoundryVersion; import org.cloudfoundry.client.CloudFoundryClient; import org.cloudfoundry.client.v2.organizations.CreateOrganizationRequest; import org.cloudfoundry.client.v2.organizations.CreateOrganizationResponse; import org.cloudfoundry.client.v2.spaces.CreateSpaceRequest; import org.cloudfoundry.client.v2.spaces.CreateSpaceResponse; import org.cloudfoundry.client.v3.isolationsegments.AddIsolationSegmentOrganizationEntitlementRequest; import org.cloudfoundry.client.v3.isolationsegments.AddIsolationSegmentOrganizationEntitlementResponse; import org.cloudfoundry.client.v3.isolationsegments.CreateIsolationSegmentRequest; import org.cloudfoundry.client.v3.isolationsegments.CreateIsolationSegmentResponse; import org.cloudfoundry.client.v3.isolationsegments.DeleteIsolationSegmentRequest; import org.cloudfoundry.client.v3.isolationsegments.GetIsolationSegmentRequest; import org.cloudfoundry.client.v3.isolationsegments.GetIsolationSegmentResponse; import org.cloudfoundry.client.v3.isolationsegments.IsolationSegmentResource; import org.cloudfoundry.client.v3.isolationsegments.ListIsolationSegmentEntitledOrganizationsRequest; import org.cloudfoundry.client.v3.isolationsegments.ListIsolationSegmentOrganizationsRelationshipRequest; import org.cloudfoundry.client.v3.isolationsegments.ListIsolationSegmentSpacesRelationshipRequest; import org.cloudfoundry.client.v3.isolationsegments.ListIsolationSegmentsRequest; import org.cloudfoundry.client.v3.isolationsegments.RemoveIsolationSegmentOrganizationEntitlementRequest; import org.cloudfoundry.client.v3.isolationsegments.UpdateIsolationSegmentRequest; import org.cloudfoundry.client.v3.organizations.OrganizationResource; import org.cloudfoundry.client.v3.spaces.AssignSpaceIsolationSegmentRequest; import org.cloudfoundry.client.v3.spaces.AssignSpaceIsolationSegmentResponse; import org.cloudfoundry.util.PaginationUtils; import org.cloudfoundry.util.ResourceUtils; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import java.time.Duration; import java.util.concurrent.TimeoutException; import static org.cloudfoundry.util.tuple.TupleUtils.function; @IfCloudFoundryVersion(greaterThanOrEqualTo = CloudFoundryVersion.PCF_1_11) public final class IsolationSegmentsTest extends AbstractIntegrationTest { @Autowired private CloudFoundryClient cloudFoundryClient; @Test public void addOrganizationEntitlement() { String isolationSegmentName = this.nameFactory.getIsolationSegmentName(); String organizationName = this.nameFactory.getOrganizationName(); Mono.zip( createIsolationSegmentId(this.cloudFoundryClient, isolationSegmentName), createOrganizationId(this.cloudFoundryClient, organizationName) ) .flatMap(function((isolationSegmentId, organizationId) -> Mono.zip( Mono.just(organizationId), this.cloudFoundryClient.isolationSegments() .addOrganizationEntitlement(AddIsolationSegmentOrganizationEntitlementRequest.builder() .data(Relationship.builder() .id(organizationId) .build()) .isolationSegmentId(isolationSegmentId) .build()) .map(response -> response.getData().get(0).getId())) )) .as(StepVerifier::create) .consumeNextWith(tupleEquality()) .expectComplete() .verify(Duration.ofMinutes(5)); } @Test public void create() { String isolationSegmentName = this.nameFactory.getIsolationSegmentName(); this.cloudFoundryClient.isolationSegments() .create(CreateIsolationSegmentRequest.builder() .name(isolationSegmentName) .build()) .thenMany(requestListIsolationSegments(this.cloudFoundryClient, isolationSegmentName)) .map(IsolationSegmentResource::getName) .as(StepVerifier::create) .expectNext(isolationSegmentName) .expectComplete() .verify(Duration.ofMinutes(5)); } @Test public void delete() { String isolationSegmentName = this.nameFactory.getIsolationSegmentName(); createIsolationSegmentId(this.cloudFoundryClient, isolationSegmentName) .flatMap(isolationSegmentId -> this.cloudFoundryClient.isolationSegments() .delete(DeleteIsolationSegmentRequest.builder() .isolationSegmentId(isolationSegmentId) .build())) .thenMany(requestListIsolationSegments(this.cloudFoundryClient, isolationSegmentName)) .as(StepVerifier::create) .expectComplete() .verify(Duration.ofMinutes(5)); } @Test public void get() { String isolationSegmentName = this.nameFactory.getIsolationSegmentName(); createIsolationSegmentId(this.cloudFoundryClient, isolationSegmentName) .flatMap(isolationSegmentId -> this.cloudFoundryClient.isolationSegments() .get(GetIsolationSegmentRequest.builder() .isolationSegmentId(isolationSegmentId) .build()) .map(GetIsolationSegmentResponse::getName)) .as(StepVerifier::create) .expectNext(isolationSegmentName) .expectComplete() .verify(Duration.ofMinutes(5)); } @Test public void list() { String isolationSegmentName = this.nameFactory.getIsolationSegmentName(); requestCreateIsolationSegment(this.cloudFoundryClient, isolationSegmentName) .thenMany(PaginationUtils.requestClientV3Resources(page -> this.cloudFoundryClient.isolationSegments() .list(ListIsolationSegmentsRequest.builder() .page(page) .build()))) .filter(response -> isolationSegmentName.equals(response.getName())) .as(StepVerifier::create) .expectNextCount(1) .expectComplete() .verify(Duration.ofMinutes(5)); } @Test public void listEntitledOrganizations() { String isolationSegmentName = this.nameFactory.getIsolationSegmentName(); String organizationName = this.nameFactory.getOrganizationName(); createOrganizationId(this.cloudFoundryClient, organizationName) .flatMap(organizationId -> Mono.zip( createEntitledIsolationSegmentId(this.cloudFoundryClient, isolationSegmentName, organizationId), Mono.just(organizationId) )) .flatMapMany(function((isolationSegmentId, organizationId) -> Mono.zip( Mono.just(organizationId), PaginationUtils.requestClientV3Resources(page -> this.cloudFoundryClient.isolationSegments() .listEntitledOrganizations(ListIsolationSegmentEntitledOrganizationsRequest.builder() .isolationSegmentId(isolationSegmentId) .page(page) .build())) .map(OrganizationResource::getId) .single() ))) .as(StepVerifier::create) .consumeNextWith(tupleEquality()) .expectComplete() .verify(Duration.ofMinutes(5)); } @Test public void listEntitledOrganizationsFilterByName() { String isolationSegmentName = this.nameFactory.getIsolationSegmentName(); String organizationName = this.nameFactory.getOrganizationName(); createOrganizationId(this.cloudFoundryClient, organizationName) .flatMap(organizationId -> Mono.zip( createEntitledIsolationSegmentId(this.cloudFoundryClient, isolationSegmentName, organizationId), Mono.just(organizationId) )) .flatMapMany(function((isolationSegmentId, organizationId) -> Mono.zip( Mono.just(organizationId), PaginationUtils.requestClientV3Resources(page -> this.cloudFoundryClient.isolationSegments() .listEntitledOrganizations(ListIsolationSegmentEntitledOrganizationsRequest.builder() .isolationSegmentId(isolationSegmentId) .name(organizationName) .page(page) .build())) .map(OrganizationResource::getId) .single() ))) .as(StepVerifier::create) .consumeNextWith(tupleEquality()) .expectComplete() .verify(Duration.ofMinutes(5)); } @Test public void listFilterById() { String isolationSegmentName = this.nameFactory.getIsolationSegmentName(); createIsolationSegmentId(this.cloudFoundryClient, isolationSegmentName) .flatMapMany(isolationSegmentId -> PaginationUtils.requestClientV3Resources(page -> this.cloudFoundryClient.isolationSegments() .list(ListIsolationSegmentsRequest.builder() .isolationSegmentId(isolationSegmentId) .page(page) .build())) .map(IsolationSegmentResource::getName)) .as(StepVerifier::create) .expectNext(isolationSegmentName) .expectComplete() .verify(Duration.ofMinutes(5)); } @Test public void listFilterByName() { String isolationSegmentName = this.nameFactory.getIsolationSegmentName(); requestCreateIsolationSegment(this.cloudFoundryClient, isolationSegmentName) .thenMany(PaginationUtils.requestClientV3Resources(page -> this.cloudFoundryClient.isolationSegments() .list(ListIsolationSegmentsRequest.builder() .name(isolationSegmentName) .page(page) .build()))) .as(StepVerifier::create) .expectNextCount(1) .expectComplete() .verify(Duration.ofMinutes(5)); } @Test public void listFilterByOrganizationId() { String isolationSegmentName = this.nameFactory.getIsolationSegmentName(); String organizationName = this.nameFactory.getOrganizationName(); createOrganizationId(this.cloudFoundryClient, organizationName) .flatMap(organizationId -> createEntitledIsolationSegmentId(this.cloudFoundryClient, isolationSegmentName, organizationId) .thenReturn(organizationId)) .flatMapMany(organizationId -> PaginationUtils .requestClientV3Resources(page -> this.cloudFoundryClient.isolationSegments() .list(ListIsolationSegmentsRequest.builder() .organizationId(organizationId) .page(page) .build()))) .filter(resource -> isolationSegmentName.equals(resource.getName())) .as(StepVerifier::create) .expectNextCount(1) .expectComplete() .verify(Duration.ofMinutes(5)); } @Test public void listOrganizationsRelationship() { String isolationSegmentName = this.nameFactory.getIsolationSegmentName(); String organizationName = this.nameFactory.getOrganizationName(); String spaceName = this.nameFactory.getSpaceName(); createOrganizationId(this.cloudFoundryClient, organizationName) .flatMap(organizationId -> Mono.zip( Mono.just(organizationId), createSpaceId(this.cloudFoundryClient, organizationId, spaceName) )) .flatMap(function((organizationId, spaceId) -> Mono.zip( createEntitledIsolationSegmentId(this.cloudFoundryClient, isolationSegmentName, organizationId), Mono.just(organizationId), Mono.just(spaceId) ))) .flatMap(function((isolationSegmentId, organizationId, spaceId) -> Mono.zip( requestAssignIsolationSegment(this.cloudFoundryClient, isolationSegmentId, spaceId) .thenReturn(isolationSegmentId), Mono.just(organizationId) ))) .flatMapMany(function((isolationSegmentId, organizationId) -> Mono.zip( Mono.just(organizationId), this.cloudFoundryClient.isolationSegments() .listOrganizationsRelationship(ListIsolationSegmentOrganizationsRelationshipRequest.builder() .isolationSegmentId(isolationSegmentId) .build()) .map(response -> response.getData().get(0).getId())))) .as(StepVerifier::create) .consumeNextWith(tupleEquality()) .expectComplete() .verify(Duration.ofMinutes(5)); } @Test public void listSpacesRelationship() { String isolationSegmentName = this.nameFactory.getIsolationSegmentName(); String organizationName = this.nameFactory.getOrganizationName(); String spaceName = this.nameFactory.getSpaceName(); createOrganizationId(this.cloudFoundryClient, organizationName) .flatMap(organizationId -> Mono.zip( Mono.just(organizationId), createSpaceId(this.cloudFoundryClient, organizationId, spaceName) )) .flatMap(function((organizationId, spaceId) -> Mono.zip( createEntitledIsolationSegmentId(this.cloudFoundryClient, isolationSegmentName, organizationId), Mono.just(spaceId) ))) .delayUntil(function((isolationSegmentId, spaceId) -> requestAssignIsolationSegment(this.cloudFoundryClient, isolationSegmentId, spaceId))) .flatMapMany(function((isolationSegmentId, spaceId) -> Mono.zip( Mono.just(spaceId), this.cloudFoundryClient.isolationSegments() .listSpacesRelationship(ListIsolationSegmentSpacesRelationshipRequest.builder() .isolationSegmentId(isolationSegmentId) .build()) .map(response -> response.getData().get(0).getId())))) .as(StepVerifier::create) .consumeNextWith(tupleEquality()) .expectComplete() .verify(Duration.ofMinutes(5)); } @Test public void removeOrganizationEntitlement() { String isolationSegmentName = this.nameFactory.getIsolationSegmentName(); String organizationName = this.nameFactory.getOrganizationName(); Mono.zip( createIsolationSegmentId(this.cloudFoundryClient, isolationSegmentName), createOrganizationId(this.cloudFoundryClient, organizationName) ) .delayUntil(function((isolationSegmentId, organizationId) -> requestAddOrganizationEntitlement(this.cloudFoundryClient, isolationSegmentId, organizationId))) .flatMap(function((isolationSegmentId, organizationId) -> this.cloudFoundryClient.isolationSegments() .removeOrganizationEntitlement(RemoveIsolationSegmentOrganizationEntitlementRequest.builder() .isolationSegmentId(isolationSegmentId) .organizationId(organizationId) .build()) .thenReturn(isolationSegmentId))) .flatMapMany(isolationSegmentId -> PaginationUtils .requestClientV3Resources(page -> this.cloudFoundryClient.isolationSegments() .listEntitledOrganizations(ListIsolationSegmentEntitledOrganizationsRequest.builder() .isolationSegmentId(isolationSegmentId) .build()))) .as(StepVerifier::create) .expectComplete() .verify(Duration.ofMinutes(5)); } @Test public void update() { String isolationSegmentName1 = this.nameFactory.getIsolationSegmentName(); String isolationSegmentName2 = this.nameFactory.getIsolationSegmentName(); createIsolationSegmentId(this.cloudFoundryClient, isolationSegmentName1) .flatMap(isolationSegmentId -> this.cloudFoundryClient.isolationSegments() .update(UpdateIsolationSegmentRequest.builder() .isolationSegmentId(isolationSegmentId) .name(isolationSegmentName2) .build())) .thenMany(requestListIsolationSegments(this.cloudFoundryClient, isolationSegmentName2)) .map(IsolationSegmentResource::getName) .as(StepVerifier::create) .expectNext(isolationSegmentName2) .expectComplete() .verify(Duration.ofMinutes(5)); } private static Mono<String> createEntitledIsolationSegmentId(CloudFoundryClient cloudFoundryClient, String isolationSegmentName, String organizationId) { return createIsolationSegmentId(cloudFoundryClient, isolationSegmentName) .delayUntil(isolationSegmentId -> requestAddIsolationSegmentOrganizationEntitlement(cloudFoundryClient, isolationSegmentId, organizationId)); } private static Mono<String> createIsolationSegmentId(CloudFoundryClient cloudFoundryClient, String isolationSegmentName) { return requestCreateIsolationSegment(cloudFoundryClient, isolationSegmentName) .map(CreateIsolationSegmentResponse::getId); } private static Mono<String> createOrganizationId(CloudFoundryClient cloudFoundryClient, String organizationName) { return requestCreateOrganization(cloudFoundryClient, organizationName) .map(ResourceUtils::getId); } private static Mono<String> createSpaceId(CloudFoundryClient cloudFoundryClient, String organizationId, String spaceName) { return requestCreateSpace(cloudFoundryClient, organizationId, spaceName) .map(ResourceUtils::getId); } private static Mono<AddIsolationSegmentOrganizationEntitlementResponse> requestAddIsolationSegmentOrganizationEntitlement(CloudFoundryClient cloudFoundryClient, String isolationSegmentId, String organizationId) { return cloudFoundryClient.isolationSegments() .addOrganizationEntitlement(AddIsolationSegmentOrganizationEntitlementRequest.builder() .isolationSegmentId(isolationSegmentId) .data(Relationship.builder() .id(organizationId) .build()) .build()); } private static Mono<AddIsolationSegmentOrganizationEntitlementResponse> requestAddOrganizationEntitlement(CloudFoundryClient cloudFoundryClient, String isolationSegmentId, String organizationId) { return cloudFoundryClient.isolationSegments() .addOrganizationEntitlement(AddIsolationSegmentOrganizationEntitlementRequest.builder() .data(Relationship.builder() .id(organizationId) .build()) .isolationSegmentId(isolationSegmentId) .build()); } private static Mono<AssignSpaceIsolationSegmentResponse> requestAssignIsolationSegment(CloudFoundryClient cloudFoundryClient, String isolationSegmentId, String spaceId) { return cloudFoundryClient.spacesV3() .assignIsolationSegment(AssignSpaceIsolationSegmentRequest.builder() .data(Relationship.builder() .id(isolationSegmentId) .build()) .spaceId(spaceId) .build()); } private static Mono<CreateIsolationSegmentResponse> requestCreateIsolationSegment(CloudFoundryClient cloudFoundryClient, String isolationSegmentName) { return cloudFoundryClient.isolationSegments() .create(CreateIsolationSegmentRequest.builder() .name(isolationSegmentName) .build()); } private static Mono<CreateOrganizationResponse> requestCreateOrganization(CloudFoundryClient cloudFoundryClient, String organizationName) { return cloudFoundryClient.organizations() .create(CreateOrganizationRequest.builder() .name(organizationName) .build()); } private static Mono<CreateSpaceResponse> requestCreateSpace(CloudFoundryClient cloudFoundryClient, String organizationId, String spaceName) { return cloudFoundryClient.spaces() .create(CreateSpaceRequest.builder() .name(spaceName) .organizationId(organizationId) .build()); } private static Flux<IsolationSegmentResource> requestListIsolationSegments(CloudFoundryClient cloudFoundryClient, String isolationSegmentName) { return PaginationUtils.requestClientV3Resources(page -> cloudFoundryClient.isolationSegments() .list(ListIsolationSegmentsRequest.builder() .name(isolationSegmentName) .page(page) .build())); } }
// ================================================================================================= // Copyright 2011 Twitter, Inc. // ------------------------------------------------------------------------------------------------- // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this work except in compliance with the License. // You may obtain a copy of the License in the LICENSE file, or 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.twitter.common.objectsize; import org.junit.Before; import org.junit.Test; import com.twitter.common.objectsize.ObjectSizeCalculator.MemoryLayoutSpecification; import static org.junit.Assert.assertEquals; public class ObjectSizeCalculatorTest { private int A; private int O; private int R; private int S; private ObjectSizeCalculator objectSizeCalculator; @Before public void setUp() { MemoryLayoutSpecification memoryLayoutSpecification = new MemoryLayoutSpecification() { @Override public int getArrayHeaderSize() { return 16; } @Override public int getObjectHeaderSize() { return 12; } @Override public int getObjectPadding() { return 8; } @Override public int getReferenceSize() { return 4; } @Override public int getSuperclassFieldPadding() { return 4; } }; A = memoryLayoutSpecification.getArrayHeaderSize(); O = memoryLayoutSpecification.getObjectHeaderSize(); R = memoryLayoutSpecification.getReferenceSize(); S = memoryLayoutSpecification.getSuperclassFieldPadding(); objectSizeCalculator = new ObjectSizeCalculator(memoryLayoutSpecification); } @Test public void testRounding() { assertEquals(0, roundTo(0, 8)); assertEquals(8, roundTo(1, 8)); assertEquals(8, roundTo(7, 8)); assertEquals(8, roundTo(8, 8)); assertEquals(16, roundTo(9, 8)); assertEquals(16, roundTo(15, 8)); assertEquals(16, roundTo(16, 8)); assertEquals(24, roundTo(17, 8)); } @Test public void testObjectSize() { assertSizeIs(O, new Object()); } static class ObjectWithFields { int length; int offset; int hashcode; char[] data = {}; } @Test public void testObjectWithFields() { assertSizeIs(O + 3 * 4 + R + A, new ObjectWithFields()); } public static class Class1 { private boolean b1; } @Test public void testOneBooleanSize() { assertSizeIs(O + 1, new Class1()); } public static class Class2 extends Class1 { private int i1; } @Test public void testSimpleSubclassSize() { assertSizeIs(O + roundTo(1, S) + 4, new Class2()); } @Test public void testZeroLengthArray() { assertSizeIs(A, new byte[0]); assertSizeIs(A, new int[0]); assertSizeIs(A, new long[0]); assertSizeIs(A, new Object[0]); } @Test public void testByteArrays() { assertSizeIs(A + 1, new byte[1]); assertSizeIs(A + 8, new byte[8]); assertSizeIs(A + 9, new byte[9]); } @Test public void testCharArrays() { assertSizeIs(A + 2 * 1, new char[1]); assertSizeIs(A + 2 * 4, new char[4]); assertSizeIs(A + 2 * 5, new char[5]); } @Test public void testIntArrays() { assertSizeIs(A + 4 * 1, new int[1]); assertSizeIs(A + 4 * 2, new int[2]); assertSizeIs(A + 4 * 3, new int[3]); } @Test public void testLongArrays() { assertSizeIs(A + 8 * 1, new long[1]); assertSizeIs(A + 8 * 2, new long[2]); assertSizeIs(A + 8 * 3, new long[3]); } @Test public void testObjectArrays() { assertSizeIs(A + R * 1, new Object[1]); assertSizeIs(A + R * 2, new Object[2]); assertSizeIs(A + R * 3, new Object[3]); assertSizeIs(A + R * 1, new String[1]); assertSizeIs(A + R * 2, new String[2]); assertSizeIs(A + R * 3, new String[3]); } public static class Circular { Circular c; } @Test public void testCircular() { Circular c1 = new Circular(); long size = objectSizeCalculator.calculateObjectSize(c1); c1.c = c1; assertEquals(size, objectSizeCalculator.calculateObjectSize(c1)); } static class ComplexObject<T> { static class Node<T> { final T value; Node<T> previous; Node<T> next; Node(T value) { this.value = value; } } private Node<T> first; private Node<T> last; void add(T item) { Node<T> node = new Node<T>(item); if (first == null) { first = node; } else { last.next = node; node.previous = last; } last = node; } } @Test public void testComplexObject() { ComplexObject<Object> l = new ComplexObject<Object>(); l.add(new Object()); l.add(new Object()); l.add(new Object()); long expectedSize = 0; expectedSize += roundTo(O + 2 * R, 8); // The complex object itself plus first and last refs. expectedSize += roundTo(O + 3 * R, 8) * 3; // 3 Nodes - each with 3 object references. expectedSize += roundTo(O, 8) * 3; // 3 vanilla objects contained in the node values. assertSizeIs(expectedSize, l); } private void assertSizeIs(long size, Object o) { assertEquals(roundTo(size, 8), objectSizeCalculator.calculateObjectSize(o)); } private static long roundTo(long x, int multiple) { return ObjectSizeCalculator.roundTo(x, multiple); } }
package controller; import model.GameWorld; import model.entities.Entity; import model.entities.movableEntity.MovableEntity; import model.entities.movableEntity.Player; import model.toolbox.Loader; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.openal.AL; import org.lwjgl.opengl.Display; import view.DisplayManager; import view.renderEngine.GuiRenderer; import view.renderEngine.MasterRenderer; import java.io.IOException; import java.util.ArrayList; import java.util.Map; /** * Controller class to handle the delegations between the Model and View * package. * <p/> * Deals with Game Loop game logic * * @author Marcel van Workum - 300313949 * @author Reuben Puketapu - 300310939 * @author Divya Patel - 300304450 * @author Ellie Coyle - 300307071 */ public class GameController { /** * The constant RUNNING. */ // network state protected static boolean RUNNING; /** * The constant READY. */ protected static boolean READY; /** * The constant NETWORK_DISCONNECTED. */ public static boolean NETWORK_DISCONNECTED; // Model private final GameWorld gameWorld; // View private final MasterRenderer renderer; private final GuiRenderer guiRenderer; // Controller private ClientController clientController; private ServerController serverController; private ActionController actionController; // networking fields private final boolean isHost; private int playerCount; /** * Delegates the creation of the MVC and then starts the game * * @param isHost the is host * @param ipAddress the ip address * @param load the load * @throws IOException */ public GameController(boolean isHost, String ipAddress, boolean load) { GameController.NETWORK_DISCONNECTED = false; GameController.RUNNING = true; // initialise view renderer = new MasterRenderer(); guiRenderer = new GuiRenderer(); // initialise the game world gameWorld = new GameWorld(this); gameWorld.initGame(load); // initialise controller for actions actionController = new ActionController(gameWorld, this); // setup client this.isHost = isHost; if (isHost) { serverController = new ServerController(this); serverController.start(); } else { clientController = new ClientController(this, ipAddress); clientController.start(); } // hook the mouse Mouse.setGrabbed(true); try { while (!READY) { Thread.sleep(50); } } catch (InterruptedException e) { System.err.println("Failed to sleep Game thread"); } // start the game doGame(); } /** * Main game loop where all the goodness happens. Handles calling rendering * methods and processing user actions */ private void doGame() { // set up audio for game AudioController.stopMenuLoop(); // checks which audio should play if (GameWorld.isOutside()) { AudioController.playGameWorldLoop(); } else { AudioController.playOfficeLoop(); } // main game loop while (!Display.isCloseRequested() && RUNNING) { // handle disconnected connections if (NETWORK_DISCONNECTED) { handleDisconnection(); break; } // process the terrains renderer.processTerrain(gameWorld.getTerrain()); // PROCESS PLAYER for (Player player : gameWorld.getAllPlayers().values()) { if (player.getUID() != gameWorld.getPlayer().getUID()) { renderer.processEntity(player); } } // Stores the objects so that you don't call the getter twice ArrayList<Entity> statics = gameWorld.getStaticEntities(); Player player = gameWorld.getPlayer(); // First rotate the commits gameWorld.rotateCommits(); // PROCESS ENTITIES for (Entity e : statics) { if (e.isWithinRange(player)) { renderer.processEntity(e); } } // PROCESS Movable entities for (MovableEntity e : gameWorld.getMoveableEntities().values()) { if (e.isWithinRange(player)) { renderer.processEntity(e); } } // Process the walls for (Entity e : gameWorld.getWallEntities()) { renderer.processEntity(e); } // handle user actions actionController.processActions(); // update the players position in the world if (!gameWorld.getInventory().isVisible() && !gameWorld.isHelpVisible()) { gameWorld.getPlayer().move(gameWorld.getTerrain(), statics); } // decrease patch progress as time passes gameWorld.decreasePatch(); // Render the player's view renderer.render(gameWorld.getLights(), gameWorld.getPlayer().getCamera()); // render the gui guiRenderer.render(gameWorld.getGuiImages()); // Render the inventory if (gameWorld.getInventory().isVisible()) { guiRenderer.render(gameWorld.getInventory().getTextureList()); } else { // only show e to interact message if inventory is not open for (MovableEntity e : gameWorld.withinDistance().values()) { guiRenderer.render(gameWorld.eInteractMessage()); } } // display any helper messages that have been triggered guiRenderer.render(gameWorld.displayMessages()); // render help menu, if it has been requested if (gameWorld.isHelpVisible()) { guiRenderer.render(gameWorld.helpMessage()); } // check if game has ended if (gameWorld.getGameState() > -1) { guiRenderer.render(gameWorld.getEndStateScreen()); } // Increment the time TimeController.tickTock(); // update the Display window DisplayManager.updateDisplay(); } // Finally clean up resources cleanUp(); } /** * Cleans up the game when it is closed */ public void cleanUp() { guiRenderer.cleanUp(); renderer.cleanUp(); Loader.cleanUp(); // Destroys the display DisplayManager.closeDisplay(); // Cleans Audio resources AL.destroy(); if (isHost) { serverController.terminate(); } else { clientController.terminate(); } } /** * Is host boolean. * * @return if this controller is the host */ public boolean isHost() { return isHost; } /** * Create player. * * @param uid the uid */ public void createPlayer(int uid) { gameWorld.addNewPlayer(GameWorld.OFFICE_SPAWN_POSITION, uid); playerCount++; } /** * Creates a ClientPlayer * * @param uid userID * @param b isHost */ public void createPlayer(int uid, boolean b) { gameWorld.addPlayer(GameWorld.OFFICE_SPAWN_POSITION, uid); playerCount++; } /** * Remove player. * * @param uid the uid */ public void removePlayer(int uid) { gameWorld.getAllPlayers().remove(uid); GameWorld.setGuiMessage("aPlayerHasLeftTheGame", 2000); playerCount--; } /** * Sends a network update to the corresponding controller * * @param status type of update * @param entity entity that was updated */ public void setNetworkUpdate(int status, MovableEntity entity) { if (!isHost()) { clientController.setNetworkUpdate(status, entity); } else { serverController.setNetworkUpdate(status, entity); } } /** * Shows "You have Been Disconnected Screen". (Handles disconnections in a * graceful way by informing client that serve has disconnected first) */ private void handleDisconnection() { while (true) { guiRenderer.render(gameWorld.getDisconnectedScreen()); DisplayManager.updateDisplay(); // wait for client to acknowledge failed connection if (Keyboard.isKeyDown(Keyboard.KEY_RETURN)) { break; } } } /** * Game size int. * * @return the int */ public int gameSize() { return playerCount; } /** * Gets game world. * * @return the game world */ public GameWorld getGameWorld() { return gameWorld; } /** * Gets players. * * @return the players */ public Map<Integer, Player> getPlayers() { return gameWorld.getAllPlayers(); } /** * Gets player with id. * * @param uid the uid * @return the player with id */ public Player getPlayerWithID(int uid) { return gameWorld.getAllPlayers().get(uid); } /** * Gets player. * * @return the player */ public Player getPlayer() { return gameWorld.getPlayer(); } }
/** * 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.ipc; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.URI; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.JobStatus; import org.apache.hadoop.mapreduce.MRConfig; import org.apache.hadoop.mapreduce.v2.MiniMRYarnCluster; import org.apache.hadoop.net.StandardSocketFactory; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * This class checks that RPCs can use specialized socket factories. */ public class TestMRCJCSocketFactory { /** * Check that we can reach a NameNode or Resource Manager using a specific * socket factory */ @Ignore //this test is not compatible with our nn selection system @Test public void testSocketFactory() throws IOException { // Create a standard mini-cluster Configuration sconf = new Configuration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(sconf).numDataNodes(1) .build(); final int nameNodePort = cluster.getNameNodePort(); // Get a reference to its DFS directly FileSystem fs = cluster.getFileSystem(); Assert.assertTrue(fs instanceof DistributedFileSystem); DistributedFileSystem directDfs = (DistributedFileSystem) fs; Configuration cconf = getCustomSocketConfigs(nameNodePort); fs = FileSystem.get(cconf); Assert.assertTrue(fs instanceof DistributedFileSystem); DistributedFileSystem dfs = (DistributedFileSystem) fs; JobClient client = null; MiniMRYarnCluster miniMRYarnCluster = null; try { // This will test RPC to the NameNode only. // could we test Client-DataNode connections? Path filePath = new Path("/dir"); Assert.assertFalse(directDfs.exists(filePath)); Assert.assertFalse(dfs.exists(filePath)); directDfs.mkdirs(filePath); Assert.assertTrue(directDfs.exists(filePath)); Assert.assertTrue(dfs.exists(filePath)); // This will test RPC to a Resource Manager fs = FileSystem.get(sconf); JobConf jobConf = new JobConf(); FileSystem.setDefaultUri(jobConf, fs.getUri().toString()); miniMRYarnCluster = initAndStartMiniMRYarnCluster(jobConf); JobConf jconf = new JobConf(miniMRYarnCluster.getConfig()); jconf.set("hadoop.rpc.socket.factory.class.default", "org.apache.hadoop.ipc.DummySocketFactory"); jconf.set(MRConfig.FRAMEWORK_NAME, MRConfig.YARN_FRAMEWORK_NAME); String rmAddress = jconf.get("yarn.resourcemanager.address"); String[] split = rmAddress.split(":"); jconf.set("yarn.resourcemanager.address", split[0] + ':' + (Integer.parseInt(split[1]) + 10)); client = new JobClient(jconf); JobStatus[] jobs = client.jobsToComplete(); Assert.assertTrue(jobs.length == 0); } finally { closeClient(client); closeDfs(dfs); closeDfs(directDfs); stopMiniMRYarnCluster(miniMRYarnCluster); shutdownDFSCluster(cluster); } } private MiniMRYarnCluster initAndStartMiniMRYarnCluster(JobConf jobConf) { MiniMRYarnCluster miniMRYarnCluster; miniMRYarnCluster = new MiniMRYarnCluster(this.getClass().getName(), 1, false); miniMRYarnCluster.init(jobConf); miniMRYarnCluster.start(); return miniMRYarnCluster; } private Configuration getCustomSocketConfigs(final int nameNodePort) { // Get another reference via network using a specific socket factory Configuration cconf = new Configuration(); FileSystem.setDefaultUri(cconf, String.format("hdfs://localhost:%s/", nameNodePort + 10)); cconf.set("hadoop.rpc.socket.factory.class.default", "org.apache.hadoop.ipc.DummySocketFactory"); cconf.set("hadoop.rpc.socket.factory.class.ClientProtocol", "org.apache.hadoop.ipc.DummySocketFactory"); cconf.set("hadoop.rpc.socket.factory.class.JobSubmissionProtocol", "org.apache.hadoop.ipc.DummySocketFactory"); return cconf; } private void shutdownDFSCluster(MiniDFSCluster cluster) { try { if (cluster != null) cluster.shutdown(); } catch (Exception ignored) { // nothing we can do ignored.printStackTrace(); } } private void stopMiniMRYarnCluster(MiniMRYarnCluster miniMRYarnCluster) { try { if (miniMRYarnCluster != null) miniMRYarnCluster.stop(); } catch (Exception ignored) { // nothing we can do ignored.printStackTrace(); } } private void closeDfs(DistributedFileSystem dfs) { try { if (dfs != null) dfs.close(); } catch (Exception ignored) { // nothing we can do ignored.printStackTrace(); } } private void closeClient(JobClient client) { try { if (client != null) client.close(); } catch (Exception ignored) { // nothing we can do ignored.printStackTrace(); } } } /** * Dummy socket factory which shift TPC ports by subtracting 10 when * establishing a connection */ class DummySocketFactory extends StandardSocketFactory { /** * Default empty constructor (for use with the reflection API). */ public DummySocketFactory() { } @Override public Socket createSocket() throws IOException { return new Socket() { @Override public void connect(SocketAddress addr, int timeout) throws IOException { assert (addr instanceof InetSocketAddress); InetSocketAddress iaddr = (InetSocketAddress) addr; SocketAddress newAddr = null; if (iaddr.isUnresolved()) newAddr = new InetSocketAddress(iaddr.getHostName(), iaddr.getPort() - 10); else newAddr = new InetSocketAddress(iaddr.getAddress(), iaddr.getPort() - 10); System.out.printf("Test socket: rerouting %s to %s\n", iaddr, newAddr); super.connect(newAddr, timeout); } }; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof DummySocketFactory)) return false; return true; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: proto/clarifai/api/concept_graph.proto package clarifai2.internal.grpc.api; public final class ConceptGraph { private ConceptGraph() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } public interface ListConceptRelationsRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:clarifai.api.ListConceptRelationsRequest) com.google.protobuf.MessageOrBuilder { /** * <code>.clarifai.api.UserAppIDSet user_app_id = 1;</code> */ boolean hasUserAppId(); /** * <code>.clarifai.api.UserAppIDSet user_app_id = 1;</code> */ clarifai2.internal.grpc.api.Common.UserAppIDSet getUserAppId(); /** * <code>.clarifai.api.UserAppIDSet user_app_id = 1;</code> */ clarifai2.internal.grpc.api.Common.UserAppIDSetOrBuilder getUserAppIdOrBuilder(); /** * <code>string concept_id = 2;</code> */ java.lang.String getConceptId(); /** * <code>string concept_id = 2;</code> */ com.google.protobuf.ByteString getConceptIdBytes(); /** * <code>string predicate = 3;</code> */ java.lang.String getPredicate(); /** * <code>string predicate = 3;</code> */ com.google.protobuf.ByteString getPredicateBytes(); /** * <code>uint32 page = 4;</code> */ int getPage(); /** * <code>uint32 per_page = 5;</code> */ int getPerPage(); } /** * Protobuf type {@code clarifai.api.ListConceptRelationsRequest} */ public static final class ListConceptRelationsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:clarifai.api.ListConceptRelationsRequest) ListConceptRelationsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListConceptRelationsRequest.newBuilder() to construct. private ListConceptRelationsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListConceptRelationsRequest() { conceptId_ = ""; predicate_ = ""; page_ = 0; perPage_ = 0; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ListConceptRelationsRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { clarifai2.internal.grpc.api.Common.UserAppIDSet.Builder subBuilder = null; if (userAppId_ != null) { subBuilder = userAppId_.toBuilder(); } userAppId_ = input.readMessage(clarifai2.internal.grpc.api.Common.UserAppIDSet.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(userAppId_); userAppId_ = subBuilder.buildPartial(); } break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); conceptId_ = s; break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); predicate_ = s; break; } case 32: { page_ = input.readUInt32(); break; } case 40: { perPage_ = input.readUInt32(); 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 clarifai2.internal.grpc.api.ConceptGraph.internal_static_clarifai_api_ListConceptRelationsRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return clarifai2.internal.grpc.api.ConceptGraph.internal_static_clarifai_api_ListConceptRelationsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest.class, clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest.Builder.class); } public static final int USER_APP_ID_FIELD_NUMBER = 1; private clarifai2.internal.grpc.api.Common.UserAppIDSet userAppId_; /** * <code>.clarifai.api.UserAppIDSet user_app_id = 1;</code> */ public boolean hasUserAppId() { return userAppId_ != null; } /** * <code>.clarifai.api.UserAppIDSet user_app_id = 1;</code> */ public clarifai2.internal.grpc.api.Common.UserAppIDSet getUserAppId() { return userAppId_ == null ? clarifai2.internal.grpc.api.Common.UserAppIDSet.getDefaultInstance() : userAppId_; } /** * <code>.clarifai.api.UserAppIDSet user_app_id = 1;</code> */ public clarifai2.internal.grpc.api.Common.UserAppIDSetOrBuilder getUserAppIdOrBuilder() { return getUserAppId(); } public static final int CONCEPT_ID_FIELD_NUMBER = 2; private volatile java.lang.Object conceptId_; /** * <code>string concept_id = 2;</code> */ public java.lang.String getConceptId() { java.lang.Object ref = conceptId_; 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(); conceptId_ = s; return s; } } /** * <code>string concept_id = 2;</code> */ public com.google.protobuf.ByteString getConceptIdBytes() { java.lang.Object ref = conceptId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); conceptId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PREDICATE_FIELD_NUMBER = 3; private volatile java.lang.Object predicate_; /** * <code>string predicate = 3;</code> */ public java.lang.String getPredicate() { java.lang.Object ref = predicate_; 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(); predicate_ = s; return s; } } /** * <code>string predicate = 3;</code> */ public com.google.protobuf.ByteString getPredicateBytes() { java.lang.Object ref = predicate_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); predicate_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_FIELD_NUMBER = 4; private int page_; /** * <code>uint32 page = 4;</code> */ public int getPage() { return page_; } public static final int PER_PAGE_FIELD_NUMBER = 5; private int perPage_; /** * <code>uint32 per_page = 5;</code> */ public int getPerPage() { return perPage_; } 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 (userAppId_ != null) { output.writeMessage(1, getUserAppId()); } if (!getConceptIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, conceptId_); } if (!getPredicateBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, predicate_); } if (page_ != 0) { output.writeUInt32(4, page_); } if (perPage_ != 0) { output.writeUInt32(5, perPage_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (userAppId_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, getUserAppId()); } if (!getConceptIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, conceptId_); } if (!getPredicateBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, predicate_); } if (page_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(4, page_); } if (perPage_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(5, perPage_); } 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 clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest)) { return super.equals(obj); } clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest other = (clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest) obj; boolean result = true; result = result && (hasUserAppId() == other.hasUserAppId()); if (hasUserAppId()) { result = result && getUserAppId() .equals(other.getUserAppId()); } result = result && getConceptId() .equals(other.getConceptId()); result = result && getPredicate() .equals(other.getPredicate()); result = result && (getPage() == other.getPage()); result = result && (getPerPage() == other.getPerPage()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasUserAppId()) { hash = (37 * hash) + USER_APP_ID_FIELD_NUMBER; hash = (53 * hash) + getUserAppId().hashCode(); } hash = (37 * hash) + CONCEPT_ID_FIELD_NUMBER; hash = (53 * hash) + getConceptId().hashCode(); hash = (37 * hash) + PREDICATE_FIELD_NUMBER; hash = (53 * hash) + getPredicate().hashCode(); hash = (37 * hash) + PAGE_FIELD_NUMBER; hash = (53 * hash) + getPage(); hash = (37 * hash) + PER_PAGE_FIELD_NUMBER; hash = (53 * hash) + getPerPage(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest 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 clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest 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 clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest 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(clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest 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; } /** * Protobuf type {@code clarifai.api.ListConceptRelationsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:clarifai.api.ListConceptRelationsRequest) clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return clarifai2.internal.grpc.api.ConceptGraph.internal_static_clarifai_api_ListConceptRelationsRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return clarifai2.internal.grpc.api.ConceptGraph.internal_static_clarifai_api_ListConceptRelationsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest.class, clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest.Builder.class); } // Construct using clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest.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(); if (userAppIdBuilder_ == null) { userAppId_ = null; } else { userAppId_ = null; userAppIdBuilder_ = null; } conceptId_ = ""; predicate_ = ""; page_ = 0; perPage_ = 0; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return clarifai2.internal.grpc.api.ConceptGraph.internal_static_clarifai_api_ListConceptRelationsRequest_descriptor; } public clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest getDefaultInstanceForType() { return clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest.getDefaultInstance(); } public clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest build() { clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest buildPartial() { clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest result = new clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest(this); if (userAppIdBuilder_ == null) { result.userAppId_ = userAppId_; } else { result.userAppId_ = userAppIdBuilder_.build(); } result.conceptId_ = conceptId_; result.predicate_ = predicate_; result.page_ = page_; result.perPage_ = perPage_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.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, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest) { return mergeFrom((clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest other) { if (other == clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest.getDefaultInstance()) return this; if (other.hasUserAppId()) { mergeUserAppId(other.getUserAppId()); } if (!other.getConceptId().isEmpty()) { conceptId_ = other.conceptId_; onChanged(); } if (!other.getPredicate().isEmpty()) { predicate_ = other.predicate_; onChanged(); } if (other.getPage() != 0) { setPage(other.getPage()); } if (other.getPerPage() != 0) { setPerPage(other.getPerPage()); } this.mergeUnknownFields(other.unknownFields); 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 { clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private clarifai2.internal.grpc.api.Common.UserAppIDSet userAppId_ = null; private com.google.protobuf.SingleFieldBuilderV3< clarifai2.internal.grpc.api.Common.UserAppIDSet, clarifai2.internal.grpc.api.Common.UserAppIDSet.Builder, clarifai2.internal.grpc.api.Common.UserAppIDSetOrBuilder> userAppIdBuilder_; /** * <code>.clarifai.api.UserAppIDSet user_app_id = 1;</code> */ public boolean hasUserAppId() { return userAppIdBuilder_ != null || userAppId_ != null; } /** * <code>.clarifai.api.UserAppIDSet user_app_id = 1;</code> */ public clarifai2.internal.grpc.api.Common.UserAppIDSet getUserAppId() { if (userAppIdBuilder_ == null) { return userAppId_ == null ? clarifai2.internal.grpc.api.Common.UserAppIDSet.getDefaultInstance() : userAppId_; } else { return userAppIdBuilder_.getMessage(); } } /** * <code>.clarifai.api.UserAppIDSet user_app_id = 1;</code> */ public Builder setUserAppId(clarifai2.internal.grpc.api.Common.UserAppIDSet value) { if (userAppIdBuilder_ == null) { if (value == null) { throw new NullPointerException(); } userAppId_ = value; onChanged(); } else { userAppIdBuilder_.setMessage(value); } return this; } /** * <code>.clarifai.api.UserAppIDSet user_app_id = 1;</code> */ public Builder setUserAppId( clarifai2.internal.grpc.api.Common.UserAppIDSet.Builder builderForValue) { if (userAppIdBuilder_ == null) { userAppId_ = builderForValue.build(); onChanged(); } else { userAppIdBuilder_.setMessage(builderForValue.build()); } return this; } /** * <code>.clarifai.api.UserAppIDSet user_app_id = 1;</code> */ public Builder mergeUserAppId(clarifai2.internal.grpc.api.Common.UserAppIDSet value) { if (userAppIdBuilder_ == null) { if (userAppId_ != null) { userAppId_ = clarifai2.internal.grpc.api.Common.UserAppIDSet.newBuilder(userAppId_).mergeFrom(value).buildPartial(); } else { userAppId_ = value; } onChanged(); } else { userAppIdBuilder_.mergeFrom(value); } return this; } /** * <code>.clarifai.api.UserAppIDSet user_app_id = 1;</code> */ public Builder clearUserAppId() { if (userAppIdBuilder_ == null) { userAppId_ = null; onChanged(); } else { userAppId_ = null; userAppIdBuilder_ = null; } return this; } /** * <code>.clarifai.api.UserAppIDSet user_app_id = 1;</code> */ public clarifai2.internal.grpc.api.Common.UserAppIDSet.Builder getUserAppIdBuilder() { onChanged(); return getUserAppIdFieldBuilder().getBuilder(); } /** * <code>.clarifai.api.UserAppIDSet user_app_id = 1;</code> */ public clarifai2.internal.grpc.api.Common.UserAppIDSetOrBuilder getUserAppIdOrBuilder() { if (userAppIdBuilder_ != null) { return userAppIdBuilder_.getMessageOrBuilder(); } else { return userAppId_ == null ? clarifai2.internal.grpc.api.Common.UserAppIDSet.getDefaultInstance() : userAppId_; } } /** * <code>.clarifai.api.UserAppIDSet user_app_id = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< clarifai2.internal.grpc.api.Common.UserAppIDSet, clarifai2.internal.grpc.api.Common.UserAppIDSet.Builder, clarifai2.internal.grpc.api.Common.UserAppIDSetOrBuilder> getUserAppIdFieldBuilder() { if (userAppIdBuilder_ == null) { userAppIdBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< clarifai2.internal.grpc.api.Common.UserAppIDSet, clarifai2.internal.grpc.api.Common.UserAppIDSet.Builder, clarifai2.internal.grpc.api.Common.UserAppIDSetOrBuilder>( getUserAppId(), getParentForChildren(), isClean()); userAppId_ = null; } return userAppIdBuilder_; } private java.lang.Object conceptId_ = ""; /** * <code>string concept_id = 2;</code> */ public java.lang.String getConceptId() { java.lang.Object ref = conceptId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); conceptId_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string concept_id = 2;</code> */ public com.google.protobuf.ByteString getConceptIdBytes() { java.lang.Object ref = conceptId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); conceptId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string concept_id = 2;</code> */ public Builder setConceptId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } conceptId_ = value; onChanged(); return this; } /** * <code>string concept_id = 2;</code> */ public Builder clearConceptId() { conceptId_ = getDefaultInstance().getConceptId(); onChanged(); return this; } /** * <code>string concept_id = 2;</code> */ public Builder setConceptIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); conceptId_ = value; onChanged(); return this; } private java.lang.Object predicate_ = ""; /** * <code>string predicate = 3;</code> */ public java.lang.String getPredicate() { java.lang.Object ref = predicate_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); predicate_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string predicate = 3;</code> */ public com.google.protobuf.ByteString getPredicateBytes() { java.lang.Object ref = predicate_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); predicate_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string predicate = 3;</code> */ public Builder setPredicate( java.lang.String value) { if (value == null) { throw new NullPointerException(); } predicate_ = value; onChanged(); return this; } /** * <code>string predicate = 3;</code> */ public Builder clearPredicate() { predicate_ = getDefaultInstance().getPredicate(); onChanged(); return this; } /** * <code>string predicate = 3;</code> */ public Builder setPredicateBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); predicate_ = value; onChanged(); return this; } private int page_ ; /** * <code>uint32 page = 4;</code> */ public int getPage() { return page_; } /** * <code>uint32 page = 4;</code> */ public Builder setPage(int value) { page_ = value; onChanged(); return this; } /** * <code>uint32 page = 4;</code> */ public Builder clearPage() { page_ = 0; onChanged(); return this; } private int perPage_ ; /** * <code>uint32 per_page = 5;</code> */ public int getPerPage() { return perPage_; } /** * <code>uint32 per_page = 5;</code> */ public Builder setPerPage(int value) { perPage_ = value; onChanged(); return this; } /** * <code>uint32 per_page = 5;</code> */ public Builder clearPerPage() { perPage_ = 0; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:clarifai.api.ListConceptRelationsRequest) } // @@protoc_insertion_point(class_scope:clarifai.api.ListConceptRelationsRequest) private static final clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest(); } public static clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListConceptRelationsRequest> PARSER = new com.google.protobuf.AbstractParser<ListConceptRelationsRequest>() { public ListConceptRelationsRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ListConceptRelationsRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ListConceptRelationsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListConceptRelationsRequest> getParserForType() { return PARSER; } public clarifai2.internal.grpc.api.ConceptGraph.ListConceptRelationsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_clarifai_api_ListConceptRelationsRequest_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_clarifai_api_ListConceptRelationsRequest_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n&proto/clarifai/api/concept_graph.proto" + "\022\014clarifai.api\032\037proto/clarifai/api/commo" + "n.proto\032)proto/clarifai/api/utils/extens" + "ions.proto\"\225\001\n\033ListConceptRelationsReque" + "st\022/\n\013user_app_id\030\001 \001(\0132\032.clarifai.api.U" + "serAppIDSet\022\022\n\nconcept_id\030\002 \001(\t\022\021\n\tpredi" + "cate\030\003 \001(\t\022\014\n\004page\030\004 \001(\r\022\020\n\010per_page\030\005 \001" + "(\rBA\n\033clarifai2.internal.grpc.apiZ\003api\242\002" + "\004CAIP\302\002\001_\312\002\021Clarifai\\Internalb\006proto3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { clarifai2.internal.grpc.api.Common.getDescriptor(), clarifai2.internal.grpc.api.utils.Extensions.getDescriptor(), }, assigner); internal_static_clarifai_api_ListConceptRelationsRequest_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_clarifai_api_ListConceptRelationsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_clarifai_api_ListConceptRelationsRequest_descriptor, new java.lang.String[] { "UserAppId", "ConceptId", "Predicate", "Page", "PerPage", }); clarifai2.internal.grpc.api.Common.getDescriptor(); clarifai2.internal.grpc.api.utils.Extensions.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
package io.karim.materialtabs.sample; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.RadioGroup; import android.widget.SeekBar; import android.widget.TextView; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; import io.karim.materialtabs.sample.ui.RadioButtonCenter; public class TabsSettingsFragment extends Fragment implements ResettableFragment { public static final String INDICATOR_COLOR = "INDICATOR_COLOR"; public static final String UNDERLINE_COLOR = "UNDERLINE_COLOR"; public static final String INDICATOR_HEIGHT = "INDICATOR_HEIGHT"; public static final String UNDERLINE_HEIGHT = "UNDERLINE_HEIGHT"; public static final String TAB_PADDING = "TAB_PADDING"; public static final String PADDING_MIDDLE = "PADDING_MIDDLE"; public static final String SAME_WEIGHT_TABS = "SAME_WEIGHT_TABS"; public static final String TEXT_ALL_CAPS = "TEXT_ALL_CAPS"; public static final String TAB_BACKGROUND = "TAB_BACKGROUND"; public static final String TOOLBAR_BACKGROUND = "TOOLBAR_BACKGROUND"; public static final String TEXT_COLOR_UNSELECTED = "TEXT_COLOR_UNSELECTED"; public static final String TEXT_COLOR_SELECTED = "TEXT_COLOR_SELECTED"; public static final String SHOW_TOOLBAR = "SHOW_TOOLBAR"; public static final String NUMBER_OF_TABS = "NUMBER_OF_TABS"; private static final int UNDERLINE_HEIGHT_DEFAULT_DP = 0; private static final int INDICATOR_HEIGHT_DEFAULT_DP = 2; private static final int TAB_PADDING_DEFAULT_DP = 12; private static final int NUMBER_OF_TABS_DEFAULT = 3; private MainActivity mainActivity; // Indicator Height @InjectView(R.id.numberOfTabsSeekBar) SeekBar numberOfTabsSeekBar; @InjectView(R.id.numberOfTabsTextView) TextView numberOfTabsTextView; // Indicator Color @InjectView(R.id.indicatorColorRadioGroup) RadioGroup indicatorColorRadioGroup; @InjectView(R.id.indicatorColorButtonWhite) RadioButtonCenter indicatorColorButtonWhite; // Underline Color @InjectView(R.id.underlineColorRadioGroup) RadioGroup underlineColorRadioGroup; @InjectView(R.id.underlineColorButtonMantis) RadioButtonCenter underlineColorButtonMantis; // Indicator Height @InjectView(R.id.indicatorHeightSeekBar) SeekBar indicatorHeightSeekBar; @InjectView(R.id.indicatorHeightTextView) TextView indicatorHeightTextView; // Underline Height @InjectView(R.id.underlineHeightSeekBar) SeekBar underlineHeightSeekBar; @InjectView(R.id.underlineHeightTextView) TextView underlineHeightTextView; // Tab Padding Left Right @InjectView(R.id.tabPaddingSeekBar) SeekBar tabPaddingSeekBar; @InjectView(R.id.tabPaddingTextView) TextView tabPaddingTextView; // Padding Middle @InjectView(R.id.paddingMiddleCheckBox) CheckBox paddingMiddleCheckBox; // Should Expand @InjectView(R.id.sameWeightTabsCheckBox) CheckBox sameWeightTabsCheckBox; // Text All Caps @InjectView(R.id.textAllCapsCheckBox) CheckBox textAllCapsCheckBox; // Show Toolbar @InjectView(R.id.showToolbarCheckBox) CheckBox showToolbarCheckBox; // Tab Text Color @InjectView(R.id.tabTextColorRadioGroup) RadioGroup tabTextColorRadioGroup; @InjectView(R.id.tabTextColorButtonWhite) RadioButtonCenter tabTextColorButtonWhite; // Tab Text Selected Color @InjectView(R.id.tabTextSelectedColorRadioGroup) RadioGroup tabTextSelectedColorRadioGroup; @InjectView(R.id.tabTextSelectedColorButtonWhite) RadioButtonCenter tabTextSelectedColorButtonWhite; // Tab Background Color @InjectView(R.id.tabBackgroundColorRadioGroup) RadioGroup tabBackgroundColorRadioGroup; @InjectView(R.id.tabBackgroundColorButtonFireEngineRed) RadioButtonCenter tabBackgroundColorButtonFireEngineRed; // Toolbar Background Color @InjectView(R.id.toolbarColorRadioGroup) RadioGroup toolbarColorRadioGroup; @InjectView(R.id.toolbarColorButtonFireEngineRed) RadioButtonCenter toolbarColorButtonFireEngineRed; int underlineHeightDp; int indicatorHeightDp; int tabPaddingDp; int numberOfTabs; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_tabs_settings, container, false); ButterKnife.inject(this, rootView); setupAndReset(); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); mainActivity = (MainActivity) getActivity(); mainActivity.addFragment(this); } @Override public void onDetach() { mainActivity.removeFragment(this); super.onDetach(); } @Override public void setupAndReset() { /** SeekBars **/ underlineHeightDp = UNDERLINE_HEIGHT_DEFAULT_DP; underlineHeightTextView.setText(getString(R.string.underline_height) + ": " + underlineHeightDp + "dp"); underlineHeightSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { underlineHeightDp = progress; underlineHeightTextView.setText(getString(R.string.underline_height) + ": " + underlineHeightDp + "dp"); mainActivity.startTabsActivityIntent.putExtra(UNDERLINE_HEIGHT, underlineHeightDp); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); numberOfTabs = NUMBER_OF_TABS_DEFAULT; numberOfTabsTextView.setText(getString(R.string.number_of_tabs) + ": " + numberOfTabs); numberOfTabsSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { numberOfTabs = progress + 1; numberOfTabsTextView.setText(getString(R.string.number_of_tabs) + ": " + numberOfTabs); mainActivity.startTabsActivityIntent.putExtra(NUMBER_OF_TABS, numberOfTabs); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); indicatorHeightDp = INDICATOR_HEIGHT_DEFAULT_DP; indicatorHeightTextView.setText(getString(R.string.indicator_height) + ": " + indicatorHeightDp + "dp"); indicatorHeightSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { indicatorHeightDp = progress; indicatorHeightTextView.setText(getString(R.string.indicator_height) + ": " + indicatorHeightDp + "dp"); mainActivity.startTabsActivityIntent.putExtra(INDICATOR_HEIGHT, indicatorHeightDp); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); tabPaddingDp = TAB_PADDING_DEFAULT_DP; tabPaddingTextView.setText(getString(R.string.tab_padding) + ": " + tabPaddingDp + "dp"); tabPaddingSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { tabPaddingDp = progress; tabPaddingTextView.setText(getString(R.string.tab_padding) + ": " + tabPaddingDp + "dp"); mainActivity.startTabsActivityIntent.putExtra(TAB_PADDING, tabPaddingDp); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); underlineHeightSeekBar.setProgress(underlineHeightDp); numberOfTabsSeekBar.setProgress(numberOfTabs); indicatorHeightSeekBar.setProgress(indicatorHeightDp); tabPaddingSeekBar.setProgress(tabPaddingDp); /** RadioGroups **/ // Indicator Color indicatorColorRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { String key = INDICATOR_COLOR; switch (checkedId) { case R.id.indicatorColorButtonFireEngineRed: mainActivity.startTabsActivityIntent.putExtra(key, R.color.fire_engine_red); break; case R.id.indicatorColorButtonGorse: mainActivity.startTabsActivityIntent.putExtra(key, R.color.gorse); break; case R.id.indicatorColorButtonIrisBlue: mainActivity.startTabsActivityIntent.putExtra(key, R.color.iris_blue); break; case R.id.indicatorColorButtonSafetyOrange: mainActivity.startTabsActivityIntent.putExtra(key, R.color.safety_orange); break; case R.id.indicatorColorButtonWhite: mainActivity.startTabsActivityIntent.putExtra(key, R.color.white); break; case R.id.indicatorColorButtonBlack: mainActivity.startTabsActivityIntent.putExtra(key, R.color.black); break; case R.id.indicatorColorButtonMantis: default: mainActivity.startTabsActivityIntent.putExtra(key, R.color.mantis); break; } } }); // Underline Color underlineColorRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { String key = UNDERLINE_COLOR; switch (checkedId) { case R.id.underlineColorButtonFireEngineRed: mainActivity.startTabsActivityIntent.putExtra(key, R.color.fire_engine_red); break; case R.id.underlineColorButtonGorse: mainActivity.startTabsActivityIntent.putExtra(key, R.color.gorse); break; case R.id.underlineColorButtonIrisBlue: mainActivity.startTabsActivityIntent.putExtra(key, R.color.iris_blue); break; case R.id.underlineColorButtonSafetyOrange: mainActivity.startTabsActivityIntent.putExtra(key, R.color.safety_orange); break; case R.id.underlineColorButtonWhite: mainActivity.startTabsActivityIntent.putExtra(key, R.color.white); break; case R.id.underlineColorButtonBlack: mainActivity.startTabsActivityIntent.putExtra(key, R.color.black); break; case R.id.underlineColorButtonMantis: default: mainActivity.startTabsActivityIntent.putExtra(key, R.color.mantis); break; } } }); // Tab Background Color tabBackgroundColorRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { String key = TAB_BACKGROUND; switch (checkedId) { case R.id.tabBackgroundColorButtonFireEngineRed: mainActivity.startTabsActivityIntent.putExtra(key, R.color.fire_engine_red); break; case R.id.tabBackgroundColorButtonGorse: mainActivity.startTabsActivityIntent.putExtra(key, R.color.gorse); break; case R.id.tabBackgroundColorButtonIrisBlue: mainActivity.startTabsActivityIntent.putExtra(key, R.color.iris_blue); break; case R.id.tabBackgroundColorButtonSafetyOrange: mainActivity.startTabsActivityIntent.putExtra(key, R.color.safety_orange); break; case R.id.tabBackgroundColorButtonWhite: mainActivity.startTabsActivityIntent.putExtra(key, R.color.white); break; case R.id.tabBackgroundColorButtonBlack: mainActivity.startTabsActivityIntent.putExtra(key, R.color.black); break; case R.id.tabBackgroundColorButtonMantis: default: mainActivity.startTabsActivityIntent.putExtra(key, R.color.mantis); break; } } }); // Toolbar Background Color toolbarColorRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { String key = TOOLBAR_BACKGROUND; switch (checkedId) { case R.id.toolbarColorButtonFireEngineRed: mainActivity.startTabsActivityIntent.putExtra(key, R.color.fire_engine_red); break; case R.id.toolbarColorButtonGorse: mainActivity.startTabsActivityIntent.putExtra(key, R.color.gorse); break; case R.id.toolbarColorButtonIrisBlue: mainActivity.startTabsActivityIntent.putExtra(key, R.color.iris_blue); break; case R.id.toolbarColorButtonSafetyOrange: mainActivity.startTabsActivityIntent.putExtra(key, R.color.safety_orange); break; case R.id.toolbarColorButtonWhite: mainActivity.startTabsActivityIntent.putExtra(key, R.color.white); break; case R.id.toolbarColorButtonBlack: mainActivity.startTabsActivityIntent.putExtra(key, R.color.black); break; case R.id.toolbarColorButtonMantis: default: mainActivity.startTabsActivityIntent.putExtra(key, R.color.mantis); break; } } }); // Text Color Unselected tabTextColorRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { String key = TEXT_COLOR_UNSELECTED; switch (checkedId) { case R.id.tabTextColorButtonFireEngineRed: mainActivity.startTabsActivityIntent.putExtra(key, R.color.fire_engine_red); break; case R.id.tabTextColorButtonGorse: mainActivity.startTabsActivityIntent.putExtra(key, R.color.gorse); break; case R.id.tabTextColorButtonIrisBlue: mainActivity.startTabsActivityIntent.putExtra(key, R.color.iris_blue); break; case R.id.tabTextColorButtonSafetyOrange: mainActivity.startTabsActivityIntent.putExtra(key, R.color.safety_orange); break; case R.id.tabTextColorButtonWhite: mainActivity.startTabsActivityIntent.putExtra(key, R.color.white); break; case R.id.tabTextColorButtonBlack: mainActivity.startTabsActivityIntent.putExtra(key, R.color.black); break; case R.id.tabTextColorButtonMantis: default: mainActivity.startTabsActivityIntent.putExtra(key, R.color.mantis); break; } } }); // Text Color Selected tabTextSelectedColorRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { String key = TEXT_COLOR_SELECTED; switch (checkedId) { case R.id.tabTextSelectedColorButtonFireEngineRed: mainActivity.startTabsActivityIntent.putExtra(key, R.color.fire_engine_red); break; case R.id.tabTextSelectedColorButtonGorse: mainActivity.startTabsActivityIntent.putExtra(key, R.color.gorse); break; case R.id.tabTextSelectedColorButtonIrisBlue: mainActivity.startTabsActivityIntent.putExtra(key, R.color.iris_blue); break; case R.id.tabTextSelectedColorButtonSafetyOrange: mainActivity.startTabsActivityIntent.putExtra(key, R.color.safety_orange); break; case R.id.tabTextSelectedColorButtonWhite: mainActivity.startTabsActivityIntent.putExtra(key, R.color.white); break; case R.id.tabTextSelectedColorButtonBlack: mainActivity.startTabsActivityIntent.putExtra(key, R.color.black); break; case R.id.tabTextSelectedColorButtonMantis: default: mainActivity.startTabsActivityIntent.putExtra(key, R.color.mantis); break; } } }); indicatorColorButtonWhite.setChecked(true); underlineColorButtonMantis.setChecked(true); tabTextColorButtonWhite.setChecked(true); tabTextSelectedColorButtonWhite.setChecked(true); tabBackgroundColorButtonFireEngineRed.setChecked(true); toolbarColorButtonFireEngineRed.setChecked(true); /** CheckBoxes **/ // Text Style Unselected sameWeightTabsCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mainActivity.startTabsActivityIntent.putExtra(SAME_WEIGHT_TABS, isChecked); } }); // Text Style Unselected paddingMiddleCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mainActivity.startTabsActivityIntent.putExtra(PADDING_MIDDLE, isChecked); } }); // Text Style Unselected textAllCapsCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mainActivity.startTabsActivityIntent.putExtra(TEXT_ALL_CAPS, isChecked); } }); // Text Style Unselected showToolbarCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mainActivity.startTabsActivityIntent.putExtra(SHOW_TOOLBAR, isChecked); } }); sameWeightTabsCheckBox.setChecked(true); paddingMiddleCheckBox.setChecked(false); textAllCapsCheckBox.setChecked(true); showToolbarCheckBox.setChecked(true); } @OnClick(R.id.tabPaddingInfoButton) public void tabPaddingInfoButtonClicked() { new AlertDialog.Builder(getActivity()).setTitle(R.string.tab_padding).setMessage(R.string.tab_padding_details).create().show(); } @OnClick(R.id.tabBackgroundColorInfoButton) public void tabBackgroundColorInfoButtonClicked() { new AlertDialog.Builder(getActivity()).setTitle(R.string.tab_background_color) .setMessage(R.string.tab_background_color_details) .create() .show(); } @OnClick(R.id.tabTextColorInfoButton) public void tabTextColorInfoButtonClicked() { new AlertDialog.Builder(getActivity()).setTitle(R.string.tab_text_color).setMessage(R.string.tab_text_color_details).create().show(); } @OnClick(R.id.tabTextSelectedColorInfoButton) public void tabTextSelectedColorInfoButtonClicked() { new AlertDialog.Builder(getActivity()).setTitle(R.string.tab_text_selected_color) .setMessage(R.string.tab_text_selected_color_details) .create() .show(); } @OnClick(R.id.toolbarColorInfoButton) public void toolbarColorInfoButtonClicked() { new AlertDialog.Builder(getActivity()).setTitle(R.string.toolbar_color).setMessage(R.string.toolbar_color_details).create().show(); } @OnClick(R.id.textAllCapsInfoButton) public void textAllCapsInfoButtonClicked() { new AlertDialog.Builder(getActivity()).setTitle(R.string.text_all_caps).setMessage(R.string.text_all_caps_details).create().show(); } @OnClick(R.id.underlineColorInfoButton) public void underlineColorInfoButtonClicked() { new AlertDialog.Builder(getActivity()).setTitle(R.string.underline_color).setMessage(R.string.underline_color_details).create().show(); } @OnClick(R.id.underlineHeightInfoButton) public void underlineHeightInfoButtonClicked() { new AlertDialog.Builder(getActivity()).setTitle(R.string.underline_height).setMessage(R.string.underline_height_details).create().show(); } @OnClick(R.id.indicatorColorInfoButton) public void indicatorColorInfoButtonClicked() { new AlertDialog.Builder(getActivity()).setTitle(R.string.indicator_color).setMessage(R.string.indicator_color_details).create().show(); } @OnClick(R.id.indicatorHeightInfoButton) public void indicatorHeightInfoButtonClicked() { new AlertDialog.Builder(getActivity()).setTitle(R.string.indicator_height).setMessage(R.string.indicator_height_details).create().show(); } @OnClick(R.id.paddingMiddleInfoButton) public void paddingMiddleInfoButtonClicked() { new AlertDialog.Builder(getActivity()).setTitle(R.string.padding_middle).setMessage(R.string.padding_middle_details).create().show(); } @OnClick(R.id.sameWeighTabsInfoButton) public void sameWeighTabsInfoButtonClicked() { new AlertDialog.Builder(getActivity()).setTitle(R.string.same_weight_tabs).setMessage(R.string.same_weight_tabs_details).create().show(); } @OnClick(R.id.showToolbarInfoButton) public void showToolbarInfoButtonClicked() { new AlertDialog.Builder(getActivity()).setTitle(R.string.show_toolbar).setMessage(R.string.show_toolbar_details).create().show(); } @OnClick(R.id.numberOfTabsInfoButton) public void numberOfTabsInfoButtonClicked() { new AlertDialog.Builder(getActivity()).setTitle(R.string.number_of_tabs).setMessage(R.string.number_of_tabs_details).create().show(); } }
/* * $Id: ServletRedirectResult.java 1459660 2013-03-22 08:05:36Z lukaszlenart $ * * 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.struts2.dispatcher; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.config.entities.ResultConfig; import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.util.logging.Logger; import com.opensymphony.xwork2.util.logging.LoggerFactory; import com.opensymphony.xwork2.util.reflection.ReflectionException; import com.opensymphony.xwork2.util.reflection.ReflectionExceptionHandler; import org.apache.struts2.ServletActionContext; import org.apache.struts2.dispatcher.mapper.ActionMapper; import org.apache.struts2.dispatcher.mapper.ActionMapping; import org.apache.struts2.views.util.UrlHelper; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.*; import static javax.servlet.http.HttpServletResponse.SC_FOUND; /** * <!-- START SNIPPET: description --> * * Calls the {@link HttpServletResponse#sendRedirect(String) sendRedirect} * method to the location specified. The response is told to redirect the * browser to the specified location (a new request from the client). The * consequence of doing this means that the action (action instance, action * errors, field errors, etc) that was just executed is lost and no longer * available. This is because actions are built on a single-thread model. The * only way to pass data is through the session or with web parameters * (url?name=value) which can be OGNL expressions. * * <!-- END SNIPPET: description --> * <p/> * <b>This result type takes the following parameters:</b> * * <!-- START SNIPPET: params --> * * <ul> * * <li><b>location (default)</b> - the location to go to after execution.</li> * * <li><b>parse</b> - true by default. If set to false, the location param will * not be parsed for Ognl expressions.</li> * * <li><b>anchor</b> - Optional. Also known as "fragment" or colloquially as * "hash". You can specify an anchor for a result.</li> * </ul> * * <p> * This result follows the same rules from {@link StrutsResultSupport}. * </p> * * <!-- END SNIPPET: params --> * * <b>Example:</b> * * <pre> * <!-- START SNIPPET: example --> * &lt;!-- * The redirect URL generated will be: * /foo.jsp#FRAGMENT * --&gt; * &lt;result name="success" type="redirect"&gt; * &lt;param name="location"&gt;foo.jsp&lt;/param&gt; * &lt;param name="parse"&gt;false&lt;/param&gt; * &lt;param name="anchor"&gt;FRAGMENT&lt;/param&gt; * &lt;/result&gt; * <!-- END SNIPPET: example --> * </pre> * */ public class ServletRedirectResult extends StrutsResultSupport implements ReflectionExceptionHandler { private static final long serialVersionUID = 6316947346435301270L; private static final Logger LOG = LoggerFactory.getLogger(ServletRedirectResult.class); protected boolean prependServletContext = true; protected ActionMapper actionMapper; protected int statusCode = SC_FOUND; protected boolean suppressEmptyParameters = false; protected Map<String, Object> requestParameters = new LinkedHashMap<String, Object>(); protected String anchor; private UrlHelper urlHelper; public ServletRedirectResult() { super(); } public ServletRedirectResult(String location) { this(location, null); } public ServletRedirectResult(String location, String anchor) { super(location); this.anchor = anchor; } @Inject public void setActionMapper(ActionMapper mapper) { this.actionMapper = mapper; } @Inject public void setUrlHelper(UrlHelper urlHelper) { this.urlHelper = urlHelper; } public void setStatusCode(int code) { this.statusCode = code; } /** * Set the optional anchor value. * * @param anchor */ public void setAnchor(String anchor) { this.anchor = anchor; } /** * Sets whether or not to prepend the servlet context path to the redirected * URL. * * @param prependServletContext <tt>true</tt> to prepend the location with the servlet context path, <tt>false</tt> otherwise. */ public void setPrependServletContext(boolean prependServletContext) { this.prependServletContext = prependServletContext; } public void execute(ActionInvocation invocation) throws Exception { if (anchor != null) { anchor = conditionalParse(anchor, invocation); } super.execute(invocation); } /** * Redirects to the location specified by calling * {@link HttpServletResponse#sendRedirect(String)}. * * @param finalLocation the location to redirect to. * @param invocation an encapsulation of the action execution state. * @throws Exception if an error occurs when redirecting. */ protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception { ActionContext ctx = invocation.getInvocationContext(); HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST); HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE); if (isPathUrl(finalLocation)) { if (!finalLocation.startsWith("/")) { ActionMapping mapping = actionMapper.getMapping(request, Dispatcher.getInstance().getConfigurationManager()); String namespace = null; if (mapping != null) { namespace = mapping.getNamespace(); } if ((namespace != null) && (namespace.length() > 0) && (!"/".equals(namespace))) { finalLocation = namespace + "/" + finalLocation; } else { finalLocation = "/" + finalLocation; } } // if the URL's are relative to the servlet context, append the servlet context path if (prependServletContext && (request.getContextPath() != null) && (request.getContextPath().length() > 0)) { finalLocation = request.getContextPath() + finalLocation; } ResultConfig resultConfig = invocation.getProxy().getConfig().getResults().get(invocation.getResultCode()); if (resultConfig != null) { Map<String, String> resultConfigParams = resultConfig.getParams(); List<String> prohibitedResultParams = getProhibitedResultParams(); for (Map.Entry<String, String> e : resultConfigParams.entrySet()) { if (!prohibitedResultParams.contains(e.getKey())) { String potentialValue = e.getValue() == null ? "" : conditionalParse(e.getValue(), invocation); if (!suppressEmptyParameters || ((potentialValue != null) && (potentialValue.length() > 0))) { requestParameters.put(e.getKey(), potentialValue); } } } } StringBuilder tmpLocation = new StringBuilder(finalLocation); urlHelper.buildParametersString(requestParameters, tmpLocation, "&"); // add the anchor if (anchor != null) { tmpLocation.append('#').append(anchor); } finalLocation = response.encodeRedirectURL(tmpLocation.toString()); } if (LOG.isDebugEnabled()) { LOG.debug("Redirecting to finalLocation " + finalLocation); } sendRedirect(response, finalLocation); } protected List<String> getProhibitedResultParams() { return Arrays.asList( DEFAULT_PARAM, "namespace", "method", "encode", "parse", "location", "prependServletContext", "suppressEmptyParameters", "anchor", "statusCode" ); } /** * Sends the redirection. Can be overridden to customize how the redirect is * handled (i.e. to use a different status code) * * @param response The response * @param finalLocation The location URI * @throws IOException */ protected void sendRedirect(HttpServletResponse response, String finalLocation) throws IOException { if (SC_FOUND == statusCode) { response.sendRedirect(finalLocation); } else { response.setStatus(statusCode); response.setHeader("Location", finalLocation); response.getWriter().write(finalLocation); response.getWriter().close(); } } private boolean isPathUrl(String url) { // filter out "http:", "https:", "mailto:", "file:", "ftp:" return !url.startsWith("http:") && !url.startsWith("https:") && !url.startsWith("mailto:") && !url.startsWith("file:") && !url.startsWith("ftp:"); } /** * Sets the suppressEmptyParameters option * * @param suppressEmptyParameters The new value for this option */ public void setSuppressEmptyParameters(boolean suppressEmptyParameters) { this.suppressEmptyParameters = suppressEmptyParameters; } /** * Adds a request parameter to be added to the redirect url * * @param key The parameter name * @param value The parameter value */ public ServletRedirectResult addParameter(String key, Object value) { requestParameters.put(key, String.valueOf(value)); return this; } public void handle(ReflectionException ex) { // Only log as debug as they are probably parameters to be appended to the url if (LOG.isDebugEnabled()) { LOG.debug(ex.getMessage(), ex); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.rabbitmq.reply; import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Connection; import org.apache.camel.AsyncCallback; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.ExchangeTimedOutException; import org.apache.camel.TimeoutMap; import org.apache.camel.component.rabbitmq.RabbitMQConstants; import org.apache.camel.component.rabbitmq.RabbitMQEndpoint; import org.apache.camel.component.rabbitmq.RabbitMQMessageConverter; import org.apache.camel.support.ExchangeHelper; import org.apache.camel.support.service.ServiceHelper; import org.apache.camel.support.service.ServiceSupport; import org.apache.camel.support.task.ForegroundTask; import org.apache.camel.support.task.Tasks; import org.apache.camel.support.task.budget.Budgets; import org.apache.camel.util.ObjectHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class ReplyManagerSupport extends ServiceSupport implements ReplyManager { private static final int CLOSE_TIMEOUT = 30 * 1000; private static final Logger LOG = LoggerFactory.getLogger(ReplyManagerSupport.class); protected final CamelContext camelContext; protected final CountDownLatch replyToLatch = new CountDownLatch(1); protected final long replyToTimeout = 1000; protected ScheduledExecutorService executorService; protected RabbitMQEndpoint endpoint; protected String replyTo; protected Connection listenerContainer; protected TimeoutMap<String, ReplyHandler> correlation; private final RabbitMQMessageConverter messageConverter = new RabbitMQMessageConverter(); public ReplyManagerSupport(CamelContext camelContext) { this.camelContext = camelContext; } @Override public void setScheduledExecutorService(ScheduledExecutorService executorService) { this.executorService = executorService; } @Override public void setEndpoint(RabbitMQEndpoint endpoint) { this.endpoint = endpoint; } @Override public void setReplyTo(String replyTo) { LOG.debug("ReplyTo destination: {}", replyTo); this.replyTo = replyTo; // trigger latch as the reply to has been resolved and set replyToLatch.countDown(); } @Override public String getReplyTo() { if (replyTo != null) { return replyTo; } try { // the reply to destination has to be resolved using a // DestinationResolver using // the MessageListenerContainer which occurs asynchronously so we // have to wait // for that to happen before we can retrieve the reply to // destination to be used LOG.trace("Waiting for replyTo to be set"); boolean done = replyToLatch.await(replyToTimeout, TimeUnit.MILLISECONDS); if (!done) { LOG.warn("ReplyTo destination was not set and timeout occurred"); } else { LOG.trace("Waiting for replyTo to be set done"); } } catch (InterruptedException e) { // ignore } return replyTo; } @Override public String registerReply( ReplyManager replyManager, Exchange exchange, AsyncCallback callback, String originalCorrelationId, String correlationId, long requestTimeout) { // add to correlation map QueueReplyHandler handler = new QueueReplyHandler(replyManager, exchange, callback, originalCorrelationId, correlationId, requestTimeout); // Just make sure we don't override the old value of the correlationId ReplyHandler result = correlation.putIfAbsent(correlationId, handler, requestTimeout); if (result != null) { String logMessage = String.format("The correlationId [%s] is not unique.", correlationId); throw new IllegalArgumentException(logMessage); } return correlationId; } protected abstract ReplyHandler createReplyHandler( ReplyManager replyManager, Exchange exchange, AsyncCallback callback, String originalCorrelationId, String correlationId, long requestTimeout); @Override public void cancelCorrelationId(String correlationId) { ReplyHandler handler = correlation.get(correlationId); if (handler != null) { LOG.warn("Cancelling correlationID: {}", correlationId); correlation.remove(correlationId); } } public void onMessage(AMQP.BasicProperties properties, byte[] message) { String correlationID = properties.getCorrelationId(); if (correlationID == null) { LOG.warn("Ignoring message with no correlationID: {}", message); return; } LOG.debug("Received reply message with correlationID [{}] -> {}", correlationID, message); // handle the reply message handleReplyMessage(correlationID, properties, message); } @Override public void processReply(ReplyHolder holder) { if (holder != null && isRunAllowed()) { try { Exchange exchange = holder.getExchange(); boolean timeout = holder.isTimeout(); if (timeout) { // timeout occurred do a WARN log so its easier to spot in // the logs if (LOG.isWarnEnabled()) { LOG.warn( "Timeout occurred after {} millis waiting for reply message with correlationID [{}] on destination {}." + " Setting ExchangeTimedOutException on {} and continue routing.", holder.getRequestTimeout(), holder.getCorrelationId(), replyTo, ExchangeHelper.logIds(exchange)); } // no response, so lets set a timed out exception String msg = "reply message with correlationID: " + holder.getCorrelationId() + " not received on destination: " + replyTo; exchange.setException(new ExchangeTimedOutException(exchange, holder.getRequestTimeout(), msg)); } else { messageConverter.populateRabbitExchange(exchange, null, holder.getProperties(), holder.getMessage(), true, endpoint.isAllowMessageBodySerialization()); // restore correlation id in case the remote server messed // with it if (holder.getOriginalCorrelationId() != null) { exchange.getMessage().setHeader(RabbitMQConstants.CORRELATIONID, holder.getOriginalCorrelationId()); } } } finally { // notify callback AsyncCallback callback = holder.getCallback(); callback.done(false); } } } protected abstract void handleReplyMessage(String correlationID, AMQP.BasicProperties properties, byte[] message); protected abstract Connection createListenerContainer() throws Exception; /** * <b>IMPORTANT:</b> This logic is only being used due to high performance in-memory only testing using InOut over * JMS. Its unlikely to happen in a real life situation with communication to a remote broker, which always will be * slower to send back reply, before Camel had a chance to update it's internal correlation map. */ protected ReplyHandler waitForProvisionCorrelationToBeUpdated(String correlationID, byte[] message) { // race condition, when using messageID as correlationID then we store a // provisional correlation id // at first, which gets updated with the JMSMessageID after the message // has been sent. And in the unlikely // event that the reply comes back really really fast, and the // correlation map hasn't yet been updated // from the provisional id to the JMSMessageID. If so we have to wait a // bit and lookup again. if (LOG.isWarnEnabled()) { LOG.warn("Early reply received with correlationID [{}] -> {}", correlationID, message); } ForegroundTask task = Tasks.foregroundTask().withBudget(Budgets.iterationBudget() .withMaxIterations(50) .withInterval(Duration.ofMillis(100)) .build()) .build(); return task.run(() -> correlation.get(correlationID), answer -> answer != null).orElse(null); } @Override protected void doStart() throws Exception { ObjectHelper.notNull(executorService, "executorService", this); ObjectHelper.notNull(endpoint, "endpoint", this); messageConverter.setAllowNullHeaders(endpoint.isAllowNullHeaders()); // timeout map to use for purging messages which have timed out, while // waiting for an expected reply // when doing request/reply over JMS LOG.debug("Using timeout checker interval with {} millis", endpoint.getRequestTimeoutCheckerInterval()); correlation = new CorrelationTimeoutMap(executorService, endpoint.getRequestTimeoutCheckerInterval()); ServiceHelper.startService(correlation); // create listener and start it listenerContainer = createListenerContainer(); LOG.debug("Using executor {}", executorService); } @Override protected void doStop() throws Exception { ServiceHelper.stopService(correlation); if (listenerContainer != null) { LOG.debug("Closing connection: {} with timeout: {} ms.", listenerContainer, CLOSE_TIMEOUT); listenerContainer.close(CLOSE_TIMEOUT); listenerContainer = null; } // must also stop executor service if (executorService != null) { camelContext.getExecutorServiceManager().shutdownGraceful(executorService); executorService = null; } } }
/* * Copyright (C) 2010 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.securepreferences.util; import android.util.Base64OutputStream; import java.io.UnsupportedEncodingException; /** * Utilities for encoding and decoding the Base64 representation of * binary data. See RFCs <a * href="http://www.ietf.org/rfc/rfc2045.txt">2045</a> and <a * href="http://www.ietf.org/rfc/rfc3548.txt">3548</a>. */ public class Base64 { /** * Default values for encoder/decoder flags. */ public static final int DEFAULT = 0; /** * Encoder flag bit to omit the padding '=' characters at the end * of the output (if any). */ public static final int NO_PADDING = 1; /** * Encoder flag bit to omit all line terminators (i.e., the output * will be on one long line). */ public static final int NO_WRAP = 2; /** * Encoder flag bit to indicate lines should be terminated with a * CRLF pair instead of just an LF. Has no effect if {@code * NO_WRAP} is specified as well. */ public static final int CRLF = 4; /** * Encoder/decoder flag bit to indicate using the "URL and * filename safe" variant of Base64 (see RFC 3548 section 4) where * {@code -} and {@code _} are used in place of {@code +} and * {@code /}. */ public static final int URL_SAFE = 8; /** * Flag to pass to {@link Base64OutputStream} to indicate that it * should not close the output stream it is wrapping when it * itself is closed. */ public static final int NO_CLOSE = 16; // -------------------------------------------------------- // shared code // -------------------------------------------------------- /* package */ static abstract class Coder { public byte[] output; public int op; /** * Encode/decode another block of input data. this.output is * provided by the caller, and must be big enough to hold all * the coded data. On exit, this.opwill be set to the length * of the coded data. * * @param finish true if this is the final call to process for * this object. Will finalize the coder state and * include any final bytes in the output. * * @return true if the input so far is good; false if some * error has been detected in the input stream.. */ public abstract boolean process(byte[] input, int offset, int len, boolean finish); /** * @return the maximum number of bytes a call to process() * could produce for the given number of input bytes. This may * be an overestimate. */ public abstract int maxOutputSize(int len); } // -------------------------------------------------------- // decoding // -------------------------------------------------------- /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * <p>The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @param str the input String to decode, which is converted to * bytes using the default charset * @param flags controls certain features of the decoded output. * Pass {@code DEFAULT} to decode standard Base64. * * @throws IllegalArgumentException if the input contains * incorrect padding */ public static byte[] decode(String str, int flags) { return decode(str.getBytes(), flags); } /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * <p>The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @param input the input array to decode * @param flags controls certain features of the decoded output. * Pass {@code DEFAULT} to decode standard Base64. * * @throws IllegalArgumentException if the input contains * incorrect padding */ public static byte[] decode(byte[] input, int flags) { return decode(input, 0, input.length, flags); } /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * <p>The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @param input the data to decode * @param offset the position within the input array at which to start * @param len the number of bytes of input to decode * @param flags controls certain features of the decoded output. * Pass {@code DEFAULT} to decode standard Base64. * * @throws IllegalArgumentException if the input contains * incorrect padding */ public static byte[] decode(byte[] input, int offset, int len, int flags) { // Allocate space for the most data the input could represent. // (It could contain less if it contains whitespace, etc.) Decoder decoder = new Decoder(flags, new byte[len*3/4]); if (!decoder.process(input, offset, len, true)) { throw new IllegalArgumentException("bad base-64"); } // Maybe we got lucky and allocated exactly enough output space. if (decoder.op == decoder.output.length) { return decoder.output; } // Need to shorten the array, so allocate a new one of the // right size and copy. byte[] temp = new byte[decoder.op]; System.arraycopy(decoder.output, 0, temp, 0, decoder.op); return temp; } /* package */ static class Decoder extends Coder { /** * Lookup table for turning bytes into their position in the * Base64 alphabet. */ private static final int DECODE[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; /** * Decode lookup table for the "web safe" variant (RFC 3548 * sec. 4) where - and _ replace + and /. */ private static final int DECODE_WEBSAFE[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; /** Non-data values in the DECODE arrays. */ private static final int SKIP = -1; private static final int EQUALS = -2; /** * States 0-3 are reading through the next input tuple. * State 4 is having read one '=' and expecting exactly * one more. * State 5 is expecting no more data or padding characters * in the input. * State 6 is the error state; an error has been detected * in the input and no future input can "fix" it. */ private int state; // state number (0 to 6) private int value; final private int[] alphabet; public Decoder(int flags, byte[] output) { this.output = output; alphabet = ((flags & URL_SAFE) == 0) ? DECODE : DECODE_WEBSAFE; state = 0; value = 0; } /** * @return an overestimate for the number of bytes {@code * len} bytes could decode to. */ public int maxOutputSize(int len) { return len * 3/4 + 10; } /** * Decode another block of input data. * * @return true if the state machine is still healthy. false if * bad base-64 data has been detected in the input stream. */ public boolean process(byte[] input, int offset, int len, boolean finish) { if (this.state == 6) return false; int p = offset; len += offset; // Using local variables makes the decoder about 12% // faster than if we manipulate the member variables in // the loop. (Even alphabet makes a measurable // difference, which is somewhat surprising to me since // the member variable is final.) int state = this.state; int value = this.value; int op = 0; final byte[] output = this.output; final int[] alphabet = this.alphabet; while (p < len) { // Try the fast path: we're starting a new tuple and the // next four bytes of the input stream are all data // bytes. This corresponds to going through states // 0-1-2-3-0. We expect to use this method for most of // the data. // // If any of the next four bytes of input are non-data // (whitespace, etc.), value will end up negative. (All // the non-data values in decode are small negative // numbers, so shifting any of them up and or'ing them // together will result in a value with its top bit set.) // // You can remove this whole block and the output should // be the same, just slower. if (state == 0) { while (p+4 <= len && (value = ((alphabet[input[p] & 0xff] << 18) | (alphabet[input[p+1] & 0xff] << 12) | (alphabet[input[p+2] & 0xff] << 6) | (alphabet[input[p+3] & 0xff]))) >= 0) { output[op+2] = (byte) value; output[op+1] = (byte) (value >> 8); output[op] = (byte) (value >> 16); op += 3; p += 4; } if (p >= len) break; } // The fast path isn't available -- either we've read a // partial tuple, or the next four input bytes aren't all // data, or whatever. Fall back to the slower state // machine implementation. int d = alphabet[input[p++] & 0xff]; switch (state) { case 0: if (d >= 0) { value = d; ++state; } else if (d != SKIP) { this.state = 6; return false; } break; case 1: if (d >= 0) { value = (value << 6) | d; ++state; } else if (d != SKIP) { this.state = 6; return false; } break; case 2: if (d >= 0) { value = (value << 6) | d; ++state; } else if (d == EQUALS) { // Emit the last (partial) output tuple; // expect exactly one more padding character. output[op++] = (byte) (value >> 4); state = 4; } else if (d != SKIP) { this.state = 6; return false; } break; case 3: if (d >= 0) { // Emit the output triple and return to state 0. value = (value << 6) | d; output[op+2] = (byte) value; output[op+1] = (byte) (value >> 8); output[op] = (byte) (value >> 16); op += 3; state = 0; } else if (d == EQUALS) { // Emit the last (partial) output tuple; // expect no further data or padding characters. output[op+1] = (byte) (value >> 2); output[op] = (byte) (value >> 10); op += 2; state = 5; } else if (d != SKIP) { this.state = 6; return false; } break; case 4: if (d == EQUALS) { ++state; } else if (d != SKIP) { this.state = 6; return false; } break; case 5: if (d != SKIP) { this.state = 6; return false; } break; } } if (!finish) { // We're out of input, but a future call could provide // more. this.state = state; this.value = value; this.op = op; return true; } // Done reading input. Now figure out where we are left in // the state machine and finish up. switch (state) { case 0: // Output length is a multiple of three. Fine. break; case 1: // Read one extra input byte, which isn't enough to // make another output byte. Illegal. this.state = 6; return false; case 2: // Read two extra input bytes, enough to emit 1 more // output byte. Fine. output[op++] = (byte) (value >> 4); break; case 3: // Read three extra input bytes, enough to emit 2 more // output bytes. Fine. output[op++] = (byte) (value >> 10); output[op++] = (byte) (value >> 2); break; case 4: // Read one padding '=' when we expected 2. Illegal. this.state = 6; return false; case 5: // Read all the padding '='s we expected and no more. // Fine. break; } this.state = state; this.op = op; return true; } } // -------------------------------------------------------- // encoding // -------------------------------------------------------- /** * Base64-encode the given data and return a newly allocated * String with the result. * * @param input the data to encode * @param flags controls certain features of the encoded output. * Passing {@code DEFAULT} results in output that * adheres to RFC 2045. */ public static String encodeToString(byte[] input, int flags) { try { return new String(encode(input, flags), "US-ASCII"); } catch (UnsupportedEncodingException e) { // US-ASCII is guaranteed to be available. throw new AssertionError(e); } } /** * Base64-encode the given data and return a newly allocated * String with the result. * * @param input the data to encode * @param offset the position within the input array at which to * start * @param len the number of bytes of input to encode * @param flags controls certain features of the encoded output. * Passing {@code DEFAULT} results in output that * adheres to RFC 2045. */ public static String encodeToString(byte[] input, int offset, int len, int flags) { try { return new String(encode(input, offset, len, flags), "US-ASCII"); } catch (UnsupportedEncodingException e) { // US-ASCII is guaranteed to be available. throw new AssertionError(e); } } /** * Base64-encode the given data and return a newly allocated * byte[] with the result. * * @param input the data to encode * @param flags controls certain features of the encoded output. * Passing {@code DEFAULT} results in output that * adheres to RFC 2045. */ public static byte[] encode(byte[] input, int flags) { return encode(input, 0, input.length, flags); } /** * Base64-encode the given data and return a newly allocated * byte[] with the result. * * @param input the data to encode * @param offset the position within the input array at which to * start * @param len the number of bytes of input to encode * @param flags controls certain features of the encoded output. * Passing {@code DEFAULT} results in output that * adheres to RFC 2045. */ public static byte[] encode(byte[] input, int offset, int len, int flags) { Encoder encoder = new Encoder(flags, null); // Compute the exact length of the array we will produce. int output_len = len / 3 * 4; // Account for the tail of the data and the padding bytes, if any. if (encoder.do_padding) { if (len % 3 > 0) { output_len += 4; } } else { switch (len % 3) { case 0: break; case 1: output_len += 2; break; case 2: output_len += 3; break; } } // Account for the newlines, if any. if (encoder.do_newline && len > 0) { output_len += (((len-1) / (3 * Encoder.LINE_GROUPS)) + 1) * (encoder.do_cr ? 2 : 1); } encoder.output = new byte[output_len]; encoder.process(input, offset, len, true); assert encoder.op == output_len; return encoder.output; } /* package */ static class Encoder extends Coder { /** * Emit a new line every this many output tuples. Corresponds to * a 76-character line length (the maximum allowable according to * <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>). */ public static final int LINE_GROUPS = 19; /** * Lookup table for turning Base64 alphabet positions (6 bits) * into output bytes. */ private static final byte ENCODE[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', }; /** * Lookup table for turning Base64 alphabet positions (6 bits) * into output bytes. */ private static final byte ENCODE_WEBSAFE[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_', }; final private byte[] tail; /* package */ int tailLen; private int count; final public boolean do_padding; final public boolean do_newline; final public boolean do_cr; final private byte[] alphabet; public Encoder(int flags, byte[] output) { this.output = output; do_padding = (flags & NO_PADDING) == 0; do_newline = (flags & NO_WRAP) == 0; do_cr = (flags & CRLF) != 0; alphabet = ((flags & URL_SAFE) == 0) ? ENCODE : ENCODE_WEBSAFE; tail = new byte[2]; tailLen = 0; count = do_newline ? LINE_GROUPS : -1; } /** * @return an overestimate for the number of bytes {@code * len} bytes could encode to. */ public int maxOutputSize(int len) { return len * 8/5 + 10; } public boolean process(byte[] input, int offset, int len, boolean finish) { // Using local variables makes the encoder about 9% faster. final byte[] alphabet = this.alphabet; final byte[] output = this.output; int op = 0; int count = this.count; int p = offset; len += offset; int v = -1; // First we need to concatenate the tail of the previous call // with any input bytes available now and see if we can empty // the tail. switch (tailLen) { case 0: // There was no tail. break; case 1: if (p+2 <= len) { // A 1-byte tail with at least 2 bytes of // input available now. v = ((tail[0] & 0xff) << 16) | ((input[p++] & 0xff) << 8) | (input[p++] & 0xff); tailLen = 0; }; break; case 2: if (p+1 <= len) { // A 2-byte tail with at least 1 byte of input. v = ((tail[0] & 0xff) << 16) | ((tail[1] & 0xff) << 8) | (input[p++] & 0xff); tailLen = 0; } break; } if (v != -1) { output[op++] = alphabet[(v >> 18) & 0x3f]; output[op++] = alphabet[(v >> 12) & 0x3f]; output[op++] = alphabet[(v >> 6) & 0x3f]; output[op++] = alphabet[v & 0x3f]; if (--count == 0) { if (do_cr) output[op++] = '\r'; output[op++] = '\n'; count = LINE_GROUPS; } } // At this point either there is no tail, or there are fewer // than 3 bytes of input available. // The main loop, turning 3 input bytes into 4 output bytes on // each iteration. while (p+3 <= len) { v = ((input[p] & 0xff) << 16) | ((input[p+1] & 0xff) << 8) | (input[p+2] & 0xff); output[op] = alphabet[(v >> 18) & 0x3f]; output[op+1] = alphabet[(v >> 12) & 0x3f]; output[op+2] = alphabet[(v >> 6) & 0x3f]; output[op+3] = alphabet[v & 0x3f]; p += 3; op += 4; if (--count == 0) { if (do_cr) output[op++] = '\r'; output[op++] = '\n'; count = LINE_GROUPS; } } if (finish) { // Finish up the tail of the input. Note that we need to // consume any bytes in tail before any bytes // remaining in input; there should be at most two bytes // total. if (p-tailLen == len-1) { int t = 0; v = ((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 4; tailLen -= t; output[op++] = alphabet[(v >> 6) & 0x3f]; output[op++] = alphabet[v & 0x3f]; if (do_padding) { output[op++] = '='; output[op++] = '='; } if (do_newline) { if (do_cr) output[op++] = '\r'; output[op++] = '\n'; } } else if (p-tailLen == len-2) { int t = 0; v = (((tailLen > 1 ? tail[t++] : input[p++]) & 0xff) << 10) | (((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 2); tailLen -= t; output[op++] = alphabet[(v >> 12) & 0x3f]; output[op++] = alphabet[(v >> 6) & 0x3f]; output[op++] = alphabet[v & 0x3f]; if (do_padding) { output[op++] = '='; } if (do_newline) { if (do_cr) output[op++] = '\r'; output[op++] = '\n'; } } else if (do_newline && op > 0 && count != LINE_GROUPS) { if (do_cr) output[op++] = '\r'; output[op++] = '\n'; } assert tailLen == 0; assert p == len; } else { // Save the leftovers in tail to be consumed on the next // call to encodeInternal. if (p == len-1) { tail[tailLen++] = input[p]; } else if (p == len-2) { tail[tailLen++] = input[p]; tail[tailLen++] = input[p+1]; } } this.op = op; this.count = count; return true; } } private Base64() { } // don't instantiate }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/talent/v4beta1/job_service.proto package com.google.cloud.talent.v4beta1; /** * * * <pre> * Input only. * Update job request. * </pre> * * Protobuf type {@code google.cloud.talent.v4beta1.UpdateJobRequest} */ public final class UpdateJobRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.talent.v4beta1.UpdateJobRequest) UpdateJobRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateJobRequest.newBuilder() to construct. private UpdateJobRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateJobRequest() {} @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private UpdateJobRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.talent.v4beta1.Job.Builder subBuilder = null; if (job_ != null) { subBuilder = job_.toBuilder(); } job_ = input.readMessage( com.google.cloud.talent.v4beta1.Job.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(job_); job_ = subBuilder.buildPartial(); } break; } case 18: { com.google.protobuf.FieldMask.Builder subBuilder = null; if (updateMask_ != null) { subBuilder = updateMask_.toBuilder(); } updateMask_ = input.readMessage(com.google.protobuf.FieldMask.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(updateMask_); updateMask_ = subBuilder.buildPartial(); } break; } default: { if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.talent.v4beta1.JobServiceProto .internal_static_google_cloud_talent_v4beta1_UpdateJobRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.talent.v4beta1.JobServiceProto .internal_static_google_cloud_talent_v4beta1_UpdateJobRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.talent.v4beta1.UpdateJobRequest.class, com.google.cloud.talent.v4beta1.UpdateJobRequest.Builder.class); } public static final int JOB_FIELD_NUMBER = 1; private com.google.cloud.talent.v4beta1.Job job_; /** * * * <pre> * Required. * The Job to be updated. * </pre> * * <code>.google.cloud.talent.v4beta1.Job job = 1;</code> */ public boolean hasJob() { return job_ != null; } /** * * * <pre> * Required. * The Job to be updated. * </pre> * * <code>.google.cloud.talent.v4beta1.Job job = 1;</code> */ public com.google.cloud.talent.v4beta1.Job getJob() { return job_ == null ? com.google.cloud.talent.v4beta1.Job.getDefaultInstance() : job_; } /** * * * <pre> * Required. * The Job to be updated. * </pre> * * <code>.google.cloud.talent.v4beta1.Job job = 1;</code> */ public com.google.cloud.talent.v4beta1.JobOrBuilder getJobOrBuilder() { return getJob(); } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Optional but strongly recommended to be provided for the best service * experience. * If [update_mask][google.cloud.talent.v4beta1.UpdateJobRequest.update_mask] * is provided, only the specified fields in * [job][google.cloud.talent.v4beta1.UpdateJobRequest.job] are updated. * Otherwise all the fields are updated. * A field mask to restrict the fields that are updated. Only * top level fields of [Job][google.cloud.talent.v4beta1.Job] are supported. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public boolean hasUpdateMask() { return updateMask_ != null; } /** * * * <pre> * Optional but strongly recommended to be provided for the best service * experience. * If [update_mask][google.cloud.talent.v4beta1.UpdateJobRequest.update_mask] * is provided, only the specified fields in * [job][google.cloud.talent.v4beta1.UpdateJobRequest.job] are updated. * Otherwise all the fields are updated. * A field mask to restrict the fields that are updated. Only * top level fields of [Job][google.cloud.talent.v4beta1.Job] are supported. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Optional but strongly recommended to be provided for the best service * experience. * If [update_mask][google.cloud.talent.v4beta1.UpdateJobRequest.update_mask] * is provided, only the specified fields in * [job][google.cloud.talent.v4beta1.UpdateJobRequest.job] are updated. * Otherwise all the fields are updated. * A field mask to restrict the fields that are updated. Only * top level fields of [Job][google.cloud.talent.v4beta1.Job] are supported. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return getUpdateMask(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (job_ != null) { output.writeMessage(1, getJob()); } if (updateMask_ != null) { output.writeMessage(2, getUpdateMask()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (job_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getJob()); } if (updateMask_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask()); } 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.talent.v4beta1.UpdateJobRequest)) { return super.equals(obj); } com.google.cloud.talent.v4beta1.UpdateJobRequest other = (com.google.cloud.talent.v4beta1.UpdateJobRequest) obj; boolean result = true; result = result && (hasJob() == other.hasJob()); if (hasJob()) { result = result && getJob().equals(other.getJob()); } result = result && (hasUpdateMask() == other.hasUpdateMask()); if (hasUpdateMask()) { result = result && getUpdateMask().equals(other.getUpdateMask()); } result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasJob()) { hash = (37 * hash) + JOB_FIELD_NUMBER; hash = (53 * hash) + getJob().hashCode(); } if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.talent.v4beta1.UpdateJobRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.talent.v4beta1.UpdateJobRequest 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.talent.v4beta1.UpdateJobRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.talent.v4beta1.UpdateJobRequest 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.talent.v4beta1.UpdateJobRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.talent.v4beta1.UpdateJobRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.talent.v4beta1.UpdateJobRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.talent.v4beta1.UpdateJobRequest 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.talent.v4beta1.UpdateJobRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.talent.v4beta1.UpdateJobRequest 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.talent.v4beta1.UpdateJobRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.talent.v4beta1.UpdateJobRequest 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.talent.v4beta1.UpdateJobRequest 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> * Input only. * Update job request. * </pre> * * Protobuf type {@code google.cloud.talent.v4beta1.UpdateJobRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.talent.v4beta1.UpdateJobRequest) com.google.cloud.talent.v4beta1.UpdateJobRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.talent.v4beta1.JobServiceProto .internal_static_google_cloud_talent_v4beta1_UpdateJobRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.talent.v4beta1.JobServiceProto .internal_static_google_cloud_talent_v4beta1_UpdateJobRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.talent.v4beta1.UpdateJobRequest.class, com.google.cloud.talent.v4beta1.UpdateJobRequest.Builder.class); } // Construct using com.google.cloud.talent.v4beta1.UpdateJobRequest.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(); if (jobBuilder_ == null) { job_ = null; } else { job_ = null; jobBuilder_ = null; } if (updateMaskBuilder_ == null) { updateMask_ = null; } else { updateMask_ = null; updateMaskBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.talent.v4beta1.JobServiceProto .internal_static_google_cloud_talent_v4beta1_UpdateJobRequest_descriptor; } @java.lang.Override public com.google.cloud.talent.v4beta1.UpdateJobRequest getDefaultInstanceForType() { return com.google.cloud.talent.v4beta1.UpdateJobRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.talent.v4beta1.UpdateJobRequest build() { com.google.cloud.talent.v4beta1.UpdateJobRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.talent.v4beta1.UpdateJobRequest buildPartial() { com.google.cloud.talent.v4beta1.UpdateJobRequest result = new com.google.cloud.talent.v4beta1.UpdateJobRequest(this); if (jobBuilder_ == null) { result.job_ = job_; } else { result.job_ = jobBuilder_.build(); } if (updateMaskBuilder_ == null) { result.updateMask_ = updateMask_; } else { result.updateMask_ = updateMaskBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.talent.v4beta1.UpdateJobRequest) { return mergeFrom((com.google.cloud.talent.v4beta1.UpdateJobRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.talent.v4beta1.UpdateJobRequest other) { if (other == com.google.cloud.talent.v4beta1.UpdateJobRequest.getDefaultInstance()) return this; if (other.hasJob()) { mergeJob(other.getJob()); } if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } 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.talent.v4beta1.UpdateJobRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.talent.v4beta1.UpdateJobRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private com.google.cloud.talent.v4beta1.Job job_ = null; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.talent.v4beta1.Job, com.google.cloud.talent.v4beta1.Job.Builder, com.google.cloud.talent.v4beta1.JobOrBuilder> jobBuilder_; /** * * * <pre> * Required. * The Job to be updated. * </pre> * * <code>.google.cloud.talent.v4beta1.Job job = 1;</code> */ public boolean hasJob() { return jobBuilder_ != null || job_ != null; } /** * * * <pre> * Required. * The Job to be updated. * </pre> * * <code>.google.cloud.talent.v4beta1.Job job = 1;</code> */ public com.google.cloud.talent.v4beta1.Job getJob() { if (jobBuilder_ == null) { return job_ == null ? com.google.cloud.talent.v4beta1.Job.getDefaultInstance() : job_; } else { return jobBuilder_.getMessage(); } } /** * * * <pre> * Required. * The Job to be updated. * </pre> * * <code>.google.cloud.talent.v4beta1.Job job = 1;</code> */ public Builder setJob(com.google.cloud.talent.v4beta1.Job value) { if (jobBuilder_ == null) { if (value == null) { throw new NullPointerException(); } job_ = value; onChanged(); } else { jobBuilder_.setMessage(value); } return this; } /** * * * <pre> * Required. * The Job to be updated. * </pre> * * <code>.google.cloud.talent.v4beta1.Job job = 1;</code> */ public Builder setJob(com.google.cloud.talent.v4beta1.Job.Builder builderForValue) { if (jobBuilder_ == null) { job_ = builderForValue.build(); onChanged(); } else { jobBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Required. * The Job to be updated. * </pre> * * <code>.google.cloud.talent.v4beta1.Job job = 1;</code> */ public Builder mergeJob(com.google.cloud.talent.v4beta1.Job value) { if (jobBuilder_ == null) { if (job_ != null) { job_ = com.google.cloud.talent.v4beta1.Job.newBuilder(job_).mergeFrom(value).buildPartial(); } else { job_ = value; } onChanged(); } else { jobBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Required. * The Job to be updated. * </pre> * * <code>.google.cloud.talent.v4beta1.Job job = 1;</code> */ public Builder clearJob() { if (jobBuilder_ == null) { job_ = null; onChanged(); } else { job_ = null; jobBuilder_ = null; } return this; } /** * * * <pre> * Required. * The Job to be updated. * </pre> * * <code>.google.cloud.talent.v4beta1.Job job = 1;</code> */ public com.google.cloud.talent.v4beta1.Job.Builder getJobBuilder() { onChanged(); return getJobFieldBuilder().getBuilder(); } /** * * * <pre> * Required. * The Job to be updated. * </pre> * * <code>.google.cloud.talent.v4beta1.Job job = 1;</code> */ public com.google.cloud.talent.v4beta1.JobOrBuilder getJobOrBuilder() { if (jobBuilder_ != null) { return jobBuilder_.getMessageOrBuilder(); } else { return job_ == null ? com.google.cloud.talent.v4beta1.Job.getDefaultInstance() : job_; } } /** * * * <pre> * Required. * The Job to be updated. * </pre> * * <code>.google.cloud.talent.v4beta1.Job job = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.talent.v4beta1.Job, com.google.cloud.talent.v4beta1.Job.Builder, com.google.cloud.talent.v4beta1.JobOrBuilder> getJobFieldBuilder() { if (jobBuilder_ == null) { jobBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.talent.v4beta1.Job, com.google.cloud.talent.v4beta1.Job.Builder, com.google.cloud.talent.v4beta1.JobOrBuilder>( getJob(), getParentForChildren(), isClean()); job_ = null; } return jobBuilder_; } private com.google.protobuf.FieldMask updateMask_ = null; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Optional but strongly recommended to be provided for the best service * experience. * If [update_mask][google.cloud.talent.v4beta1.UpdateJobRequest.update_mask] * is provided, only the specified fields in * [job][google.cloud.talent.v4beta1.UpdateJobRequest.job] are updated. * Otherwise all the fields are updated. * A field mask to restrict the fields that are updated. Only * top level fields of [Job][google.cloud.talent.v4beta1.Job] are supported. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public boolean hasUpdateMask() { return updateMaskBuilder_ != null || updateMask_ != null; } /** * * * <pre> * Optional but strongly recommended to be provided for the best service * experience. * If [update_mask][google.cloud.talent.v4beta1.UpdateJobRequest.update_mask] * is provided, only the specified fields in * [job][google.cloud.talent.v4beta1.UpdateJobRequest.job] are updated. * Otherwise all the fields are updated. * A field mask to restrict the fields that are updated. Only * top level fields of [Job][google.cloud.talent.v4beta1.Job] are supported. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Optional but strongly recommended to be provided for the best service * experience. * If [update_mask][google.cloud.talent.v4beta1.UpdateJobRequest.update_mask] * is provided, only the specified fields in * [job][google.cloud.talent.v4beta1.UpdateJobRequest.job] are updated. * Otherwise all the fields are updated. * A field mask to restrict the fields that are updated. Only * top level fields of [Job][google.cloud.talent.v4beta1.Job] are supported. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; onChanged(); } else { updateMaskBuilder_.setMessage(value); } return this; } /** * * * <pre> * Optional but strongly recommended to be provided for the best service * experience. * If [update_mask][google.cloud.talent.v4beta1.UpdateJobRequest.update_mask] * is provided, only the specified fields in * [job][google.cloud.talent.v4beta1.UpdateJobRequest.job] are updated. * Otherwise all the fields are updated. * A field mask to restrict the fields that are updated. Only * top level fields of [Job][google.cloud.talent.v4beta1.Job] are supported. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); onChanged(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Optional but strongly recommended to be provided for the best service * experience. * If [update_mask][google.cloud.talent.v4beta1.UpdateJobRequest.update_mask] * is provided, only the specified fields in * [job][google.cloud.talent.v4beta1.UpdateJobRequest.job] are updated. * Otherwise all the fields are updated. * A field mask to restrict the fields that are updated. Only * top level fields of [Job][google.cloud.talent.v4beta1.Job] are supported. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (updateMask_ != null) { updateMask_ = com.google.protobuf.FieldMask.newBuilder(updateMask_).mergeFrom(value).buildPartial(); } else { updateMask_ = value; } onChanged(); } else { updateMaskBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Optional but strongly recommended to be provided for the best service * experience. * If [update_mask][google.cloud.talent.v4beta1.UpdateJobRequest.update_mask] * is provided, only the specified fields in * [job][google.cloud.talent.v4beta1.UpdateJobRequest.job] are updated. * Otherwise all the fields are updated. * A field mask to restrict the fields that are updated. Only * top level fields of [Job][google.cloud.talent.v4beta1.Job] are supported. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder clearUpdateMask() { if (updateMaskBuilder_ == null) { updateMask_ = null; onChanged(); } else { updateMask_ = null; updateMaskBuilder_ = null; } return this; } /** * * * <pre> * Optional but strongly recommended to be provided for the best service * experience. * If [update_mask][google.cloud.talent.v4beta1.UpdateJobRequest.update_mask] * is provided, only the specified fields in * [job][google.cloud.talent.v4beta1.UpdateJobRequest.job] are updated. * Otherwise all the fields are updated. * A field mask to restrict the fields that are updated. Only * top level fields of [Job][google.cloud.talent.v4beta1.Job] are supported. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Optional but strongly recommended to be provided for the best service * experience. * If [update_mask][google.cloud.talent.v4beta1.UpdateJobRequest.update_mask] * is provided, only the specified fields in * [job][google.cloud.talent.v4beta1.UpdateJobRequest.job] are updated. * Otherwise all the fields are updated. * A field mask to restrict the fields that are updated. Only * top level fields of [Job][google.cloud.talent.v4beta1.Job] are supported. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Optional but strongly recommended to be provided for the best service * experience. * If [update_mask][google.cloud.talent.v4beta1.UpdateJobRequest.update_mask] * is provided, only the specified fields in * [job][google.cloud.talent.v4beta1.UpdateJobRequest.job] are updated. * Otherwise all the fields are updated. * A field mask to restrict the fields that are updated. Only * top level fields of [Job][google.cloud.talent.v4beta1.Job] are supported. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.talent.v4beta1.UpdateJobRequest) } // @@protoc_insertion_point(class_scope:google.cloud.talent.v4beta1.UpdateJobRequest) private static final com.google.cloud.talent.v4beta1.UpdateJobRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.talent.v4beta1.UpdateJobRequest(); } public static com.google.cloud.talent.v4beta1.UpdateJobRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateJobRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateJobRequest>() { @java.lang.Override public UpdateJobRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new UpdateJobRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<UpdateJobRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateJobRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.talent.v4beta1.UpdateJobRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
package org.keycloak.testsuite.model; import org.junit.Assert; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import org.keycloak.models.ClientModel; import org.keycloak.models.FederatedIdentityModel; import org.keycloak.models.ModelDuplicateException; import org.keycloak.models.PasswordPolicy; import org.keycloak.models.RealmModel; import org.keycloak.models.RequiredCredentialModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserCredentialValueModel; import org.keycloak.models.UserFederationProviderModel; import org.keycloak.models.UserModel; import org.keycloak.models.UserProvider; import org.keycloak.representations.idm.CredentialRepresentation; import org.keycloak.services.managers.RealmManager; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class AdapterTest extends AbstractModelTest { private RealmModel realmModel; @Test public void test1CreateRealm() throws Exception { realmModel = realmManager.createRealm("JUGGLER"); realmModel.setAccessCodeLifespan(100); realmModel.setAccessCodeLifespanUserAction(600); realmModel.setEnabled(true); realmModel.setName("JUGGLER"); KeyPair keyPair = generateKeypair(); realmModel.setPrivateKey(keyPair.getPrivate()); realmModel.setPublicKey(keyPair.getPublic()); realmModel.setAccessTokenLifespan(1000); realmModel.addDefaultRole("foo"); session.getTransaction().commit(); resetSession(); realmModel = realmManager.getRealm(realmModel.getId()); assertNotNull(realmModel); Assert.assertEquals(realmModel.getAccessCodeLifespan(), 100); Assert.assertEquals(600, realmModel.getAccessCodeLifespanUserAction()); Assert.assertEquals(realmModel.getAccessTokenLifespan(), 1000); Assert.assertEquals(realmModel.isEnabled(), true); Assert.assertEquals(realmModel.getName(), "JUGGLER"); Assert.assertArrayEquals(realmModel.getPrivateKey().getEncoded(), keyPair.getPrivate().getEncoded()); Assert.assertArrayEquals(realmModel.getPublicKey().getEncoded(), keyPair.getPublic().getEncoded()); Assert.assertEquals(1, realmModel.getDefaultRoles().size()); Assert.assertEquals("foo", realmModel.getDefaultRoles().get(0)); } @Test public void testRealmListing() throws Exception { realmModel = realmManager.createRealm("JUGGLER"); realmModel.setAccessCodeLifespan(100); realmModel.setAccessCodeLifespanUserAction(600); realmModel.setEnabled(true); realmModel.setName("JUGGLER"); KeyPair keyPair = generateKeypair(); realmModel.setPrivateKey(keyPair.getPrivate()); realmModel.setPublicKey(keyPair.getPublic()); realmModel.setAccessTokenLifespan(1000); realmModel.addDefaultRole("foo"); realmModel = realmManager.getRealm(realmModel.getId()); assertNotNull(realmModel); Assert.assertEquals(realmModel.getAccessCodeLifespan(), 100); Assert.assertEquals(600, realmModel.getAccessCodeLifespanUserAction()); Assert.assertEquals(realmModel.getAccessTokenLifespan(), 1000); Assert.assertEquals(realmModel.isEnabled(), true); Assert.assertEquals(realmModel.getName(), "JUGGLER"); Assert.assertArrayEquals(realmModel.getPrivateKey().getEncoded(), keyPair.getPrivate().getEncoded()); Assert.assertArrayEquals(realmModel.getPublicKey().getEncoded(), keyPair.getPublic().getEncoded()); Assert.assertEquals(1, realmModel.getDefaultRoles().size()); Assert.assertEquals("foo", realmModel.getDefaultRoles().get(0)); realmModel.getId(); commit(); List<RealmModel> realms = model.getRealms(); Assert.assertEquals(realms.size(), 2); } @Test public void test2RequiredCredential() throws Exception { test1CreateRealm(); realmModel.addRequiredCredential(CredentialRepresentation.PASSWORD); List<RequiredCredentialModel> storedCreds = realmModel.getRequiredCredentials(); Assert.assertEquals(1, storedCreds.size()); Set<String> creds = new HashSet<String>(); creds.add(CredentialRepresentation.PASSWORD); creds.add(CredentialRepresentation.TOTP); realmModel.updateRequiredCredentials(creds); storedCreds = realmModel.getRequiredCredentials(); Assert.assertEquals(2, storedCreds.size()); boolean totp = false; boolean password = false; for (RequiredCredentialModel cred : storedCreds) { Assert.assertTrue(cred.isInput()); if (cred.getType().equals(CredentialRepresentation.PASSWORD)) { password = true; Assert.assertTrue(cred.isSecret()); } else if (cred.getType().equals(CredentialRepresentation.TOTP)) { totp = true; Assert.assertFalse(cred.isSecret()); } } Assert.assertTrue(totp); Assert.assertTrue(password); } @Test public void testCredentialValidation() throws Exception { test1CreateRealm(); UserProvider userProvider = realmManager.getSession().users(); UserModel user = userProvider.addUser(realmModel, "bburke"); UserCredentialModel cred = new UserCredentialModel(); cred.setType(CredentialRepresentation.PASSWORD); cred.setValue("geheim"); user.updateCredential(cred); Assert.assertTrue(userProvider.validCredentials(realmModel, user, UserCredentialModel.password("geheim"))); List<UserCredentialValueModel> creds = user.getCredentialsDirectly(); Assert.assertEquals(creds.get(0).getHashIterations(), 1); realmModel.setPasswordPolicy( new PasswordPolicy("hashIterations(200)")); Assert.assertTrue(userProvider.validCredentials(realmModel, user, UserCredentialModel.password("geheim"))); creds = user.getCredentialsDirectly(); Assert.assertEquals(creds.get(0).getHashIterations(), 200); realmModel.setPasswordPolicy( new PasswordPolicy("hashIterations(1)")); } @Test public void testDeleteUser() throws Exception { test1CreateRealm(); UserModel user = realmManager.getSession().users().addUser(realmModel, "bburke"); user.setSingleAttribute("attr1", "val1"); user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD); RoleModel testRole = realmModel.addRole("test"); user.grantRole(testRole); ClientModel app = realmModel.addClient("test-app"); RoleModel appRole = app.addRole("test"); user.grantRole(appRole); FederatedIdentityModel socialLink = new FederatedIdentityModel("google", "google1", user.getUsername()); realmManager.getSession().users().addFederatedIdentity(realmModel, user, socialLink); UserCredentialModel cred = new UserCredentialModel(); cred.setType(CredentialRepresentation.PASSWORD); cred.setValue("password"); user.updateCredential(cred); commit(); realmModel = model.getRealm("JUGGLER"); Assert.assertTrue(realmManager.getSession().users().removeUser(realmModel, user)); assertNull(realmManager.getSession().users().getUserByUsername("bburke", realmModel)); } @Test public void testRemoveApplication() throws Exception { test1CreateRealm(); UserModel user = realmManager.getSession().users().addUser(realmModel, "bburke"); ClientModel client = realmModel.addClient("client"); ClientModel app = realmModel.addClient("test-app"); RoleModel appRole = app.addRole("test"); user.grantRole(appRole); client.addScopeMapping(appRole); RoleModel realmRole = realmModel.addRole("test"); app.addScopeMapping(realmRole); Assert.assertTrue(realmModel.removeClient(app.getId())); Assert.assertFalse(realmModel.removeClient(app.getId())); assertNull(realmModel.getClientById(app.getId())); } @Test public void testRemoveRealm() throws Exception { test1CreateRealm(); UserModel user = realmManager.getSession().users().addUser(realmModel, "bburke"); UserCredentialModel cred = new UserCredentialModel(); cred.setType(CredentialRepresentation.PASSWORD); cred.setValue("password"); user.updateCredential(cred); ClientModel client = realmModel.addClient("client"); ClientModel app = realmModel.addClient("test-app"); RoleModel appRole = app.addRole("test"); user.grantRole(appRole); client.addScopeMapping(appRole); RoleModel realmRole = realmModel.addRole("test"); RoleModel realmRole2 = realmModel.addRole("test2"); realmRole.addCompositeRole(realmRole2); realmRole.addCompositeRole(appRole); app.addScopeMapping(realmRole); commit(); realmModel = model.getRealm("JUGGLER"); Assert.assertTrue(realmManager.removeRealm(realmModel)); Assert.assertFalse(realmManager.removeRealm(realmModel)); assertNull(realmManager.getRealm(realmModel.getId())); } @Test public void testRemoveRole() throws Exception { test1CreateRealm(); UserModel user = realmManager.getSession().users().addUser(realmModel, "bburke"); ClientModel client = realmModel.addClient("client"); ClientModel app = realmModel.addClient("test-app"); RoleModel appRole = app.addRole("test"); user.grantRole(appRole); client.addScopeMapping(appRole); RoleModel realmRole = realmModel.addRole("test"); app.addScopeMapping(realmRole); commit(); realmModel = model.getRealm("JUGGLER"); app = realmModel.getClientByClientId("test-app"); user = realmManager.getSession().users().getUserByUsername("bburke", realmModel); Assert.assertTrue(realmModel.removeRoleById(realmRole.getId())); Assert.assertFalse(realmModel.removeRoleById(realmRole.getId())); assertNull(realmModel.getRole(realmRole.getName())); Assert.assertTrue(realmModel.removeRoleById(appRole.getId())); Assert.assertFalse(realmModel.removeRoleById(appRole.getId())); assertNull(app.getRole(appRole.getName())); user = realmManager.getSession().users().getUserByUsername("bburke", realmModel); } @Test public void testUserSearch() throws Exception { test1CreateRealm(); { UserModel user = realmManager.getSession().users().addUser(realmModel, "bburke"); user.setLastName("Burke"); user.setFirstName("Bill"); user.setEmail("bburke@redhat.com"); UserModel user2 = realmManager.getSession().users().addUser(realmModel, "doublefirst"); user2.setFirstName("Knut Ole"); user2.setLastName("Alver"); user2.setEmail("knut@redhat.com"); UserModel user3 = realmManager.getSession().users().addUser(realmModel, "doublelast"); user3.setFirstName("Ole"); user3.setLastName("Alver Veland"); user3.setEmail("knut2@redhat.com"); } RealmManager adapter = realmManager; { List<UserModel> userModels = adapter.searchUsers("total junk query", realmModel); Assert.assertEquals(userModels.size(), 0); } { List<UserModel> userModels = adapter.searchUsers("Bill Burke", realmModel); Assert.assertEquals(userModels.size(), 1); UserModel bburke = userModels.get(0); Assert.assertEquals(bburke.getFirstName(), "Bill"); Assert.assertEquals(bburke.getLastName(), "Burke"); Assert.assertEquals(bburke.getEmail(), "bburke@redhat.com"); } { List<UserModel> userModels = adapter.searchUsers("bill burk", realmModel); Assert.assertEquals(userModels.size(), 1); UserModel bburke = userModels.get(0); Assert.assertEquals(bburke.getFirstName(), "Bill"); Assert.assertEquals(bburke.getLastName(), "Burke"); Assert.assertEquals(bburke.getEmail(), "bburke@redhat.com"); } { ArrayList<String> users = new ArrayList<String>(); for (UserModel u : adapter.searchUsers("ole alver", realmModel)) { users.add(u.getUsername()); } String[] usernames = users.toArray(new String[users.size()]); Arrays.sort(usernames); Assert.assertArrayEquals(new String[]{"doublefirst", "doublelast"}, usernames); } { List<UserModel> userModels = adapter.searchUsers("bburke@redhat.com", realmModel); Assert.assertEquals(userModels.size(), 1); UserModel bburke = userModels.get(0); Assert.assertEquals(bburke.getFirstName(), "Bill"); Assert.assertEquals(bburke.getLastName(), "Burke"); Assert.assertEquals(bburke.getEmail(), "bburke@redhat.com"); } { List<UserModel> userModels = adapter.searchUsers("rke@redhat.com", realmModel); Assert.assertEquals(userModels.size(), 1); UserModel bburke = userModels.get(0); Assert.assertEquals(bburke.getFirstName(), "Bill"); Assert.assertEquals(bburke.getLastName(), "Burke"); Assert.assertEquals(bburke.getEmail(), "bburke@redhat.com"); } { List<UserModel> userModels = adapter.searchUsers("bburke", realmModel); Assert.assertEquals(userModels.size(), 1); UserModel bburke = userModels.get(0); Assert.assertEquals(bburke.getFirstName(), "Bill"); Assert.assertEquals(bburke.getLastName(), "Burke"); Assert.assertEquals(bburke.getEmail(), "bburke@redhat.com"); } { List<UserModel> userModels = adapter.searchUsers("BurK", realmModel); Assert.assertEquals(userModels.size(), 1); UserModel bburke = userModels.get(0); Assert.assertEquals(bburke.getFirstName(), "Bill"); Assert.assertEquals(bburke.getLastName(), "Burke"); Assert.assertEquals(bburke.getEmail(), "bburke@redhat.com"); } { List<UserModel> userModels = adapter.searchUsers("Burke", realmModel); Assert.assertEquals(userModels.size(), 1); UserModel bburke = userModels.get(0); Assert.assertEquals(bburke.getFirstName(), "Bill"); Assert.assertEquals(bburke.getLastName(), "Burke"); Assert.assertEquals(bburke.getEmail(), "bburke@redhat.com"); } { UserModel user = realmManager.getSession().users().addUser(realmModel, "mburke"); user.setLastName("Burke"); user.setFirstName("Monica"); user.setEmail("mburke@redhat.com"); } { UserModel user = realmManager.getSession().users().addUser(realmModel, "thor"); user.setLastName("Thorgersen"); user.setFirstName("Stian"); user.setEmail("thor@redhat.com"); } { List<UserModel> userModels = adapter.searchUsers("Monica Burke", realmModel); Assert.assertEquals(userModels.size(), 1); UserModel bburke = userModels.get(0); Assert.assertEquals(bburke.getFirstName(), "Monica"); Assert.assertEquals(bburke.getLastName(), "Burke"); Assert.assertEquals(bburke.getEmail(), "mburke@redhat.com"); } { List<UserModel> userModels = adapter.searchUsers("mburke@redhat.com", realmModel); Assert.assertEquals(userModels.size(), 1); UserModel bburke = userModels.get(0); Assert.assertEquals(bburke.getFirstName(), "Monica"); Assert.assertEquals(bburke.getLastName(), "Burke"); Assert.assertEquals(bburke.getEmail(), "mburke@redhat.com"); } { List<UserModel> userModels = adapter.searchUsers("mburke", realmModel); Assert.assertEquals(userModels.size(), 1); UserModel bburke = userModels.get(0); Assert.assertEquals(bburke.getFirstName(), "Monica"); Assert.assertEquals(bburke.getLastName(), "Burke"); Assert.assertEquals(bburke.getEmail(), "mburke@redhat.com"); } { List<UserModel> userModels = adapter.searchUsers("Burke", realmModel); Assert.assertEquals(userModels.size(), 2); UserModel first = userModels.get(0); UserModel second = userModels.get(1); if (!first.getEmail().equals("bburke@redhat.com") && !second.getEmail().equals("bburke@redhat.com")) { Assert.fail(); } if (!first.getEmail().equals("mburke@redhat.com") && !second.getEmail().equals("mburke@redhat.com")) { Assert.fail(); } } RealmModel otherRealm = adapter.createRealm("other"); realmManager.getSession().users().addUser(otherRealm, "bburke"); Assert.assertEquals(1, realmManager.getSession().users().getUsers(otherRealm).size()); Assert.assertEquals(1, realmManager.getSession().users().searchForUser("bu", otherRealm).size()); } @Test public void testRoles() throws Exception { test1CreateRealm(); realmModel.addRole("admin"); realmModel.addRole("user"); Set<RoleModel> roles = realmModel.getRoles(); Assert.assertEquals(3, roles.size()); UserModel user = realmManager.getSession().users().addUser(realmModel, "bburke"); RoleModel realmUserRole = realmModel.getRole("user"); user.grantRole(realmUserRole); Assert.assertTrue(user.hasRole(realmUserRole)); RoleModel found = realmModel.getRoleById(realmUserRole.getId()); assertNotNull(found); assertRolesEquals(found, realmUserRole); // Test app roles ClientModel application = realmModel.addClient("app1"); application.addRole("user"); application.addRole("bar"); Set<RoleModel> appRoles = application.getRoles(); Assert.assertEquals(2, appRoles.size()); RoleModel appBarRole = application.getRole("bar"); assertNotNull(appBarRole); found = realmModel.getRoleById(appBarRole.getId()); assertNotNull(found); assertRolesEquals(found, appBarRole); user.grantRole(appBarRole); user.grantRole(application.getRole("user")); roles = user.getRealmRoleMappings(); Assert.assertEquals(roles.size(), 2); assertRolesContains(realmUserRole, roles); Assert.assertTrue(user.hasRole(realmUserRole)); // Role "foo" is default realm role Assert.assertTrue(user.hasRole(realmModel.getRole("foo"))); roles = user.getClientRoleMappings(application); Assert.assertEquals(roles.size(), 2); assertRolesContains(application.getRole("user"), roles); assertRolesContains(appBarRole, roles); Assert.assertTrue(user.hasRole(appBarRole)); // Test that application role 'user' don't clash with realm role 'user' Assert.assertNotEquals(realmModel.getRole("user").getId(), application.getRole("user").getId()); Assert.assertEquals(6, user.getRoleMappings().size()); // Revoke some roles user.deleteRoleMapping(realmModel.getRole("foo")); user.deleteRoleMapping(appBarRole); roles = user.getRoleMappings(); Assert.assertEquals(4, roles.size()); assertRolesContains(realmUserRole, roles); assertRolesContains(application.getRole("user"), roles); Assert.assertFalse(user.hasRole(appBarRole)); } @Test public void testScopes() throws Exception { test1CreateRealm(); RoleModel realmRole = realmModel.addRole("realm"); ClientModel app1 = realmModel.addClient("app1"); RoleModel appRole = app1.addRole("app"); ClientModel app2 = realmModel.addClient("app2"); app2.addScopeMapping(realmRole); app2.addScopeMapping(appRole); ClientModel client = realmModel.addClient("client"); client.addScopeMapping(realmRole); client.addScopeMapping(appRole); commit(); realmModel = model.getRealmByName("JUGGLER"); app1 = realmModel.getClientByClientId("app1"); app2 = realmModel.getClientByClientId("app2"); client = realmModel.getClientByClientId("client"); Set<RoleModel> scopeMappings = app2.getScopeMappings(); Assert.assertEquals(2, scopeMappings.size()); Assert.assertTrue(scopeMappings.contains(realmModel.getRole("realm"))); Assert.assertTrue(scopeMappings.contains(app1.getRole("app"))); scopeMappings = client.getScopeMappings(); Assert.assertEquals(2, scopeMappings.size()); Assert.assertTrue(scopeMappings.contains(realmModel.getRole("realm"))); Assert.assertTrue(scopeMappings.contains(app1.getRole("app"))); } @Test public void testRealmNameCollisions() throws Exception { test1CreateRealm(); commit(); // Try to create realm with duplicate name try { test1CreateRealm(); commit(); Assert.fail("Expected exception"); } catch (ModelDuplicateException e) { } commit(true); // Try to rename realm to duplicate name realmManager.createRealm("JUGGLER2"); commit(); try { realmManager.getRealmByName("JUGGLER2").setName("JUGGLER"); commit(); Assert.fail("Expected exception"); } catch (ModelDuplicateException e) { } resetSession(); } @Test public void testAppNameCollisions() throws Exception { realmManager.createRealm("JUGGLER1").addClient("app1"); realmManager.createRealm("JUGGLER2").addClient("app1"); commit(); // Try to create app with duplicate name try { realmManager.getRealmByName("JUGGLER1").addClient("app1"); commit(); Assert.fail("Expected exception"); } catch (ModelDuplicateException e) { } commit(true); // Ty to rename app to duplicate name realmManager.getRealmByName("JUGGLER1").addClient("app2"); commit(); try { realmManager.getRealmByName("JUGGLER1").getClientByClientId("app2").setClientId("app1"); commit(); Assert.fail("Expected exception"); } catch (ModelDuplicateException e) { } resetSession(); } @Test public void testClientNameCollisions() throws Exception { realmManager.createRealm("JUGGLER1").addClient("client1"); realmManager.createRealm("JUGGLER2").addClient("client1"); commit(); // Try to create app with duplicate name try { realmManager.getRealmByName("JUGGLER1").addClient("client1"); commit(); Assert.fail("Expected exception"); } catch (ModelDuplicateException e) { } commit(true); // Ty to rename app to duplicate name realmManager.getRealmByName("JUGGLER1").addClient("client2"); commit(); try { realmManager.getRealmByName("JUGGLER1").addClient("client2").setClientId("client1"); commit(); Assert.fail("Expected exception"); } catch (ModelDuplicateException e) { } resetSession(); } @Test public void testUsernameCollisions() throws Exception { RealmModel juggler1 = realmManager.createRealm("JUGGLER1"); realmManager.getSession().users().addUser(juggler1, "user1"); RealmModel juggler2 = realmManager.createRealm("JUGGLER2"); realmManager.getSession().users().addUser(juggler2, "user1"); commit(); // Try to create user with duplicate login name try { juggler1 = realmManager.getRealmByName("JUGGLER1"); realmManager.getSession().users().addUser(juggler1, "user1"); commit(); Assert.fail("Expected exception"); } catch (ModelDuplicateException e) { } commit(true); // Ty to rename user to duplicate login name juggler1 = realmManager.getRealmByName("JUGGLER1"); realmManager.getSession().users().addUser(juggler1, "user2"); commit(); try { juggler1 = realmManager.getRealmByName("JUGGLER1"); realmManager.getSession().users().getUserByUsername("user2", juggler1).setUsername("user1"); commit(); Assert.fail("Expected exception"); } catch (ModelDuplicateException e) { } resetSession(); } @Test public void testEmailCollisions() throws Exception { RealmModel juggler1 = realmManager.createRealm("JUGGLER1"); realmManager.getSession().users().addUser(juggler1, "user1").setEmail("email@example.com"); RealmModel juggler2 = realmManager.createRealm("JUGGLER2"); realmManager.getSession().users().addUser(juggler2, "user1").setEmail("email@example.com"); commit(); // Try to create user with duplicate email juggler1 = realmManager.getRealmByName("JUGGLER1"); try { realmManager.getSession().users().addUser(juggler1, "user2").setEmail("email@example.com"); commit(); Assert.fail("Expected exception"); } catch (ModelDuplicateException e) { } resetSession(); // Ty to rename user to duplicate email juggler1 = realmManager.getRealmByName("JUGGLER1"); realmManager.getSession().users().addUser(juggler1, "user3").setEmail("email2@example.com"); commit(); try { juggler1 = realmManager.getRealmByName("JUGGLER1"); realmManager.getSession().users().getUserByUsername("user3", juggler1).setEmail("email@example.com"); commit(); Assert.fail("Expected exception"); } catch (ModelDuplicateException e) { } resetSession(); } @Test public void testAppRoleCollisions() throws Exception { realmManager.createRealm("JUGGLER1").addRole("role1"); realmManager.getRealmByName("JUGGLER1").addClient("app1").addRole("role1"); realmManager.getRealmByName("JUGGLER1").addClient("app2").addRole("role1"); commit(); // Try to add role with same name try { realmManager.getRealmByName("JUGGLER1").getClientByClientId("app1").addRole("role1"); commit(); Assert.fail("Expected exception"); } catch (ModelDuplicateException e) { } commit(true); // Ty to rename role to duplicate name realmManager.getRealmByName("JUGGLER1").getClientByClientId("app1").addRole("role2"); commit(); try { realmManager.getRealmByName("JUGGLER1").getClientByClientId("app1").getRole("role2").setName("role1"); commit(); Assert.fail("Expected exception"); } catch (ModelDuplicateException e) { } resetSession(); } @Test public void testRealmRoleCollisions() throws Exception { realmManager.createRealm("JUGGLER1").addRole("role1"); realmManager.getRealmByName("JUGGLER1").addClient("app1").addRole("role1"); realmManager.getRealmByName("JUGGLER1").addClient("app2").addRole("role1"); commit(); // Try to add role with same name try { realmManager.getRealmByName("JUGGLER1").addRole("role1"); commit(); Assert.fail("Expected exception"); } catch (ModelDuplicateException e) { } commit(true); // Ty to rename role to duplicate name realmManager.getRealmByName("JUGGLER1").addRole("role2"); commit(); try { realmManager.getRealmByName("JUGGLER1").getRole("role2").setName("role1"); commit(); Assert.fail("Expected exception"); } catch (ModelDuplicateException e) { } resetSession(); } @Test public void testUserFederationProviderDisplayNameCollisions() throws Exception { RealmModel realm = realmManager.createRealm("JUGGLER1"); Map<String, String> cfg = Collections.emptyMap(); realm.addUserFederationProvider("ldap", cfg, 1, "providerName1", -1, -1, 0); realm.addUserFederationProvider("ldap", cfg, 1, "providerName2", -1, -1, 0); commit(); // Try to add federation provider with same display name try { realmManager.getRealmByName("JUGGLER1").addUserFederationProvider("ldap", cfg, 1, "providerName1", -1, -1, 0); commit(); Assert.fail("Expected exception"); } catch (ModelDuplicateException e) { } commit(true); // Try to rename federation provider tu duplicate display name try { List<UserFederationProviderModel> fedProviders = realmManager.getRealmByName("JUGGLER1").getUserFederationProviders(); for (UserFederationProviderModel fedProvider : fedProviders) { if ("providerName1".equals(fedProvider.getDisplayName())) { fedProvider.setDisplayName("providerName2"); realm.updateUserFederationProvider(fedProvider); break; } } commit(); Assert.fail("Expected exception"); } catch (ModelDuplicateException e) { } commit(true); // Try to rename federation provider tu duplicate display name try { List<UserFederationProviderModel> fedProviders = realmManager.getRealmByName("JUGGLER1").getUserFederationProviders(); for (UserFederationProviderModel fedProvider : fedProviders) { if ("providerName1".equals(fedProvider.getDisplayName())) { fedProvider.setDisplayName("providerName2"); break; } } realm.setUserFederationProviders(fedProviders); commit(); Assert.fail("Expected exception"); } catch (ModelDuplicateException e) { } commit(true); } private KeyPair generateKeypair() throws NoSuchAlgorithmException { return KeyPairGenerator.getInstance("RSA").generateKeyPair(); } }
/* * Copyright 2015, The Querydsl Team (http://www.querydsl.com/team) * * 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.querydsl.sql; import static com.google.common.base.CharMatcher.inRange; import java.lang.reflect.Field; import java.sql.Types; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.CharMatcher; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.querydsl.core.*; import com.querydsl.core.QueryFlag.Position; import com.querydsl.core.types.*; import com.querydsl.sql.types.Type; /** * {@code SQLTemplates} extends {@link Templates} to provides SQL specific extensions * and acts as database specific Dialect for Querydsl SQL * * @author tiwe */ public class SQLTemplates extends Templates { protected static final Expression<?> FOR_SHARE = ExpressionUtils.operation( Object.class, SQLOps.FOR_SHARE, ImmutableList.<Expression<?>>of()); protected static final Expression<?> FOR_UPDATE = ExpressionUtils.operation( Object.class, SQLOps.FOR_UPDATE, ImmutableList.<Expression<?>>of()); protected static final Expression<?> NO_WAIT = ExpressionUtils.operation( Object.class, SQLOps.NO_WAIT, ImmutableList.<Expression<?>>of()); protected static final int TIME_WITH_TIMEZONE = 2013; protected static final int TIMESTAMP_WITH_TIMEZONE = 2014; protected static final Set<String> SQL_RESERVED_WORDS = ImmutableSet.of( "ABS", "ALL", "ALLOCATE", "ALTER", "AND", "ANY", "ARE", "ARRAY", "ARRAY_AGG", "AS", "ASENSITIVE", "ASYMMETRIC", "AT", "ATOMIC", "AUTHORIZATION", "AVG", "BEGIN", "BETWEEN", "BIGINT", "BINARY", "BLOB", "BOOLEAN", "BOTH", "BY", "CALL", "CALLED", "CARDINALITY", "CASCADED", "CASE", "CAST", "CEIL", "CEILING", "CHAR", "CHARACTER", "CHARACTER_LENGTH", "CHAR_LENGTH", "CHECK", "CLOB", "CLOSE", "COALESCE", "COLLATE", "COLLECT", "COLUMN", "COMMIT", "CONDITION", "CONNECT", "CONSTRAINT", "CONVERT", "CORR", "CORRESPONDING", "COUNT", "COVAR_POP", "COVAR_SAMP", "CREATE", "CROSS", "CUBE", "CUME_DIST", "CURRENT", "CURRENT_CATALOG", "CURRENT_DATE", "CURRENT_DEFAULT_TRANSFORM_GROUP", "CURRENT_PATH", "CURRENT_ROLE", "CURRENT_SCHEMA", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_TRANSFORM_GROUP_FOR_TYPE", "CURRENT_USER", "CURSOR", "CYCLE", "DATE", "DAY", "DEALLOCATE", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DELETE", "DENSE_RANK", "DEREF", "DESCRIBE", "DETERMINISTIC", "DISCONNECT", "DISTINCT", "DOUBLE", "DROP", "DYNAMIC", "EACH", "ELEMENT", "ELSE", "END", "END-EXEC", "ESCAPE", "EVERY", "EXCEPT", "EXEC", "EXECUTE", "EXISTS", "EXP", "EXTERNAL", "EXTRACT", "FALSE", "FETCH", "FILTER", "FIRST_VALUE", "FLOAT", "FLOOR", "FOR", "FOREIGN", "FREE", "FROM", "FULL", "FUNCTION", "FUSION", "GET", "GLOBAL", "GRANT", "GROUP", "GROUPING", "HAVING", "HOLD", "HOUR", "IDENTITY", "IN", "INDICATOR", "INNER", "INOUT", "INSENSITIVE", "INSERT", "INT", "INTEGER", "INTERSECT", "INTERSECTION", "INTERVAL", "INTO", "IS", "JOIN", "LAG", "LANGUAGE", "LARGE", "LAST_VALUE", "LATERAL", "LEAD", "LEADING", "LEFT", "LIKE", "LIKE_REGEX", "LN", "LOCAL", "LOCALTIME", "LOCALTIMESTAMP", "LOWER", "MATCH", "MAX", "MAX_CARDINALITY", "MEMBER", "MERGE", "METHOD", "MIN", "MINUTE", "MOD", "MODIFIES", "MODULE", "MONTH", "MULTISET", "NATIONAL", "NATURAL", "NCHAR", "NCLOB", "NEW", "NO", "NONE", "NORMALIZE", "NOT", "NTH_VALUE", "NTILE", "NULL", "NULLIF", "NUMERIC", "OCCURRENCES_REGEX", "OCTET_LENGTH", "OF", "OFFSET", "OLD", "ON", "ONLY", "OPEN", "OR", "ORDER", "OUT", "OUTER", "OVER", "OVERLAPS", "OVERLAY", "PARAMETER", "PARTITION", "PERCENTILE_CONT", "PERCENTILE_DISC", "PERCENT_RANK", "POSITION", "POSITION_REGEX", "POWER", "PRECISION", "PREPARE", "PRIMARY", "PROCEDURE", "RANGE", "RANK", "READS", "REAL", "RECURSIVE", "REF", "REFERENCES", "REFERENCING", "REGR_AVGX", "REGR_AVGY", "REGR_COUNT", "REGR_INTERCEPT", "REGR_R2", "REGR_SLOPE", "REGR_SXX", "REGR_SXY", "REGR_SYY", "RELEASE", "RESULT", "RETURN", "RETURNS", "REVOKE", "RIGHT", "ROLLBACK", "ROLLUP", "ROW", "ROWS", "ROW_NUMBER", "SAVEPOINT", "SCOPE", "SCROLL", "SEARCH", "SECOND", "SELECT", "SENSITIVE", "SESSION_USER", "SET", "SIMILAR", "SMALLINT", "SOME", "SPECIFIC", "SPECIFICTYPE", "SQL", "SQLEXCEPTION", "SQLSTATE", "SQLWARNING", "SQRT", "START", "STATIC", "STDDEV_POP", "STDDEV_SAMP", "SUBMULTISET", "SUBSTRING", "SUBSTRING_REGEX", "SUM", "SYMMETRIC", "SYSTEM", "SYSTEM_USER", "TABLE", "TABLESAMPLE", "THEN", "TIME", "TIMESTAMP", "TIMEZONE_HOUR", "TIMEZONE_MINUTE", "TO", "TRAILING", "TRANSLATE", "TRANSLATE_REGEX", "TRANSLATION", "TREAT", "TRIGGER", "TRIM", "TRIM_ARRAY", "TRUE", "TRUNCATE", "UESCAPE", "UNION", "UNIQUE", "UNKNOWN", "UNNEST", "UPDATE", "UPPER", "USER", "USING", "VALUE", "VALUES", "VARBINARY", "VARCHAR", "VARYING", "VAR_POP", "VAR_SAMP", "WHEN", "WHENEVER", "WHERE", "WIDTH_BUCKET", "WINDOW", "WITH", "WITHIN", "WITHOUT", "XML", "XMLAGG", "XMLATTRIBUTES", "XMLBINARY", "XMLCAST", "XMLCOMMENT", "XMLCONCAT", "XMLDOCUMENT", "XMLELEMENT", "XMLEXISTS", "XMLFOREST", "XMLITERATE", "XMLNAMESPACES", "XMLPARSE", "XMLPI", "XMLQUERY", "XMLSERIALIZE", "XMLTABLE", "XMLTEXT", "XMLVALIDATE", "YEAR"); public static final Expression<?> RECURSIVE = ExpressionUtils.template(Object.class, ""); @SuppressWarnings("FieldNameHidesFieldInSuperclass") //Intentional public static final SQLTemplates DEFAULT = new SQLTemplates("\"",'\\',false); private static final CharMatcher NON_UNDERSCORE_ALPHA_NUMERIC = CharMatcher.is('_').or(inRange('a', 'z').or(inRange('A', 'Z'))).or(inRange('0', '9')) .negate().precomputed(); private static final CharMatcher NON_UNDERSCORE_ALPHA = CharMatcher.is('_').or(inRange('a', 'z').or(inRange('A', 'Z'))).negate().precomputed(); private final Set<String> reservedWords; /** * Fluent builder for {@code SQLTemplates} instances * */ public abstract static class Builder { protected boolean printSchema, quote, newLineToSingleSpace; protected char escape = '\\'; public Builder printSchema() { printSchema = true; return this; } public Builder quote() { quote = true; return this; } public Builder newLineToSingleSpace() { newLineToSingleSpace = true; return this; } public Builder escape(char ch) { escape = ch; return this; } protected abstract SQLTemplates build(char escape, boolean quote); public SQLTemplates build() { SQLTemplates templates = build(escape, quote); if (newLineToSingleSpace) { templates.newLineToSingleSpace(); } templates.setPrintSchema(printSchema); return templates; } } private final Map<String, Integer> typeNameToCode = Maps.newHashMap(); private final Map<Integer, String> codeToTypeName = Maps.newHashMap(); private final Map<SchemaAndTable, SchemaAndTable> tableOverrides = Maps.newHashMap(); private final List<Type<?>> customTypes = Lists.newArrayList(); private final String quoteStr; private final boolean useQuotes; private boolean printSchema; private String createTable = "create table "; private String asc = " asc"; private String autoIncrement = " auto_increment"; private String columnAlias = " "; private String count = "count "; private String countStar = "count(*)"; private String delete = "delete "; private String desc = " desc"; private String distinctCountEnd = ")"; private String distinctCountStart = "count(distinct "; private String dummyTable = "dual"; private String from = "\nfrom "; private String fullJoin = "\nfull join "; private String groupBy = "\ngroup by "; private String having = "\nhaving "; private String innerJoin = "\ninner join "; private String insertInto = "insert into "; private String join = "\njoin "; private String key = "key"; private String leftJoin = "\nleft join "; private String rightJoin = "\nright join "; private String limitTemplate = "\nlimit {0}"; private String mergeInto = "merge into "; private boolean nativeMerge; private String notNull = " not null"; private String offsetTemplate = "\noffset {0}"; private String on = "\non "; private String orderBy = "\norder by "; private String select = "select "; private String selectDistinct = "select distinct "; private String set = "set "; private String tableAlias = " "; private String update = "update "; private String values = "\nvalues "; private String defaultValues = "\nvalues ()"; private String where = "\nwhere "; private String with = "with "; private String withRecursive = "with recursive "; private String createIndex = "create index "; private String createUniqueIndex = "create unique index "; private String nullsFirst = " nulls first"; private String nullsLast = " nulls last"; private boolean parameterMetadataAvailable = true; private boolean batchCountViaGetUpdateCount = false; private boolean unionsWrapped = true; private boolean functionJoinsWrapped = false; private boolean limitRequired = false; private boolean countDistinctMultipleColumns = false; private boolean countViaAnalytics = false; private boolean wrapSelectParameters = false; private boolean arraysSupported = true; private boolean forShareSupported = false; private int listMaxSize = 0; private boolean supportsUnquotedReservedWordsAsIdentifier = false; private int maxLimit = Integer.MAX_VALUE; private QueryFlag forShareFlag = new QueryFlag(Position.END, FOR_SHARE); private QueryFlag forUpdateFlag = new QueryFlag(Position.END, FOR_UPDATE); private QueryFlag noWaitFlag = new QueryFlag(Position.END, NO_WAIT); @Deprecated protected SQLTemplates(String quoteStr, char escape, boolean useQuotes) { this(SQL_RESERVED_WORDS, quoteStr, escape, useQuotes); } protected SQLTemplates(Set<String> reservedKeywords, String quoteStr, char escape, boolean useQuotes) { super(escape); this.reservedWords = reservedKeywords; this.quoteStr = quoteStr; this.useQuotes = useQuotes; add(SQLOps.ALL, "{0}.*"); // flags add(SQLOps.WITH_ALIAS, "{0} as {1}", 0); add(SQLOps.WITH_COLUMNS, "{0} {1}", 0); add(SQLOps.FOR_UPDATE, "\nfor update"); add(SQLOps.FOR_SHARE, "\nfor share"); add(SQLOps.NO_WAIT, " nowait"); add(SQLOps.QUALIFY, "\nqualify {0}"); // boolean add(Ops.AND, "{0} and {1}"); add(Ops.NOT, "not {0}", Precedence.NOT); add(Ops.OR, "{0} or {1}"); // math add(Ops.MathOps.RANDOM, "rand()"); add(Ops.MathOps.RANDOM2, "rand({0})"); add(Ops.MathOps.CEIL, "ceiling({0})"); add(Ops.MathOps.POWER, "power({0},{1})"); add(Ops.MOD, "mod({0},{1})", Precedence.HIGHEST); // date time add(Ops.DateTimeOps.CURRENT_DATE, "current_date"); add(Ops.DateTimeOps.CURRENT_TIME, "current_time"); add(Ops.DateTimeOps.CURRENT_TIMESTAMP, "current_timestamp"); add(Ops.DateTimeOps.MILLISECOND, "0"); add(Ops.DateTimeOps.SECOND, "extract(second from {0})"); add(Ops.DateTimeOps.MINUTE, "extract(minute from {0})"); add(Ops.DateTimeOps.HOUR, "extract(hour from {0})"); add(Ops.DateTimeOps.WEEK, "extract(week from {0})"); add(Ops.DateTimeOps.MONTH, "extract(month from {0})"); add(Ops.DateTimeOps.YEAR, "extract(year from {0})"); add(Ops.DateTimeOps.YEAR_MONTH, "extract(year from {0}) * 100 + extract(month from {0})", Precedence.ARITH_LOW); add(Ops.DateTimeOps.YEAR_WEEK, "extract(year from {0}) * 100 + extract(week from {0})", Precedence.ARITH_LOW); add(Ops.DateTimeOps.DAY_OF_WEEK, "extract(day_of_week from {0})"); add(Ops.DateTimeOps.DAY_OF_MONTH, "extract(day from {0})"); add(Ops.DateTimeOps.DAY_OF_YEAR, "extract(day_of_year from {0})"); add(Ops.DateTimeOps.ADD_YEARS, "dateadd('year',{1},{0})"); add(Ops.DateTimeOps.ADD_MONTHS, "dateadd('month',{1},{0})"); add(Ops.DateTimeOps.ADD_WEEKS, "dateadd('week',{1},{0})"); add(Ops.DateTimeOps.ADD_DAYS, "dateadd('day',{1},{0})"); add(Ops.DateTimeOps.ADD_HOURS, "dateadd('hour',{1},{0})"); add(Ops.DateTimeOps.ADD_MINUTES, "dateadd('minute',{1},{0})"); add(Ops.DateTimeOps.ADD_SECONDS, "dateadd('second',{1},{0})"); add(Ops.DateTimeOps.DIFF_YEARS, "datediff('year',{0},{1})"); add(Ops.DateTimeOps.DIFF_MONTHS, "datediff('month',{0},{1})"); add(Ops.DateTimeOps.DIFF_WEEKS, "datediff('week',{0},{1})"); add(Ops.DateTimeOps.DIFF_DAYS, "datediff('day',{0},{1})"); add(Ops.DateTimeOps.DIFF_HOURS, "datediff('hour',{0},{1})"); add(Ops.DateTimeOps.DIFF_MINUTES, "datediff('minute',{0},{1})"); add(Ops.DateTimeOps.DIFF_SECONDS, "datediff('second',{0},{1})"); add(Ops.DateTimeOps.TRUNC_YEAR, "date_trunc('year',{0})"); add(Ops.DateTimeOps.TRUNC_MONTH, "date_trunc('month',{0})"); add(Ops.DateTimeOps.TRUNC_WEEK, "date_trunc('week',{0})"); add(Ops.DateTimeOps.TRUNC_DAY, "date_trunc('day',{0})"); add(Ops.DateTimeOps.TRUNC_HOUR, "date_trunc('hour',{0})"); add(Ops.DateTimeOps.TRUNC_MINUTE, "date_trunc('minute',{0})"); add(Ops.DateTimeOps.TRUNC_SECOND, "date_trunc('second',{0})"); // string add(Ops.CONCAT, "{0} || {1}", Precedence.ARITH_LOW); add(Ops.MATCHES, "{0} regexp {1}", Precedence.COMPARISON); add(Ops.CHAR_AT, "cast(substr({0},{1s}+1,1) as char)"); add(Ops.EQ_IGNORE_CASE, "{0l} = {1l}"); add(Ops.INDEX_OF, "locate({1},{0})-1", Precedence.ARITH_LOW); add(Ops.INDEX_OF_2ARGS, "locate({1},{0},{2s}+1)-1", Precedence.ARITH_LOW); add(Ops.STRING_IS_EMPTY, "length({0}) = 0"); add(Ops.SUBSTR_1ARG, "substr({0},{1s}+1)", Precedence.ARITH_LOW); add(Ops.SUBSTR_2ARGS, "substr({0},{1s}+1,{2s}-{1s})", Precedence.ARITH_LOW); add(Ops.StringOps.LOCATE, "locate({0},{1})"); add(Ops.StringOps.LOCATE2, "locate({0},{1},{2})"); // like with escape add(Ops.LIKE, "{0} like {1} escape '" + escape + "'", Precedence.COMPARISON); add(Ops.ENDS_WITH, "{0} like {%1} escape '" + escape + "'", Precedence.COMPARISON); add(Ops.ENDS_WITH_IC, "{0l} like {%%1} escape '" + escape + "'", Precedence.COMPARISON); add(Ops.STARTS_WITH, "{0} like {1%} escape '" + escape + "'", Precedence.COMPARISON); add(Ops.STARTS_WITH_IC, "{0l} like {1%%} escape '" + escape + "'", Precedence.COMPARISON); add(Ops.STRING_CONTAINS, "{0} like {%1%} escape '" + escape + "'", Precedence.COMPARISON); add(Ops.STRING_CONTAINS_IC, "{0l} like {%%1%%} escape '" + escape + "'", Precedence.COMPARISON); add(SQLOps.CAST, "cast({0} as {1s})"); add(SQLOps.UNION, "{0}\nunion\n{1}", Precedence.OR + 1); add(SQLOps.UNION_ALL, "{0}\nunion all\n{1}", Precedence.OR + 1); add(SQLOps.NEXTVAL, "nextval('{0s}')"); // analytic functions add(SQLOps.CORR, "corr({0},{1})"); add(SQLOps.COVARPOP, "covar_pop({0},{1})"); add(SQLOps.COVARSAMP, "covar_samp({0},{1})"); add(SQLOps.CUMEDIST, "cume_dist()"); add(SQLOps.CUMEDIST2, "cume_dist({0})"); add(SQLOps.DENSERANK, "dense_rank()"); add(SQLOps.DENSERANK2, "dense_rank({0})"); add(SQLOps.FIRSTVALUE, "first_value({0})"); add(SQLOps.LAG, "lag({0})"); add(SQLOps.LASTVALUE, "last_value({0})"); add(SQLOps.LEAD, "lead({0})"); add(SQLOps.LISTAGG, "listagg({0},'{1s}')"); add(SQLOps.NTHVALUE, "nth_value({0}, {1})"); add(SQLOps.NTILE, "ntile({0})"); add(SQLOps.PERCENTILECONT, "percentile_cont({0})"); add(SQLOps.PERCENTILEDISC, "percentile_disc({0})"); add(SQLOps.PERCENTRANK, "percent_rank()"); add(SQLOps.PERCENTRANK2, "percent_rank({0})"); add(SQLOps.RANK, "rank()"); add(SQLOps.RANK2, "rank({0})"); add(SQLOps.RATIOTOREPORT, "ratio_to_report({0})"); add(SQLOps.REGR_SLOPE, "regr_slope({0}, {1})"); add(SQLOps.REGR_INTERCEPT, "regr_intercept({0}, {1})"); add(SQLOps.REGR_COUNT, "regr_count({0}, {1})"); add(SQLOps.REGR_R2, "regr_r2({0}, {1})"); add(SQLOps.REGR_AVGX, "regr_avgx({0}, {1})"); add(SQLOps.REGR_AVGY, "regr_avgy({0}, {1})"); add(SQLOps.REGR_SXX, "regr_sxx({0}, {1})"); add(SQLOps.REGR_SYY, "regr_syy({0}, {1})"); add(SQLOps.REGR_SXY, "regr_sxy({0}, {1})"); add(SQLOps.ROWNUMBER, "row_number()"); add(SQLOps.STDDEV, "stddev({0})"); add(SQLOps.STDDEVPOP, "stddev_pop({0})"); add(SQLOps.STDDEVSAMP, "stddev_samp({0})"); add(SQLOps.STDDEV_DISTINCT, "stddev(distinct {0})"); add(SQLOps.VARIANCE, "variance({0})"); add(SQLOps.VARPOP, "var_pop({0})"); add(SQLOps.VARSAMP, "var_samp({0})"); add(Ops.AggOps.BOOLEAN_ANY, "some({0})"); add(Ops.AggOps.BOOLEAN_ALL, "every({0})"); // default type names addTypeNameToCode("null", Types.NULL); addTypeNameToCode("char", Types.CHAR); addTypeNameToCode("datalink", Types.DATALINK); addTypeNameToCode("numeric", Types.NUMERIC); addTypeNameToCode("decimal", Types.DECIMAL); addTypeNameToCode("integer", Types.INTEGER); addTypeNameToCode("smallint", Types.SMALLINT); addTypeNameToCode("float", Types.FLOAT); addTypeNameToCode("real", Types.REAL); addTypeNameToCode("double", Types.DOUBLE); addTypeNameToCode("varchar", Types.VARCHAR); addTypeNameToCode("longnvarchar", Types.LONGNVARCHAR); addTypeNameToCode("nchar", Types.NCHAR); addTypeNameToCode("boolean", Types.BOOLEAN); addTypeNameToCode("nvarchar", Types.NVARCHAR); addTypeNameToCode("rowid", Types.ROWID); addTypeNameToCode("timestamp", Types.TIMESTAMP); addTypeNameToCode("timestamp", TIMESTAMP_WITH_TIMEZONE); addTypeNameToCode("bit", Types.BIT); addTypeNameToCode("time", Types.TIME); addTypeNameToCode("time", TIME_WITH_TIMEZONE); addTypeNameToCode("tinyint", Types.TINYINT); addTypeNameToCode("other", Types.OTHER); addTypeNameToCode("bigint", Types.BIGINT); addTypeNameToCode("longvarbinary", Types.LONGVARBINARY); addTypeNameToCode("varbinary", Types.VARBINARY); addTypeNameToCode("date", Types.DATE); addTypeNameToCode("binary", Types.BINARY); addTypeNameToCode("longvarchar", Types.LONGVARCHAR); addTypeNameToCode("struct", Types.STRUCT); addTypeNameToCode("array", Types.ARRAY); addTypeNameToCode("java_object", Types.JAVA_OBJECT); addTypeNameToCode("distinct", Types.DISTINCT); addTypeNameToCode("ref", Types.REF); addTypeNameToCode("blob", Types.BLOB); addTypeNameToCode("clob", Types.CLOB); addTypeNameToCode("nclob", Types.NCLOB); addTypeNameToCode("sqlxml", Types.SQLXML); } public String serialize(String literal, int jdbcType) { switch (jdbcType) { case Types.TIMESTAMP: case TIMESTAMP_WITH_TIMEZONE: return "(timestamp '" + literal + "')"; case Types.DATE: return "(date '" + literal + "')"; case Types.TIME: case TIME_WITH_TIMEZONE: return "(time '" + literal + "')"; case Types.CHAR: case Types.CLOB: case Types.LONGNVARCHAR: case Types.LONGVARCHAR: case Types.NCHAR: case Types.NCLOB: case Types.NVARCHAR: case Types.VARCHAR: return "'" + escapeLiteral(literal) + "'"; case Types.BIGINT: case Types.BIT: case Types.BOOLEAN: case Types.DECIMAL: case Types.DOUBLE: case Types.FLOAT: case Types.INTEGER: case Types.NULL: case Types.NUMERIC: case Types.SMALLINT: case Types.TINYINT: return literal; default: // for other JDBC types the Type instance is expected to provide // the necessary quoting return literal; } } public String escapeLiteral(String str) { StringBuilder builder = new StringBuilder(); for (char ch : str.toCharArray()) { if (ch == '\'') { builder.append("''"); continue; } builder.append(ch); } return builder.toString(); } protected void addTypeNameToCode(String type, int code, boolean override) { if (!typeNameToCode.containsKey(type)) { typeNameToCode.put(type, code); } if (override || !codeToTypeName.containsKey(code)) { codeToTypeName.put(code, type); } } protected void addTypeNameToCode(String type, int code) { addTypeNameToCode(type, code, false); } protected void addTableOverride(SchemaAndTable from, SchemaAndTable to) { tableOverrides.put(from, to); } public final List<Type<?>> getCustomTypes() { return customTypes; } public final String getAsc() { return asc; } public final String getAutoIncrement() { return autoIncrement; } public final String getColumnAlias() { return columnAlias; } public final String getCount() { return count; } public final String getCountStar() { return countStar; } public final String getDelete() { return delete; } public final String getDesc() { return desc; } public final String getDistinctCountEnd() { return distinctCountEnd; } public final String getDistinctCountStart() { return distinctCountStart; } public final String getDummyTable() { return dummyTable; } public final String getFrom() { return from; } public final String getFullJoin() { return fullJoin; } public final String getGroupBy() { return groupBy; } public final String getHaving() { return having; } public final String getInnerJoin() { return innerJoin; } public final String getInsertInto() { return insertInto; } public final String getJoin() { return join; } public final String getJoinSymbol(JoinType joinType) { switch (joinType) { case JOIN: return join; case INNERJOIN: return innerJoin; case FULLJOIN: return fullJoin; case LEFTJOIN: return leftJoin; case RIGHTJOIN: return rightJoin; default: return ", "; } } public final String getKey() { return key; } public final String getLeftJoin() { return leftJoin; } public final String getRightJoin() { return rightJoin; } public final String getLimitTemplate() { return limitTemplate; } public final String getMergeInto() { return mergeInto; } public final String getNotNull() { return notNull; } public final String getOffsetTemplate() { return offsetTemplate; } public final String getOn() { return on; } public final String getOrderBy() { return orderBy; } public final String getSelect() { return select; } public final String getSelectDistinct() { return selectDistinct; } public final String getSet() { return set; } public final String getTableAlias() { return tableAlias; } public final Map<SchemaAndTable, SchemaAndTable> getTableOverrides() { return tableOverrides; } public String getTypeNameForCode(int code) { return codeToTypeName.get(code); } public String getCastTypeNameForCode(int code) { return getTypeNameForCode(code); } public Integer getCodeForTypeName(String type) { return typeNameToCode.get(type); } public final String getUpdate() { return update; } public final String getValues() { return values; } public final String getDefaultValues() { return defaultValues; } public final String getWhere() { return where; } public final boolean isNativeMerge() { return nativeMerge; } public final boolean isSupportsAlias() { return true; } public final String getCreateIndex() { return createIndex; } public final String getCreateUniqueIndex() { return createUniqueIndex; } public final String getCreateTable() { return createTable; } public final String getWith() { return with; } public final String getWithRecursive() { return withRecursive; } public final boolean isCountDistinctMultipleColumns() { return countDistinctMultipleColumns; } public final boolean isPrintSchema() { return printSchema; } public final boolean isParameterMetadataAvailable() { return parameterMetadataAvailable; } public final boolean isBatchCountViaGetUpdateCount() { return batchCountViaGetUpdateCount; } public final boolean isUseQuotes() { return useQuotes; } public final boolean isUnionsWrapped() { return unionsWrapped; } public boolean isForShareSupported() { return forShareSupported; } public final boolean isFunctionJoinsWrapped() { return functionJoinsWrapped; } public final boolean isLimitRequired() { return limitRequired; } public final String getNullsFirst() { return nullsFirst; } public final String getNullsLast() { return nullsLast; } public final boolean isCountViaAnalytics() { return countViaAnalytics; } public final boolean isWrapSelectParameters() { return wrapSelectParameters; } public final boolean isArraysSupported() { return arraysSupported; } public final int getListMaxSize() { return listMaxSize; } public final boolean isSupportsUnquotedReservedWordsAsIdentifier() { return supportsUnquotedReservedWordsAsIdentifier; } public final QueryFlag getForShareFlag() { return forShareFlag; } public final QueryFlag getForUpdateFlag() { return forUpdateFlag; } public final QueryFlag getNoWaitFlag() { return noWaitFlag; } protected void newLineToSingleSpace() { for (Class<?> cl : Arrays.<Class<?>>asList(getClass(), SQLTemplates.class)) { for (Field field : cl.getDeclaredFields()) { try { if (field.getType().equals(String.class)) { field.setAccessible(true); Object val = field.get(this); if (val != null) { field.set(this, val.toString().replace('\n',' ')); } } } catch (IllegalAccessException e) { throw new QueryException(e.getMessage(), e); } } } } public final String quoteIdentifier(String identifier) { return quoteIdentifier(identifier, false); } public final String quoteIdentifier(String identifier, boolean precededByDot) { if (useQuotes || requiresQuotes(identifier, precededByDot)) { return quoteStr + identifier + quoteStr; } else { return identifier; } } protected boolean requiresQuotes(final String identifier, final boolean precededByDot) { if (NON_UNDERSCORE_ALPHA_NUMERIC.matchesAnyOf(identifier)) { return true; } else if (NON_UNDERSCORE_ALPHA.matches(identifier.charAt(0))) { return true; } else if (precededByDot && supportsUnquotedReservedWordsAsIdentifier) { return false; } else { return isReservedWord(identifier); } } private boolean isReservedWord(String identifier) { return reservedWords.contains(identifier.toUpperCase()); } /** * template method for SELECT serialization * * @param metadata * @param forCountRow * @param context */ public void serialize(QueryMetadata metadata, boolean forCountRow, SQLSerializer context) { context.serializeForQuery(metadata, forCountRow); if (!metadata.getFlags().isEmpty()) { context.serialize(Position.END, metadata.getFlags()); } } /** * template method for DELETE serialization * * @param metadata * @param entity * @param context */ public void serializeDelete(QueryMetadata metadata, RelationalPath<?> entity, SQLSerializer context) { context.serializeForDelete(metadata, entity); // limit if (metadata.getModifiers().isRestricting()) { serializeModifiers(metadata, context); } if (!metadata.getFlags().isEmpty()) { context.serialize(Position.END, metadata.getFlags()); } } /** * template method for INSERT serialization * * @param metadata * @param entity * @param columns * @param values * @param subQuery * @param context */ public void serializeInsert(QueryMetadata metadata, RelationalPath<?> entity, List<Path<?>> columns, List<Expression<?>> values, SubQueryExpression<?> subQuery, SQLSerializer context) { context.serializeForInsert(metadata, entity, columns, values, subQuery); if (!metadata.getFlags().isEmpty()) { context.serialize(Position.END, metadata.getFlags()); } } /** * template method for MERGE serialization * * @param metadata * @param entity * @param keys * @param columns * @param values * @param subQuery * @param context */ public void serializeMerge(QueryMetadata metadata, RelationalPath<?> entity, List<Path<?>> keys, List<Path<?>> columns, List<Expression<?>> values, SubQueryExpression<?> subQuery, SQLSerializer context) { context.serializeForMerge(metadata, entity, keys, columns, values, subQuery); if (!metadata.getFlags().isEmpty()) { context.serialize(Position.END, metadata.getFlags()); } } /** * template method for UPDATE serialization * * @param metadata * @param entity * @param updates * @param context */ public void serializeUpdate(QueryMetadata metadata, RelationalPath<?> entity, Map<Path<?>, Expression<?>> updates, SQLSerializer context) { context.serializeForUpdate(metadata, entity, updates); // limit if (metadata.getModifiers().isRestricting()) { serializeModifiers(metadata, context); } if (!metadata.getFlags().isEmpty()) { context.serialize(Position.END, metadata.getFlags()); } } /** * template method for LIMIT and OFFSET serialization * * @param metadata * @param context */ protected void serializeModifiers(QueryMetadata metadata, SQLSerializer context) { QueryModifiers mod = metadata.getModifiers(); if (mod.getLimit() != null) { context.handle(limitTemplate, mod.getLimit()); } else if (limitRequired) { context.handle(limitTemplate, maxLimit); } if (mod.getOffset() != null) { context.handle(offsetTemplate, mod.getOffset()); } } protected void addCustomType(Type<?> type) { customTypes.add(type); } protected void setAsc(String asc) { this.asc = asc; } protected void setAutoIncrement(String autoIncrement) { this.autoIncrement = autoIncrement; } protected void setColumnAlias(String columnAlias) { this.columnAlias = columnAlias; } protected void setCount(String count) { this.count = count; } protected void setCountStar(String countStar) { this.countStar = countStar; } protected void setDelete(String delete) { this.delete = delete; } protected void setDesc(String desc) { this.desc = desc; } protected void setDistinctCountEnd(String distinctCountEnd) { this.distinctCountEnd = distinctCountEnd; } protected void setDistinctCountStart(String distinctCountStart) { this.distinctCountStart = distinctCountStart; } protected void setDummyTable(String dummyTable) { this.dummyTable = dummyTable; } protected void setForShareSupported(boolean forShareSupported) { this.forShareSupported = forShareSupported; } protected void setFrom(String from) { this.from = from; } protected void setFullJoin(String fullJoin) { this.fullJoin = fullJoin; } protected void setGroupBy(String groupBy) { this.groupBy = groupBy; } protected void setHaving(String having) { this.having = having; } protected void setInnerJoin(String innerJoin) { this.innerJoin = innerJoin; } protected void setInsertInto(String insertInto) { this.insertInto = insertInto; } protected void setJoin(String join) { this.join = join; } protected void setKey(String key) { this.key = key; } protected void setLeftJoin(String leftJoin) { this.leftJoin = leftJoin; } protected void setRightJoin(String rightJoin) { this.rightJoin = rightJoin; } protected void setMergeInto(String mergeInto) { this.mergeInto = mergeInto; } protected void setNativeMerge(boolean nativeMerge) { this.nativeMerge = nativeMerge; } protected void setNotNull(String notNull) { this.notNull = notNull; } protected void setOffsetTemplate(String offsetTemplate) { this.offsetTemplate = offsetTemplate; } protected void setOn(String on) { this.on = on; } protected void setOrderBy(String orderBy) { this.orderBy = orderBy; } protected void setSelect(String select) { this.select = select; } protected void setSelectDistinct(String selectDistinct) { this.selectDistinct = selectDistinct; } protected void setSet(String set) { this.set = set; } protected void setTableAlias(String tableAlias) { this.tableAlias = tableAlias; } protected void setUpdate(String update) { this.update = update; } protected void setValues(String values) { this.values = values; } protected void setDefaultValues(String defaultValues) { this.defaultValues = defaultValues; } protected void setWhere(String where) { this.where = where; } protected void setWith(String with) { this.with = with; } protected void setWithRecursive(String withRecursive) { this.withRecursive = withRecursive; } protected void setCreateIndex(String createIndex) { this.createIndex = createIndex; } protected void setCreateUniqueIndex(String createUniqueIndex) { this.createUniqueIndex = createUniqueIndex; } protected void setCreateTable(String createTable) { this.createTable = createTable; } protected void setPrintSchema(boolean printSchema) { this.printSchema = printSchema; } protected void setParameterMetadataAvailable(boolean parameterMetadataAvailable) { this.parameterMetadataAvailable = parameterMetadataAvailable; } protected void setBatchCountViaGetUpdateCount(boolean batchCountViaGetUpdateCount) { this.batchCountViaGetUpdateCount = batchCountViaGetUpdateCount; } protected void setUnionsWrapped(boolean unionsWrapped) { this.unionsWrapped = unionsWrapped; } protected void setFunctionJoinsWrapped(boolean functionJoinsWrapped) { this.functionJoinsWrapped = functionJoinsWrapped; } protected void setNullsFirst(String nullsFirst) { this.nullsFirst = nullsFirst; } protected void setNullsLast(String nullsLast) { this.nullsLast = nullsLast; } protected void setLimitRequired(boolean limitRequired) { this.limitRequired = limitRequired; } protected void setCountDistinctMultipleColumns(boolean countDistinctMultipleColumns) { this.countDistinctMultipleColumns = countDistinctMultipleColumns; } protected void setCountViaAnalytics(boolean countViaAnalytics) { this.countViaAnalytics = countViaAnalytics; } protected void setWrapSelectParameters(boolean b) { this.wrapSelectParameters = b; } protected void setArraysSupported(boolean b) { this.arraysSupported = b; } protected void setListMaxSize(int i) { listMaxSize = i; } protected void setSupportsUnquotedReservedWordsAsIdentifier(boolean b) { this.supportsUnquotedReservedWordsAsIdentifier = b; } protected void setMaxLimit(int i) { this.maxLimit = i; } protected void setForShareFlag(QueryFlag flag) { forShareFlag = flag; } protected void setForUpdateFlag(QueryFlag flag) { forUpdateFlag = flag; } protected void setNoWaitFlag(QueryFlag flag) { noWaitFlag = flag; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.distributed.test; import java.net.InetAddress; import java.util.Collections; import com.google.common.collect.ImmutableMap; import org.junit.Assert; import org.junit.Test; import org.apache.cassandra.distributed.Cluster; import org.apache.cassandra.distributed.api.Feature; public class InternodeEncryptionOptionsTest extends AbstractEncryptionOptionsImpl { @Test public void nodeWillNotStartWithBadKeystoreTest() throws Throwable { try (Cluster cluster = builder().withNodes(1).withConfig(c -> { c.with(Feature.NETWORK); c.set("server_encryption_options", ImmutableMap.of("optional", true, "keystore", "/path/to/bad/keystore/that/should/not/exist", "truststore", "/path/to/bad/truststore/that/should/not/exist")); }).createWithoutStarting()) { assertCannotStartDueToConfigurationException(cluster); } } @Test public void legacySslPortProvidedWithEncryptionNoneWillNotStartTest() throws Throwable { try (Cluster cluster = builder().withNodes(1).withConfig(c -> { c.with(Feature.NETWORK); c.set("ssl_storage_port", 7013); c.set("server_encryption_options", ImmutableMap.builder().putAll(validKeystore) .put("internode_encryption", "none") .put("optional", false) .put("legacy_ssl_storage_port_enabled", "true") .build()); }).createWithoutStarting()) { assertCannotStartDueToConfigurationException(cluster); } } @Test public void optionalTlsConnectionDisabledWithoutKeystoreTest() throws Throwable { try (Cluster cluster = builder().withNodes(1).withConfig(c -> c.with(Feature.NETWORK)).createWithoutStarting()) { InetAddress address = cluster.get(1).config().broadcastAddress().getAddress(); int port = cluster.get(1).config().broadcastAddress().getPort(); TlsConnection tlsConnection = new TlsConnection(address.getHostAddress(), port); tlsConnection.assertCannotConnect(); cluster.startup(); Assert.assertEquals("TLS connection should not be possible without keystore", ConnectResult.FAILED_TO_NEGOTIATE, tlsConnection.connect()); } } @Test public void optionalTlsConnectionAllowedWithKeystoreTest() throws Throwable { try (Cluster cluster = builder().withNodes(1).withConfig(c -> { c.with(Feature.NETWORK); c.set("server_encryption_options", validKeystore); }).createWithoutStarting()) { InetAddress address = cluster.get(1).config().broadcastAddress().getAddress(); int port = cluster.get(1).config().broadcastAddress().getPort(); TlsConnection tlsConnection = new TlsConnection(address.getHostAddress(), port); tlsConnection.assertCannotConnect(); cluster.startup(); Assert.assertEquals("TLS connection should be possible with keystore by default", ConnectResult.NEGOTIATED, tlsConnection.connect()); } } @Test public void optionalTlsConnectionAllowedToStoragePortTest() throws Throwable { try (Cluster cluster = builder().withNodes(1).withConfig(c -> { c.with(Feature.NETWORK); c.set("storage_port", 7012); c.set("ssl_storage_port", 7013); c.set("server_encryption_options", ImmutableMap.builder().putAll(validKeystore) .put("internode_encryption", "none") .put("optional", true) .put("legacy_ssl_storage_port_enabled", "true") .build()); }).createWithoutStarting()) { InetAddress address = cluster.get(1).config().broadcastAddress().getAddress(); int regular_port = (int) cluster.get(1).config().get("storage_port"); int ssl_port = (int) cluster.get(1).config().get("ssl_storage_port"); // Create the connections and prove they cannot connect before server start TlsConnection connectToRegularPort = new TlsConnection(address.getHostAddress(), regular_port); connectToRegularPort.assertCannotConnect(); TlsConnection connectToSslStoragePort = new TlsConnection(address.getHostAddress(), ssl_port); connectToSslStoragePort.assertCannotConnect(); cluster.startup(); Assert.assertEquals("TLS native connection should be possible to ssl_storage_port", ConnectResult.NEGOTIATED, connectToSslStoragePort.connect()); Assert.assertEquals("TLS native connection should be possible with valid keystore by default", ConnectResult.NEGOTIATED, connectToRegularPort.connect()); } } @Test public void legacySslStoragePortEnabledWithSameRegularAndSslPortTest() throws Throwable { try (Cluster cluster = builder().withNodes(1).withConfig(c -> { c.with(Feature.NETWORK); c.set("storage_port", 7012); // must match in-jvm dtest assigned ports c.set("ssl_storage_port", 7012); c.set("server_encryption_options", ImmutableMap.builder().putAll(validKeystore) .put("internode_encryption", "none") .put("optional", true) .put("legacy_ssl_storage_port_enabled", "true") .build()); }).createWithoutStarting()) { InetAddress address = cluster.get(1).config().broadcastAddress().getAddress(); int ssl_port = (int) cluster.get(1).config().get("ssl_storage_port"); // Create the connections and prove they cannot connect before server start TlsConnection connectToSslStoragePort = new TlsConnection(address.getHostAddress(), ssl_port); connectToSslStoragePort.assertCannotConnect(); cluster.startup(); Assert.assertEquals("TLS native connection should be possible to ssl_storage_port", ConnectResult.NEGOTIATED, connectToSslStoragePort.connect()); } } @Test public void tlsConnectionRejectedWhenUnencrypted() throws Throwable { try (Cluster cluster = builder().withNodes(1).withConfig(c -> { c.with(Feature.NETWORK); c.set("server_encryption_options", ImmutableMap.builder().putAll(validKeystore) .put("internode_encryption", "none") .put("optional", false) .build()); }).createWithoutStarting()) { InetAddress address = cluster.get(1).config().broadcastAddress().getAddress(); int regular_port = (int) cluster.get(1).config().get("storage_port"); // Create the connections and prove they cannot connect before server start TlsConnection connection = new TlsConnection(address.getHostAddress(), regular_port); connection.assertCannotConnect(); cluster.startup(); Assert.assertEquals("TLS native connection should be possible with valid keystore by default", ConnectResult.FAILED_TO_NEGOTIATE, connection.connect()); } } @Test public void allInternodeEncryptionEstablishedTest() throws Throwable { try (Cluster cluster = builder().withNodes(2).withConfig(c -> { c.with(Feature.NETWORK) .with(Feature.GOSSIP) // To make sure AllMembersAliveMonitor checks gossip (which uses internode conns) .with(Feature.NATIVE_PROTOCOL); // For virtual tables c.set("server_encryption_options", ImmutableMap.builder().putAll(validKeystore) .put("internode_encryption", "all") .build()); }).start()) { // Just check startup - cluster should not be able to establish internode connections xwithout encrypted connections for (int i = 1; i <= cluster.size(); i++) { Object[][] result = cluster.get(i).executeInternal("SELECT successful_connection_attempts, address, port FROM system_views.internode_outbound"); Assert.assertEquals(1, result.length); long successfulConnectionAttempts = (long) result[0][0]; Assert.assertTrue("At least one connection: " + successfulConnectionAttempts, successfulConnectionAttempts > 0); } } } @Test public void negotiatedProtocolMustBeAcceptedProtocolTest() throws Throwable { try (Cluster cluster = builder().withNodes(1).withConfig(c -> { c.with(Feature.NETWORK); c.set("server_encryption_options", ImmutableMap.builder().putAll(validKeystore) .put("internode_encryption", "all") .put("accepted_protocols", Collections.singletonList("TLSv1.1")) .build()); }).start()) { InetAddress address = cluster.get(1).config().broadcastAddress().getAddress(); int port = cluster.get(1).config().broadcastAddress().getPort(); TlsConnection tls10Connection = new TlsConnection(address.getHostAddress(), port, Collections.singletonList("TLSv1")); Assert.assertEquals("Should not be possible to establish a TLSv1 connection", ConnectResult.FAILED_TO_NEGOTIATE, tls10Connection.connect()); tls10Connection.assertReceivedHandshakeException(); TlsConnection tls11Connection = new TlsConnection(address.getHostAddress(), port, Collections.singletonList("TLSv1.1")); Assert.assertEquals("Should be possible to establish a TLSv1.1 connection", ConnectResult.NEGOTIATED, tls11Connection.connect()); Assert.assertEquals("TLSv1.1", tls11Connection.lastProtocol()); TlsConnection tls12Connection = new TlsConnection(address.getHostAddress(), port, Collections.singletonList("TLSv1.2")); Assert.assertEquals("Should not be possible to establish a TLSv1.2 connection", ConnectResult.FAILED_TO_NEGOTIATE, tls12Connection.connect()); tls12Connection.assertReceivedHandshakeException(); } } @Test public void connectionCannotAgreeOnClientAndServer() throws Throwable { try (Cluster cluster = builder().withNodes(1).withConfig(c -> { c.with(Feature.NETWORK); c.set("server_encryption_options", ImmutableMap.builder().putAll(validKeystore) .put("internode_encryption", "all") .put("accepted_protocols", Collections.singletonList("TLSv1.2")) .put("cipher_suites", Collections.singletonList("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384")) .build()); }).start()) { InetAddress address = cluster.get(1).config().broadcastAddress().getAddress(); int port = cluster.get(1).config().broadcastAddress().getPort(); TlsConnection connection = new TlsConnection(address.getHostAddress(), port, Collections.singletonList("TLSv1.2"), Collections.singletonList("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256")); Assert.assertEquals("Should not be possible to establish a TLSv1.2 connection with different ciphers", ConnectResult.FAILED_TO_NEGOTIATE, connection.connect()); connection.assertReceivedHandshakeException(); } } @Test public void nodeMustNotStartWithNonExistantProtocol() throws Throwable { try (Cluster cluster = builder().withNodes(1).withConfig(c -> { c.with(Feature.NETWORK); c.set("server_encryption_options", ImmutableMap.<String,Object>builder().putAll(nonExistantProtocol) .put("internode_encryption", "all").build()); }).createWithoutStarting()) { assertCannotStartDueToConfigurationException(cluster); } } @Test public void nodeMustNotStartWithNonExistantCipher() throws Throwable { try (Cluster cluster = builder().withNodes(1).withConfig(c -> { c.with(Feature.NETWORK); c.set("server_encryption_options", ImmutableMap.<String,Object>builder().putAll(nonExistantCipher) .put("internode_encryption", "all").build()); }).createWithoutStarting()) { assertCannotStartDueToConfigurationException(cluster); } } }
/******************************************************************************* * Copyright 2016 Jalian Systems Pvt. Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package net.sourceforge.marathon.resource; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; import java.util.logging.Logger; import java.util.stream.Collectors; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Platform; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.event.EventHandler; import javafx.event.EventType; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonType; import javafx.scene.control.ContextMenu; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.SelectionMode; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.control.TreeCell; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.input.Clipboard; import javafx.scene.input.ClipboardContent; import javafx.scene.input.DataFormat; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.input.TransferMode; import javafx.util.Callback; import javafx.util.Duration; import net.sourceforge.marathon.display.MarathonFileChooserInfo; import net.sourceforge.marathon.fx.api.FXUIUtils; import net.sourceforge.marathon.resource.navigator.FileResource; import net.sourceforge.marathon.resource.navigator.FolderResource; public class ResourceView extends TreeView<Resource> implements IResourceChangeListener { public static final Logger LOGGER = Logger.getLogger(ResourceView.class.getName()); private IResourceActionHandler handler; private Operation clipboardOperation; private ContextMenu contextMenu = new ContextMenu(); private IResourceActionSource source; private ArrayList<TreeItem<Resource>> draggedItems; public enum Operation { COPY, CUT; Operation() { } }; private final class TextFieldTreeCellImpl extends TreeCell<Resource> { private TextField textField; private Timeline dragTimeline; public TextFieldTreeCellImpl() { addEventHandler(KeyEvent.KEY_RELEASED, (event) -> { if (event.getCode() == KeyCode.F2) { startEdit(); } }); addEventFilter(MouseEvent.MOUSE_PRESSED, (e) -> { TreeItem<Resource> treeItem = getTreeItem(); if (e.getButton() != MouseButton.PRIMARY || e.isShiftDown() || e.isControlDown() || e.isMetaDown() || e.getClickCount() != 2) { return; } if (e.getClickCount() == 2 && treeItem != null && treeItem.isLeaf() && treeItem.getValue().canOpen()) { e.consume(); if (isEditing()) { cancelEdit(); } if (e.isAltDown()) { handler.openWithSystem(source, treeItem.getValue()); } else { handler.open(source, treeItem.getValue()); } } }); setOnDragDetected((e) -> { ObservableList<TreeItem<Resource>> selectedItems = getTreeView().getSelectionModel().getSelectedItems(); ClipboardContent content = new ClipboardContent(); for (TreeItem<Resource> treeItem : selectedItems) { treeItem.getValue().copy(content); } TransferMode[] mode = TransferMode.COPY_OR_MOVE; if (org.openqa.selenium.Platform.getCurrent().is(org.openqa.selenium.Platform.MAC)) { if (e.isAltDown()) { mode = new TransferMode[] { TransferMode.COPY }; } else { mode = new TransferMode[] { TransferMode.MOVE }; } } Dragboard db = startDragAndDrop(mode); db.setContent(content); draggedItems = new ArrayList<>(selectedItems); }); setOnDragEntered((e) -> { setStyle("-fx-background-color:aliceblue;"); dragTimeline = new Timeline(new KeyFrame(Duration.millis(1500), ae -> { if (dragTimeline != null && getItem() != null && !getItem().isExpanded() && !getItem().isLeaf()) { Timeline flasher = new Timeline(new KeyFrame(Duration.seconds(0.1), x -> { setStyle("-fx-background-color:yellow;"); }), new KeyFrame(Duration.seconds(0.2), x -> { setStyle(""); })); flasher.setCycleCount(5); flasher.play(); flasher.setOnFinished(x -> { if (dragTimeline != null) { getItem().setExpanded(true); } setStyle(""); }); } })); dragTimeline.play(); }); setOnDragExited((e) -> { dragTimeline.stop(); dragTimeline = null; setStyle(""); }); setOnDragDropped((e) -> { Resource resource = getItem(); Dragboard dragboard = e.getDragboard(); Operation operation = Operation.COPY; if (e.getTransferMode() == TransferMode.MOVE) { operation = Operation.CUT; } resource.pasteInto(dragboard, operation); e.setDropCompleted(true); }); setOnDragOver((e) -> { Resource resource = getItem(); if (resource != null && resource.droppable(e.getDragboard())) { e.acceptTransferModes(TransferMode.COPY_OR_MOVE); } }); setOnDragDone((e) -> { if (e.getTransferMode() == TransferMode.MOVE) { completeMove(); } }); } @Override public void startEdit() { Resource resource = getItem(); if (resource == null || !resource.canRename()) { return; } super.startEdit(); if (textField == null) { createTextField(); } textField.setText(getString()); setText(null); setGraphic(textField); textField.selectAll(); textField.requestFocus(); } @Override public void cancelEdit() { super.cancelEdit(); if (getItem() != null) { setText(getItem().getName()); } if (getTreeItem() != null) { setGraphic(getTreeItem().getGraphic()); } } @Override public void updateItem(Resource item, boolean empty) { super.updateItem(item, empty); if (empty) { setText(null); setGraphic(null); } else { if (isEditing()) { if (textField != null) { textField.setText(getString()); } setText(null); setGraphic(textField); } else { setText(getString()); setGraphic(getTreeItem().getGraphic()); String d = getTreeItem().getValue().getDescription(); if (d != null) { setTooltip(new Tooltip(d)); } } } } private void createTextField() { textField = new TextField(getString()); textField.setOnKeyReleased(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent t) { if (t.getCode() == KeyCode.ENTER) { Resource value = getTreeItem().getValue(); File file = new File(((FolderResource) value.getParent()).getFilePath().toFile(), textField.getText()); if (file.exists()) { FXUIUtils.showMessageDialog(null, "File " + file.getName() + " already exists", null, AlertType.ERROR); cancelEdit(); return; } Resource renamed = value.rename(textField.getText()); if (renamed != null) { commitEdit(renamed); Resource parent = (Resource) value.getParent(); if (parent != null) { int index = parent.getChildren().indexOf(value); parent.getChildren().remove(index); parent.getChildren().add(index, renamed); } } else { cancelEdit(); } } else if (t.getCode() == KeyCode.ESCAPE) { cancelEdit(); } } }); } private String getString() { return getItem() == null ? "" : getItem().toString(); } } public static class ResourceModificationEvent extends Event { private static final long serialVersionUID = -8307438128922036441L; public static final EventType<ResourceModificationEvent> ANY = new EventType<>(Event.ANY, "ResourceModificationEvent"); public static final EventType<ResourceModificationEvent> DELETE = new EventType<>(ANY, "ResourceDeleted"); public static final EventType<ResourceModificationEvent> UPDATE = new EventType<>(ANY, "ResourceUpdated"); public static final EventType<ResourceModificationEvent> MOVED = new EventType<>(ANY, "ResourceMoved"); public static final EventType<ResourceModificationEvent> COPIED = new EventType<>(ANY, "ResourceCopied"); private Resource to; private Resource from; private Resource resource; public ResourceModificationEvent(EventType<ResourceModificationEvent> eventType, Resource resource) { super(resource, resource, eventType); this.resource = resource; } public ResourceModificationEvent(EventType<ResourceModificationEvent> eventType, Resource from, Resource to) { super(from, to, eventType); this.from = from; this.to = to; } @Override public String toString() { return "ResourceModificationEvent [getTarget()=" + getTarget() + ", getEventType()=" + getEventType() + ", getSource()=" + getSource() + "]"; } public Resource getResource() { return resource; } public Resource getFrom() { return from; } public Resource getTo() { return to; } } public ResourceView(IResourceActionSource source, Resource root, IResourceActionHandler handler, IResourceChangeListener listener) { this.source = source; this.handler = handler; setEditable(true); setRoot(root); getRoot().addEventHandler(ResourceModificationEvent.ANY, (event) -> { if (event.getEventType() == ResourceModificationEvent.DELETE) { listener.deleted(source, event.getResource()); } if (event.getEventType() == ResourceModificationEvent.UPDATE) { listener.updated(source, event.getResource()); } if (event.getEventType() == ResourceModificationEvent.MOVED) { listener.moved(source, event.getFrom(), event.getTo()); } if (event.getEventType() == ResourceModificationEvent.COPIED) { listener.copied(source, event.getFrom(), event.getTo()); } }); setContextMenu(contextMenu); setContextMenuItems(); getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); getSelectionModel().getSelectedItems().addListener(new ListChangeListener<TreeItem<Resource>>() { @Override public void onChanged(Change<? extends TreeItem<Resource>> c) { setContextMenuItems(); } }); Callback<TreeView<Resource>, TreeCell<Resource>> value = new Callback<TreeView<Resource>, TreeCell<Resource>>() { @Override public TreeCell<Resource> call(TreeView<Resource> param) { return new TextFieldTreeCellImpl(); } }; setCellFactory(value); } private void expandTreeView(TreeItem<Resource> item) { if (item != null && !item.isLeaf()) { item.setExpanded(true); for (TreeItem<Resource> child : item.getChildren()) { expandTreeView(child); } } } private void collapseTreeView(TreeItem<?> item) { if (item != null && !item.isLeaf()) { item.setExpanded(false); for (TreeItem<?> child : item.getChildren()) { collapseTreeView(child); } } } public void setContextMenuItems() { contextMenu.getItems().clear(); MenuItem m; ObservableList<TreeItem<Resource>> selectedItems = getSelectionModel().getSelectedItems(); if (selectedItems.size() == 0) { return; } // Bug : selected items in the list are not properly indexed when the // selected items are unselected from top to bottom. @SuppressWarnings("unused") Resource i = (Resource) selectedItems.get(0); Resource item = (Resource) selectedItems.get(0); if (item != null && selectedItems.size() == 1 && (item instanceof FolderResource || item instanceof FileResource)) { m = new Menu("New"); m.setDisable(item == null || selectedItems.size() != 1); contextMenu.getItems().add(m); ObservableList<MenuItem> items = ((Menu) m).getItems(); m = FXUIUtils.createMenuItem("file", "New File", ""); m.setOnAction((event) -> newFile(item)); items.add(m); m = FXUIUtils.createMenuItem("fldr_closed", "New Folder", ""); m.setOnAction((event) -> newFolder(item)); items.add(m); } m = FXUIUtils.createMenuItem("open", "Open", ""); m.setDisable(item == null || !item.canOpen() || selectedItems.size() != 1); m.setOnAction((event) -> handler.open(source, item)); contextMenu.getItems().add(m); Menu mm = new Menu("Open With"); mm.setDisable(item == null || !item.canOpen() || selectedItems.size() != 1); m = FXUIUtils.createMenuItem("defaultEditor", "Default Editor", ""); m.setDisable(item == null || !item.canOpen() || selectedItems.size() != 1); m.setOnAction((event) -> handler.open(source, item)); mm.getItems().add(m); m = FXUIUtils.createMenuItem("textEditor", "Text Editor", ""); m.setDisable(item == null || !item.canOpen() || selectedItems.size() != 1); m.setOnAction((event) -> handler.openAsText(source, item)); mm.getItems().add(m); m = FXUIUtils.createMenuItem("systemEditor", "System Editor", ""); m.setDisable(item == null || !item.canOpen() || selectedItems.size() != 1); m.setOnAction((event) -> handler.openWithSystem(source, item)); mm.getItems().add(m); contextMenu.getItems().add(mm); contextMenu.getItems().add(new SeparatorMenuItem()); m = FXUIUtils.createMenuItem("play", "Play", ""); m.setDisable(item == null || !canRun(selectedItems)); m.setOnAction((event) -> handler.play(source, selectedItems.stream().map(TreeItem::getValue).collect(Collectors.toList()))); contextMenu.getItems().add(m); m = FXUIUtils.createMenuItem("slowPlay", "Slow Play", ""); m.setDisable(item == null || !item.canPlaySingle() || selectedItems.size() != 1); m.setOnAction((event) -> handler.slowPlay(source, item)); contextMenu.getItems().add(m); m = FXUIUtils.createMenuItem("debug", "Debug", ""); m.setDisable(item == null || !item.canPlaySingle() || selectedItems.size() != 1); m.setOnAction((event) -> handler.debug(source, item)); contextMenu.getItems().add(m); contextMenu.getItems().add(new SeparatorMenuItem()); m = FXUIUtils.createMenuItem("cut", "Cut", "Shortcut+X"); m.setDisable(item == null || selectedItems.size() < 1); m.setOnAction((event) -> cut(selectedItems)); contextMenu.getItems().add(m); m = FXUIUtils.createMenuItem("copy", "Copy", "Shortcut+C"); m.setDisable(item == null || selectedItems.size() < 1); m.setOnAction((event) -> copy(selectedItems)); contextMenu.getItems().add(m); m = FXUIUtils.createMenuItem("paste", "Paste", "Shortcut+V"); m.setDisable(item == null || selectedItems.size() != 1); m.setOnAction((event) -> { paste(item); }); contextMenu.getItems().add(m); contextMenu.getItems().add(new SeparatorMenuItem()); m = FXUIUtils.createMenuItem("delete", "Delete", "Delete"); m.setDisable(item == null || selectedItems.size() < 1 || !canDelete(selectedItems)); m.setOnAction((event) -> delete(selectedItems)); contextMenu.getItems().add(m); m = FXUIUtils.createMenuItem("rename", "Rename", ""); m.setDisable(item == null || !item.canRename() || selectedItems.size() != 1); m.setOnAction((event) -> edit(item)); contextMenu.getItems().add(m); contextMenu.getItems().add(new SeparatorMenuItem()); m = FXUIUtils.createMenuItem("expandAll", "Expand All", ""); m.setOnAction((event) -> expandAll()); contextMenu.getItems().add(m); m = FXUIUtils.createMenuItem("collapseAll", "Collapse All", ""); m.setOnAction((event) -> collapseAll()); contextMenu.getItems().add(m); contextMenu.getItems().add(new SeparatorMenuItem()); m = FXUIUtils.createMenuItem("refresh", "Refresh", "Shortcut+F5"); m.setOnAction((x) -> refreshView()); contextMenu.getItems().add(m); if (item != null && item.canHide()) { m = FXUIUtils.createMenuItem("hide", "Hide", ""); m.setDisable(!canHide(selectedItems)); m.setOnAction((x) -> hide(selectedItems)); contextMenu.getItems().add(m); } if (item != null) { MenuItem[] unhideMenuItems = item.getUnhideMenuItem(); if (unhideMenuItems != null && unhideMenuItems.length > 0) { for (MenuItem menuItem : unhideMenuItems) { EventHandler<ActionEvent> onAction = menuItem.getOnAction(); menuItem.setOnAction((event) -> { onAction.handle(event); Platform.runLater(() -> refreshView()); }); } m = new Menu("Unhide", null, unhideMenuItems); contextMenu.getItems().add(m); } } if (item != null && item.hasProperties() && selectedItems.size() == 1) { m = FXUIUtils.createMenuItem("properties", "Properties...", ""); m.setOnAction((event) -> handler.addProperties(source, item)); contextMenu.getItems().add(m); } } private void newFolder(Resource resource) { Path filePath = resource.getFilePath(); if (filePath == null) { return; } File file; if (resource instanceof FolderResource) { file = resource.getFilePath().toFile(); } else { file = resource.getFilePath().getParent().toFile(); } File newFile = FXUIUtils.showMarathonSaveFileChooser(new MarathonFileChooserInfo("Create new folder", file, true), "Create a folder with the given name", FXUIUtils.getIcon("fldr_obj")); if (newFile == null) { return; } if (newFile.exists()) { FXUIUtils.showMessageDialog(this.getScene().getWindow(), "Folder with name '" + newFile.getName() + "' already exists.", "Folder exists", AlertType.INFORMATION); } else { newFile.mkdir(); } refreshView(); } private void newFile(Resource resource) { Path filePath = resource.getFilePath(); if (filePath == null) { return; } File file; if (resource instanceof FolderResource) { file = resource.getFilePath().toFile(); } else { file = resource.getFilePath().getParent().toFile(); } File newFile = FXUIUtils.showMarathonSaveFileChooser(new MarathonFileChooserInfo("Create new file", file, true), "Create a new file with the given name", FXUIUtils.getIcon("file_obj")); if (newFile == null) { return; } if (newFile.exists()) { FXUIUtils.showMessageDialog(this.getScene().getWindow(), "File with name '" + newFile.getName() + "' already exists.", "File exists", AlertType.INFORMATION); } else { try { newFile.createNewFile(); } catch (IOException e) { FXUIUtils.showExceptionMessage("Couldn't create file.", e); } } refreshView(); } private void hide(ObservableList<TreeItem<Resource>> selectedItems) { List<Resource> resources = selectedItems.stream().map((item) -> item.getValue()).collect(Collectors.toList()); for (Resource r : resources) { r.hide(); } refreshView(); } private boolean canHide(ObservableList<TreeItem<Resource>> selectedItems) { return selectedItems.stream().map(TreeItem::getValue).filter(((Predicate<? super Resource>) Resource::canHide).negate()) .count() <= 0; } private boolean canRun(ObservableList<TreeItem<Resource>> selectedItems) { return selectedItems.stream().map(TreeItem::getValue).filter(((Predicate<? super Resource>) Resource::canRun).negate()) .count() <= 0; } private void refreshView() { ArrayList<Integer> selection = new ArrayList<>(getSelectionModel().getSelectedIndices()); getSelectionModel().clearSelection(); ((Resource) getRoot()).refresh(); int[] selectedIndices = new int[selection.size() - 1]; if (selection.size() > 1) { for (int i = 1; i < selection.size(); i++) { selectedIndices[i - 1] = selection.get(i); } } int selectedIndex = selection.size() > 0 ? selection.get(0) : -1; if (selectedIndex != -1) { getSelectionModel().selectIndices(selectedIndex, selectedIndices); } } private boolean canDelete(ObservableList<TreeItem<Resource>> selectedItems) { for (TreeItem<Resource> treeItem : selectedItems) { if (treeItem == null) { continue; } if (!treeItem.getValue().canDelete()) { return false; } } return true; } private void paste(Resource item) { item.paste(Clipboard.getSystemClipboard(), clipboardOperation); if (clipboardOperation == Operation.CUT) { completeMove(); } } private void delete(ObservableList<TreeItem<Resource>> selectedItems) { Optional<ButtonType> option = Optional.empty(); ArrayList<TreeItem<Resource>> items = new ArrayList<>(selectedItems); for (TreeItem<Resource> treeItem : items) { option = treeItem.getValue().delete(option); if (option.isPresent() && option.get() == ButtonType.CANCEL) { break; } } } private void cut(ObservableList<TreeItem<Resource>> selectedItems) { copy(selectedItems); clipboardOperation = Operation.CUT; draggedItems = new ArrayList<>(selectedItems); } private void copy(ObservableList<TreeItem<Resource>> selectedItems) { Clipboard clipboard = Clipboard.getSystemClipboard(); Map<DataFormat, Object> content = new HashMap<>(); for (TreeItem<Resource> treeItem : selectedItems) { Resource resource = treeItem.getValue(); if (resource != null) { if (!resource.copy(content)) { FXUIUtils.showMessageDialog(null, "Clipboard operation failed", "Unhandled resource selection", AlertType.ERROR); } } } clipboard.setContent(content); clipboardOperation = Operation.COPY; } public void expandAll() { expandTreeView(getRoot()); } public void collapseAll() { collapseTreeView(getRoot()); getRoot().setExpanded(true); } public void cut() { cut(getSelectionModel().getSelectedItems()); } public void copy() { copy(getSelectionModel().getSelectedItems()); } public void paste() { paste(getSelectionModel().getSelectedItem().getValue()); } @Override public void deleted(IResourceActionSource source, Resource resource) { List<Resource> found = new ArrayList<>(); ((Resource) getRoot()).findNodes(resource, found); for (Resource r : found) { if (r != null) { r.deleted(); } } } @Override public void updated(IResourceActionSource source, Resource resource) { ((RootResource) getRoot()).updated(resource); } @Override public void moved(IResourceActionSource source, Resource from, Resource to) { ((RootResource) getRoot()).moved(from, to); } @Override public void copied(IResourceActionSource source, Resource from, Resource to) { ((RootResource) getRoot()).copied(from, to); } private void completeMove() { if (draggedItems != null) { for (TreeItem<Resource> treeItem : draggedItems) { treeItem.getValue().moved(); } } draggedItems = null; } }
package com.mcsqd.cordova.plugins.streamingmedia; import android.app.Activity; import android.content.res.Configuration; import android.graphics.Color; import android.media.AudioManager; import android.content.Intent; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.widget.ImageView; import android.view.View; import android.view.Window; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.MediaController; public class SimpleAudioStream extends Activity implements MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener, MediaController.MediaPlayerControl { private String TAG = getClass().getSimpleName(); private MediaPlayer mMediaPlayer = null; private MediaController mMediaController = null; private LinearLayout mAudioView; private View mMediaControllerView; private String mAudioUrl; private Boolean mShouldAutoClose = true; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); this.requestWindowFeature(Window.FEATURE_NO_TITLE); Bundle b = getIntent().getExtras(); mAudioUrl = b.getString("mediaUrl"); String backgroundColor = b.getString("bgColor"); String backgroundImagePath = b.getString("bgImage"); String backgroundImageScale = b.getString("bgImageScale"); mShouldAutoClose = b.getBoolean("shouldAutoClose"); mShouldAutoClose = mShouldAutoClose == null ? true : mShouldAutoClose; backgroundImageScale = backgroundImageScale == null ? "center" : backgroundImageScale.toLowerCase(); ImageView.ScaleType bgImageScaleType; // Default background to black int bgColor = Color.BLACK; if (backgroundColor != null) { bgColor = Color.parseColor(backgroundColor); } if (backgroundImageScale.equals("fit")) { bgImageScaleType = ImageView.ScaleType.FIT_CENTER; } else if (backgroundImageScale.equals("stretch")) { bgImageScaleType = ImageView.ScaleType.FIT_XY; } else { bgImageScaleType = ImageView.ScaleType.CENTER; } RelativeLayout audioView = new RelativeLayout(this); audioView.setBackgroundColor(bgColor); if (backgroundImagePath != null) { ImageView bgImage = new ImageView(this); new ImageLoadTask(backgroundImagePath, bgImage, getApplicationContext()).execute(null, null); RelativeLayout.LayoutParams bgImageLayoutParam = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); bgImageLayoutParam.addRule(RelativeLayout.CENTER_IN_PARENT); bgImage.setLayoutParams(bgImageLayoutParam); bgImage.setScaleType(bgImageScaleType); audioView.addView(bgImage); } RelativeLayout.LayoutParams relLayoutParam = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); mMediaControllerView = new View(this); audioView.addView(mMediaControllerView); setContentView(audioView, relLayoutParam); play(); } private void play() { Uri myUri = Uri.parse(mAudioUrl); try { if (mMediaPlayer == null) { mMediaPlayer = new MediaPlayer(); } else { try { mMediaPlayer.stop(); mMediaPlayer.reset(); } catch (Exception e) { Log.e(TAG, e.toString()); } } mMediaPlayer.setDataSource(this, myUri); // Go to Initialized state mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.setOnBufferingUpdateListener(this); mMediaPlayer.setOnErrorListener(this); mMediaController = new MediaController(this); mMediaPlayer.prepareAsync(); Log.d(TAG, "LoadClip Done"); } catch (Throwable t) { Log.d(TAG, t.toString()); } } @Override public void onPrepared(MediaPlayer mp) { Log.d(TAG, "Stream is prepared"); mMediaController.setMediaPlayer(this); mMediaController.setAnchorView(mMediaControllerView); mMediaPlayer.start(); mMediaController.setEnabled(true); mMediaController.show(); } @Override public void start() { if (mMediaPlayer!=null) { mMediaPlayer.start(); } } @Override public void pause() { if (mMediaPlayer!=null) { try { mMediaPlayer.pause(); } catch (Exception e) { Log.d(TAG, e.toString()); } } } private void stop() { if (mMediaPlayer!=null) { try { mMediaPlayer.stop(); } catch (Exception e) { Log.d(TAG, e.toString()); } } } public int getDuration() { return (mMediaPlayer!=null) ? mMediaPlayer.getDuration() : 0; } public int getCurrentPosition() { return (mMediaPlayer!=null) ? mMediaPlayer.getCurrentPosition() : 0; } public void seekTo(int i) { if (mMediaPlayer!=null) { mMediaPlayer.seekTo(i); } } public boolean isPlaying() { if (mMediaPlayer!=null) { try { return mMediaPlayer.isPlaying(); } catch (Exception e) { Log.d(TAG, e.toString()); } } return false; } public int getBufferPercentage() { return 0; } public boolean canPause() { return true; } public boolean canSeekBackward() { return true; } public boolean canSeekForward() { return true; } @Override public int getAudioSessionId() { return 0; } @Override public void onDestroy() { super.onDestroy(); if (mMediaPlayer!=null){ try { mMediaPlayer.reset(); mMediaPlayer.release(); } catch (Exception e) { Log.e(TAG, e.toString()); } mMediaPlayer = null; } } private void wrapItUp(int resultCode, String message) { Intent intent = new Intent(); intent.putExtra("message", message); setResult(resultCode, intent); finish(); } @Override public void onCompletion(MediaPlayer mp) { stop(); if (mShouldAutoClose) { Log.v(TAG, "FINISHING ACTIVITY"); wrapItUp(RESULT_OK, null); } } public boolean onError(MediaPlayer mp, int what, int extra) { StringBuilder sb = new StringBuilder(); sb.append("Media Player Error: "); switch (what) { case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK: sb.append("Not Valid for Progressive Playback"); break; case MediaPlayer.MEDIA_ERROR_SERVER_DIED: sb.append("Server Died"); break; case MediaPlayer.MEDIA_ERROR_UNKNOWN: sb.append("Unknown"); break; default: sb.append(" Non standard ("); sb.append(what); sb.append(")"); } sb.append(" (" + what + ") "); sb.append(extra); Log.e(TAG, sb.toString()); wrapItUp(RESULT_CANCELED, sb.toString()); return true; } public void onBufferingUpdate(MediaPlayer mp, int percent) { Log.d(TAG, "PlayerService onBufferingUpdate : " + percent + "%"); } @Override public void onBackPressed() { wrapItUp(RESULT_OK, null); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } @Override protected void onStop() { super.onStop(); mMediaController.hide(); try { mMediaPlayer.stop(); mMediaPlayer.reset(); mMediaPlayer.release(); } catch(Exception e) { Log.e(TAG, e.toString()); } } @Override public boolean onTouchEvent(MotionEvent event) { mMediaController.show(); return false; } }
package rosa.gwt.common.client; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import rosa.gwt.common.client.resource.Labels; import rosa.search.SearchResult; import com.google.gwt.user.client.rpc.AsyncCallback; /** * Wraps SearchService in a user friendly abstraction. User fields and user * queries that are mapped to lucene fields and lucene queries. */ // TODO Better to have a more user friendly query model and move the complexity server side. See bible historiale search service. public class Searcher { // FIXME: Awful hack public static String LC = "en"; private final Map<String, SearchResult> searchCache; // url -> result private final static int MAX_SUBSTRING_EXPANSIONS = 10; private final static String[][] oldfrenchspelling = new String[][] { { "i", "j", "y" }, { "i", "j", "g" }, { "v", "u" }, { "c", "q", "k", "cc" }, { "s", "\u00E7", "ss", "z" } }; private final SearchServiceAsync searchservice; // ALL is treated specially to match all lucene fields used by other // UserFields public enum UserField { ALL(Labels.INSTANCE.allFields()), POETRY( Labels.INSTANCE.linesOfVerse(), Transcription.TR_POETRY, NarrativeTag.START_LINE_TRANSCRIPTION), RUBRIC(Labels.INSTANCE .rubric(), Transcription.TR_RUBRIC), ILLUSTRATION_TITLE( Labels.INSTANCE.illustrationTitle(), Transcription.TR_ILLUSTRATION, ImageTag.IM_TITLE), LECOY( Labels.INSTANCE.lecoy(), Transcription.TR_LECOY), NOTE( Labels.INSTANCE.criticalNote(), Transcription.TR_NOTE), ILLUSTRATION_CHAR( Labels.INSTANCE.illustrationChar(), ImageTag.IM_CHAR), ILLUSTRATION_KEYWORDS( Labels.INSTANCE.illustrationKeywords(), ImageTag.IM_KEYWORD), DESCRIPTION( Labels.INSTANCE.bookDescription(), Description.DS_TEXT), IMAGE( Labels.INSTANCE.imageName(), Base.IMAGE, Base.IMAGE_ALTERNATES), NARRATIVE_SECTION( Labels.INSTANCE.narrativeSections(), NarrativeTag.SECTION_ID, NarrativeTag.SECTION_DESCRIPTION); public final String display; public final LuceneField[] fields; private UserField(String display, LuceneField... fields) { this.display = display; this.fields = fields; } // TODO build map? public static UserField findByLuceneField(String lucenename) { for (UserField uf : values()) { for (LuceneField f : uf.fields) { if (f.lucenename().equals(lucenename)) { return uf; } } } return null; } } public Searcher(SearchServiceAsync searchservice) { this.searchCache = new HashMap<String, SearchResult>(); this.searchservice = searchservice; } public enum LuceneFieldType { OLD_FRENCH, ENGLISH, FRENCH, TEXT, STRING, NUMBER; } private interface LuceneField { public String lucenename(); public LuceneFieldType type(); } private enum Transcription implements LuceneField { TR_POETRY(LuceneFieldType.OLD_FRENCH), TR_RUBRIC( LuceneFieldType.OLD_FRENCH), TR_ILLUSTRATION( LuceneFieldType.ENGLISH), TR_LECOY(LuceneFieldType.TEXT), TR_NOTE( LuceneFieldType.ENGLISH), TR_LINE(LuceneFieldType.NUMBER), TR_CATCHPHRASE( LuceneFieldType.OLD_FRENCH); private final LuceneFieldType type; private Transcription(LuceneFieldType type) { this.type = type; } public String lucenename() { return name().toLowerCase(); } public LuceneFieldType type() { return type; } }; private enum Description implements LuceneField { DS_REPOSITORY(LuceneFieldType.TEXT), DS_SHELFMARK(LuceneFieldType.TEXT), DS_CITY( LuceneFieldType.TEXT), DS_DATE(LuceneFieldType.TEXT), DS_ORIGIN( LuceneFieldType.TEXT), DS_HEIGHT(LuceneFieldType.NUMBER), DS_WIDTH( LuceneFieldType.NUMBER), DS_TYPE(LuceneFieldType.TEXT), DS_NUM_ILLUSTRATIONS( LuceneFieldType.NUMBER), DS_NUM_FOLIOS(LuceneFieldType.NUMBER), DS_TEXT( LuceneFieldType.TEXT); private final LuceneFieldType type; private Description(LuceneFieldType type) { this.type = type; } public String lucenename() { return name().toLowerCase() + "_" + LC; } public LuceneFieldType type() { return type; } } private enum ImageTag implements LuceneField { IM_TITLE(LuceneFieldType.ENGLISH), IM_CHAR(LuceneFieldType.OLD_FRENCH), IM_KEYWORD( LuceneFieldType.ENGLISH); private final LuceneFieldType type; private ImageTag(LuceneFieldType type) { this.type = type; } public String lucenename() { return name().toLowerCase(); } public LuceneFieldType type() { return type; } } private enum Base implements LuceneField { BOOK(LuceneFieldType.STRING), IMAGE(LuceneFieldType.STRING), IMAGE_ALTERNATES( LuceneFieldType.STRING); private final LuceneFieldType type; private Base(LuceneFieldType type) { this.type = type; } public String lucenename() { return name().toLowerCase(); } public LuceneFieldType type() { return type; } } private enum NarrativeTag implements LuceneField { SECTION_ID(LuceneFieldType.STRING), START_LINE_TRANSCRIPTION( LuceneFieldType.OLD_FRENCH), SECTION_DESCRIPTION( LuceneFieldType.ENGLISH); private final LuceneFieldType type; private NarrativeTag(LuceneFieldType type) { this.type = type; } public String lucenename() { return name().toLowerCase(); } public LuceneFieldType type() { return type; } } /** * Return a user or lucene query which exactly matches a string. */ public static String createLiteralQuery(String s) { StringBuilder sb = new StringBuilder(s.length()); sb.append("\""); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '&' || c == '|' || c == '(' || c == ')' || c == '}' || c == '{' || c == '[' || c == ']' || c == ':' || c == '^' || c == '!' || c == '\"' || c == '+' || c == '-' || c == '~' || c == '*' || c == '?' || c == '\\') { sb.append('\\'); } sb.append(c); } sb.append("\""); return sb.toString(); } // Tokenize a user query into lucene terms and phrases. // Phrases will be surrounded by " // Unsupported lucene characters are escaped. // Always returns valid lucene terms public static List<String> parseUserQuery(String query) { List<String> luceneterms = new ArrayList<String>(); final int TERM = 1; final int SEP = 2; final int PHRASE = 3; final int PHRASE_PROXIMITY = 4; int state = SEP; boolean escaped = false; StringBuilder luceneprefix = new StringBuilder(); StringBuilder luceneterm = new StringBuilder(); StringBuilder lucenesuffix = new StringBuilder(); int numquotes = 0; for (int i = 0; i < query.length(); i++) { char c = query.charAt(i); // System.err.println(c + " [" + luceneprefix + "] [" + luceneterm + // "] [" + lucenesuffix + "]" ); if (state == PHRASE_PROXIMITY) { if (Character.isDigit(c)) { lucenesuffix.append(c); } else { addQueryTerm(luceneterms, luceneprefix, luceneterm, lucenesuffix); // push back i--; state = SEP; } } else if (c == ' ' || c == '\t' || c == '\r' || c == '\n') { if (state == TERM) { addQueryTerm(luceneterms, luceneprefix, luceneterm, lucenesuffix); state = SEP; } else if (state == PHRASE) { luceneterm.append(' '); } } else if (escaped) { escaped = false; luceneterm.append('\\'); luceneterm.append(c); } else if (c == '\\') { escaped = true; } else if (state == SEP && (c == '+' || c == '-')) { if (luceneprefix.length() == 0) { luceneprefix.append(c); } } else if (c == '"') { numquotes++; if (state == PHRASE) { lucenesuffix.append(c); // Check for ~num if (i + 2 < query.length() && query.charAt(i + 1) == '~' && Character.isDigit(query.charAt(i + 2))) { lucenesuffix.append(query.charAt(i + 1)); lucenesuffix.append(query.charAt(i + 2)); i += 2; state = PHRASE_PROXIMITY; } else { addQueryTerm(luceneterms, luceneprefix, luceneterm, lucenesuffix); state = SEP; } } else { if (luceneterm.length() > 0) { addQueryTerm(luceneterms, luceneprefix, luceneterm, lucenesuffix); } luceneprefix.append(c); state = PHRASE; } } else if (c == '&' || c == '|' || c == '(' || c == ')' || c == '}' || c == '{' || c == '[' || c == ']' || c == ':' || c == '^' || c == '!' || c == '~' || c == '+' || c == '-') { luceneterm.append('\\'); luceneterm.append(c); } else { if (state == SEP) { state = TERM; } luceneterm.append(c); } } // Phrase started, but didn't end with quote, add quote. if ((numquotes & 1) > 0) { lucenesuffix.append('\"'); } addQueryTerm(luceneterms, luceneprefix, luceneterm, lucenesuffix); // System.err.println("parsed user query into num terms " // + luceneterms.size()); return luceneterms; } private static void addQueryTerm(List<String> terms, StringBuilder luceneprefix, StringBuilder term, StringBuilder lucenesuffix) { if (term.length() > 0) { terms.add(luceneprefix.toString() + term + lucenesuffix); // System.err.println("Added: " + terms.get(terms.size() - 1)); } term.setLength(0); luceneprefix.setLength(0); lucenesuffix.setLength(0); } public void searchCollection(final UserField[] userfields, final String[] userqueries, final String[] restrictedbookids, final int offset, final int max, String[][] charnames, final AsyncCallback<SearchResult> cb) { String lucenequery = createLuceneQuery(userfields, userqueries, restrictedbookids, charnames); searchCollection(lucenequery, offset, max, cb); } private void searchCollection(final String lucenequery, final int offset, final int max, final AsyncCallback<SearchResult> cb) { final String key = lucenequery + ":" + offset + ":" + max; SearchResult result = (SearchResult) searchCache.get(key); if (result != null) { cb.onSuccess(result); return; } searchservice.search(lucenequery, offset, max, new AsyncCallback<SearchResult>() { public void onFailure(Throwable caught) { cb.onFailure(caught); } public void onSuccess(SearchResult result) { searchCache.put(key, result); cb.onSuccess(result); } }); } private void buildLuceneQuery(StringBuilder sb, LuceneField[] fields, List<String> terms, String[][] charnames) { String oldfrquery = buildLuceneQuery(terms, LuceneFieldType.OLD_FRENCH, charnames); String textquery = buildLuceneQuery(terms, LuceneFieldType.TEXT, charnames); String simplequery = buildLuceneQuery(terms, LuceneFieldType.STRING, charnames); for (LuceneField field : fields) { addFieldQuery(sb, field, oldfrquery, textquery, simplequery); sb.append(' '); } } /** * Create lucene query given specified user queries in user fields. The * lucene query is restricted to only include results matching the given * book ids. * * @param userfields * @param userqueries * @param restrictedbookids * @return */ private String createLuceneQuery(UserField[] userfields, String[] userqueries, String[] restrictedbookids, String[][] charnames) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < userfields.length; i++) { UserField uf = userfields[i]; String userquery = userqueries[i]; if (uf == null || userquery == null) { continue; } List<String> terms = parseUserQuery(userquery); if (uf == UserField.ALL) { for (UserField uf2 : UserField.values()) { if (uf2 != UserField.ALL) { buildLuceneQuery(sb, uf2.fields, terms, charnames); } } } else { buildLuceneQuery(sb, uf.fields, terms, charnames); } } if (restrictedbookids != null && restrictedbookids.length > 0) { sb.insert(0, '('); sb.append(") && " + Base.BOOK.lucenename() + ":("); for (String bookid : restrictedbookids) { sb.append(createLiteralQuery(bookid)); sb.append(' '); } sb.append(')'); } return sb.toString(); } private static void addFieldQuery(StringBuilder sb, LuceneField field, String oldfrquery, String textquery, String simplequery) { sb.append(field.lucenename()); sb.append(":("); if (field.type() == LuceneFieldType.OLD_FRENCH) { sb.append(oldfrquery); } else if (field.type() == LuceneFieldType.NUMBER || field.type() == LuceneFieldType.STRING) { sb.append(simplequery); } else { sb.append(textquery); } sb.append(")"); } private String buildLuceneQuery(List<String> terms, LuceneFieldType type, String[][] charnames) { StringBuilder sb = new StringBuilder(); for (String term : terms) { if (!term.trim().isEmpty()) { expandLuceneTerm(sb, charnames, term, type); sb.append(' '); } } return sb.toString(); } private static void expandLuceneTerm(StringBuilder sb, String[][] charnames, String term, LuceneFieldType type) { if (type == LuceneFieldType.OLD_FRENCH) { // expand char names and then spellings boolean bool = isLuceneBoolean(term); boolean fuzzy = isLuceneFuzzy(term); if (bool || fuzzy) { sb.append('('); sb.append(term); sb.append(')'); sb.append(' '); } else { // Need two hashsets because of concurrent modification HashSet<String> terms = expandWords(charnames, term); HashSet<String> result = new HashSet<String>(terms); for (int i = 0; i < oldfrenchspelling.length; i++) { for (String s : terms) { expandVariants(result, oldfrenchspelling[i], s); } } combineTerms(sb, result); } } else if (type == LuceneFieldType.NUMBER || type == LuceneFieldType.STRING) { sb.append('('); sb.append(term); sb.append(')'); sb.append(' '); } else { // expand char names combineTerms(sb, expandWords(charnames, term)); } } private static void combineTerms(StringBuilder sb, Collection<String> terms) { sb.append('('); for (String s : terms) { sb.append(s); sb.append(' '); } sb.append(')'); } private static boolean isLucenePhrase(String term) { return term.matches("(\\+|\\-)?\\\".*\\\"(~\\d+)?"); } private static boolean isLuceneBoolean(String term) { return term.startsWith("+") || term.startsWith("-"); } private static boolean isLuceneFuzzy(String term) { return term.endsWith("~") || term.contains("*") || term.contains("?"); } /** * @param expansion * List of variants. Variants is list of words * @param lucene * term * @return set of lucene terms */ private static HashSet<String> expandWords(String[][] expansion, String term) { boolean phrase = isLucenePhrase(term); HashSet<String> result = new HashSet<String>(); result.add(term); next: for (String[] variants : expansion) { for (String variant : variants) { if (variant.isEmpty()) { continue; } if (phrase) { if (term.contains(variant)) { expandVariants(result, variants, term); continue next; } } else { if (term.equalsIgnoreCase(variant)) { for (String v : variants) { if (v != variant && !v.isEmpty()) { result.add(createLiteralQuery(v)); } } continue next; } } } } return result; } private static void expandVariants(Collection<String> result, String[] variants, String string) { result.add(string); for (int i = 0; i < string.length(); i++) { boolean foundexpansion = false; for (String sub : variants) { i = string.indexOf(sub, i); if (i == -1) { continue; } String start = string.substring(0, i); String end = string.substring(i + sub.length()); for (String s : variants) { result.add(start + s + end); } if (result.size() > MAX_SUBSTRING_EXPANSIONS) { return; } } if (!foundexpansion) { return; } } } }
/* * Autopsy Forensic Browser * * Copyright 2019 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.report.infrastructure; import org.sleuthkit.autopsy.report.modules.portablecase.PortableCaseReportModuleSettings; import java.awt.Component; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; import javax.swing.ListModel; import javax.swing.event.ListDataListener; import org.openide.util.NbBundle; import org.sleuthkit.autopsy.casemodule.Case; import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.report.modules.portablecase.PortableCaseReportModule.GetInterestingItemSetNamesCallback; import org.sleuthkit.datamodel.BlackboardArtifact; import org.sleuthkit.datamodel.BlackboardAttribute; import org.sleuthkit.datamodel.TskCoreException; /** * The subpanel showing the interesting item sets */ @SuppressWarnings("PMD.SingularField") // UI widgets cause lots of false positives class PortableCaseInterestingItemsListPanel extends javax.swing.JPanel { private List<String> setNames; private final Map<String, Boolean> setNameSelections = new LinkedHashMap<>(); private final SetNamesListModel setNamesListModel = new SetNamesListModel(); private final SetNamesListCellRenderer setNamesRenderer = new SetNamesListCellRenderer(); private Map<String, Long> setCounts; private final ReportWizardPortableCaseOptionsPanel wizPanel; private final PortableCaseReportModuleSettings settings; private final boolean useCaseSpecificData; /** * Creates new form PortableCaseListPanel */ PortableCaseInterestingItemsListPanel(ReportWizardPortableCaseOptionsPanel wizPanel, PortableCaseReportModuleSettings options, boolean useCaseSpecificData) { this.wizPanel = wizPanel; this.useCaseSpecificData = useCaseSpecificData; this.settings = options; initComponents(); customizeComponents(); // update tag selection jAllSetsCheckBox.setSelected(settings.areAllSetsSelected()); setNamesListBox.setEnabled(!jAllSetsCheckBox.isSelected()); selectButton.setEnabled(!jAllSetsCheckBox.isSelected()); deselectButton.setEnabled(!jAllSetsCheckBox.isSelected()); selectAllSets(jAllSetsCheckBox.isSelected()); this.jAllSetsCheckBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { setNamesListBox.setEnabled(!jAllSetsCheckBox.isSelected()); selectButton.setEnabled(!jAllSetsCheckBox.isSelected()); deselectButton.setEnabled(!jAllSetsCheckBox.isSelected()); selectAllSets(jAllSetsCheckBox.isSelected()); } }); } @NbBundle.Messages({ "PortableCaseInterestingItemsListPanel.error.errorTitle=Error getting intesting item set names for case", "PortableCaseInterestingItemsListPanel.error.noOpenCase=There is no case open", "PortableCaseInterestingItemsListPanel.error.errorLoadingTags=Error loading interesting item set names", }) private void customizeComponents() { // Get the set names in use for the current case. setNames = new ArrayList<>(); setCounts = new HashMap<>(); // only try to load tag names if we are displaying case specific data, otherwise // we will be displaying case specific data in command line wizard if there is // a case open in the background if (useCaseSpecificData) { try { // Get all SET_NAMEs from interesting item artifacts String innerSelect = "SELECT (value_text) AS set_name FROM blackboard_attributes WHERE (artifact_type_id = '" + BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_FILE_HIT.getTypeID() + "' OR artifact_type_id = '" + BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_ARTIFACT_HIT.getTypeID() + "') AND attribute_type_id = '" + BlackboardAttribute.ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID() + "'"; // NON-NLS // Get the count of each SET_NAME String query = "set_name, count(1) AS set_count FROM (" + innerSelect + ") set_names GROUP BY set_name"; // NON-NLS GetInterestingItemSetNamesCallback callback = new GetInterestingItemSetNamesCallback(); Case.getCurrentCaseThrows().getSleuthkitCase().getCaseDbAccessManager().select(query, callback); setCounts = callback.getSetCountMap(); setNames.addAll(setCounts.keySet()); } catch (TskCoreException ex) { Logger.getLogger(ReportWizardPortableCaseOptionsVisualPanel.class.getName()).log(Level.SEVERE, "Failed to get interesting item set names", ex); // NON-NLS } catch (NoCurrentCaseException ex) { // There may not be a case open when configuring report modules for Command Line execution if (Case.isCaseOpen()) { Logger.getLogger(ReportWizardPortableCaseOptionsVisualPanel.class.getName()).log(Level.SEVERE, "Exception while getting open case.", ex); // NON-NLS } } } Collections.sort(setNames); // Mark the set names as unselected. Note that setNameSelections is a // LinkedHashMap so that order is preserved and the setNames and setNameSelections // containers are "parallel" containers. for (String setName : setNames) { setNameSelections.put(setName, Boolean.FALSE); } // Set up the tag names JList component to be a collection of check boxes // for selecting tag names. The mouse click listener updates setNameSelections // to reflect user choices. setNamesListBox.setModel(setNamesListModel); setNamesListBox.setCellRenderer(setNamesRenderer); setNamesListBox.setVisibleRowCount(-1); setNamesListBox.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent evt) { JList<?> list = (JList) evt.getSource(); int index = list.locationToIndex(evt.getPoint()); if (index > -1) { String value = setNamesListModel.getElementAt(index); setNameSelections.put(value, !setNameSelections.get(value)); list.repaint(); updateSetNameList(); } } }); } /** * Save the current selections and enabled/disable the finish button as needed. */ private void updateSetNameList() { settings.updateSetNames(getSelectedSetNames()); settings.setAllSetsSelected(jAllSetsCheckBox.isSelected()); wizPanel.setFinish(settings.isValid()); } /** * This class is a list model for the set names JList component. */ private class SetNamesListModel implements ListModel<String> { @Override public int getSize() { return setNames.size(); } @Override public String getElementAt(int index) { return setNames.get(index); } @Override public void addListDataListener(ListDataListener l) { // Nothing to do } @Override public void removeListDataListener(ListDataListener l) { // Nothing to do } } /** * This class renders the items in the set names JList component as JCheckbox components. */ private class SetNamesListCellRenderer extends JCheckBox implements ListCellRenderer<String> { private static final long serialVersionUID = 1L; @Override public Component getListCellRendererComponent(JList<? extends String> list, String value, int index, boolean isSelected, boolean cellHasFocus) { if (value != null) { setEnabled(list.isEnabled()); setSelected(setNameSelections.get(value)); setFont(list.getFont()); setBackground(list.getBackground()); setForeground(list.getForeground()); setText(value + " (" + setCounts.get(value) + ")"); // NON-NLS return this; } return new JLabel(); } } /** * Gets the subset of the interesting item set names in use selected by the user. * * @return A list, possibly empty, of String data transfer objects (DTOs). */ private List<String> getSelectedSetNames() { List<String> selectedSetNames = new ArrayList<>(); for (String setName : setNames) { if (setNameSelections.get(setName)) { selectedSetNames.add(setName); } } return selectedSetNames; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); setNamesListBox = new javax.swing.JList<>(); descLabel = new javax.swing.JLabel(); selectButton = new javax.swing.JButton(); deselectButton = new javax.swing.JButton(); jAllSetsCheckBox = new javax.swing.JCheckBox(); jScrollPane1.setViewportView(setNamesListBox); org.openide.awt.Mnemonics.setLocalizedText(descLabel, org.openide.util.NbBundle.getMessage(PortableCaseInterestingItemsListPanel.class, "PortableCaseInterestingItemsListPanel.descLabel.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(selectButton, org.openide.util.NbBundle.getMessage(PortableCaseInterestingItemsListPanel.class, "PortableCaseInterestingItemsListPanel.selectButton.text")); // NOI18N selectButton.setMaximumSize(new java.awt.Dimension(87, 23)); selectButton.setMinimumSize(new java.awt.Dimension(87, 23)); selectButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { selectButtonActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(deselectButton, org.openide.util.NbBundle.getMessage(PortableCaseInterestingItemsListPanel.class, "PortableCaseInterestingItemsListPanel.deselectButton.text")); // NOI18N deselectButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deselectButtonActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(jAllSetsCheckBox, org.openide.util.NbBundle.getMessage(PortableCaseInterestingItemsListPanel.class, "PortableCaseInterestingItemsListPanel.jAllSetsCheckBox.text")); // NOI18N jAllSetsCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jAllSetsCheckBoxActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(descLabel) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(selectButton, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(deselectButton)) .addComponent(jAllSetsCheckBox)) .addGap(0, 8, Short.MAX_VALUE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(descLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jAllSetsCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(selectButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(deselectButton))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); }// </editor-fold>//GEN-END:initComponents private void deselectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deselectButtonActionPerformed selectAllSets(false); }//GEN-LAST:event_deselectButtonActionPerformed private void selectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectButtonActionPerformed selectAllSets(true); }//GEN-LAST:event_selectButtonActionPerformed private void jAllSetsCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jAllSetsCheckBoxActionPerformed selectAllSets(true); }//GEN-LAST:event_jAllSetsCheckBoxActionPerformed private void selectAllSets(boolean select) { Boolean state = Boolean.TRUE; if (!select) { state = Boolean.FALSE; } for (String setName : setNames) { setNameSelections.put(setName, state); } updateSetNameList(); setNamesListBox.repaint(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel descLabel; private javax.swing.JButton deselectButton; private javax.swing.JCheckBox jAllSetsCheckBox; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton selectButton; private javax.swing.JList<String> setNamesListBox; // End of variables declaration//GEN-END:variables }
import java.util.Arrays; public class COmKInstance { // constants private static final double BIG_NUM = 10000000000.0; private static final double TINY_NUM = 0.00000000001; // Problem input public double[][] p; public double[] maxP; public DataCenter[] dcs; public int n; public int m; public double[] w; // Problem output private double objVal; private boolean isSolved; public COmKInstance(double[][] inP, int[] inServers, double[] inW) { p = inP; n = p.length; m = p[1].length; maxP = new double[n]; for (int j = 0; j < n; j++) { double currMax = p[j][0]; for (int i = 1; i < m; i++) { if (currMax < p[j][i]) { currMax = p[j][i]; } } maxP[j] = currMax; } dcs = new DataCenter[m]; w = inW; isSolved = false; for (int i = 0; i < m; i++) { dcs[i] = new DataCenter(inServers[i]); } } public double getObjVal() { return objVal; } public void setObjVal(double in) { objVal = in; } public boolean getIsSolved() { return isSolved; } public void listSchedule(int[] sigma) { if (sigma.length != n || isSolved) { throw new IllegalArgumentException(); } objVal = 0.0; // for all jobs for (int i = 0; i < n; i++) { int job = sigma[i]; double latest = 0; // find the latest completion time across DataCenters for (int l = 0; l < m; l++) { if (p[job][l] > 0) { double localTime = dcs[l].scheduleJobOnMinServer(job, p[job][l]); if (localTime > latest) { latest = localTime; } } } // record the objective value objVal = objVal + w[job] * latest; } isSolved = true; } public void multiListSchedule(int[][] multiSigma) { // multiSigma[dc] is the permutation of {1,...,n} for DataCenter "dc" double[] latest = new double[n]; for (int dc = 0; dc < m; dc++) { for (int j = 0; j < n; j++) { int job = multiSigma[dc][j]; if (p[job][dc] > 0) { double localTime = dcs[dc].scheduleJobOnMinServer(job, p[job][dc]); if (localTime > latest[job]) { latest[job] = localTime; } } } } for (int j = 0; j < n; j++) { objVal = objVal + w[j] * latest[j]; } isSolved = true; } public void transformThenMonaldo() { double[][] transP = new double[n][m + n]; double[][] transPTranspose = new double[m + n][n]; int[] transK = new int[m + n]; for (int j = 0; j < n; j++) { for (int i = 0; i < m; i++) { transP[j][i] = p[j][i] / ((double) dcs[i].servers.size()); transPTranspose[i][j] = transP[j][i]; } transP[j][m + j] = maxP[j]; transPTranspose[m + j][j] = transP[j][m + j]; } int[] sigma = monaldo(transP, transPTranspose); listSchedule(sigma); } public int[] monaldo(double[][] inP, double[][] inPTranspose) { // assume K = 1 for all DC's double[] altW = new double[n]; boolean[] scheduled = new boolean[n]; for (int j = 0; j < n; j++) { altW[j] = w[j]; } int[] toReturn = new int[inP.length]; double[] load = new double[inP[1].length]; for (int i = 0; i < inP[1].length; i++) { for (int j = 0; j < n; j++) { load[i] = load[i] + inP[j][i]; } } for (int j = (n-1); j >= 0; j--) { int mu = findMax(load); // find the job on this bottleneck double[] times = inPTranspose[mu]; double[] priority = elementByElementDivide(altW, times); int job = findMin(priority, scheduled); // schedule this job toReturn[j] = job; // update loads and weights double theta = altW[job] / inP[job][mu]; updateWeights(altW, inPTranspose[mu], theta, scheduled); updateLoads(load, inP[job]); scheduled[job] = true; } return toReturn; } private void updateWeights(double[] wt, double[] inPMu, double theta, boolean[] sched) { for (int j = 0; j < n; j++) { if (!sched[j]) { wt[j] = Math.max(wt[j] - theta * inPMu[j], 0.0); } } } private void updateLoads(double[] l, double[] inP) { for (int i = 0; i < inP.length; i++) { l[i] = l[i] - inP[i]; } } private double[] elementByElementDivide(double[] num, double[] den) { if (num.length != den.length) { throw new IllegalArgumentException("Dimensions don't match."); } double[] out = new double[num.length]; for (int i = 0; i < num.length; i++) { if (den[i] < TINY_NUM) { out[i] = BIG_NUM; } else { out[i] = num[i] / den[i]; } } return out; } private int findMax(double[] v) { // return index of min value of v int toReturn = 0; double currMax = 0.0; for (int i = 0; i < v.length; i++) { if (v[i] > currMax) { toReturn = i; currMax = v[i]; } } return toReturn; } private int findMin(double[] v, boolean[] notCandidate) { // return index of min value of v int toReturn = 0; double currMin = BIG_NUM; for (int i = 0; i < v.length; i++) { if (!notCandidate[i] && v[i] < currMin) { toReturn = i; currMin = v[i]; } } return toReturn; } }
package org.apache.maven.lifecycle.internal.builder.multithreaded; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.maven.lifecycle.internal.ProjectBuildList; import org.apache.maven.lifecycle.internal.ProjectSegment; /** * <strong>NOTE:</strong> This class is not part of any public api and can be changed or deleted without prior notice. * This class in particular may spontaneously self-combust and be replaced by a plexus-compliant thread aware * logger implementation at any time. * * @since 3.0 * @author Kristian Rosenvold */ @SuppressWarnings( { "SynchronizationOnLocalVariableOrMethodParameter" } ) public class ThreadOutputMuxer { private final Iterator<ProjectSegment> projects; private final ThreadLocal<ProjectSegment> projectBuildThreadLocal = new ThreadLocal<>(); private final Map<ProjectSegment, ByteArrayOutputStream> streams = new HashMap<>(); private final Map<ProjectSegment, PrintStream> printStreams = new HashMap<>(); private final ByteArrayOutputStream defaultOutputStreamForUnknownData = new ByteArrayOutputStream(); private final PrintStream defaultPrintStream = new PrintStream( defaultOutputStreamForUnknownData ); private final Set<ProjectSegment> completedBuilds = Collections.synchronizedSet( new HashSet<>() ); private volatile ProjectSegment currentBuild; private final PrintStream originalSystemOUtStream; private final ConsolePrinter printer; /** * A simple but safe solution for printing to the console. */ class ConsolePrinter implements Runnable { private volatile boolean running; private final ProjectBuildList projectBuildList; ConsolePrinter( ProjectBuildList projectBuildList ) { this.projectBuildList = projectBuildList; } public void run() { running = true; for ( ProjectSegment projectBuild : projectBuildList ) { final PrintStream projectStream = printStreams.get( projectBuild ); ByteArrayOutputStream projectOs = streams.get( projectBuild ); do { synchronized ( projectStream ) { try { projectStream.wait( 100 ); } catch ( InterruptedException e ) { throw new RuntimeException( e ); } try { projectOs.writeTo( originalSystemOUtStream ); } catch ( IOException e ) { throw new RuntimeException( e ); } projectOs.reset(); } } while ( !completedBuilds.contains( projectBuild ) ); } running = false; } /* Wait until we are sure the print-stream thread is running. */ public void waitUntilRunning( boolean expect ) { while ( !running == expect ) { try { Thread.sleep( 10 ); } catch ( InterruptedException e ) { throw new RuntimeException( e ); } } } } public ThreadOutputMuxer( ProjectBuildList segmentChunks, PrintStream originalSystemOut ) { projects = segmentChunks.iterator(); for ( ProjectSegment segmentChunk : segmentChunks ) { final ByteArrayOutputStream value = new ByteArrayOutputStream(); streams.put( segmentChunk, value ); printStreams.put( segmentChunk, new PrintStream( value ) ); } setNext(); this.originalSystemOUtStream = originalSystemOut; System.setOut( new ThreadBoundPrintStream( this.originalSystemOUtStream ) ); printer = new ConsolePrinter( segmentChunks ); new Thread( printer ).start(); printer.waitUntilRunning( true ); } public void close() { printer.waitUntilRunning( false ); System.setOut( this.originalSystemOUtStream ); } private void setNext() { currentBuild = projects.hasNext() ? projects.next() : null; } private boolean ownsRealOutputStream( ProjectSegment projectBuild ) { return projectBuild.equals( currentBuild ); } private PrintStream getThreadBoundPrintStream() { ProjectSegment threadProject = projectBuildThreadLocal.get(); if ( threadProject == null ) { return defaultPrintStream; } if ( ownsRealOutputStream( threadProject ) ) { return originalSystemOUtStream; } return printStreams.get( threadProject ); } public void associateThreadWithProjectSegment( ProjectSegment projectBuild ) { projectBuildThreadLocal.set( projectBuild ); } public void setThisModuleComplete( ProjectSegment projectBuild ) { completedBuilds.add( projectBuild ); PrintStream stream = printStreams.get( projectBuild ); synchronized ( stream ) { stream.notifyAll(); } disconnectThreadFromProject(); } private void disconnectThreadFromProject() { projectBuildThreadLocal.remove(); } private class ThreadBoundPrintStream extends PrintStream { ThreadBoundPrintStream( PrintStream systemOutStream ) { super( systemOutStream ); } private PrintStream getOutputStreamForCurrentThread() { return getThreadBoundPrintStream(); } @Override public void println() { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.println(); currentStream.notifyAll(); } } @Override public void print( char c ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.print( c ); currentStream.notifyAll(); } } @Override public void println( char x ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.println( x ); currentStream.notifyAll(); } } @Override public void print( double d ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.print( d ); currentStream.notifyAll(); } } @Override public void println( double x ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.println( x ); currentStream.notifyAll(); } } @Override public void print( float f ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.print( f ); currentStream.notifyAll(); } } @Override public void println( float x ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.println( x ); currentStream.notifyAll(); } } @Override public void print( int i ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.print( i ); currentStream.notifyAll(); } } @Override public void println( int x ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.println( x ); currentStream.notifyAll(); } } @Override public void print( long l ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.print( l ); currentStream.notifyAll(); } } @Override public void println( long x ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.print( x ); currentStream.notifyAll(); } } @Override public void print( boolean b ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.print( b ); currentStream.notifyAll(); } } @Override public void println( boolean x ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.print( x ); currentStream.notifyAll(); } } @Override public void print( char s[] ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.print( s ); currentStream.notifyAll(); } } @Override public void println( char x[] ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.print( x ); currentStream.notifyAll(); } } @Override public void print( Object obj ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.print( obj ); currentStream.notifyAll(); } } @Override public void println( Object x ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.println( x ); currentStream.notifyAll(); } } @Override public void print( String s ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.print( s ); currentStream.notifyAll(); } } @Override public void println( String x ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.println( x ); currentStream.notifyAll(); } } @Override public void write( byte b[], int off, int len ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.write( b, off, len ); currentStream.notifyAll(); } } @Override public void close() { getOutputStreamForCurrentThread().close(); } @Override public void flush() { getOutputStreamForCurrentThread().flush(); } @Override public void write( int b ) { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.write( b ); currentStream.notifyAll(); } } @Override public void write( byte b[] ) throws IOException { final PrintStream currentStream = getOutputStreamForCurrentThread(); synchronized ( currentStream ) { currentStream.write( b ); currentStream.notifyAll(); } } } }
package io.github.repir.Strategy; import io.github.repir.Strategy.Operator.QTerm; import io.github.repir.Strategy.Operator.Operator; import io.github.htools.lib.Log; import io.github.repir.Repository.Repository; import java.util.ArrayList; /** * For {@link RetrievalModel} {@link Strategy}s, a Graph is constructed in which * the nodes are {@link Operator}s that hierarchically process the results. * The {@link GraphRoot} is not an {@link Operator}, but controls the construction * of the Graph and provides access and facilities for its nodes. {@link GraphComponent} * describes commonalities for all nodes. * <p/> * Components should announce their modes through {@link ANNOUNCEKEY}s, which * are communicated via {@link #announce(io.github.repir.Strategy.GraphComponent.ANNOUNCEKEY, io.github.repir.Strategy.Operator.Operator)} * via the edges towards the root. * By communicating via the edges, the parent nodes can overrule the how its * children are used. For instance, a Term is {@link ScoreFunction.Scorable} by * default, however, if the Term appears in a {@link ProximityOperator}, the entire * operator should be scored and not the individual terms; ProximityOperator should * therefore block the SCORABLE value send by its childeren. * <p/> * Some other information is passed from the {@link GraphRoot} via the edges, like * setWillBeScored and setTermPositionsNeeded. If setWillBeScored reaches a node * with true, it will know to request the statistics needed for scoring. If the children * of a node should not be scored, false is passed to their childeren. setTermPositions * is send with the value false from the root, if a node needs term positions, it * should switch the value to true. The receiving terms will then know to request * positional postings lists. Atm term positions are always used by default. * <p/> * GraphComponent complies to some standard facilities to remove or replace * nodes in the graph. By communicating these via the edges as a request, this * enables the nodes to override default behavior. */ public abstract class GraphComponent { public static Log log = new Log(GraphComponent.class); public ArrayList<Operator> containednodes = new ArrayList<Operator>(); public GraphComponent parent; public RetrievalModel retrievalmodel; public Repository repository; protected GraphComponent(RetrievalModel retrievalmodel) { this.retrievalmodel = retrievalmodel; this.repository = retrievalmodel.repository; } protected GraphComponent(Repository repository) { this.repository = repository; } public abstract void announce(ANNOUNCEKEY key, Operator node); /** * recursively removes a feature from the contained containednodes * <p/> * @param remove the feature to remove */ public void remove(Operator remove) { for (int f = 0; f < containednodes.size(); f++) { Operator feature = containednodes.get(f); if (feature == remove) { containednodes.remove(f--); } else { feature.remove(remove); if (!(feature instanceof QTerm) && feature.containednodes.isEmpty()) { containednodes.remove(f--); } } } } /** * @param search the Operator to be recursively replaced in the GraphRoot * @param replace a list of containednodes to replace every matching Operator * with */ public void replace(Operator replace, ArrayList<Operator> insert) { for (int f = containednodes.size() - 1; f >= 0; f--) { Operator feature = containednodes.get(f); if (feature == replace) { containednodes.remove(f); if (insert != null) { containednodes.addAll(f, insert); for (Operator node : insert) node.parent = this; } } else { feature.replace(replace, insert); } } } public void replace(Operator replace, Operator insert) { ArrayList<Operator> list = new ArrayList<Operator>(); list.add(insert); replace(replace, list); } public void doAnnounceContainedFeatures() { for (int f = containednodes.size() - 1; f >= 0; f--) { containednodes.get(f).doAnnounceContainedFeatures(); } } public void doExpand() { for (int f = containednodes.size() - 1; f >= 0; f--) { containednodes.get(f).doExpand(); } } public void doConfigureContainedFeatures() { for (int f = containednodes.size() - 1; f >= 0; f--) { containednodes.get(f).doConfigureContainedFeatures(); } } public void setWillBeScored( boolean willbescored ) { for (int f = containednodes.size() - 1; f >= 0; f--) { containednodes.get(f).setWillBeScored( willbescored ); } } public void setTermPositionsNeeded( boolean positional ) { for (int f = containednodes.size() - 1; f >= 0; f--) { containednodes.get(f).setTermPositionsNeeded( positional ); } } public void doReadStatistics( ) { for (int f = containednodes.size() - 1; f >= 0; f--) { containednodes.get(f).doReadStatistics( ); } } public void doSetupCollector( ) { for (int f = containednodes.size() - 1; f >= 0; f--) { containednodes.get(f).doSetupCollector( ); } } public void doPrepareRetrieval( ) { for (int f = containednodes.size() - 1; f >= 0; f--) { containednodes.get(f).doPrepareRetrieval( ); } } /** * Recursive search for a feature in the GraphRoot, using equals method. * <p/> * @param needle Operator that has same properties as the one to search * for i.e. that is used in the equals method. * @return Operator that is equal to the needle, or null if not exists. */ public Operator find(Operator needle) { Operator found = null; for (Operator f : containednodes) { if (f.getClass().equals(needle.getClass()) && f.equals(needle)) { found = f; break; } else { found = f.find(needle); } if (found != null) { break; } } return found; } /** * @param containednodes list of Features * @return a space separated representation of the list of containednodes */ public static String toTermString(int id, ArrayList<Operator> features) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < features.size(); i++) { if ((id & (1 << i)) > 0) { sb.append(features.get(i).toTermString()).append(" "); } } return sb.toString(); } /** * @param f Operator to be added to this Operator's contained Features. */ public void add(Operator f) { containednodes.add(f); f.parent = this; } public void add(ArrayList<Operator> list) { for (Operator n : list) add( n ); } public ArrayList<QTerm> getStopWords() { ArrayList<QTerm> results = new ArrayList<QTerm>(); for (Operator g : containednodes) { if (g instanceof QTerm && ((QTerm)g).isStopword()) { results.add((QTerm)g); } } return results; } public ArrayList<QTerm> getNonStopWords() { ArrayList<QTerm> results = new ArrayList<QTerm>(); for (Operator g : containednodes) { if (g instanceof QTerm && !((QTerm)g).isStopword()) { results.add((QTerm)g); } } return results; } public enum ANNOUNCEKEY { TERM, STOPWORD, // with intent to remove UNUSED, // with intent to remove NONEXIST, // with intent to remove NEEDSCOLLECT, NEEDSCACHECOLLECT, REMOVE, COMPLETED, SCORABLE } }
/* * Copyright (c) 2018, Ethan <https://github.com/shmeeps> * 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 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 net.runelite.client.plugins.prayer; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Rectangle; import java.time.Duration; import java.time.Instant; import javax.inject.Inject; import lombok.AccessLevel; import lombok.Setter; import net.runelite.api.Client; import net.runelite.api.Point; import net.runelite.api.Prayer; import net.runelite.api.Skill; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.ui.overlay.Overlay; import net.runelite.client.ui.overlay.OverlayLayer; import net.runelite.client.ui.overlay.OverlayPosition; import net.runelite.client.ui.overlay.tooltip.Tooltip; import net.runelite.client.ui.overlay.tooltip.TooltipManager; import net.runelite.client.util.ColorUtil; import org.apache.commons.lang3.StringUtils; class PrayerDoseOverlay extends Overlay { private static final float PULSE_TIME = 1200f; private static final Color START_COLOR = new Color(0, 255, 255); private static final Color END_COLOR = new Color(0, 92, 92); private final Client client; private final PrayerConfig config; private final TooltipManager tooltipManager; private Instant startOfLastTick = Instant.now(); private boolean trackTick = true; @Setter(AccessLevel.PACKAGE) private int prayerBonus; @Setter(AccessLevel.PACKAGE) private boolean hasPrayerPotion; @Setter(AccessLevel.PACKAGE) private boolean hasRestorePotion; @Setter(AccessLevel.PACKAGE) private boolean hasHolyWrench; @Inject private PrayerDoseOverlay(final Client client, final TooltipManager tooltipManager, final PrayerConfig config) { this.client = client; this.tooltipManager = tooltipManager; this.config = config; setPosition(OverlayPosition.DYNAMIC); setLayer(OverlayLayer.ABOVE_WIDGETS); } void onTick() { // Only track the time on every other tick if (trackTick) { startOfLastTick = Instant.now(); //Reset the tick timer trackTick = false; } else { trackTick = true; } } @Override public Dimension render(Graphics2D graphics) { final Widget xpOrb = client.getWidget(WidgetInfo.MINIMAP_QUICK_PRAYER_ORB); if (xpOrb == null) { return null; } final Rectangle bounds = xpOrb.getBounds(); if (bounds.getX() <= 0) { return null; } final Point mousePosition = client.getMouseCanvasPosition(); if (config.showPrayerStatistics() && bounds.contains(mousePosition.getX(), mousePosition.getY())) { final String tooltip = "Time Remaining: " + getEstimatedTimeRemaining() + "</br>" + "Prayer Bonus: " + prayerBonus; tooltipManager.add(new Tooltip(tooltip)); } if (!config.showPrayerDoseIndicator() || (!hasPrayerPotion && !hasRestorePotion)) { return null; } final int currentPrayer = client.getBoostedSkillLevel(Skill.PRAYER); final int maxPrayer = client.getRealSkillLevel(Skill.PRAYER); final int prayerPointsMissing = maxPrayer - currentPrayer; if (prayerPointsMissing <= 0) { return null; } final double dosePercentage = hasHolyWrench ? .27 : .25; final int basePointsRestored = (int) Math.floor(maxPrayer * dosePercentage); // how many points a prayer and super restore will heal final int prayerPotionPointsRestored = basePointsRestored + 7; final int superRestorePointsRestored = basePointsRestored + 8; final boolean usePrayerPotion = prayerPointsMissing >= prayerPotionPointsRestored; final boolean useSuperRestore = prayerPointsMissing >= superRestorePointsRestored; if (!usePrayerPotion && !useSuperRestore) { return null; } // Purposefully using height twice here as the bounds of the prayer orb includes the number sticking out the side final int orbInnerSize = (int) bounds.getHeight(); final int orbInnerX = (int) (bounds.getX() + 24); // x pos of the inside of the prayer orb final int orbInnerY = (int) (bounds.getY() - 1); // y pos of the inside of the prayer orb final long timeSinceLastTick = Duration.between(startOfLastTick, Instant.now()).toMillis(); final float tickProgress = Math.min(timeSinceLastTick / PULSE_TIME, 1); // Cap between 0 and 1 final double t = tickProgress * Math.PI; // Convert to 0 - pi graphics.setColor(ColorUtil.colorLerp(START_COLOR, END_COLOR, Math.sin(t))); graphics.setStroke(new BasicStroke(2)); graphics.drawOval(orbInnerX, orbInnerY, orbInnerSize, orbInnerSize); return new Dimension((int) bounds.getWidth(), (int) bounds.getHeight()); } private double getPrayerDrainRate(Client client) { double drainRate = 0.0; for (Prayer prayer : Prayer.values()) { if (client.isPrayerActive(prayer)) { drainRate += prayer.getDrainRate(); } } return drainRate; } private String getEstimatedTimeRemaining() { // Base data final double drainRate = getPrayerDrainRate(client); if (drainRate == 0) { return "N/A"; } final int currentPrayer = client.getBoostedSkillLevel(Skill.PRAYER); // Calculate how many seconds each prayer points last so the prayer bonus can be applied final double secondsPerPoint = (60.0 / drainRate) * (1.0 + (prayerBonus / 30.0)); // Calculate the number of seconds left final double secondsLeft = (currentPrayer * secondsPerPoint); final int minutes = (int) Math.floor(secondsLeft / 60.0); final int seconds = (int) Math.floor(secondsLeft - (minutes * 60.0)); // Return the text return Integer.toString(minutes) + ":" + StringUtils.leftPad(Integer.toString(seconds), 2, "0"); } }
package org.openxsp.stack; import javax.sip.SipStack; import javax.sip.address.Address; import javax.sip.address.AddressFactory; import javax.sip.address.SipURI; import javax.sip.header.ContactHeader; import javax.sip.header.FromHeader; import javax.sip.header.ToHeader; /** * Created by Frank Schulze on 11.04.14. * frank.schulze at fokus.fraunhofer.de */ public class User { //Stack Factorys private SipStack sipStack; //User Data private String name; private String sipProvider; private String displayName; //remote user private int peerPort; private String peerHost; //fprivate boolean isRemoteUser; private String headerTag; //Sip private SipURI sipURIAddress; private FromHeader fromHeader; private ToHeader toHeader; private ContactHeader contactHeader; /* * Constructor */ /*public User(SipStack sipStack) throws Exception { if (sipStack == null) throw new Exception("empty SipStack"); else { this.sipStack = sipStack; isRemoteUser = false; } }*/ public User(SipStack sipStack, String host, int port) throws Exception{ if (host == null) { throw new Exception("empty Host"); } else if (port <= 0) { throw new Exception("empty Port, and"+ port +" is not a valid port"); } else if (sipStack == null) { throw new Exception("empty SipStack"); } else { this.peerHost = host; this.peerPort = port; this.sipStack = sipStack; // isRemoteUser = true; } } /* * Getter and Setter */ public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSipProvider() { return sipProvider; } public void setSipProvider(String sipProvider) { this.sipProvider = sipProvider; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getHeaderTag() { return headerTag; } public void setHeaderTag(String headerTag) { this.headerTag = headerTag; } public FromHeader getFromHeader() { return fromHeader; } public void resetFromHeader() { fromHeader = null; } public ToHeader getToHeader() { return toHeader; } public void resetToHeader() { toHeader = null; } public SipStack getSipStack() { return sipStack; } public String getPeerHostPort() { return peerHost + ":" + peerPort; } public SipURI getSipURIAddress() { if (sipURIAddress == null) { try { createSipURI(); } catch (Exception e) { return null; } } return sipURIAddress; } public int getPeerPort() { return peerPort; } public void setPeerPort(int peerPort) { this.peerPort = peerPort; } public String getPeerHost() { return peerHost; } public void setPeerHost(String peerHost) { this.peerHost = peerHost; } public ContactHeader getContactHeader() { return contactHeader; } public void setContactHeader(ContactHeader contactHeader) { this.contactHeader = contactHeader; } /* * private functions */ private void createSipURI() throws Exception { AddressFactory x = sipStack.getAddressFactory(); sipURIAddress = x.createSipURI(name, sipProvider); } /* * public functions */ public FromHeader createFromHeader() { if (fromHeader != null) return fromHeader; try { //create own(from) SipURI if (sipURIAddress == null) { createSipURI(); } //create Name Address Address fromNameAddress = sipStack.getAddressFactory().createAddress(sipURIAddress); fromNameAddress.setDisplayName(displayName); fromHeader = sipStack.getHeaderFactory().createFromHeader(fromNameAddress, headerTag); } catch (Exception ex) { System.out.println("Exception in createFromHeader : " +ex.toString()); ex.printStackTrace(); } return fromHeader; } public ToHeader createToHeader() { if (toHeader != null) return toHeader; try { if (sipURIAddress == null) { createSipURI(); } Address toNameAddress = sipStack.getAddressFactory().createAddress(sipURIAddress); toNameAddress.setDisplayName(displayName); //create name Address toHeader = sipStack.getHeaderFactory().createToHeader(toNameAddress,null); } catch (Exception ex) { System.out.println("Exception in createToHeader : " + ex.toString()); ex.printStackTrace(); } return toHeader; } }
/** * 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.applications.mawo.server.common; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Abstract class for MaWo Task. */ public abstract class AbstractTask implements Task { /** * Task identifier. */ private TaskId taskID = new TaskId(); /** * Task environment. */ private Map<String, String> environment = new HashMap<String, String>(); /** * Command which need to be executed as Task. */ private String taskCmd; /** * Type of task. */ private TaskType taskType; /** * Task timeout. */ private long timeout; /** * logger for abstract class. */ static final Logger LOG = LoggerFactory.getLogger(AbstractTask.class); /** * AbstractTask constructor. */ public AbstractTask() { } /** * AbstrackTask constructor. * @param taskId : Task identifier * @param localenvironment : Task environment vars * @param taskCMD : Cmd to run * @param localtimeout : Task timeout in seconds */ public AbstractTask(final TaskId taskId, final Map<String, String> localenvironment, final String taskCMD, final long localtimeout) { this(); setTaskId(taskId); setEnvironment(localenvironment); setTaskCmd(taskCMD); setTimeout(localtimeout); LOG.info("Created Task - type: " + this.taskType + ", TaskId: " + this.taskID.toString() + ", cmd: '" + taskCMD + "' Timeout: " + timeout); } /** * Get environment for a Task. * @return environment of a Task */ @Override public final Map<String, String> getEnvironment() { return environment; } /** * Set environment for a Task. * @param localenvironment : Map of environment vars */ @Override public final void setEnvironment(final Map<String, String> localenvironment) { this.environment = localenvironment; } /** * Get TaskCmd for a Task. * @return TaskCMD: Its a task command line such as sleep 10 */ @Override public final String getTaskCmd() { return taskCmd; } /** * Set TaskCmd for a Task. * @param taskCMD : Task command line */ @Override public final void setTaskCmd(final String taskCMD) { this.taskCmd = taskCMD; } /** * Get TaskId for a Task. * @return TaskID: Task command line */ @Override public final TaskId getTaskId() { return taskID; } /** * Set Task Id. * @param taskId : Task Identifier */ @Override public final void setTaskId(final TaskId taskId) { if (taskId != null) { this.taskID = taskId; } } /** * Get TaskType for a Task. * @return TaskType: Type of Task */ @Override public final TaskType getTaskType() { return taskType; } /** * Set TaskType for a Task. * @param type Simple or Composite Task */ public final void setTaskType(final TaskType type) { this.taskType = type; } /** * Get Timeout for a Task. * @return timeout in seconds */ @Override public final long getTimeout() { return this.timeout; } /** * Set Task Timeout in seconds. * @param taskTimeout : Timeout in seconds */ @Override public final void setTimeout(final long taskTimeout) { this.timeout = taskTimeout; } /** * Write Task. * @param out : dataoutout object. * @throws IOException : Throws IO exception if any error occurs. */ @Override public final void write(final DataOutput out) throws IOException { taskID.write(out); int environmentSize = 0; if (environment == null) { environmentSize = 0; } else { environmentSize = environment.size(); } new IntWritable(environmentSize).write(out); if (environmentSize != 0) { for (Entry<String, String> envEntry : environment.entrySet()) { new Text(envEntry.getKey()).write(out); new Text(envEntry.getValue()).write(out); } } Text taskCmdText; if (taskCmd == null) { taskCmdText = new Text(""); } else { taskCmdText = new Text(taskCmd); } taskCmdText.write(out); WritableUtils.writeEnum(out, taskType); WritableUtils.writeVLong(out, timeout); } /** * Read Fields from file. * @param in : datainput object. * @throws IOException : Throws IOException in case of error. */ @Override public final void readFields(final DataInput in) throws IOException { this.taskID = new TaskId(); taskID.readFields(in); IntWritable envSize = new IntWritable(0); envSize.readFields(in); for (int i = 0; i < envSize.get(); i++) { Text key = new Text(); Text value = new Text(); key.readFields(in); value.readFields(in); environment.put(key.toString(), value.toString()); } Text taskCmdText = new Text(); taskCmdText.readFields(in); taskCmd = taskCmdText.toString(); taskType = WritableUtils.readEnum(in, TaskType.class); timeout = WritableUtils.readVLong(in); } /** * ToString. * @return String representation of Task */ @Override public final String toString() { return "TaskId: " + this.taskID.toString() + ", TaskType: " + this.taskType + ", cmd: '" + taskCmd + "'"; } }
/** * Copyright (c) 2015 - 2016 Yahoo! Inc., 2016 YCSB contributors. 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. See accompanying * LICENSE file. */ package com.yahoo.ycsb.db; import static org.junit.Assert.*; import com.yahoo.ycsb.ByteIterator; import com.yahoo.ycsb.DBException; import com.yahoo.ycsb.StringByteIterator; import org.junit.*; import java.sql.*; import java.util.HashMap; import java.util.Map; import java.util.HashSet; import java.util.Set; import java.util.Properties; import java.util.Vector; public class JdbcDBClientTest { private static final String TEST_DB_DRIVER = "org.hsqldb.jdbc.JDBCDriver"; private static final String TEST_DB_URL = "jdbc:hsqldb:mem:ycsb"; private static final String TEST_DB_USER = "sa"; private static final String TABLE_NAME = "USERTABLE"; private static final int FIELD_LENGTH = 32; private static final String FIELD_PREFIX = "FIELD"; private static final String KEY_PREFIX = "user"; private static final String KEY_FIELD = "YCSB_KEY"; private static final int NUM_FIELDS = 3; private static Connection jdbcConnection = null; private static JdbcDBClient jdbcDBClient = null; @BeforeClass public static void setup() { setupWithBatch(1, true); } public static void setupWithBatch(int batchSize, boolean autoCommit) { try { jdbcConnection = DriverManager.getConnection(TEST_DB_URL); jdbcDBClient = new JdbcDBClient(); Properties p = new Properties(); p.setProperty(JdbcDBClient.CONNECTION_URL, TEST_DB_URL); p.setProperty(JdbcDBClient.DRIVER_CLASS, TEST_DB_DRIVER); p.setProperty(JdbcDBClient.CONNECTION_USER, TEST_DB_USER); p.setProperty(JdbcDBClient.DB_BATCH_SIZE, Integer.toString(batchSize)); p.setProperty(JdbcDBClient.JDBC_BATCH_UPDATES, "true"); p.setProperty(JdbcDBClient.JDBC_AUTO_COMMIT, Boolean.toString(autoCommit)); jdbcDBClient.setProperties(p); jdbcDBClient.init(); } catch (SQLException e) { e.printStackTrace(); fail("Could not create local Database"); } catch (DBException e) { e.printStackTrace(); fail("Could not create JdbcDBClient instance"); } } @AfterClass public static void teardown() { try { if (jdbcConnection != null) { jdbcConnection.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (jdbcDBClient != null) { jdbcDBClient.cleanup(); } } catch (DBException e) { e.printStackTrace(); } } @Before public void prepareTest() { try { DatabaseMetaData metaData = jdbcConnection.getMetaData(); ResultSet tableResults = metaData.getTables(null, null, TABLE_NAME, null); if (tableResults.next()) { // If the table already exists, just truncate it jdbcConnection.prepareStatement( String.format("TRUNCATE TABLE %s", TABLE_NAME) ).execute(); } else { // If the table does not exist then create it StringBuilder createString = new StringBuilder( String.format("CREATE TABLE %s (%s VARCHAR(100) PRIMARY KEY", TABLE_NAME, KEY_FIELD) ); for (int i = 0; i < NUM_FIELDS; i++) { createString.append( String.format(", %s%d VARCHAR(100)", FIELD_PREFIX, i) ); } createString.append(")"); jdbcConnection.prepareStatement(createString.toString()).execute(); } } catch (SQLException e) { e.printStackTrace(); fail("Failed to prepare test"); } } /* This is a copy of buildDeterministicValue() from core:com.yahoo.ycsb.workloads.CoreWorkload.java. That method is neither public nor static so we need a copy. */ private String buildDeterministicValue(String key, String fieldkey) { int size = FIELD_LENGTH; StringBuilder sb = new StringBuilder(size); sb.append(key); sb.append(':'); sb.append(fieldkey); while (sb.length() < size) { sb.append(':'); sb.append(sb.toString().hashCode()); } sb.setLength(size); return sb.toString(); } /* Inserts a row of deterministic values for the given insertKey using the jdbcDBClient. */ private HashMap<String, ByteIterator> insertRow(String insertKey) { HashMap<String, ByteIterator> insertMap = new HashMap<String, ByteIterator>(); for (int i = 0; i < 3; i++) { insertMap.put(FIELD_PREFIX + i, new StringByteIterator(buildDeterministicValue(insertKey, FIELD_PREFIX + i))); } jdbcDBClient.insert(TABLE_NAME, insertKey, insertMap); return insertMap; } @Test public void insertTest() { try { String insertKey = "user0"; HashMap<String, ByteIterator> insertMap = insertRow(insertKey); ResultSet resultSet = jdbcConnection.prepareStatement( String.format("SELECT * FROM %s", TABLE_NAME) ).executeQuery(); // Check we have a result Row assertTrue(resultSet.next()); // Check that all the columns have expected values assertEquals(resultSet.getString(KEY_FIELD), insertKey); for (int i = 0; i < 3; i++) { assertEquals(resultSet.getString(FIELD_PREFIX + i), insertMap.get(FIELD_PREFIX + i).toString()); } // Check that we do not have any more rows assertFalse(resultSet.next()); resultSet.close(); } catch (SQLException e) { e.printStackTrace(); fail("Failed insertTest"); } } @Test public void updateTest() { try { String preupdateString = "preupdate"; StringBuilder fauxInsertString = new StringBuilder( String.format("INSERT INTO %s VALUES(?", TABLE_NAME) ); for (int i = 0; i < NUM_FIELDS; i++) { fauxInsertString.append(",?"); } fauxInsertString.append(")"); PreparedStatement fauxInsertStatement = jdbcConnection.prepareStatement(fauxInsertString.toString()); for (int i = 2; i < NUM_FIELDS + 2; i++) { fauxInsertStatement.setString(i, preupdateString); } fauxInsertStatement.setString(1, "user0"); fauxInsertStatement.execute(); fauxInsertStatement.setString(1, "user1"); fauxInsertStatement.execute(); fauxInsertStatement.setString(1, "user2"); fauxInsertStatement.execute(); HashMap<String, ByteIterator> updateMap = new HashMap<String, ByteIterator>(); for (int i = 0; i < 3; i++) { updateMap.put(FIELD_PREFIX + i, new StringByteIterator(buildDeterministicValue("user1", FIELD_PREFIX + i))); } jdbcDBClient.update(TABLE_NAME, "user1", updateMap); ResultSet resultSet = jdbcConnection.prepareStatement( String.format("SELECT * FROM %s ORDER BY %s", TABLE_NAME, KEY_FIELD) ).executeQuery(); // Ensure that user0 record was not changed resultSet.next(); assertEquals("Assert first row key is user0", resultSet.getString(KEY_FIELD), "user0"); for (int i = 0; i < 3; i++) { assertEquals("Assert first row fields contain preupdateString", resultSet.getString(FIELD_PREFIX + i), preupdateString); } // Check that all the columns have expected values for user1 record resultSet.next(); assertEquals(resultSet.getString(KEY_FIELD), "user1"); for (int i = 0; i < 3; i++) { assertEquals(resultSet.getString(FIELD_PREFIX + i), updateMap.get(FIELD_PREFIX + i).toString()); } // Ensure that user2 record was not changed resultSet.next(); assertEquals("Assert third row key is user2", resultSet.getString(KEY_FIELD), "user2"); for (int i = 0; i < 3; i++) { assertEquals("Assert third row fields contain preupdateString", resultSet.getString(FIELD_PREFIX + i), preupdateString); } resultSet.close(); } catch (SQLException e) { e.printStackTrace(); fail("Failed updateTest"); } } @Test public void readTest() { String insertKey = "user0"; HashMap<String, ByteIterator> insertMap = insertRow(insertKey); Set<String> readFields = new HashSet<String>(); HashMap<String, ByteIterator> readResultMap = new HashMap<String, ByteIterator>(); // Test reading a single field readFields.add("FIELD0"); jdbcDBClient.read(TABLE_NAME, insertKey, readFields, readResultMap); assertEquals("Assert that result has correct number of fields", readFields.size(), readResultMap.size()); for (String field: readFields) { assertEquals("Assert " + field + " was read correctly", insertMap.get(field).toString(), readResultMap.get(field).toString()); } readResultMap = new HashMap<String, ByteIterator>(); // Test reading all fields readFields.add("FIELD1"); readFields.add("FIELD2"); jdbcDBClient.read(TABLE_NAME, insertKey, readFields, readResultMap); assertEquals("Assert that result has correct number of fields", readFields.size(), readResultMap.size()); for (String field: readFields) { assertEquals("Assert " + field + " was read correctly", insertMap.get(field).toString(), readResultMap.get(field).toString()); } } @Test public void deleteTest() { try { insertRow("user0"); String deleteKey = "user1"; insertRow(deleteKey); insertRow("user2"); jdbcDBClient.delete(TABLE_NAME, deleteKey); ResultSet resultSet = jdbcConnection.prepareStatement( String.format("SELECT * FROM %s", TABLE_NAME) ).executeQuery(); int totalRows = 0; while (resultSet.next()) { assertNotEquals("Assert this is not the deleted row key", deleteKey, resultSet.getString(KEY_FIELD)); totalRows++; } // Check we do not have a result Row assertEquals("Assert we ended with the correct number of rows", totalRows, 2); resultSet.close(); } catch (SQLException e) { e.printStackTrace(); fail("Failed deleteTest"); } } @Test public void scanTest() throws SQLException { Map<String, HashMap<String, ByteIterator>> keyMap = new HashMap<String, HashMap<String, ByteIterator>>(); for (int i = 0; i < 5; i++) { String insertKey = KEY_PREFIX + i; keyMap.put(insertKey, insertRow(insertKey)); } Set<String> fieldSet = new HashSet<String>(); fieldSet.add("FIELD0"); fieldSet.add("FIELD1"); int startIndex = 1; int resultRows = 3; Vector<HashMap<String, ByteIterator>> resultVector = new Vector<HashMap<String, ByteIterator>>(); jdbcDBClient.scan(TABLE_NAME, KEY_PREFIX + startIndex, resultRows, fieldSet, resultVector); // Check the resultVector is the correct size assertEquals("Assert the correct number of results rows were returned", resultRows, resultVector.size()); // Check each vector row to make sure we have the correct fields int testIndex = startIndex; for (Map<String, ByteIterator> result: resultVector) { assertEquals("Assert that this row has the correct number of fields", fieldSet.size(), result.size()); for (String field: fieldSet) { assertEquals("Assert this field is correct in this row", keyMap.get(KEY_PREFIX + testIndex).get(field).toString(), result.get(field).toString()); } testIndex++; } } @Test public void insertBatchTest() throws DBException { insertBatchTest(20); } @Test public void insertPartialBatchTest() throws DBException { insertBatchTest(19); } public void insertBatchTest(int numRows) throws DBException { teardown(); setupWithBatch(10, false); try { String insertKey = "user0"; HashMap<String, ByteIterator> insertMap = insertRow(insertKey); assertEquals(3, insertMap.size()); ResultSet resultSet = jdbcConnection.prepareStatement( String.format("SELECT * FROM %s", TABLE_NAME) ).executeQuery(); // Check we do not have a result Row (because batch is not full yet) assertFalse(resultSet.next()); // insert more rows, completing 1 batch (still results are partial). for (int i = 1; i < numRows; i++) { insertMap = insertRow("user" + i); } // assertNumRows(10 * (numRows / 10)); // call cleanup, which should insert the partial batch jdbcDBClient.cleanup(); // Prevent a teardown() from printing an error jdbcDBClient = null; // Check that we have all rows assertNumRows(numRows); } catch (SQLException e) { e.printStackTrace(); fail("Failed insertBatchTest"); } finally { teardown(); // for next tests setup(); } } private void assertNumRows(long numRows) throws SQLException { ResultSet resultSet = jdbcConnection.prepareStatement( String.format("SELECT * FROM %s", TABLE_NAME) ).executeQuery(); for (int i = 0; i < numRows; i++) { assertTrue("expecting " + numRows + " results, received only " + i, resultSet.next()); } assertFalse("expecting " + numRows + " results, received more", resultSet.next()); resultSet.close(); } }
package org.edx.mobile.module.analytics; import android.content.ComponentName; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.segment.analytics.Properties; import com.segment.analytics.Traits; public interface ISegment { /* * Events mentioned in PDF * 1)Identify * 2)Video playing events * a)edx.video.played * b)edx.video.paused * c)edx.video.stopped * d)edx.video.transcript.shown * e)edx.video.transcript.hidden * 3)Load events edx.video.loaded * 4)Seek events (NOTE: may not be implemented for General * Availability due to technical limitations in the video player) */ Traits identifyUser(String userID, String email, String username); Properties trackVideoPlaying(String videoId, Double currentTime, String courseId, String unitUrl); Properties trackVideoPause(String videoId, Double currentTime, String courseId, String unitUrl); Properties trackVideoStop(String videoId, Double currentTime, String courseId, String unitUrl); Properties trackShowTranscript(String videoId, Double currentTime, String courseId, String unitUrl); Properties trackHideTranscript(String videoId, Double currentTime, String courseId, String unitUrl); Properties trackVideoLoading(String videoId, String courseId, String unitUrl); Properties trackVideoSeek(String videoId, Double oldTime, Double newTime, String courseId, String unitUrl, Boolean skipSeek); void resetIdentifyUser(); /* Events not mentioned in PDF */ Properties trackScreenView(String screenName); Properties trackScreenView(String screenName, String courseId, String value); Properties trackDownloadComplete(String videoId, String courseId, String unitUrl); Properties trackOpenInBrowser(String url); Properties trackSectionBulkVideoDownload(String enrollmentId, String section, long videoCount); Properties trackSubSectionBulkVideoDownload(String section, String subSection, String enrollmentId, long videoCount); Properties trackUserLogin(String method); Properties trackUserLogout(); Properties trackTranscriptLanguage(String videoId, Double currentTime, String lang, String courseId, String unitUrl); Properties trackSingleVideoDownload(String videoId, String courseId, String unitUrl); Properties trackVideoOrientation(String videoId, Double currentTime, boolean isLandscape, String courseId, String unitUrl); Properties trackUserSignUpForAccount(); Properties trackUserFindsCourses(); Properties trackCreateAccountClicked(String appVersion, String source); Properties trackEnrollClicked(String courseId, boolean email_opt_in); Properties trackNotificationReceived(@Nullable String courseId); Properties trackNotificationTapped(@Nullable String courseId); /** * Sets given tracker instance and uses it for analytics. * This method is useful in some cases where a given tracker is to be used. * For example, unit tests might use mocked tracker object. * @param tracker */ void setTracker(ISegmentTracker tracker); Properties trackUserCellConnection(String carrierName, boolean isZeroRated); Properties trackUserConnectionSpeed(String connectionType, float connectionSpeed); Properties courseGroupAccessed(String courseId); Properties gameGroupAccessed(long groupID, int groupUserCount); Properties groupCreated(long groupID, int invitedUserCount); Properties groupInvited(long groupID, int invitedUserCount); Properties courseShared(String courseId, String socialNetwork); Properties certificateShared(@NonNull String courseId, @NonNull String certificateUrl, @NonNull ComponentName componentName); Properties courseDetailShared(@NonNull String courseId, @NonNull String aboutUrl, @NonNull ComponentName componentName); Properties socialConnectionEvent(boolean connected, String socialNetwork); Properties coursesVisibleToFriendsChange(boolean visible); Properties trackCourseOutlineMode(boolean isVideoMode); Properties trackCourseComponentViewed(String blockId, String courseId); Properties trackOpenInBrowser(String blockId, String courseId, boolean isSupported); Properties trackProfileViewed(@NonNull String username); Properties trackProfilePhotoSet(boolean fromCamera); interface Keys { String NAME = "name"; String OLD_TIME = "old_time"; String NEW_TIME = "new_time"; String SEEK_TYPE = "seek_type"; String REQUESTED_SKIP_INTERVAL = "requested_skip_interval"; String MODULE_ID = "module_id"; String CODE = "code"; String CURRENT_TIME = "current_time"; String COURSE_ID = "course_id"; String OPEN_BROWSER = "open_in_browser_url"; String COMPONENT = "component"; String COURSE_SECTION = "course_section"; String COURSE_SUBSECTION = "course_subsection"; String NO_OF_VIDEOS = "number_of_videos"; String FULLSCREEN = "settings.video.fullscreen"; String LANGUAGE = "language"; String TARGET_URL = "target_url"; String URL = "url"; String CONTEXT = "context"; String DATA = "data"; String METHOD = "method"; String APP = "app_name"; String EMAIL_OPT_IN = "email_opt_in"; String PROVIDER = "provider"; String BLOCK_ID = "block_id"; String SUPPORTED = "supported"; String NEW_OUTLINE_MODE = "new-mode"; String DEVICE_ORIENTATION = "device-orientation"; String NAVIGATION_MODE = "navigation-mode"; String CELL_CARRIER = "cell_carrier"; String CELL_ZERO_RATED = "cell_zero_rated"; String CONNECTION_TYPE = "connection_type"; String CONNECTION_SPEED = "connection_speed"; String GROUP_ID = "group_id"; String GROUP_USER_COUNT = "group_user_count"; String GROUP_INVITED_USER_COUNT = "group_invited_count"; String SOCIAL_NETWORK = "social_network"; String TYPE = "type"; String SOCIAL_CONNECTION_STATE = "social_connection_state"; String SETTING_COURSES_VISIBLE_STATE = "settings_courses_visible_state"; String CATEGORY = "category"; String LABEL = "label"; String ACTION = "action"; String COMPONENT_VIEWED = "Component Viewed"; } interface Values { String SCREEN = "screen"; String SKIP = "skip"; String SLIDE = "slide"; String MOBILE = "mobile"; String VIDEOPLAYER = "videoplayer"; String PASSWORD = "Password"; String FACEBOOK = "Google"; String GOOGLE = "Facebook"; String DOWNLOAD_MODULE = "downloadmodule"; String VIDEO_LOADED = "edx.video.loaded"; String VIDEO_PLAYED = "edx.video.played"; String VIDEO_PAUSED = "edx.video.paused"; String VIDEO_STOPPED = "edx.video.stopped"; //The seek event name has been changed as per MOB-1273 String VIDEO_SEEKED = "edx.video.position.changed"; String TRANSCRIPT_SHOWN = "edx.video.transcript.shown"; String TRANSCRIPT_HIDDEN = "edx.video.transcript.hidden"; String TRANSCRIPT_LANGUAGE = "edx.bi.video.transcript.language.selected"; String FULLSREEN_TOGGLED = "edx.bi.video.screen.fullscreen.toggled"; String BROWSER_LAUNCHED = "edx.bi.app.browser.launched"; String SINGLE_VIDEO_DOWNLOAD = "edx.bi.video.download.requested"; String BULKDOWNLOAD_SECTION = "edx.bi.video.section.bulkdownload.requested"; String BULK_DOWNLOAD_SUBSECTION = "edx.bi.video.subsection.bulkdownload.requested"; String VIDEO_DOWNLOADED = "edx.bi.video.downloaded"; String USERLOGOUT = "edx.bi.app.user.logout"; String USERLOGIN = "edx.bi.app.user.login"; String APP_NAME = "edx.mobileapp.android"; String USER_NO_ACCOUNT = "edx.bi.app.user.signup.clicked"; String USER_FIND_COURSES = "edx.bi.app.search.find_courses.clicked"; String CREATE_ACCOUNT_CLICK = "edx.bi.app.user.register.clicked"; String USER_COURSE_ENROLL = "edx.bi.app.course.enroll.clicked"; String CONVERSION = "conversion"; String USER_ENGAGEMENT = "user-engagement"; String COURSE_DISCOVERY = "course-discovery"; String PUSH_NOTIFICATION = "notifications"; String ANNOUNCEMENT = "announcement"; String CONNECTION_CELL = "edx.bi.app.connection.cell"; String CONNECTION_SPEED = "edx.bi.app.connection.speed"; String NOTIFICATION_RECEIVED = "edx.bi.app.notification.course.update.received"; String NOTIFICATION_TAPPED = "edx.bi.app.notification.course.update.tapped"; String ACCESS_COURSE_GROUP = "edx.bi.app.groups.course_access"; String ACCESS_GAME_GROUP = "edx.bi.app.groups.game_access"; String CREATE_GAME_GROUP = "edx.bi.app.groups.game_create"; String INVITE_GAME_GROUP = "edx.bi.app.groups.game_invite"; String SOCIAL_COURSE_SHARED = "edx.bi.app.social.course_share"; String SOCIAL_CERTIFICATE_SHARED = "edx.bi.app.certificate.shared"; String SOCIAL_COURSE_DETAIL_SHARED = "edx.bi.app.course.shared"; String SOCIAL_CONNECTION_CHANGE = "edx.bi.app.social.connection"; String SETTING_COURSES_VISIBLE_CHANGE = "edx.bi.app.user.share_courses"; String NAVIGATION = "navigation"; String SOCIAL_SHARING = "social-sharing"; String PROFILE = "profiles"; String CAMERA = "camera"; String LIBRARY = "library"; String SWITCH_OUTLINE_MODE = "edx.bi.app.navigation.switched-mode.clicked"; String PROFILE_VIEWED = "edx.bi.app.profile.view"; String PROFILE_PHOTO_SET = "edx.bi.app.profile.setphoto"; String COMPONENT_VIEWED = "edx.bi.app.navigation.component.viewed"; String OPEN_IN_BROWSER = "edx.bi.app.navigation.open-in-browser"; String OUTLINE_MODE_FULL = "full"; String OUTLINE_MODE_VIDEO = "video"; String SWITCH_TO_FULL_MODE = "Switch to Full Mode"; String SWITCH_TO_VIDEO_MODE = "Switch to Video Mode"; String OPEN_IN_WEB_SUPPORTED = "Open in browser - Supported"; String OPEN_IN_WEB_NOT_SUPPORTED = "Open in browser - Unsupported"; String LANDSCAPE = "landscape"; String PORTRAIT = "portrait"; String WIFI = "wifi"; String CELL_DATA = "cell_data"; } interface Screens { String COURSE_INFO_SCREEN = "Course Info"; String LAUNCH_ACTIVITY = "Launch"; String COURSE_DASHBOARD = "Course Dashboard"; String COURSE_OUTLINE = "Course Outline"; String SECTION_OUTLINE = "Section Outline"; String UNIT_DETAIL = "Unit Detail"; String CERTIFICATE = "Certificate"; String CREATE_GAME_GROUPS = "Create Games Group"; String DOWNLOADS = "Downloads"; String FIND_COURSES = "Find Courses"; String FRIENDS_IN_COURSE = "Friends In This Course"; String GROUP_LIST = "Group List"; String LOGIN = "Login"; String MY_VIDEOS = "My Videos"; String MY_VIDEOS_ALL = "My Videos - All Videos"; String MY_VIDEOS_RECENT = "My Videos - Recent Videos"; String MY_COURSES = "My Courses"; String MY_FRIENDS_COURSES = "My Friends' Courses"; String SETTINGS = "Settings"; String SOCIAL_FRIEND_PICKER = "Social Friend Picker"; } interface Events { String LOADED_VIDEO = "Loaded Video"; String PLAYED_VIDEO = "Played Video"; String PAUSED_VIDEO = "Paused Video"; String STOPPED_VIDEO = "Stopped Video"; String SEEK_VIDEO = "Seeked Video"; String SHOW_TRANSCRIPT = "Show Transcript"; String HIDE_TRANSCRIPT = "Hide Transcript"; String VIDEO_DOWNLOADED = "Video Downloaded"; String BULK_DOWNLOAD_SECTION = "Bulk Download Section"; String BULK_DOWNLOAD_SUBSECTION = "Bulk Download Subsection"; String SINGLE_VIDEO_DOWNLOAD = "Single Video Download"; String SCREEN_TOGGLED = "Screen Toggled"; String USER_LOGIN = "User Login"; String USER_LOGOUT = "User Logout"; String BROWSER_LAUNCHED = "Browser Launched"; String LANGUAGE_CLICKED = "Language Clicked"; String SIGN_UP = "Sign up Clicked"; String FIND_COURSES = "Find Courses Clicked"; String CREATE_ACCOUNT_CLICKED = "Create Account Clicked"; String ENROLL_COURSES = "Enroll Course Clicked"; String TRACK_CELL_CONNECTION = "Cell Connection Established"; String SPEED = "Connected Speed Report"; String COURSE_GROUP_ACCESSED = "Course Group Accessed"; String GAME_GROUP_ACCESSED = "Game Group Accessed"; String GAME_GROUP_CREATE = "Game Group Created"; String GAME_GROUP_INVITE = "Game Group Invited"; String SOCIAL_COURSE_SHARED = "Social Course Shared"; String SOCIAL_CERTIFICATE_SHARED = "Shared a certificate"; String SOCIAL_COURSE_DETAIL_SHARED = "Shared a course"; String SOCIAL_CONNECTION_CHANGE = "Social Connection Change"; String SETTING_COURSES_VISIBLE_CHANGE = "Settings Courses Visibility Change"; String SWITCH_OUTLINE_MODE = "Switch outline mode"; String COMPONENT_VIEWED = "Component Viewed"; String OPEN_IN_BROWSER = "Browser Launched"; String PUSH_NOTIFICATION_RECEIVED = "notification-received"; String PUSH_NOTIFICATION_TAPPED = "notification-tapped"; String PROFILE_VIEWED = "Viewed a profile"; String PROFILE_PHOTO_SET = "Set a profile picture"; } }
package com.raw.khipu.form.profile; import java.util.HashMap; import java.util.Map; import com.raw.khipu.dto.Profile; import com.raw.khipu.form.DialogBox; import com.raw.khipu.form.DialogBox.ConfirmListener; import com.raw.khipu.form.FormViewImpl; import com.raw.khipu.i18n.AppMessages; import com.vaadin.data.util.BeanItemContainer; import com.vaadin.ui.Button; import com.vaadin.ui.Notification; import com.vaadin.ui.TextField; public class ProfileFormViewImpl extends FormViewImpl { private static final long serialVersionUID = 5011463172197746695L; private Button btnCreate; private Button btnModify; private Button btnEnable; private Button btnDelete; private TextField idProfile; private TextField name; private TextField enabled; public ProfileFormViewImpl() { btnCreate = new Button("", this); btnCreate.setData("btnCreate"); btnModify = new Button("", this); btnModify.setData("btnModify"); btnEnable = new Button("", this); btnEnable.setData("btnEnable"); btnDelete = new Button("", this); btnDelete.setData("btnDelete"); getToolBar().addComponent(btnCreate); getToolBar().addComponent(btnModify); getToolBar().addComponent(btnEnable); getToolBar().addComponent(btnDelete); // add fields to edit form layout idProfile = new TextField(); name = new TextField(); enabled = new TextField(); getFormEditLayout().addComponent(idProfile); getFormEditLayout().addComponent(name); getFormEditLayout().addComponent(enabled); } @Override public void bindTableModelWithComponents() { try { // Bind dat model list with Table Component setTableModelWithComponent(0, ((ProfileFormModel) getFormModel()).getProfiles(), getFirstTable()); // Set BeanItemContainer with Entity Class setPropertyBeanItemContainer(new BeanItemContainer<Profile>(Profile.class)); } catch (Exception e) { e.printStackTrace(); } } @Override public void prepareEdition(String mode) { try { // Define the entity class for the first table setEntityClass(Profile.class); if (mode.equalsIgnoreCase(CREATE_MODE)) { // Bind form component fields with Bean Field Group for CREATE edition setBeanFieldGroupWithComponent(new Profile(), this, null); // Locale edit window title setEditWindowTitle(getApp().getMessageLocale(AppMessages.btnCreate) + " " + getApp().getMessageLocale(AppMessages.Profile)); } if (mode.equalsIgnoreCase(MODIFY_MODE)) { // Bind form component fields with Bean Field Group for MODIFY edition setBeanFieldGroupWithComponent(((Profile) getFirstTable().getValue()), this, ((Profile) getFirstTable().getValue()).getIdProfile()); // Locale edit window title setEditWindowTitle(getApp().getMessageLocale(AppMessages.btnModify) + " " + getApp().getMessageLocale(AppMessages.Profile)); } if (mode.equalsIgnoreCase(CHANGE_STATUS_MODE)) { // Bind form component fields with Bean Field Group for MODIFY edition setBeanFieldGroupWithComponent(((Profile) getFirstTable().getValue()), this, ((Profile) getFirstTable().getValue()).getIdProfile()); DialogBox box = new DialogBox(getApp()); box.show(getApp().getMessageLocale(AppMessages.FormWarning), getApp().getMessageLocale(AppMessages.FormAreYouSureDisable), new ConfirmListener() { private static final long serialVersionUID = 3500651267535289099L; @Override public void onClose(DialogBox dialog) throws Exception { if (dialog.isConfirmed()) { // Get selected record and udpdate it Profile record = (Profile) getFieldGroup().getItemDataSource().getBean(); record.setEnabled(0); // Update record in database getFormModel().updateRecord(getEntityClass(), record, record.getIdProfile()); // Refresh table component getFirstTable().refreshRowCache(); } } }); } if (mode.equalsIgnoreCase(DELETE_MODE)) { // Bind form component fields with Bean Field Group for MODIFY edition setBeanFieldGroupWithComponent(((Profile) getFirstTable().getValue()), this, ((Profile) getFirstTable().getValue()).getIdProfile()); DialogBox box = new DialogBox(getApp()); box.show(getApp().getMessageLocale(AppMessages.FormWarning), getApp().getMessageLocale(AppMessages.FormAreYouSureDelete), new ConfirmListener() { private static final long serialVersionUID = 3500651267535289099L; @Override public void onClose(DialogBox dialog) throws Exception { if (dialog.isConfirmed()) { // Get selected record Profile record = (Profile) getFieldGroup().getItemDataSource().getBean(); // Delete record in database getFormModel().deleteRecord(getEntityClass(), record.getIdProfile()); // Delete record on table compoenent and refresh it getFirstTable().removeItem(record); getFirstTable().refreshRowCache(); } } }); } } catch (java.lang.NullPointerException e) { Notification.show(getApp().getMessageLocale(AppMessages.FormWarning), getApp() .getMessageLocale(AppMessages.FormMustSelectRecord), Notification.Type.WARNING_MESSAGE); } catch (Exception e) { Notification.show(getApp().getMessageLocale(AppMessages.FormError), e.getMessage(), Notification.Type.ERROR_MESSAGE); } } @Override public void applyValidations() { idProfile.setEnabled(false); name.setRequired(true); name.setImmediate(true); name.setNullRepresentation(""); name.setRequiredError(getApp().getMessageLocale(AppMessages.FormItemIsRequired)); enabled.setRequired(true); enabled.setImmediate(true); enabled.setNullRepresentation(""); enabled.setRequiredError(getApp().getMessageLocale(AppMessages.FormItemIsRequired)); } @Override public void refreshComponents() { try { // Get new data from model bindTableModelWithComponents(); // Populate data on component populateComponent(0); // Apply locale charactheristics setVisibleColumns(); } catch (Exception e) { e.printStackTrace(); } } @Override public void setVisibleColumns() { getFirstTable().setVisibleColumns("idProfile", "name", "enabled"); getFirstTable().sort(new Object[] { "idProfile" }, new boolean[] { true, true }); } @Override public void setLocaleComponents() { setFormTitle(getApp().getMessageLocale(AppMessages.Profile)); // Locale Columns Table getFirstTable().setColumnHeader("idProfile", getApp().getMessageLocale(AppMessages.ProfileId)); getFirstTable().setColumnHeader("name", getApp().getMessageLocale(AppMessages.ProfileName)); getFirstTable().setColumnHeader("enabled", getApp().getMessageLocale(AppMessages.ProfileEnabled)); // Locale main buttons btnCreate.setCaption(getApp().getMessageLocale(AppMessages.btnCreate)); btnModify.setCaption(getApp().getMessageLocale(AppMessages.btnModify)); btnEnable.setCaption(getApp().getMessageLocale(AppMessages.btnEnable)); btnDelete.setCaption(getApp().getMessageLocale(AppMessages.btnDelete)); // Locale Edit Form idProfile.setCaption(getApp().getMessageLocale(AppMessages.ProfileId)); name.setCaption(getApp().getMessageLocale(AppMessages.ProfileName)); enabled.setCaption(getApp().getMessageLocale(AppMessages.ProfileEnabled)); } @Override public void registerChildForms() throws Exception { // Prepare parameters to child form Map<String, Object> params = new HashMap<String, Object>(); // Register child forms addDetailForm( "form.profileDetail.ProfileDetailFormFacade", getApp().getMainView().openForm("form.profileDetail.ProfileDetailFormFacade", params, null, false)); } }
/* * Copyright (c) 2010 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ovirt.engine.api.common.util; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import javax.ws.rs.Path; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import org.ovirt.engine.api.model.ActionsBuilder; import org.ovirt.engine.api.model.BaseResource; import org.ovirt.engine.api.model.CdRom; import org.ovirt.engine.api.model.Cluster; import org.ovirt.engine.api.model.DataCenter; import org.ovirt.engine.api.model.DetailedLink; import org.ovirt.engine.api.model.Disk; import org.ovirt.engine.api.model.Domain; import org.ovirt.engine.api.model.Event; import org.ovirt.engine.api.model.File; import org.ovirt.engine.api.model.GlusterVolume; import org.ovirt.engine.api.model.Group; import org.ovirt.engine.api.model.Host; import org.ovirt.engine.api.model.HostNIC; import org.ovirt.engine.api.model.Link; import org.ovirt.engine.api.model.LinkCapabilities; import org.ovirt.engine.api.model.NIC; import org.ovirt.engine.api.model.Network; import org.ovirt.engine.api.model.Parameter; import org.ovirt.engine.api.model.ParametersSet; import org.ovirt.engine.api.model.Permission; import org.ovirt.engine.api.model.Permit; import org.ovirt.engine.api.model.Request; import org.ovirt.engine.api.model.Role; import org.ovirt.engine.api.model.Snapshot; import org.ovirt.engine.api.model.Statistic; import org.ovirt.engine.api.model.Storage; import org.ovirt.engine.api.model.StorageDomain; import org.ovirt.engine.api.model.Tag; import org.ovirt.engine.api.model.Template; import org.ovirt.engine.api.model.Url; import org.ovirt.engine.api.model.User; import org.ovirt.engine.api.model.VM; import org.ovirt.engine.api.model.VmPool; import org.ovirt.engine.api.resource.AssignedNetworkResource; import org.ovirt.engine.api.resource.AssignedNetworksResource; import org.ovirt.engine.api.resource.AssignedPermissionsResource; import org.ovirt.engine.api.resource.AssignedRolesResource; import org.ovirt.engine.api.resource.AssignedTagResource; import org.ovirt.engine.api.resource.AssignedTagsResource; import org.ovirt.engine.api.resource.AttachedStorageDomainResource; import org.ovirt.engine.api.resource.AttachedStorageDomainsResource; import org.ovirt.engine.api.resource.ClusterResource; import org.ovirt.engine.api.resource.ClustersResource; import org.ovirt.engine.api.resource.DataCenterResource; import org.ovirt.engine.api.resource.DataCentersResource; import org.ovirt.engine.api.resource.DeviceResource; import org.ovirt.engine.api.resource.DevicesResource; import org.ovirt.engine.api.resource.DiskResource; import org.ovirt.engine.api.resource.DomainGroupResource; import org.ovirt.engine.api.resource.DomainGroupsResource; import org.ovirt.engine.api.resource.DomainResource; import org.ovirt.engine.api.resource.DomainUserResource; import org.ovirt.engine.api.resource.DomainUsersResource; import org.ovirt.engine.api.resource.DomainsResource; import org.ovirt.engine.api.resource.EventResource; import org.ovirt.engine.api.resource.EventsResource; import org.ovirt.engine.api.resource.FileResource; import org.ovirt.engine.api.resource.FilesResource; import org.ovirt.engine.api.resource.GlusterVolumeResource; import org.ovirt.engine.api.resource.GlusterVolumesResource; import org.ovirt.engine.api.resource.GroupResource; import org.ovirt.engine.api.resource.GroupsResource; import org.ovirt.engine.api.resource.HostNicResource; import org.ovirt.engine.api.resource.HostNicsResource; import org.ovirt.engine.api.resource.HostResource; import org.ovirt.engine.api.resource.HostStorageResource; import org.ovirt.engine.api.resource.HostsResource; import org.ovirt.engine.api.resource.NetworkResource; import org.ovirt.engine.api.resource.NetworksResource; import org.ovirt.engine.api.resource.NicResource; import org.ovirt.engine.api.resource.PermissionResource; import org.ovirt.engine.api.resource.PermitResource; import org.ovirt.engine.api.resource.PermitsResource; import org.ovirt.engine.api.resource.ReadOnlyDeviceResource; import org.ovirt.engine.api.resource.ReadOnlyDevicesResource; import org.ovirt.engine.api.resource.RoleResource; import org.ovirt.engine.api.resource.RolesResource; import org.ovirt.engine.api.resource.SnapshotResource; import org.ovirt.engine.api.resource.SnapshotsResource; import org.ovirt.engine.api.resource.StatisticResource; import org.ovirt.engine.api.resource.StatisticsResource; import org.ovirt.engine.api.resource.StorageDomainContentResource; import org.ovirt.engine.api.resource.StorageDomainContentsResource; import org.ovirt.engine.api.resource.StorageDomainResource; import org.ovirt.engine.api.resource.StorageDomainsResource; import org.ovirt.engine.api.resource.StorageResource; import org.ovirt.engine.api.resource.TagResource; import org.ovirt.engine.api.resource.TagsResource; import org.ovirt.engine.api.resource.TemplateResource; import org.ovirt.engine.api.resource.TemplatesResource; import org.ovirt.engine.api.resource.UserResource; import org.ovirt.engine.api.resource.UsersResource; import org.ovirt.engine.api.resource.VmPoolResource; import org.ovirt.engine.api.resource.VmPoolsResource; import org.ovirt.engine.api.resource.VmResource; import org.ovirt.engine.api.resource.VmsResource; /** * Contains a static addLinks() method which constructs any href attributes * and action links required by a representation. * * The information used to build links is obtained from the annotations on * the API definition interfaces. * For example, a link to a VM is the combination of the @Path attribute on * VmsResource and the VM id - i.e. '/restapi-definition/vms/{vm_id}' * * Resource collections which are a sub-resource of a parent collection * present a more difficult challenge. For example, the link to a VM tag * is the combination of the @Path attribute on VmsResource, the VM id, * the @Path attribute on VmResource.getTagsResource() and the tag id - * i.e. '/restapi-definition/vms/{vm_id}/tags/{tag_id}' * In most cases the parent type may be computed, but in exceptional * cases there are a number of equally valid candidates. Disambiguation * is achieved via an explicit suggestedParentType parameter. * * To be able to do this we need, for each collection, the collection type * (e.g. AssignedTagsResource), the resource type (e.g. AssignedTagResource) * and the parent model type (e.g. VM). The TYPES map below is populated * with this information for every resource type. */ public class LinkHelper { private static final String SEARCH_RELATION = "/search"; private static final String SEARCH_TEMPLATE = "?search={query}"; private static final String PARAMETER_TEMPLATE = "&%s={%s}"; /** * A constant representing the pseudo-parent of a top-level collection */ private static final Class<? extends BaseResource> NO_PARENT = BaseResource.class; /** * A map describing every possible collection */ private static ModelToCollectionsMap TYPES = new ModelToCollectionsMap(); static { ParentToCollectionMap map; map = new ParentToCollectionMap(ReadOnlyDeviceResource.class, ReadOnlyDevicesResource.class, Template.class); TYPES.put(CdRom.class, map); map = new ParentToCollectionMap(DeviceResource.class, DevicesResource.class, VM.class); TYPES.put(CdRom.class, map); map = new ParentToCollectionMap(ClusterResource.class, ClustersResource.class); TYPES.put(Cluster.class, map); map = new ParentToCollectionMap(DataCenterResource.class, DataCentersResource.class); TYPES.put(DataCenter.class, map); map = new ParentToCollectionMap(ReadOnlyDeviceResource.class, ReadOnlyDevicesResource.class, Template.class); TYPES.put(Disk.class, map); map = new ParentToCollectionMap(DeviceResource.class, DevicesResource.class, VM.class); TYPES.put(Disk.class, map); map = new ParentToCollectionMap(DiskResource.class, DevicesResource.class, VM.class); TYPES.put(Disk.class, map); map = new ParentToCollectionMap(HostResource.class, HostsResource.class); TYPES.put(Host.class, map); map = new ParentToCollectionMap(HostNicResource.class, HostNicsResource.class, Host.class); TYPES.put(HostNIC.class, map); map = new ParentToCollectionMap(FileResource.class, FilesResource.class, StorageDomain.class); TYPES.put(File.class, map); map = new ParentToCollectionMap(GroupResource.class, GroupsResource.class); map.add(DomainGroupResource.class, DomainGroupsResource.class, Domain.class); TYPES.put(Group.class, map); map = new ParentToCollectionMap(PermissionResource.class, AssignedPermissionsResource.class, User.class); map.add(PermissionResource.class, AssignedPermissionsResource.class, Group.class); map.add(PermissionResource.class, AssignedPermissionsResource.class, Role.class); map.add(PermissionResource.class, AssignedPermissionsResource.class, VM.class); TYPES.put(Permission.class, map); map = new ParentToCollectionMap(NetworkResource.class, NetworksResource.class); map.add(AssignedNetworkResource.class, AssignedNetworksResource.class, Cluster.class); TYPES.put(Network.class, map); map = new ParentToCollectionMap(DeviceResource.class, DevicesResource.class); map.add(DeviceResource.class, DevicesResource.class, VM.class); map.add(DeviceResource.class, DevicesResource.class, Template.class); map.add(ReadOnlyDeviceResource.class, ReadOnlyDevicesResource.class, Template.class); map.add(NicResource.class, DevicesResource.class, VM.class); TYPES.put(NIC.class, map); map = new ParentToCollectionMap(PermitResource.class, PermitsResource.class, Role.class); TYPES.put(Permit.class, map); map = new ParentToCollectionMap(RoleResource.class, RolesResource.class); map.add(RoleResource.class, AssignedRolesResource.class, User.class); TYPES.put(Role.class, map); map = new ParentToCollectionMap(SnapshotResource.class, SnapshotsResource.class, VM.class); TYPES.put(Snapshot.class, map); map = new ParentToCollectionMap(StorageResource.class, HostStorageResource.class, Host.class); TYPES.put(Storage.class, map); map = new ParentToCollectionMap(StorageDomainResource.class, StorageDomainsResource.class); map.add(AttachedStorageDomainResource.class, AttachedStorageDomainsResource.class, DataCenter.class); TYPES.put(StorageDomain.class, map); map = new ParentToCollectionMap(TagResource.class, TagsResource.class); map.add(AssignedTagResource.class, AssignedTagsResource.class, Host.class); map.add(AssignedTagResource.class, AssignedTagsResource.class, User.class); map.add(AssignedTagResource.class, AssignedTagsResource.class, VM.class); map.add(AssignedTagResource.class, AssignedTagsResource.class, Group.class); TYPES.put(Tag.class, map); map = new ParentToCollectionMap(TemplateResource.class, TemplatesResource.class); map.add(StorageDomainContentResource.class, StorageDomainContentsResource.class, StorageDomain.class); TYPES.put(Template.class, map); map = new ParentToCollectionMap(UserResource.class, UsersResource.class); map.add(DomainUserResource.class, DomainUsersResource.class, Domain.class); TYPES.put(User.class, map); map = new ParentToCollectionMap(VmResource.class, VmsResource.class); map.add(StorageDomainContentResource.class, StorageDomainContentsResource.class, StorageDomain.class); TYPES.put(VM.class, map); map = new ParentToCollectionMap(VmPoolResource.class, VmPoolsResource.class); TYPES.put(VmPool.class, map); map = new ParentToCollectionMap(EventResource.class, EventsResource.class); TYPES.put(Event.class, map); map = new ParentToCollectionMap(DomainResource.class, DomainsResource.class); TYPES.put(Domain.class, map); map = new ParentToCollectionMap(StatisticResource.class, StatisticsResource.class, Disk.class); map.add(StatisticResource.class, StatisticsResource.class, Host.class); map.add(StatisticResource.class, StatisticsResource.class, HostNIC.class); map.add(StatisticResource.class, StatisticsResource.class, NIC.class); map.add(StatisticResource.class, StatisticsResource.class, VM.class); TYPES.put(Statistic.class, map); map = new ParentToCollectionMap(GlusterVolumeResource.class, GlusterVolumesResource.class); map.add(GlusterVolumeResource.class, GlusterVolumesResource.class, Cluster.class); TYPES.put(GlusterVolume.class, map); } /** * Obtain the relative path to a top-level collection * * The path is simply the value of the @Path annotation on the * supplied collection resource type * * @param clz the collection resource type * @return the relative path to the collection */ private static String getPath(Class<?> clz) { Path pathAnnotation = clz.getAnnotation(Path.class); String path = pathAnnotation.value(); if (path.startsWith("/")) { path = path.substring(1); } return path; } /** * Obtain the relative path to a sub-collection * * The path is obtained from the @Path annotation on the method on @parent * which returns an instance of @clz * * A case-insensitive check for @type's name as a substring of the method * is also performed to guard against the case where @parent has multiple * methods returning instances of @clz, e.g. VmResource has multiple * methods return DevicesResource instances * * @param clz the collection resource type (e.g. AssignedTagsResource) * @param parent the parent resource type (e.g. VmResource) * @param type the model type (e.g. Tag) * @return the relative path to the collection */ private static String getPath(Class<?> clz, Class<?> parent, Class<?> type) { for (Method method : parent.getMethods()) { if (method.getName().startsWith("get") && clz.isAssignableFrom(method.getReturnType()) && isPluralResourceGetter(method.getName(), type.getSimpleName())) { Path pathAnnotation = method.getAnnotation(Path.class); return pathAnnotation.value(); } } return null; } private static boolean isPluralResourceGetter(String method, String type) { method = method.toLowerCase(); type = type.toLowerCase(); method = chopStart(method, "get"); method = chopEnd(method, "resource"); method = chopEnd(method, "s"); if (type.endsWith("y")) { method = chopEnd(method, "ie"); type = chopEnd(type, "y"); } return method.contains(type); } private static String chopStart(String str, String chop) { if (str.startsWith(chop)) { return str.substring(chop.length()); } else { return str; } } private static String chopEnd(String str, String chop) { if (str.endsWith(chop)) { return str.substring(0, str.length() - chop.length()); } else { return str; } } /** * Obtain a set of inline BaseResource objects from @obj * * i.e. return the value of any properties on @obj which are a * sub-type of BaseResource * * @param obj the object to check * @return a list of any inline BaseResource objects */ private static List<BaseResource> getInlineResources(Object obj) { ArrayList<BaseResource> ret = new ArrayList<BaseResource>(); for (Method method : obj.getClass().getMethods()) { if (method.getName().startsWith("get") && BaseResource.class.isAssignableFrom(method.getReturnType())) { try { BaseResource inline = (BaseResource)method.invoke(obj); if (inline != null) { ret.add(inline); } } catch (Exception e) { // invocation target exception should not occur on simple getter } } } return ret; } /** * Unset the property on @model of type @type * * @param model the object with the property to unset * @param type the type of the property */ private static void unsetInlineResource(BaseResource model, Class<?> type) { for (Method method : model.getClass().getMethods()) { if (method.getName().startsWith("set")) { try { if (type.isAssignableFrom(method.getParameterTypes()[0])) { method.invoke(model, new Object[]{null}); return; } } catch (Exception e) { // invocation target exception should not occur on simple setter } } } } /** * Return any parent object set on @model * * i.e. return the value of any bean property whose type matches @parentType * * @param model object to check * @param parentType the type of the parent * @return the parent object, or null if not set */ private static <R extends BaseResource> BaseResource getParentModel(R model, Class<?> parentType) { for (BaseResource inline : getInlineResources(model)) { if (parentType.isAssignableFrom(inline.getClass())) { return inline; } } return null; } /** * Lookup the #Collection instance which represents this object * * i.e. for a VM tag (i.e. a Tag object which its VM property set) * return the #Collection instance which encapsulates AssignedTagResource, * AssignedTagsResource and VM. * * @param model the object to query for * @return the #Collection instance representing the object's collection */ private static Collection getCollection(BaseResource model) { return getCollection(model, null); } /** * Lookup the #Collection instance which represents this object * * i.e. for a VM tag (i.e. a Tag object which its VM property set) * return the #Collection instance which encapsulates AssignedTagResource, * AssignedTagsResource and VM. * * @param model the object to query for * @param suggestedParentType the suggested parent type * @return the #Collection instance representing the object's collection */ private static Collection getCollection(BaseResource model, Class<? extends BaseResource> suggestedParentType) { ParentToCollectionMap collections = TYPES.get(model.getClass()); if (suggestedParentType != null) { for (Class<? extends BaseResource> parentType : collections.keySet()) { if (parentType.equals(suggestedParentType)) { return collections.get(parentType); } } } for (Class<? extends BaseResource> parentType : collections.keySet()) { if (parentType != NO_PARENT && getParentModel(model, parentType) != null) { return collections.get(parentType); } } return collections.get(NO_PARENT); } /** * Create a #UriBuilder which encapsulates the path to an object * * i.e. for a VM tag, return a UriBuilder which encapsulates * '/restapi-definition/vms/{vm_id}/tags/{tag_id}' * * @param uriInfo the URI info * @param model the object * @return the #UriBuilder encapsulating the object's path */ public static <R extends BaseResource> UriBuilder getUriBuilder(UriInfo uriInfo, R model) { return getUriBuilder(uriInfo, model, null); } /** * Create a #UriBuilder which encapsulates the path to an object * * i.e. for a VM tag, return a UriBuilder which encapsulates * '/restapi-definition/vms/{vm_id}/tags/{tag_id}' * * @param uriInfo the URI info * @param model the object * @param suggestedParentType the suggested parent type * @return the #UriBuilder encapsulating the object's path */ public static <R extends BaseResource> UriBuilder getUriBuilder(UriInfo uriInfo, R model, Class<? extends BaseResource> suggestedParentType) { Collection collection = getCollection(model, suggestedParentType); if (collection == null) { return null; } UriBuilder uriBuilder; if (collection.getParentType() != NO_PARENT) { BaseResource parent = getParentModel(model, collection.getParentType()); Collection parentCollection = getCollection(parent, suggestedParentType); String path = getPath(collection.getCollectionType(), parentCollection.getResourceType(), model.getClass()); uriBuilder = getUriBuilder(uriInfo, parent).path(path); } else { String path = getPath(collection.getCollectionType()); uriBuilder = uriInfo != null ? UriBuilder.fromPath(uriInfo.getBaseUri().getPath()).path(path) : UriBuilder.fromPath(path); } return uriBuilder.path(model.getId()); } /** * Set the href attribute on the supplied object * * e.g. set href = '/restapi-definition/vms/{vm_id}/tags/{tag_id}' on a VM tag * * @param uriInfo the URI info * @param model the object * @return the model, with the href attribute set */ private static <R extends BaseResource> void setHref(UriInfo uriInfo, R model) { setHref(uriInfo, model, null); } /** * Set the href attribute on the supplied object * * e.g. set href = '/restapi-definition/vms/{vm_id}/tags/{tag_id}' on a VM tag * * @param uriInfo the URI info * @param model the object * @param suggestedParentType the suggested parent type * @return the model, with the href attribute set */ private static <R extends BaseResource> void setHref(UriInfo uriInfo, R model, Class<? extends BaseResource> suggestedParentType) { UriBuilder uriBuilder = getUriBuilder(uriInfo, model, suggestedParentType); if (uriBuilder != null) { model.setHref(uriBuilder.build().toString()); } } /** * Construct the set of action links for an object * * @param uriInfo the URI info * @param model the object * @param suggestedParentType the suggested parent type * @return the object, including its set of action links */ private static <R extends BaseResource> void setActions(UriInfo uriInfo, R model, Class<? extends BaseResource> suggestedParentType) { Collection collection = getCollection(model); UriBuilder uriBuilder = getUriBuilder(uriInfo, model, suggestedParentType); if (uriBuilder != null) { ActionsBuilder actionsBuilder = new ActionsBuilder(uriBuilder, collection.getResourceType()); model.setActions(actionsBuilder.build()); } } /** * Set the href attribute on the object (and its inline objects) * and construct its set of action links * * @param uriInfo the URI info * @param model the object * @param suggestedParentType the suggested parent type * @return the object, with href attributes and action links */ public static <R extends BaseResource> R addLinks(UriInfo uriInfo, R model) { return addLinks(uriInfo, model, null); } public static <R extends BaseResource> R addLinks(UriInfo uriInfo, R model, Class<? extends BaseResource> suggestedParentType) { setHref(uriInfo, model, suggestedParentType); setActions(uriInfo, model, suggestedParentType); for (BaseResource inline : getInlineResources(model)) { if (inline.getId() != null) { setHref(uriInfo, inline); } for (BaseResource grandParent : getInlineResources(inline)) { unsetInlineResource(inline, grandParent.getClass()); } } return model; } /** * Appends searchable links to resource's Href * * @param url to append to * @param resource to add links to * @param rel link ro add * @param flags used to specify different link options */ public static void addLink(BaseResource resource, String rel, LinkFlags flags) { addLink(resource.getHref(), resource, rel, flags); } /** * Adds searchable links to resource * * @param url to append to * @param resource to add links to * @param rel link ro add * @param flags used to specify different link options */ public static void addLink(String url, BaseResource resource, String rel, LinkFlags flags) { addLink(url, resource, rel, flags, new ParametersSet()); } /** * Adds searchable links to resource * * @param url to append to * @param resource to add links to * @param rel link to add * @param flags used to specify different link options * @param params the URL params to append */ public static void addLink(String url, BaseResource resource, String rel, LinkFlags flags, ParametersSet params) { Link link = new Link(); link.setRel(rel); link.setHref(combine(url, rel)); resource.getLinks().add(link); if (flags == LinkFlags.SEARCHABLE) { addLink(url, resource, rel, params); } } /** * Appends searchable links to resource's Href * * @param url to append to and combine search dialect * @param resource to add links to * @param rel link ro add */ public static void addLink(BaseResource resource, String rel) { addLink(resource.getHref(), resource, rel); } /** * Adds searchable links to resource * * @param url to append to and combine search dialect * @param resource to add links to * @param rel link ro add * @param params the URL params to append */ public static void addLink(String url, BaseResource resource, String rel, ParametersSet params) { Link link = new Link(); link.setRel(rel + SEARCH_RELATION); link.setHref(combine(combine(url, rel) + SEARCH_TEMPLATE, params)); resource.getLinks().add(link); } /** * Adds searchable links to resource * * @param url to append to and combine search dialect * @param resource to add links to * @param rel link ro add */ public static void addLink(String url, BaseResource resource, String rel) { Link link = new Link(); link.setRel(rel + SEARCH_RELATION); link.setHref(combine(url, rel) + SEARCH_TEMPLATE); resource.getLinks().add(link); } /** * Combine URL params to URI path. * * @param head the path head * @param params the URL params to append * @return the combined head and params */ public static String combine(String head, ParametersSet params) { String combined_params = ""; if (params != null) { for (Parameter entry : params.getParameters()) { combined_params += String.format(PARAMETER_TEMPLATE, entry.getName(), entry.getValue()); } } return head + combined_params; } /** * Create a search link with the given parameters * * @param url the url * @param rel the link to add * @param flags flags for this link, e.g: 'searchable' * @return the link the was created */ public static DetailedLink createLink(String url, String rel, LinkFlags flags) { return createLink(url, rel, flags, new ParametersSet()); } /** * Create a search link with the given parameters * * @param url the url * @param rel the link to add * @param flags flags for this link, e.g: 'searchable' * @param params url parameters * @return the link the was created */ public static DetailedLink createLink(String url, String rel, LinkFlags flags, ParametersSet params) { DetailedLink link = new DetailedLink(); link.setRel(rel); link.setHref(combine(url, rel)); if (flags == LinkFlags.SEARCHABLE) { LinkCapabilities capabilities = new LinkCapabilities(); capabilities.setSearchable(true); link.setLinkCapabilities(capabilities); } link.setRequest(new Request()); link.getRequest().setUrl(new Url()); link.getRequest().getUrl().getParametersSets().add(params); return link; } /** * Create a search link with the given parameters * * @param url the url * @param rel the link to add * @param params url parameters * @return the link the was created */ public static Link createLink(String url, String rel, List<ParametersSet> params) { Link link = new Link(); link.setRel(rel + SEARCH_RELATION); link.setHref(combine(url + SEARCH_TEMPLATE, params)); return link; } public static Link createLink(String url, String rel) { Link link = new Link(); link.setRel(rel); link.setHref(url); return link; } /** * Create a search link with the given parameters * @param url the url * @param rel the link to add * @return link with search */ public static Link createSearchLink(String url, String rel) { Link link = new Link(); link.setRel(rel + SEARCH_RELATION); link.setHref(combine(url, rel) + SEARCH_TEMPLATE); return link; } /** * Combine head and tail portions of a URI path. * * @param head the path head * @param tail the path tail * @return the combined head and tail */ public static String combine(String head, String tail) { if (head.endsWith("/")) { head = head.substring(0, head.length() - 1); } if (tail.startsWith("/")) { tail = tail.substring(1); } return head + "/" + tail; } /** * Combine URL params to URI path. * * @param head the path head * @param params the URL params to append * @return the combined head and params */ public static String combine(String head, List<ParametersSet> params) { String combined_params = ""; if (params != null) { for (ParametersSet ps : params) { for (Parameter param : ps.getParameters()) { combined_params += String.format(PARAMETER_TEMPLATE, param.getName(), param.getValue()); } } } return head + combined_params; } /** * A #Map sub-class which maps a model type (e.g. Tag.class) to a * set of suitable collection definitions. */ private static class ModelToCollectionsMap extends HashMap<Class<? extends BaseResource>, ParentToCollectionMap> { } /** * A #Map sub-class which maps a parent model type to collection * definition. * * e.g. the map for Tag contains a collection definition for the * describing the VM, Host and User tags sub-collections. It also * contains a collection definition describing the top-level * tags collection which is keyed on the NO_PARENT key. */ private static class ParentToCollectionMap extends LinkedHashMap<Class<? extends BaseResource>, Collection> { public ParentToCollectionMap(Class<?> resourceType, Class<?> collectionType, Class<? extends BaseResource> parentType) { super(); add(resourceType, collectionType, parentType); } public ParentToCollectionMap(Class<?> resourceType, Class<?> collectionType) { this(resourceType, collectionType, NO_PARENT); } public void add(Class<?> resourceType, Class<?> collectionType, Class<? extends BaseResource> parentType) { put(parentType, new Collection(resourceType, collectionType, parentType)); } } /** * A description of a collection type, its resource type and the parent * resource which contains it, if any. * * e.g. for the VM tags collection, resourceType is AssignedTagResource, * collectionType is AssignedTagsResource and parentType is VM */ private static class Collection { private final Class<?> resourceType; private final Class<?> collectionType; private final Class<?> parentType; public Collection(Class<?> resourceType, Class<?> collectionType, Class<?> parentType) { this.resourceType = resourceType; this.collectionType = collectionType; this.parentType = parentType; } public Class<?> getResourceType() { return resourceType; } public Class<?> getCollectionType() { return collectionType; } public Class<?> getParentType() { return parentType; } } /** * Used to specify link options */ public enum LinkFlags { NONE, SEARCHABLE; } }
/* * Copyright 2010-2015 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.elasticache.model; import java.io.Serializable; import com.amazonaws.AmazonWebServiceRequest; /** * Container for the parameters to the {@link com.amazonaws.services.elasticache.AmazonElastiCache#describeEvents(DescribeEventsRequest) DescribeEvents operation}. * <p> * The <i>DescribeEvents</i> action returns events related to cache * clusters, cache security groups, and cache parameter groups. You can * obtain events specific to a particular cache cluster, cache security * group, or cache parameter group by providing the name as a parameter. * </p> * <p> * By default, only the events occurring within the last hour are * returned; however, you can retrieve up to 14 days' worth of events if * necessary. * </p> * * @see com.amazonaws.services.elasticache.AmazonElastiCache#describeEvents(DescribeEventsRequest) */ public class DescribeEventsRequest extends AmazonWebServiceRequest implements Serializable, Cloneable { /** * The identifier of the event source for which events will be returned. * If not specified, then all sources are included in the response. */ private String sourceIdentifier; /** * The event source to retrieve events for. If no value is specified, all * events are returned. <p>Valid values are: <code>cache-cluster</code> | * <code>cache-parameter-group</code> | <code>cache-security-group</code> * | <code>cache-subnet-group</code> * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>cache-cluster, cache-parameter-group, cache-security-group, cache-subnet-group */ private String sourceType; /** * The beginning of the time interval to retrieve events for, specified * in ISO 8601 format. */ private java.util.Date startTime; /** * The end of the time interval for which to retrieve events, specified * in ISO 8601 format. */ private java.util.Date endTime; /** * The number of minutes' worth of events to retrieve. */ private Integer duration; /** * The maximum number of records to include in the response. If more * records exist than the specified <code>MaxRecords</code> value, a * marker is included in the response so that the remaining results can * be retrieved. <p>Default: 100 <p>Constraints: minimum 20; maximum 100. */ private Integer maxRecords; /** * An optional marker returned from a prior request. Use this marker for * pagination of results from this action. If this parameter is * specified, the response includes only records beyond the marker, up to * the value specified by <i>MaxRecords</i>. */ private String marker; /** * Default constructor for a new DescribeEventsRequest object. Callers should use the * setter or fluent setter (with...) methods to initialize this object after creating it. */ public DescribeEventsRequest() {} /** * The identifier of the event source for which events will be returned. * If not specified, then all sources are included in the response. * * @return The identifier of the event source for which events will be returned. * If not specified, then all sources are included in the response. */ public String getSourceIdentifier() { return sourceIdentifier; } /** * The identifier of the event source for which events will be returned. * If not specified, then all sources are included in the response. * * @param sourceIdentifier The identifier of the event source for which events will be returned. * If not specified, then all sources are included in the response. */ public void setSourceIdentifier(String sourceIdentifier) { this.sourceIdentifier = sourceIdentifier; } /** * The identifier of the event source for which events will be returned. * If not specified, then all sources are included in the response. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param sourceIdentifier The identifier of the event source for which events will be returned. * If not specified, then all sources are included in the response. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeEventsRequest withSourceIdentifier(String sourceIdentifier) { this.sourceIdentifier = sourceIdentifier; return this; } /** * The event source to retrieve events for. If no value is specified, all * events are returned. <p>Valid values are: <code>cache-cluster</code> | * <code>cache-parameter-group</code> | <code>cache-security-group</code> * | <code>cache-subnet-group</code> * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>cache-cluster, cache-parameter-group, cache-security-group, cache-subnet-group * * @return The event source to retrieve events for. If no value is specified, all * events are returned. <p>Valid values are: <code>cache-cluster</code> | * <code>cache-parameter-group</code> | <code>cache-security-group</code> * | <code>cache-subnet-group</code> * * @see SourceType */ public String getSourceType() { return sourceType; } /** * The event source to retrieve events for. If no value is specified, all * events are returned. <p>Valid values are: <code>cache-cluster</code> | * <code>cache-parameter-group</code> | <code>cache-security-group</code> * | <code>cache-subnet-group</code> * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>cache-cluster, cache-parameter-group, cache-security-group, cache-subnet-group * * @param sourceType The event source to retrieve events for. If no value is specified, all * events are returned. <p>Valid values are: <code>cache-cluster</code> | * <code>cache-parameter-group</code> | <code>cache-security-group</code> * | <code>cache-subnet-group</code> * * @see SourceType */ public void setSourceType(String sourceType) { this.sourceType = sourceType; } /** * The event source to retrieve events for. If no value is specified, all * events are returned. <p>Valid values are: <code>cache-cluster</code> | * <code>cache-parameter-group</code> | <code>cache-security-group</code> * | <code>cache-subnet-group</code> * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>cache-cluster, cache-parameter-group, cache-security-group, cache-subnet-group * * @param sourceType The event source to retrieve events for. If no value is specified, all * events are returned. <p>Valid values are: <code>cache-cluster</code> | * <code>cache-parameter-group</code> | <code>cache-security-group</code> * | <code>cache-subnet-group</code> * * @return A reference to this updated object so that method calls can be chained * together. * * @see SourceType */ public DescribeEventsRequest withSourceType(String sourceType) { this.sourceType = sourceType; return this; } /** * The event source to retrieve events for. If no value is specified, all * events are returned. <p>Valid values are: <code>cache-cluster</code> | * <code>cache-parameter-group</code> | <code>cache-security-group</code> * | <code>cache-subnet-group</code> * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>cache-cluster, cache-parameter-group, cache-security-group, cache-subnet-group * * @param sourceType The event source to retrieve events for. If no value is specified, all * events are returned. <p>Valid values are: <code>cache-cluster</code> | * <code>cache-parameter-group</code> | <code>cache-security-group</code> * | <code>cache-subnet-group</code> * * @see SourceType */ public void setSourceType(SourceType sourceType) { this.sourceType = sourceType.toString(); } /** * The event source to retrieve events for. If no value is specified, all * events are returned. <p>Valid values are: <code>cache-cluster</code> | * <code>cache-parameter-group</code> | <code>cache-security-group</code> * | <code>cache-subnet-group</code> * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>cache-cluster, cache-parameter-group, cache-security-group, cache-subnet-group * * @param sourceType The event source to retrieve events for. If no value is specified, all * events are returned. <p>Valid values are: <code>cache-cluster</code> | * <code>cache-parameter-group</code> | <code>cache-security-group</code> * | <code>cache-subnet-group</code> * * @return A reference to this updated object so that method calls can be chained * together. * * @see SourceType */ public DescribeEventsRequest withSourceType(SourceType sourceType) { this.sourceType = sourceType.toString(); return this; } /** * The beginning of the time interval to retrieve events for, specified * in ISO 8601 format. * * @return The beginning of the time interval to retrieve events for, specified * in ISO 8601 format. */ public java.util.Date getStartTime() { return startTime; } /** * The beginning of the time interval to retrieve events for, specified * in ISO 8601 format. * * @param startTime The beginning of the time interval to retrieve events for, specified * in ISO 8601 format. */ public void setStartTime(java.util.Date startTime) { this.startTime = startTime; } /** * The beginning of the time interval to retrieve events for, specified * in ISO 8601 format. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param startTime The beginning of the time interval to retrieve events for, specified * in ISO 8601 format. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeEventsRequest withStartTime(java.util.Date startTime) { this.startTime = startTime; return this; } /** * The end of the time interval for which to retrieve events, specified * in ISO 8601 format. * * @return The end of the time interval for which to retrieve events, specified * in ISO 8601 format. */ public java.util.Date getEndTime() { return endTime; } /** * The end of the time interval for which to retrieve events, specified * in ISO 8601 format. * * @param endTime The end of the time interval for which to retrieve events, specified * in ISO 8601 format. */ public void setEndTime(java.util.Date endTime) { this.endTime = endTime; } /** * The end of the time interval for which to retrieve events, specified * in ISO 8601 format. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param endTime The end of the time interval for which to retrieve events, specified * in ISO 8601 format. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeEventsRequest withEndTime(java.util.Date endTime) { this.endTime = endTime; return this; } /** * The number of minutes' worth of events to retrieve. * * @return The number of minutes' worth of events to retrieve. */ public Integer getDuration() { return duration; } /** * The number of minutes' worth of events to retrieve. * * @param duration The number of minutes' worth of events to retrieve. */ public void setDuration(Integer duration) { this.duration = duration; } /** * The number of minutes' worth of events to retrieve. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param duration The number of minutes' worth of events to retrieve. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeEventsRequest withDuration(Integer duration) { this.duration = duration; return this; } /** * The maximum number of records to include in the response. If more * records exist than the specified <code>MaxRecords</code> value, a * marker is included in the response so that the remaining results can * be retrieved. <p>Default: 100 <p>Constraints: minimum 20; maximum 100. * * @return The maximum number of records to include in the response. If more * records exist than the specified <code>MaxRecords</code> value, a * marker is included in the response so that the remaining results can * be retrieved. <p>Default: 100 <p>Constraints: minimum 20; maximum 100. */ public Integer getMaxRecords() { return maxRecords; } /** * The maximum number of records to include in the response. If more * records exist than the specified <code>MaxRecords</code> value, a * marker is included in the response so that the remaining results can * be retrieved. <p>Default: 100 <p>Constraints: minimum 20; maximum 100. * * @param maxRecords The maximum number of records to include in the response. If more * records exist than the specified <code>MaxRecords</code> value, a * marker is included in the response so that the remaining results can * be retrieved. <p>Default: 100 <p>Constraints: minimum 20; maximum 100. */ public void setMaxRecords(Integer maxRecords) { this.maxRecords = maxRecords; } /** * The maximum number of records to include in the response. If more * records exist than the specified <code>MaxRecords</code> value, a * marker is included in the response so that the remaining results can * be retrieved. <p>Default: 100 <p>Constraints: minimum 20; maximum 100. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param maxRecords The maximum number of records to include in the response. If more * records exist than the specified <code>MaxRecords</code> value, a * marker is included in the response so that the remaining results can * be retrieved. <p>Default: 100 <p>Constraints: minimum 20; maximum 100. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeEventsRequest withMaxRecords(Integer maxRecords) { this.maxRecords = maxRecords; return this; } /** * An optional marker returned from a prior request. Use this marker for * pagination of results from this action. If this parameter is * specified, the response includes only records beyond the marker, up to * the value specified by <i>MaxRecords</i>. * * @return An optional marker returned from a prior request. Use this marker for * pagination of results from this action. If this parameter is * specified, the response includes only records beyond the marker, up to * the value specified by <i>MaxRecords</i>. */ public String getMarker() { return marker; } /** * An optional marker returned from a prior request. Use this marker for * pagination of results from this action. If this parameter is * specified, the response includes only records beyond the marker, up to * the value specified by <i>MaxRecords</i>. * * @param marker An optional marker returned from a prior request. Use this marker for * pagination of results from this action. If this parameter is * specified, the response includes only records beyond the marker, up to * the value specified by <i>MaxRecords</i>. */ public void setMarker(String marker) { this.marker = marker; } /** * An optional marker returned from a prior request. Use this marker for * pagination of results from this action. If this parameter is * specified, the response includes only records beyond the marker, up to * the value specified by <i>MaxRecords</i>. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param marker An optional marker returned from a prior request. Use this marker for * pagination of results from this action. If this parameter is * specified, the response includes only records beyond the marker, up to * the value specified by <i>MaxRecords</i>. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeEventsRequest withMarker(String marker) { this.marker = marker; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getSourceIdentifier() != null) sb.append("SourceIdentifier: " + getSourceIdentifier() + ","); if (getSourceType() != null) sb.append("SourceType: " + getSourceType() + ","); if (getStartTime() != null) sb.append("StartTime: " + getStartTime() + ","); if (getEndTime() != null) sb.append("EndTime: " + getEndTime() + ","); if (getDuration() != null) sb.append("Duration: " + getDuration() + ","); if (getMaxRecords() != null) sb.append("MaxRecords: " + getMaxRecords() + ","); if (getMarker() != null) sb.append("Marker: " + getMarker() ); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getSourceIdentifier() == null) ? 0 : getSourceIdentifier().hashCode()); hashCode = prime * hashCode + ((getSourceType() == null) ? 0 : getSourceType().hashCode()); hashCode = prime * hashCode + ((getStartTime() == null) ? 0 : getStartTime().hashCode()); hashCode = prime * hashCode + ((getEndTime() == null) ? 0 : getEndTime().hashCode()); hashCode = prime * hashCode + ((getDuration() == null) ? 0 : getDuration().hashCode()); hashCode = prime * hashCode + ((getMaxRecords() == null) ? 0 : getMaxRecords().hashCode()); hashCode = prime * hashCode + ((getMarker() == null) ? 0 : getMarker().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeEventsRequest == false) return false; DescribeEventsRequest other = (DescribeEventsRequest)obj; if (other.getSourceIdentifier() == null ^ this.getSourceIdentifier() == null) return false; if (other.getSourceIdentifier() != null && other.getSourceIdentifier().equals(this.getSourceIdentifier()) == false) return false; if (other.getSourceType() == null ^ this.getSourceType() == null) return false; if (other.getSourceType() != null && other.getSourceType().equals(this.getSourceType()) == false) return false; if (other.getStartTime() == null ^ this.getStartTime() == null) return false; if (other.getStartTime() != null && other.getStartTime().equals(this.getStartTime()) == false) return false; if (other.getEndTime() == null ^ this.getEndTime() == null) return false; if (other.getEndTime() != null && other.getEndTime().equals(this.getEndTime()) == false) return false; if (other.getDuration() == null ^ this.getDuration() == null) return false; if (other.getDuration() != null && other.getDuration().equals(this.getDuration()) == false) return false; if (other.getMaxRecords() == null ^ this.getMaxRecords() == null) return false; if (other.getMaxRecords() != null && other.getMaxRecords().equals(this.getMaxRecords()) == false) return false; if (other.getMarker() == null ^ this.getMarker() == null) return false; if (other.getMarker() != null && other.getMarker().equals(this.getMarker()) == false) return false; return true; } @Override public DescribeEventsRequest clone() { return (DescribeEventsRequest) super.clone(); } }
/* * Copyright (c) Facebook, Inc. and 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 com.facebook.buck.core.starlark.rule.attr.impl; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.facebook.buck.core.artifact.Artifact; import com.facebook.buck.core.artifact.ArtifactDeclarationException; import com.facebook.buck.core.cell.TestCellPathResolver; import com.facebook.buck.core.cell.nameresolver.CellNameResolver; import com.facebook.buck.core.filesystems.ForwardRelPath; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.BuildTargetFactory; import com.facebook.buck.core.model.ConstantHostTargetConfigurationResolver; import com.facebook.buck.core.model.UnconfiguredTargetConfiguration; import com.facebook.buck.core.model.impl.BuildTargetPaths; import com.facebook.buck.core.rules.analysis.impl.FakeRuleAnalysisContextImpl; import com.facebook.buck.core.starlark.rule.attr.Attribute; import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem; import com.facebook.buck.rules.coercer.CoerceFailedException; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.nio.file.Paths; import net.starlark.java.eval.Starlark; import net.starlark.java.eval.StarlarkList; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class OutputListAttributeTest { private final FakeProjectFilesystem filesystem = new FakeProjectFilesystem(); private final CellNameResolver cellRoots = TestCellPathResolver.get(filesystem).getCellNameResolver(); private final OutputListAttribute attr = ImmutableOutputListAttribute.of(ImmutableList.of(), "", true, true); @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void coercesProperly() throws CoerceFailedException { ImmutableList<String> coercedPaths = attr.getValue( cellRoots, filesystem, ForwardRelPath.of(""), UnconfiguredTargetConfiguration.INSTANCE, new ConstantHostTargetConfigurationResolver(UnconfiguredTargetConfiguration.INSTANCE), ImmutableList.of("foo/bar.cpp", "foo/baz.cpp")); assertEquals(ImmutableList.of("foo/bar.cpp", "foo/baz.cpp"), coercedPaths); } @Test public void failsMandatoryCoercionProperly() throws CoerceFailedException { thrown.expect(CoerceFailedException.class); attr.getValue( cellRoots, filesystem, ForwardRelPath.of(""), UnconfiguredTargetConfiguration.INSTANCE, new ConstantHostTargetConfigurationResolver(UnconfiguredTargetConfiguration.INSTANCE), 1); } @Test public void failsMandatoryCoercionIfNoneProvided() throws CoerceFailedException { thrown.expect(CoerceFailedException.class); attr.getValue( cellRoots, filesystem, ForwardRelPath.of(""), UnconfiguredTargetConfiguration.INSTANCE, new ConstantHostTargetConfigurationResolver(UnconfiguredTargetConfiguration.INSTANCE), Starlark.NONE); } @Test @SuppressWarnings("unchecked") public void failsTransformIfInvalidCoercedTypeProvided() { thrown.expect(Exception.class); ((Attribute<Object>) (Attribute<?>) attr) .getPostCoercionTransform() .postCoercionTransform(1, new FakeRuleAnalysisContextImpl(ImmutableMap.of())); } @Test public void failsTransformationOnInvalidPath() throws Throwable { thrown.expect(ArtifactDeclarationException.class); ImmutableList<String> value = attr.getValue( cellRoots, filesystem, ForwardRelPath.of(""), UnconfiguredTargetConfiguration.INSTANCE, new ConstantHostTargetConfigurationResolver(UnconfiguredTargetConfiguration.INSTANCE), ImmutableList.of("foo/baz.cpp", "foo/bar\0")); attr.getPostCoercionTransform() .postCoercionTransform(value, new FakeRuleAnalysisContextImpl(ImmutableMap.of())); } @Test public void failsTransformationOnAbsolutePath() throws CoerceFailedException { thrown.expect(ArtifactDeclarationException.class); ImmutableList<String> value = attr.getValue( cellRoots, filesystem, ForwardRelPath.of(""), UnconfiguredTargetConfiguration.INSTANCE, new ConstantHostTargetConfigurationResolver(UnconfiguredTargetConfiguration.INSTANCE), ImmutableList.of("foo/baz.cpp", Paths.get("").toAbsolutePath().toString())); attr.getPostCoercionTransform() .postCoercionTransform(value, new FakeRuleAnalysisContextImpl(ImmutableMap.of())); } @Test public void failsTransformationOnParentPath() throws CoerceFailedException { thrown.expect(ArtifactDeclarationException.class); ImmutableList<String> value = attr.getValue( cellRoots, filesystem, ForwardRelPath.of(""), UnconfiguredTargetConfiguration.INSTANCE, new ConstantHostTargetConfigurationResolver(UnconfiguredTargetConfiguration.INSTANCE), ImmutableList.of("foo/baz.cpp", "../foo.txt")); attr.getPostCoercionTransform() .postCoercionTransform(value, new FakeRuleAnalysisContextImpl(ImmutableMap.of())); } @SuppressWarnings("unchecked") @Test public void transformsToArtifact() throws CoerceFailedException { BuildTarget target = BuildTargetFactory.newInstance("//foo:bar"); ImmutableList<String> outputPaths = attr.getValue( cellRoots, filesystem, ForwardRelPath.of(""), UnconfiguredTargetConfiguration.INSTANCE, new ConstantHostTargetConfigurationResolver(UnconfiguredTargetConfiguration.INSTANCE), ImmutableList.of("subdir/other.cpp", "main.cpp")); Object coerced = attr.getPostCoercionTransform() .postCoercionTransform( outputPaths, new FakeRuleAnalysisContextImpl(target, ImmutableMap.of())); assertThat(coerced, Matchers.instanceOf(StarlarkList.class)); StarlarkList<Artifact> artifacts = (StarlarkList<Artifact>) coerced; assertEquals(2, artifacts.size()); for (Artifact artifact : artifacts) { assertFalse(artifact.isBound()); assertFalse(artifact.isSource()); } boolean includeTargetConfigHash = filesystem.getBuckPaths().shouldIncludeTargetConfigHash(target.getCellRelativeBasePath()); assertEquals( ImmutableList.of( BuildTargetPaths.getBasePath(includeTargetConfigHash, target, "%s__") .toPath(filesystem.getFileSystem()) .resolve("subdir") .resolve("other.cpp") .toString(), BuildTargetPaths.getBasePath(includeTargetConfigHash, target, "%s__") .toPath(filesystem.getFileSystem()) .resolve("main.cpp") .toString()), artifacts.stream().map(Artifact::getShortPath).collect(ImmutableList.toImmutableList())); } @Test public void failsIfEmptyListProvidedAndNotAllowed() throws CoerceFailedException { thrown.expect(CoerceFailedException.class); thrown.expectMessage("may not be empty"); OutputListAttribute attr = ImmutableOutputListAttribute.of(ImmutableList.of(), "", true, false); attr.getValue( cellRoots, filesystem, ForwardRelPath.of(""), UnconfiguredTargetConfiguration.INSTANCE, new ConstantHostTargetConfigurationResolver(UnconfiguredTargetConfiguration.INSTANCE), ImmutableList.of()); } @Test public void succeedsIfEmptyListProvidedAndAllowed() throws CoerceFailedException { ImmutableList<String> value = attr.getValue( cellRoots, filesystem, ForwardRelPath.of(""), UnconfiguredTargetConfiguration.INSTANCE, new ConstantHostTargetConfigurationResolver(UnconfiguredTargetConfiguration.INSTANCE), ImmutableList.of()); assertTrue(value.isEmpty()); } }
/* Copyright (C) 2005-2011 Fabio Riccardi */ package com.lightcrafts.image.metadata; import java.awt.image.RenderedImage; import java.io.IOException; import java.util.*; import org.w3c.dom.Element; import org.w3c.dom.Document; import com.lightcrafts.image.BadImageFileException; import com.lightcrafts.image.ImageInfo; import com.lightcrafts.image.metadata.providers.*; import com.lightcrafts.image.metadata.values.DateMetaValue; import com.lightcrafts.image.metadata.values.ImageMetaValue; import com.lightcrafts.image.metadata.values.RationalMetaValue; import com.lightcrafts.image.types.JPEGImageType; import com.lightcrafts.image.UnknownImageTypeException; import static com.lightcrafts.image.metadata.ImageMetaType.*; import static com.lightcrafts.image.metadata.ImageOrientation.ORIENTATION_UNKNOWN; import static com.lightcrafts.image.metadata.TIFFTags.*; import static com.lightcrafts.image.metadata.XMPConstants.*; import static com.lightcrafts.image.types.TIFFConstants.*; /** * An <code>TIFFDirectory</code> is-an {@link ImageMetadataDirectory} for * holding TIFF metadata. * * @author Paul J. Lucas [paul@lightcrafts.com] * @see <i>TIFF Revision 6.0</i>, Adobe Systems, Incorporated, June 1992. */ @SuppressWarnings({"CloneableClassWithoutClone"}) public class TIFFDirectory extends ImageMetadataDirectory implements ApertureProvider, ArtistProvider, BitsPerChannelProvider, CaptionProvider, CaptureDateTimeProvider, CopyrightProvider, FlashProvider, MakeModelProvider, OrientationProvider, RatingProvider, ResolutionProvider, ShutterSpeedProvider, ThumbnailImageProvider, TitleProvider, WidthHeightProvider { ////////// public ///////////////////////////////////////////////////////// /** * {@inheritDoc} */ public float getAperture() { ImageMetaValue value = getValue( TIFF_FNUMBER ); if ( value == null ) value = getValue( TIFF_APERTURE_VALUE ); if ( !(value instanceof RationalMetaValue) ) return 0; return MetadataUtil.fixFStop( value.getFloatValue() ); } /** * {@inheritDoc} */ public String getArtist() { final ImageMetaValue value = getValue( TIFF_ARTIST ); return value != null ? value.getStringValue() : null; } /** * {@inheritDoc} */ public int getBitsPerChannel() { final ImageMetaValue value = getValue( TIFF_BITS_PER_SAMPLE ); return value != null ? value.getIntValue() : 0; } /** * {@inheritDoc} */ public String getCameraMake( boolean includeModel ) { return getCameraMake( TIFF_MAKE, TIFF_MODEL, includeModel ); } /** * {@inheritDoc} */ public String getCaption() { final ImageMetaValue value = getValue( TIFF_IMAGE_DESCRIPTION ); return value != null ? value.getStringValue() : null; } /** * {@inheritDoc} */ public Date getCaptureDateTime() { final ImageMetaValue value = getValue( TIFF_DATE_TIME ); return value instanceof DateMetaValue ? ((DateMetaValue)value).getDateValue() : null; } /** * {@inheritDoc} */ public String getCopyright() { final ImageMetaValue value = getValue( TIFF_COPYRIGHT ); return value != null ? value.getStringValue() : null; } /** * {@inheritDoc} */ public String getFlash() { final ImageMetaValue flashValue = getValue( TIFF_FLASH ); return hasTagValueLabelFor( flashValue ); } /** * {@inheritDoc} */ public int getImageHeight() { final ImageMetaValue value = getValue( TIFF_IMAGE_LENGTH ); return value != null ? value.getIntValue() : 0; } /** * {@inheritDoc} */ public int getImageWidth() { final ImageMetaValue value = getValue( TIFF_IMAGE_WIDTH ); return value != null ? value.getIntValue() : 0; } /** * Gets the name of this directory. * * @return Always returns &quot;TIFF&quot;. */ public String getName() { return "TIFF"; } /** * {@inheritDoc} */ public ImageOrientation getOrientation() { final ImageMetaValue value = getValue( TIFF_ORIENTATION ); if ( value != null ) try { return ImageOrientation.getOrientationFor( value.getIntValue() ); } catch ( IllegalArgumentException e ) { // ignore } return ORIENTATION_UNKNOWN; } /** * {@inheritDoc} */ public int getRating() { final ImageMetaValue rating = getValue( TIFF_MS_RATING ); return rating != null ? rating.getIntValue() : 0; } /** * {@inheritDoc} */ public double getResolution() { final ImageMetaValue res = getValue( TIFF_X_RESOLUTION ); return res != null ? res.getDoubleValue() : 0; } /** * {@inheritDoc} */ public int getResolutionUnit() { final ImageMetaValue unit = getValue( TIFF_RESOLUTION_UNIT ); if ( unit != null ) { switch ( unit.getIntValue() ) { case TIFF_RESOLUTION_UNIT_CM: return RESOLUTION_UNIT_CM; case TIFF_RESOLUTION_UNIT_INCH: return RESOLUTION_UNIT_INCH; } } return RESOLUTION_UNIT_NONE; } /** * {@inheritDoc} */ public float getShutterSpeed() { boolean isAPEX = false; ImageMetaValue value = getValue( TIFF_EXPOSURE_TIME ); if ( value == null ) { value = getValue( TIFF_SHUTTER_SPEED_VALUE ); isAPEX = true; } if ( !(value instanceof RationalMetaValue) ) return 0; if ( isAPEX ) return EXIFDirectory.calcShutterSpeedFromAPEX( value ); return value.getFloatValue(); } /** * {@inheritDoc} */ public ImageMetaTagInfo getTagInfoFor( Integer id ) { return m_tagsByID.get( id ); } /** * {@inheritDoc} */ public ImageMetaTagInfo getTagInfoFor( String name ) { return m_tagsByName.get( name ); } /** * {@inheritDoc} */ public RenderedImage getThumbnailImage( ImageInfo imageInfo ) throws BadImageFileException, IOException, UnknownImageTypeException { return JPEGImageType.getImageFromBuffer( imageInfo.getByteBuffer(), getValue( TIFF_JPEG_INTERCHANGE_FORMAT ), 0, getValue( TIFF_JPEG_INTERCHANGE_FORMAT_LENGTH ), 0, 0 ); } /** * {@inheritDoc} */ public String getTitle() { final ImageMetaValue value = getValue( TIFF_DOCUMENT_NAME ); return value != null ? value.getStringValue() : null; } /** * {@inheritDoc} */ public Collection<Element> toXMP( Document xmpDoc ) { return toXMP( xmpDoc, XMP_TIFF_NS, XMP_TIFF_PREFIX ); } ////////// protected ////////////////////////////////////////////////////// /** * {@inheritDoc}. */ protected ResourceBundle getTagLabelBundle() { return m_tagBundle; } /** * {@inheritDoc} */ protected Class<? extends ImageMetaTags> getTagsInterface() { return TIFFTags.class; } ////////// private //////////////////////////////////////////////////////// /** * Add the tag mappings. * * @param id The tag's ID. * @param name The tag's name. * @param type The tag's {@link ImageMetaType}. * @param isChangeable Whether the tag is user-changeable. */ private static void add( int id, String name, ImageMetaType type, boolean isChangeable ) { final ImageMetaTagInfo tagInfo = new ImageMetaTagInfo( id, name, type, isChangeable ); m_tagsByID.put( id, tagInfo ); m_tagsByName.put( name, tagInfo ); } /** * This is where the actual labels for the tags are. */ private static final ResourceBundle m_tagBundle = ResourceBundle.getBundle( "com.lightcrafts.image.metadata.TIFFTags" ); /** * A mapping of tags by ID. */ private static final Map<Integer,ImageMetaTagInfo> m_tagsByID = new HashMap<Integer, ImageMetaTagInfo>(); /** * A mapping of tags by name. */ private static final Map<String,ImageMetaTagInfo> m_tagsByName = new HashMap<String, ImageMetaTagInfo>(); static { add( TIFF_APERTURE_VALUE, "ApertureValue", META_URATIONAL, false ); add( TIFF_ARTIST, "Artist", META_STRING, true ); add( TIFF_BATTERY_LEVEL, "BatteryLevel", META_STRING, false ); add( TIFF_BITS_PER_SAMPLE, "BitsPerSample", META_USHORT, false ); add( TIFF_BRIGHTNESS_VALUE, "BrightnessValue", META_SRATIONAL, false ); add( TIFF_CELL_LENGTH, "CellLength", META_USHORT, false ); add( TIFF_CELL_WIDTH, "CellWidth", META_USHORT, false ); add( TIFF_CLIP_PATH, "ClipPath", META_UBYTE, false ); add( TIFF_COLOR_MAP, "ColorMap", META_USHORT, false ); add( TIFF_COMPRESSION, "Compression", META_USHORT, false ); add( TIFF_COPYRIGHT, "Copyright", META_STRING, true ); add( TIFF_DATE_TIME, "DateTime", META_DATE, false ); add( TIFF_DOCUMENT_NAME, "DocumentName", META_STRING, true ); add( TIFF_DOT_RANGE, "DotRange", META_USHORT, false ); add( TIFF_EXIF_IFD_POINTER, "EXIFIFDPointer", META_ULONG, false ); add( TIFF_EXPOSURE_BIAS_VALUE, "ExposureBiasValue", META_SRATIONAL, false ); add( TIFF_EXPOSURE_PROGRAM, "ExposureProgram", META_USHORT, false ); add( TIFF_EXPOSURE_INDEX, "ExposureIndex", META_URATIONAL, false ); add( TIFF_EXPOSURE_TIME, "ExposureTime", META_URATIONAL, false ); add( TIFF_EXTRA_SAMPLES, "ExtraSamples", META_USHORT, false ); add( TIFF_FILL_ORDER, "FillOrder", META_USHORT, false ); add( TIFF_FLASH, "Flash", META_USHORT, false ); add( TIFF_FLASH_ENERGY, "FlashEnergy", META_URATIONAL, false ); add( TIFF_FNUMBER, "FNumber", META_URATIONAL, false ); add( TIFF_FREE_BYTE_COUNTS, "FreeByteCounts", META_ULONG, false ); add( TIFF_FREE_OFFSETS, "FreeOffsets", META_ULONG, false ); add( TIFF_GPS_IFD_POINTER, "GPSInfoIfdPointer", META_ULONG, false ); add( TIFF_GRAY_RESPONSE_CURVE, "GrayResponseCurve", META_USHORT, false ); add( TIFF_GRAY_RESPONSE_UNIT, "GrayResponseUnit", META_USHORT, false ); add( TIFF_HALFTONE_HINTS, "HalftoneHints", META_USHORT, false ); add( TIFF_HOST_COMPUTER, "HostComputer", META_STRING, false ); add( TIFF_ICC_PROFILE, "ICCProfile", META_UNDEFINED, false ); add( TIFF_IMAGE_DESCRIPTION, "ImageDescription", META_STRING, true ); add( TIFF_IMAGE_HISTORY, "ImageHistory", META_STRING, false ); add( TIFF_IMAGE_ID, "ImageID", META_STRING, true ); add( TIFF_IMAGE_LENGTH, "ImageLength", META_USHORT, false ); add( TIFF_IMAGE_WIDTH, "ImageWidth", META_USHORT, false ); add( TIFF_INDEXED, "Indexed", META_USHORT, false ); add( TIFF_INK_NAMES, "InkNames", META_STRING, false ); add( TIFF_INK_SET, "InkSet", META_USHORT, false ); add( TIFF_JPEG_AC_TABLES, "JPEGACTables", META_ULONG, false ); add( TIFF_JPEG_DC_TABLES, "JPEGDCTables", META_ULONG, false ); add( TIFF_JPEG_INTERCHANGE_FORMAT, "JPEGInterchangeFormat", META_ULONG, false ); add( TIFF_JPEG_INTERCHANGE_FORMAT_LENGTH, "JPEGInterchangeFormatLength", META_ULONG, false ); add( TIFF_JPEG_LOSSLESS_PREDICTORS, "JPEGLosslessPredictors", META_USHORT, false ); add( TIFF_JPEG_POINT_TRANSFORMS, "JPEGPointTransforms", META_USHORT, false ); add( TIFF_JPEG_PROC, "JPEGProc", META_USHORT, false ); add( TIFF_JPEG_Q_TABLES, "JPEGQTables", META_ULONG, false ); add( TIFF_JPEG_RESTART_INTERVAL, "JPEGRestartInterval", META_USHORT, false ); add( TIFF_LIGHT_SOURCE, "LightSource", META_USHORT, false ); add( TIFF_MAKE, "Make", META_STRING, false ); add( TIFF_MAX_APERTURE_VALUE, "MaxApertureValue", META_URATIONAL, false ); add( TIFF_MAX_SAMPLE_VALUE, "MaxSampleValue", META_USHORT, false ); add( TIFF_METERING_MODE, "MeteringMode", META_USHORT, false ); add( TIFF_MIN_SAMPLE_VALUE, "MinSampleValue", META_USHORT, false ); add( TIFF_MODEL, "Model", META_STRING, false ); add( TIFF_MS_RATING, "MSRating", META_USHORT, true ); add( TIFF_NEW_SUBFILE_TYPE, "NewSubfileType", META_ULONG, false ); add( TIFF_NUMBER_OF_INKS, "NumberOfInks", META_USHORT, false ); add( TIFF_OPI_PROXY, "OPIProxy", META_USHORT, false ); add( TIFF_ORIENTATION, "Orientation", META_USHORT, false ); add( TIFF_PAGE_NAME, "PageName", META_STRING, false ); add( TIFF_PAGE_NUMBER, "PageNumber", META_USHORT, false ); add( TIFF_PHOTOMETRIC_INTERPRETATION, "PhotometricInterpretation", META_USHORT, false ); add( TIFF_PHOTOSHOP_IMAGE_RESOURCES, "PhotoshopImageResources", META_UBYTE, false ); add( TIFF_PLANAR_CONFIGURATION, "PlanarConfiguration", META_USHORT, false ); add( TIFF_PREDICTOR, "Predictor", META_USHORT, false ); add( TIFF_PRIMARY_CHROMATICITIES, "PrimaryChromaticities", META_URATIONAL, false ); add( TIFF_REFERENCE_BLACK_WHITE, "ReferenceBlackWhite", META_URATIONAL, false ); add( TIFF_RESOLUTION_UNIT, "ResolutionUnit", META_USHORT, false ); add( TIFF_RICH_TIFF_IPTC, "RichTIFFIPTC", META_UNDEFINED, false ); add( TIFF_ROWS_PER_STRIP, "RowsPerStrip", META_USHORT, false ); add( TIFF_SAMPLE_FORMAT, "SampleFormat", META_USHORT, false ); add( TIFF_SAMPLES_PER_PIXEL, "SamplesPerPixel", META_USHORT, false ); add( TIFF_SECURITY_CLASSIFICATION, "SecurityClassification", META_STRING, false ); add( TIFF_SENSING_METHOD, "SensingMethod", META_USHORT, false ); add( TIFF_SHUTTER_SPEED_VALUE, "ShutterSpeedValue", META_SRATIONAL, false ); add( TIFF_SMAX_SAMPLE_VALUE, "SMaxSampleValue", META_SRATIONAL, false ); add( TIFF_SMIN_SAMPLE_VALUE, "SMinSampleValue", META_SRATIONAL, false ); add( TIFF_SOFTWARE, "Software", META_STRING, false ); add( TIFF_SPECTRAL_SENSITIVITY, "SpectralSensitivity", META_STRING, false ); add( TIFF_STRIP_BYTE_COUNTS, "StripByteCounts", META_ULONG, false ); add( TIFF_STRIP_OFFSETS, "StripOffsets", META_ULONG, false ); add( TIFF_SUBFILE_TYPE, "SubfileType", META_USHORT, false ); add( TIFF_SUB_IFDS, "SubIFDs", META_ULONG, false ); add( TIFF_SUBJECT_DISTANCE, "SubjectDistance", META_URATIONAL, false ); add( TIFF_SUBJECT_LOCATION, "SubjectLocation", META_USHORT, false ); add( TIFF_T4_OPTIONS, "T4Options", META_ULONG, false ); add( TIFF_T6_OPTIONS, "T6Options", META_ULONG, false ); add( TIFF_TARGET_PRINTER, "TargetPrinter", META_STRING, true ); add( TIFF_THRESHHOLDING, "Threshholding", META_USHORT, false ); add( TIFF_TIFF_EP_STANDARD_ID, "TIFFEPStandardID", META_UBYTE, false ); add( TIFF_TILE_BYTE_COUNTS, "TileByteCounts", META_ULONG, false ); add( TIFF_TILE_LENGTH, "TileLength", META_ULONG, false ); add( TIFF_TILE_OFFSETS, "TileOffsets", META_ULONG, false ); add( TIFF_TILE_WIDTH, "TileWidth", META_ULONG, false ); add( TIFF_TRANSFER_FUNCTION, "TransferFunction", META_USHORT, false ); add( TIFF_TRANSFER_RANGE, "TransferRange", META_USHORT, false ); add( TIFF_WHITE_POINT, "WhitePoint", META_URATIONAL, false ); add( TIFF_X_CLIP_PATH_UNITS, "XClipPathUnits", META_ULONG, false ); add( TIFF_XMP_PACKET, "XMPPacket", META_UBYTE, false ); add( TIFF_X_POSITION, "XPosition", META_URATIONAL, false ); add( TIFF_X_RESOLUTION, "XResolution", META_URATIONAL, false ); add( TIFF_YCBCR_COEFFICIENTS, "YCbCrCoefficients", META_URATIONAL, false ); add( TIFF_YCBCR_POSITIONING, "YCbCrPositioning", META_USHORT, false ); add( TIFF_YCBCR_SUBSAMPLING, "YCbCrSubSampling", META_USHORT, false ); add( TIFF_Y_CLIP_PATH_UNITS, "YClipPathUnits", META_ULONG, false ); add( TIFF_Y_POSITION, "YPosition", META_URATIONAL, false ); add( TIFF_Y_RESOLUTION, "YResolution", META_URATIONAL, false ); } } /* vim:set et sw=4 ts=4: */
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; import org.apache.hadoop.mapreduce.ClusterMetrics; import org.apache.hadoop.mapreduce.TaskTrackerInfo; /** * Status information on the current state of the Map-Reduce cluster. * * <p><code>ClusterStatus</code> provides clients with information such as: * <ol> * <li> * Size of the cluster. * </li> * <li> * Name of the trackers. * </li> * <li> * Task capacity of the cluster. * </li> * <li> * The number of currently running map & reduce tasks. * </li> * <li> * State of the <code>JobTracker</code>. * </li> * <li> * Details regarding black listed trackers. * </li> * </ol></p> * * <p>Clients can query for the latest <code>ClusterStatus</code>, via * {@link JobClient#getClusterStatus()}.</p> * * @see JobClient * @deprecated Use {@link ClusterMetrics} or {@link TaskTrackerInfo} instead */ @Deprecated public class ClusterStatus implements Writable { /** * Class which encapsulates information about a blacklisted tasktracker. * * The information includes the tasktracker's name and reasons for * getting blacklisted. The toString method of the class will print * the information in a whitespace separated fashion to enable parsing. */ public static class BlackListInfo implements Writable { private String trackerName; private String reasonForBlackListing; private String blackListReport; BlackListInfo() { } /** * Gets the blacklisted tasktracker's name. * * @return tracker's name. */ public String getTrackerName() { return trackerName; } /** * Gets the reason for which the tasktracker was blacklisted. * * @return reason which tracker was blacklisted */ public String getReasonForBlackListing() { return reasonForBlackListing; } /** * Sets the blacklisted tasktracker's name. * * @param trackerName of the tracker. */ void setTrackerName(String trackerName) { this.trackerName = trackerName; } /** * Sets the reason for which the tasktracker was blacklisted. * * @param reasonForBlackListing */ void setReasonForBlackListing(String reasonForBlackListing) { this.reasonForBlackListing = reasonForBlackListing; } /** * Gets a descriptive report about why the tasktracker was blacklisted. * * @return report describing why the tasktracker was blacklisted. */ public String getBlackListReport() { return blackListReport; } /** * Sets a descriptive report about why the tasktracker was blacklisted. * @param blackListReport report describing why the tasktracker * was blacklisted. */ void setBlackListReport(String blackListReport) { this.blackListReport = blackListReport; } @Override public void readFields(DataInput in) throws IOException { trackerName = Text.readString(in); reasonForBlackListing = Text.readString(in); blackListReport = Text.readString(in); } @Override public void write(DataOutput out) throws IOException { Text.writeString(out, trackerName); Text.writeString(out, reasonForBlackListing); Text.writeString(out, blackListReport); } @Override /** * Print information related to the blacklisted tasktracker in a * whitespace separated fashion. * * The method changes any newlines in the report describing why * the tasktracker was blacklisted to a ':' for enabling better * parsing. */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append(trackerName); sb.append("\t"); sb.append(reasonForBlackListing); sb.append("\t"); sb.append(blackListReport.replace("\n", ":")); return sb.toString(); } } private int numActiveTrackers; private Collection<String> activeTrackers = new ArrayList<String>(); private int numBlacklistedTrackers; private int numExcludedNodes; private long ttExpiryInterval; private int map_tasks; private int reduce_tasks; private int max_map_tasks; private int max_reduce_tasks; private JobTracker.State state; private long used_memory; private long max_memory; private Collection<BlackListInfo> blacklistedTrackersInfo = new ArrayList<BlackListInfo>(); ClusterStatus() {} /** * Construct a new cluster status. * * @param trackers no. of tasktrackers in the cluster * @param blacklists no of blacklisted task trackers in the cluster * @param ttExpiryInterval the tasktracker expiry interval * @param maps no. of currently running map-tasks in the cluster * @param reduces no. of currently running reduce-tasks in the cluster * @param maxMaps the maximum no. of map tasks in the cluster * @param maxReduces the maximum no. of reduce tasks in the cluster * @param state the {@link JobTracker.State} of the <code>JobTracker</code> */ ClusterStatus(int trackers, int blacklists, long ttExpiryInterval, int maps, int reduces, int maxMaps, int maxReduces, JobTracker.State state) { this(trackers, blacklists, ttExpiryInterval, maps, reduces, maxMaps, maxReduces, state, 0); } /** * Construct a new cluster status. * * @param trackers no. of tasktrackers in the cluster * @param blacklists no of blacklisted task trackers in the cluster * @param ttExpiryInterval the tasktracker expiry interval * @param maps no. of currently running map-tasks in the cluster * @param reduces no. of currently running reduce-tasks in the cluster * @param maxMaps the maximum no. of map tasks in the cluster * @param maxReduces the maximum no. of reduce tasks in the cluster * @param state the {@link JobTracker.State} of the <code>JobTracker</code> * @param numDecommissionedNodes number of decommission trackers */ ClusterStatus(int trackers, int blacklists, long ttExpiryInterval, int maps, int reduces, int maxMaps, int maxReduces, JobTracker.State state, int numDecommissionedNodes) { numActiveTrackers = trackers; numBlacklistedTrackers = blacklists; this.numExcludedNodes = numDecommissionedNodes; this.ttExpiryInterval = ttExpiryInterval; map_tasks = maps; reduce_tasks = reduces; max_map_tasks = maxMaps; max_reduce_tasks = maxReduces; this.state = state; used_memory = Runtime.getRuntime().totalMemory(); max_memory = Runtime.getRuntime().maxMemory(); } /** * Construct a new cluster status. * * @param activeTrackers active tasktrackers in the cluster * @param blacklistedTrackers blacklisted tasktrackers in the cluster * @param ttExpiryInterval the tasktracker expiry interval * @param maps no. of currently running map-tasks in the cluster * @param reduces no. of currently running reduce-tasks in the cluster * @param maxMaps the maximum no. of map tasks in the cluster * @param maxReduces the maximum no. of reduce tasks in the cluster * @param state the {@link JobTracker.State} of the <code>JobTracker</code> */ ClusterStatus(Collection<String> activeTrackers, Collection<BlackListInfo> blacklistedTrackers, long ttExpiryInterval, int maps, int reduces, int maxMaps, int maxReduces, JobTracker.State state) { this(activeTrackers, blacklistedTrackers, ttExpiryInterval, maps, reduces, maxMaps, maxReduces, state, 0); } /** * Construct a new cluster status. * * @param activeTrackers active tasktrackers in the cluster * @param blackListedTrackerInfo blacklisted tasktrackers information * in the cluster * @param ttExpiryInterval the tasktracker expiry interval * @param maps no. of currently running map-tasks in the cluster * @param reduces no. of currently running reduce-tasks in the cluster * @param maxMaps the maximum no. of map tasks in the cluster * @param maxReduces the maximum no. of reduce tasks in the cluster * @param state the {@link JobTracker.State} of the <code>JobTracker</code> * @param numDecommissionNodes number of decommission trackers */ ClusterStatus(Collection<String> activeTrackers, Collection<BlackListInfo> blackListedTrackerInfo, long ttExpiryInterval, int maps, int reduces, int maxMaps, int maxReduces, JobTracker.State state, int numDecommissionNodes) { this(activeTrackers.size(), blackListedTrackerInfo.size(), ttExpiryInterval, maps, reduces, maxMaps, maxReduces, state, numDecommissionNodes); this.activeTrackers = activeTrackers; this.blacklistedTrackersInfo = blackListedTrackerInfo; } /** * Get the number of task trackers in the cluster. * * @return the number of task trackers in the cluster. */ public int getTaskTrackers() { return numActiveTrackers; } /** * Get the names of task trackers in the cluster. * * @return the active task trackers in the cluster. */ public Collection<String> getActiveTrackerNames() { return activeTrackers; } /** * Get the names of task trackers in the cluster. * * @return the blacklisted task trackers in the cluster. */ public Collection<String> getBlacklistedTrackerNames() { ArrayList<String> blacklistedTrackers = new ArrayList<String>(); for(BlackListInfo bi : blacklistedTrackersInfo) { blacklistedTrackers.add(bi.getTrackerName()); } return blacklistedTrackers; } /** * Get the number of blacklisted task trackers in the cluster. * * @return the number of blacklisted task trackers in the cluster. */ public int getBlacklistedTrackers() { return numBlacklistedTrackers; } /** * Get the number of excluded hosts in the cluster. * @return the number of excluded hosts in the cluster. */ public int getNumExcludedNodes() { return numExcludedNodes; } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTTExpiryInterval() { return ttExpiryInterval; } /** * Get the number of currently running map tasks in the cluster. * * @return the number of currently running map tasks in the cluster. */ public int getMapTasks() { return map_tasks; } /** * Get the number of currently running reduce tasks in the cluster. * * @return the number of currently running reduce tasks in the cluster. */ public int getReduceTasks() { return reduce_tasks; } /** * Get the maximum capacity for running map tasks in the cluster. * * @return the maximum capacity for running map tasks in the cluster. */ public int getMaxMapTasks() { return max_map_tasks; } /** * Get the maximum capacity for running reduce tasks in the cluster. * * @return the maximum capacity for running reduce tasks in the cluster. */ public int getMaxReduceTasks() { return max_reduce_tasks; } /** * Get the current state of the <code>JobTracker</code>, * as {@link JobTracker.State} * * @return the current state of the <code>JobTracker</code>. */ public JobTracker.State getJobTrackerState() { return state; } /** * Get the total heap memory used by the <code>JobTracker</code> * * @return the size of heap memory used by the <code>JobTracker</code> */ public long getUsedMemory() { return used_memory; } /** * Get the maximum configured heap memory that can be used by the <code>JobTracker</code> * * @return the configured size of max heap memory that can be used by the <code>JobTracker</code> */ public long getMaxMemory() { return max_memory; } /** * Gets the list of blacklisted trackers along with reasons for blacklisting. * * @return the collection of {@link BlackListInfo} objects. * */ public Collection<BlackListInfo> getBlackListedTrackersInfo() { return blacklistedTrackersInfo; } public void write(DataOutput out) throws IOException { if (activeTrackers.size() == 0) { out.writeInt(numActiveTrackers); out.writeInt(0); } else { out.writeInt(activeTrackers.size()); out.writeInt(activeTrackers.size()); for (String tracker : activeTrackers) { Text.writeString(out, tracker); } } if (blacklistedTrackersInfo.size() == 0) { out.writeInt(numBlacklistedTrackers); out.writeInt(blacklistedTrackersInfo.size()); } else { out.writeInt(blacklistedTrackersInfo.size()); out.writeInt(blacklistedTrackersInfo.size()); for (BlackListInfo tracker : blacklistedTrackersInfo) { tracker.write(out); } } out.writeInt(numExcludedNodes); out.writeLong(ttExpiryInterval); out.writeInt(map_tasks); out.writeInt(reduce_tasks); out.writeInt(max_map_tasks); out.writeInt(max_reduce_tasks); out.writeLong(used_memory); out.writeLong(max_memory); WritableUtils.writeEnum(out, state); } public void readFields(DataInput in) throws IOException { numActiveTrackers = in.readInt(); int numTrackerNames = in.readInt(); if (numTrackerNames > 0) { for (int i = 0; i < numTrackerNames; i++) { String name = Text.readString(in); activeTrackers.add(name); } } numBlacklistedTrackers = in.readInt(); int blackListTrackerInfoSize = in.readInt(); if(blackListTrackerInfoSize > 0) { for (int i = 0; i < blackListTrackerInfoSize; i++) { BlackListInfo info = new BlackListInfo(); info.readFields(in); blacklistedTrackersInfo.add(info); } } numExcludedNodes = in.readInt(); ttExpiryInterval = in.readLong(); map_tasks = in.readInt(); reduce_tasks = in.readInt(); max_map_tasks = in.readInt(); max_reduce_tasks = in.readInt(); used_memory = in.readLong(); max_memory = in.readLong(); state = WritableUtils.readEnum(in, JobTracker.State.class); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.indexing.common.task; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import org.apache.commons.io.FileUtils; import org.apache.druid.client.cache.CacheConfig; import org.apache.druid.client.cache.CachePopulatorStats; import org.apache.druid.client.cache.MapCache; import org.apache.druid.common.config.NullHandling; import org.apache.druid.data.input.Firehose; import org.apache.druid.data.input.FirehoseFactory; import org.apache.druid.data.input.InputRow; import org.apache.druid.data.input.impl.DimensionsSpec; import org.apache.druid.data.input.impl.FloatDimensionSchema; import org.apache.druid.data.input.impl.InputRowParser; import org.apache.druid.data.input.impl.LongDimensionSchema; import org.apache.druid.data.input.impl.MapInputRowParser; import org.apache.druid.data.input.impl.StringDimensionSchema; import org.apache.druid.data.input.impl.TimeAndDimsParseSpec; import org.apache.druid.data.input.impl.TimestampSpec; import org.apache.druid.discovery.DataNodeService; import org.apache.druid.discovery.DruidNodeAnnouncer; import org.apache.druid.discovery.LookupNodeService; import org.apache.druid.indexer.IngestionState; import org.apache.druid.indexer.TaskState; import org.apache.druid.indexer.TaskStatus; import org.apache.druid.indexing.common.Counters; import org.apache.druid.indexing.common.IngestionStatsAndErrorsTaskReportData; import org.apache.druid.indexing.common.SegmentLoaderFactory; import org.apache.druid.indexing.common.TaskReport; import org.apache.druid.indexing.common.TaskReportFileWriter; import org.apache.druid.indexing.common.TaskToolbox; import org.apache.druid.indexing.common.TaskToolboxFactory; import org.apache.druid.indexing.common.TestUtils; import org.apache.druid.indexing.common.actions.LocalTaskActionClientFactory; import org.apache.druid.indexing.common.actions.TaskActionClientFactory; import org.apache.druid.indexing.common.actions.TaskActionToolbox; import org.apache.druid.indexing.common.actions.TaskAuditLogConfig; import org.apache.druid.indexing.common.config.TaskConfig; import org.apache.druid.indexing.common.config.TaskStorageConfig; import org.apache.druid.indexing.common.index.RealtimeAppenderatorIngestionSpec; import org.apache.druid.indexing.common.index.RealtimeAppenderatorTuningConfig; import org.apache.druid.indexing.common.stats.RowIngestionMeters; import org.apache.druid.indexing.common.stats.RowIngestionMetersFactory; import org.apache.druid.indexing.overlord.DataSourceMetadata; import org.apache.druid.indexing.overlord.HeapMemoryTaskStorage; import org.apache.druid.indexing.overlord.SegmentPublishResult; import org.apache.druid.indexing.overlord.TaskLockbox; import org.apache.druid.indexing.overlord.TaskStorage; import org.apache.druid.indexing.overlord.supervisor.SupervisorManager; import org.apache.druid.indexing.test.TestDataSegmentAnnouncer; import org.apache.druid.indexing.test.TestDataSegmentKiller; import org.apache.druid.indexing.test.TestDataSegmentPusher; import org.apache.druid.jackson.DefaultObjectMapper; import org.apache.druid.java.util.common.DateTimes; import org.apache.druid.java.util.common.ISE; import org.apache.druid.java.util.common.Pair; import org.apache.druid.java.util.common.StringUtils; import org.apache.druid.java.util.common.concurrent.Execs; import org.apache.druid.java.util.common.granularity.Granularities; import org.apache.druid.java.util.common.jackson.JacksonUtils; import org.apache.druid.java.util.common.logger.Logger; import org.apache.druid.java.util.common.parsers.ParseException; import org.apache.druid.java.util.emitter.EmittingLogger; import org.apache.druid.java.util.emitter.core.NoopEmitter; import org.apache.druid.java.util.emitter.service.ServiceEmitter; import org.apache.druid.java.util.metrics.MonitorScheduler; import org.apache.druid.math.expr.ExprMacroTable; import org.apache.druid.metadata.EntryExistsException; import org.apache.druid.metadata.IndexerSQLMetadataStorageCoordinator; import org.apache.druid.metadata.TestDerbyConnector; import org.apache.druid.query.DefaultQueryRunnerFactoryConglomerate; import org.apache.druid.query.Druids; import org.apache.druid.query.IntervalChunkingQueryRunnerDecorator; import org.apache.druid.query.Query; import org.apache.druid.query.QueryPlus; import org.apache.druid.query.QueryRunner; import org.apache.druid.query.QueryRunnerFactoryConglomerate; import org.apache.druid.query.QueryToolChest; import org.apache.druid.query.Result; import org.apache.druid.query.SegmentDescriptor; import org.apache.druid.query.aggregation.AggregatorFactory; import org.apache.druid.query.aggregation.CountAggregatorFactory; import org.apache.druid.query.aggregation.LongSumAggregatorFactory; import org.apache.druid.query.filter.DimFilter; import org.apache.druid.query.filter.SelectorDimFilter; import org.apache.druid.query.timeseries.TimeseriesQuery; import org.apache.druid.query.timeseries.TimeseriesQueryEngine; import org.apache.druid.query.timeseries.TimeseriesQueryQueryToolChest; import org.apache.druid.query.timeseries.TimeseriesQueryRunnerFactory; import org.apache.druid.query.timeseries.TimeseriesResultValue; import org.apache.druid.segment.TestHelper; import org.apache.druid.segment.indexing.DataSchema; import org.apache.druid.segment.indexing.RealtimeIOConfig; import org.apache.druid.segment.indexing.granularity.UniformGranularitySpec; import org.apache.druid.segment.loading.SegmentLoaderConfig; import org.apache.druid.segment.loading.SegmentLoaderLocalCacheManager; import org.apache.druid.segment.loading.StorageLocationConfig; import org.apache.druid.segment.realtime.plumber.SegmentHandoffNotifier; import org.apache.druid.segment.realtime.plumber.SegmentHandoffNotifierFactory; import org.apache.druid.segment.transform.ExpressionTransform; import org.apache.druid.segment.transform.TransformSpec; import org.apache.druid.server.DruidNode; import org.apache.druid.server.coordination.DataSegmentServerAnnouncer; import org.apache.druid.server.coordination.ServerType; import org.apache.druid.server.security.AuthTestUtils; import org.apache.druid.timeline.DataSegment; import org.apache.druid.timeline.partition.LinearShardSpec; import org.apache.druid.timeline.partition.NumberedShardSpec; import org.apache.druid.utils.Runnables; import org.easymock.EasyMock; import org.joda.time.DateTime; import org.joda.time.Period; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; public class AppenderatorDriverRealtimeIndexTaskTest { private static final Logger log = new Logger(AppenderatorDriverRealtimeIndexTaskTest.class); private static final ServiceEmitter emitter = new ServiceEmitter( "service", "host", new NoopEmitter() ); private static final ObjectMapper objectMapper = TestHelper.makeJsonMapper(); private static final String FAIL_DIM = "__fail__"; private static class TestFirehose implements Firehose { private final InputRowParser<Map<String, Object>> parser; private final Deque<Optional<Map<String, Object>>> queue = new ArrayDeque<>(); private boolean closed = false; public TestFirehose(final InputRowParser<Map<String, Object>> parser) { this.parser = parser; } public void addRows(List<Map<String, Object>> rows) { synchronized (this) { rows.stream().map(Optional::ofNullable).forEach(queue::add); notifyAll(); } } @Override public boolean hasMore() { try { synchronized (this) { while (queue.isEmpty() && !closed) { wait(); } return !queue.isEmpty(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.propagate(e); } } @Override public InputRow nextRow() { synchronized (this) { final InputRow row = parser.parseBatch(queue.removeFirst().orElse(null)).get(0); if (row != null && row.getRaw(FAIL_DIM) != null) { throw new ParseException(FAIL_DIM); } return row; } } @Override public Runnable commit() { return Runnables.getNoopRunnable(); } @Override public void close() { synchronized (this) { closed = true; notifyAll(); } } } private static class TestFirehoseFactory implements FirehoseFactory<InputRowParser> { public TestFirehoseFactory() { } @Override @SuppressWarnings("unchecked") public Firehose connect(InputRowParser parser, File temporaryDirectory) throws ParseException { return new TestFirehose(parser); } } @Rule public final ExpectedException expectedException = ExpectedException.none(); @Rule public final TemporaryFolder tempFolder = new TemporaryFolder(); @Rule public final TestDerbyConnector.DerbyConnectorRule derbyConnectorRule = new TestDerbyConnector.DerbyConnectorRule(); private DateTime now; private ListeningExecutorService taskExec; private Map<SegmentDescriptor, Pair<Executor, Runnable>> handOffCallbacks; private Collection<DataSegment> publishedSegments; private CountDownLatch segmentLatch; private CountDownLatch handoffLatch; private TaskStorage taskStorage; private TaskLockbox taskLockbox; private TaskToolboxFactory taskToolboxFactory; private File baseDir; private File reportsFile; private RowIngestionMetersFactory rowIngestionMetersFactory; @Before public void setUp() throws IOException { EmittingLogger.registerEmitter(emitter); emitter.start(); taskExec = MoreExecutors.listeningDecorator(Execs.singleThreaded("realtime-index-task-test-%d")); now = DateTimes.nowUtc(); TestDerbyConnector derbyConnector = derbyConnectorRule.getConnector(); derbyConnector.createDataSourceTable(); derbyConnector.createTaskTables(); derbyConnector.createSegmentTable(); derbyConnector.createPendingSegmentsTable(); baseDir = tempFolder.newFolder(); reportsFile = File.createTempFile("KafkaIndexTaskTestReports-" + System.currentTimeMillis(), "json"); makeToolboxFactory(baseDir); } @After public void tearDown() { taskExec.shutdownNow(); reportsFile.delete(); } @Test(timeout = 60_000L) public void testDefaultResource() { final AppenderatorDriverRealtimeIndexTask task = makeRealtimeTask(null); Assert.assertEquals(task.getId(), task.getTaskResource().getAvailabilityGroup()); } @Test(timeout = 60_000L) public void testHandoffTimeout() throws Exception { expectPublishedSegments(1); final AppenderatorDriverRealtimeIndexTask task = makeRealtimeTask(null, TransformSpec.NONE, true, 100L, true, 0, 1); final ListenableFuture<TaskStatus> statusFuture = runTask(task); // Wait for firehose to show up, it starts off null. while (task.getFirehose() == null) { Thread.sleep(50); } final TestFirehose firehose = (TestFirehose) task.getFirehose(); firehose.addRows( ImmutableList.of( ImmutableMap.of("t", now.getMillis(), "dim1", "foo", "met1", "1") ) ); // Stop the firehose, this will drain out existing events. firehose.close(); // handoff would timeout, resulting in exception TaskStatus status = statusFuture.get(); Assert.assertTrue(status.getErrorMsg() .contains("java.util.concurrent.TimeoutException: Timeout waiting for task.")); } @Test(timeout = 60_000L) public void testBasics() throws Exception { expectPublishedSegments(1); final AppenderatorDriverRealtimeIndexTask task = makeRealtimeTask(null); final ListenableFuture<TaskStatus> statusFuture = runTask(task); // Wait for firehose to show up, it starts off null. while (task.getFirehose() == null) { Thread.sleep(50); } final TestFirehose firehose = (TestFirehose) task.getFirehose(); firehose.addRows( ImmutableList.of( ImmutableMap.of("t", now.getMillis(), "dim1", "foo", "met1", "1"), ImmutableMap.of("t", now.getMillis(), "dim2", "bar", "met1", 2.0) ) ); // Stop the firehose, this will drain out existing events. firehose.close(); // Wait for publish. Collection<DataSegment> publishedSegments = awaitSegments(); // Check metrics. Assert.assertEquals(2, task.getRowIngestionMeters().getProcessed()); Assert.assertEquals(0, task.getRowIngestionMeters().getThrownAway()); Assert.assertEquals(0, task.getRowIngestionMeters().getUnparseable()); // Do some queries. Assert.assertEquals(2, sumMetric(task, null, "rows").longValue()); Assert.assertEquals(3, sumMetric(task, null, "met1").longValue()); awaitHandoffs(); for (DataSegment publishedSegment : publishedSegments) { Pair<Executor, Runnable> executorRunnablePair = handOffCallbacks.get( new SegmentDescriptor( publishedSegment.getInterval(), publishedSegment.getVersion(), publishedSegment.getShardSpec().getPartitionNum() ) ); Assert.assertNotNull( publishedSegment + " missing from handoff callbacks: " + handOffCallbacks, executorRunnablePair ); // Simulate handoff. executorRunnablePair.lhs.execute(executorRunnablePair.rhs); } handOffCallbacks.clear(); // Wait for the task to finish. final TaskStatus taskStatus = statusFuture.get(); Assert.assertEquals(TaskState.SUCCESS, taskStatus.getStatusCode()); } @Test(timeout = 60_000L) public void testLateData() throws Exception { expectPublishedSegments(1); final AppenderatorDriverRealtimeIndexTask task = makeRealtimeTask(null); final ListenableFuture<TaskStatus> statusFuture = runTask(task); // Wait for firehose to show up, it starts off null. while (task.getFirehose() == null) { Thread.sleep(50); } final TestFirehose firehose = (TestFirehose) task.getFirehose(); firehose.addRows( ImmutableList.of( ImmutableMap.of("t", now.getMillis(), "dim1", "foo", "met1", "1"), // Data is from 2 days ago, should still be processed ImmutableMap.of("t", now.minus(new Period("P2D")).getMillis(), "dim2", "bar", "met1", 2.0) ) ); // Stop the firehose, this will drain out existing events. firehose.close(); // Wait for publish. Collection<DataSegment> publishedSegments = awaitSegments(); // Check metrics. Assert.assertEquals(2, task.getRowIngestionMeters().getProcessed()); Assert.assertEquals(0, task.getRowIngestionMeters().getThrownAway()); Assert.assertEquals(0, task.getRowIngestionMeters().getUnparseable()); // Do some queries. Assert.assertEquals(2, sumMetric(task, null, "rows").longValue()); Assert.assertEquals(3, sumMetric(task, null, "met1").longValue()); awaitHandoffs(); for (DataSegment publishedSegment : publishedSegments) { Pair<Executor, Runnable> executorRunnablePair = handOffCallbacks.get( new SegmentDescriptor( publishedSegment.getInterval(), publishedSegment.getVersion(), publishedSegment.getShardSpec().getPartitionNum() ) ); Assert.assertNotNull( publishedSegment + " missing from handoff callbacks: " + handOffCallbacks, executorRunnablePair ); // Simulate handoff. executorRunnablePair.lhs.execute(executorRunnablePair.rhs); } handOffCallbacks.clear(); // Wait for the task to finish. final TaskStatus taskStatus = statusFuture.get(); Assert.assertEquals(TaskState.SUCCESS, taskStatus.getStatusCode()); } @Test(timeout = 60_000L) public void testMaxRowsPerSegment() throws Exception { // Expect 2 segments as we will hit maxRowsPerSegment expectPublishedSegments(2); final AppenderatorDriverRealtimeIndexTask task = makeRealtimeTask(null); final ListenableFuture<TaskStatus> statusFuture = runTask(task); // Wait for firehose to show up, it starts off null. while (task.getFirehose() == null) { Thread.sleep(50); } final TestFirehose firehose = (TestFirehose) task.getFirehose(); // maxRowsPerSegment is 1000 as configured in #makeRealtimeTask for (int i = 0; i < 2000; i++) { firehose.addRows( ImmutableList.of( ImmutableMap.of("t", now.getMillis(), "dim1", "foo-" + i, "met1", "1") ) ); } // Stop the firehose, this will drain out existing events. firehose.close(); // Wait for publish. Collection<DataSegment> publishedSegments = awaitSegments(); // Check metrics. Assert.assertEquals(2000, task.getRowIngestionMeters().getProcessed()); Assert.assertEquals(0, task.getRowIngestionMeters().getThrownAway()); Assert.assertEquals(0, task.getRowIngestionMeters().getUnparseable()); // Do some queries. Assert.assertEquals(2000, sumMetric(task, null, "rows").longValue()); Assert.assertEquals(2000, sumMetric(task, null, "met1").longValue()); awaitHandoffs(); for (DataSegment publishedSegment : publishedSegments) { Pair<Executor, Runnable> executorRunnablePair = handOffCallbacks.get( new SegmentDescriptor( publishedSegment.getInterval(), publishedSegment.getVersion(), publishedSegment.getShardSpec().getPartitionNum() ) ); Assert.assertNotNull( publishedSegment + " missing from handoff callbacks: " + handOffCallbacks, executorRunnablePair ); // Simulate handoff. executorRunnablePair.lhs.execute(executorRunnablePair.rhs); } handOffCallbacks.clear(); // Wait for the task to finish. final TaskStatus taskStatus = statusFuture.get(); Assert.assertEquals(TaskState.SUCCESS, taskStatus.getStatusCode()); } @Test(timeout = 60_000L) public void testMaxTotalRows() throws Exception { // Expect 2 segments as we will hit maxTotalRows expectPublishedSegments(2); final AppenderatorDriverRealtimeIndexTask task = makeRealtimeTask(null, Integer.MAX_VALUE, 1500L); final ListenableFuture<TaskStatus> statusFuture = runTask(task); // Wait for firehose to show up, it starts off null. while (task.getFirehose() == null) { Thread.sleep(50); } final TestFirehose firehose = (TestFirehose) task.getFirehose(); // maxTotalRows is 1500 for (int i = 0; i < 2000; i++) { firehose.addRows( ImmutableList.of( ImmutableMap.of("t", now.getMillis(), "dim1", "foo-" + i, "met1", "1") ) ); } // Stop the firehose, this will drain out existing events. firehose.close(); // Wait for publish. Collection<DataSegment> publishedSegments = awaitSegments(); // Check metrics. Assert.assertEquals(2000, task.getRowIngestionMeters().getProcessed()); Assert.assertEquals(0, task.getRowIngestionMeters().getThrownAway()); Assert.assertEquals(0, task.getRowIngestionMeters().getUnparseable()); // Do some queries. Assert.assertEquals(2000, sumMetric(task, null, "rows").longValue()); Assert.assertEquals(2000, sumMetric(task, null, "met1").longValue()); awaitHandoffs(); Assert.assertEquals(2, publishedSegments.size()); for (DataSegment publishedSegment : publishedSegments) { Pair<Executor, Runnable> executorRunnablePair = handOffCallbacks.get( new SegmentDescriptor( publishedSegment.getInterval(), publishedSegment.getVersion(), publishedSegment.getShardSpec().getPartitionNum() ) ); Assert.assertNotNull( publishedSegment + " missing from handoff callbacks: " + handOffCallbacks, executorRunnablePair ); // Simulate handoff. executorRunnablePair.lhs.execute(executorRunnablePair.rhs); } handOffCallbacks.clear(); // Wait for the task to finish. final TaskStatus taskStatus = statusFuture.get(); Assert.assertEquals(TaskState.SUCCESS, taskStatus.getStatusCode()); } @Test(timeout = 60_000L) public void testTransformSpec() throws Exception { expectPublishedSegments(2); final TransformSpec transformSpec = new TransformSpec( new SelectorDimFilter("dim1", "foo", null), ImmutableList.of( new ExpressionTransform("dim1t", "concat(dim1,dim1)", ExprMacroTable.nil()) ) ); final AppenderatorDriverRealtimeIndexTask task = makeRealtimeTask(null, transformSpec, true, 0, true, 0, 1); final ListenableFuture<TaskStatus> statusFuture = runTask(task); // Wait for firehose to show up, it starts off null. while (task.getFirehose() == null) { Thread.sleep(50); } final TestFirehose firehose = (TestFirehose) task.getFirehose(); firehose.addRows( ImmutableList.of( ImmutableMap.of("t", now.getMillis(), "dim1", "foo", "met1", "1"), ImmutableMap.of("t", now.minus(new Period("P1D")).getMillis(), "dim1", "foo", "met1", 2.0), ImmutableMap.of("t", now.getMillis(), "dim2", "bar", "met1", 2.0) ) ); // Stop the firehose, this will drain out existing events. firehose.close(); Collection<DataSegment> publishedSegments = awaitSegments(); // Check metrics. Assert.assertEquals(2, task.getRowIngestionMeters().getProcessed()); Assert.assertEquals(1, task.getRowIngestionMeters().getThrownAway()); Assert.assertEquals(0, task.getRowIngestionMeters().getUnparseable()); // Do some queries. Assert.assertEquals(2, sumMetric(task, null, "rows").longValue()); Assert.assertEquals(2, sumMetric(task, new SelectorDimFilter("dim1t", "foofoo", null), "rows").longValue()); if (NullHandling.replaceWithDefault()) { Assert.assertEquals(0, sumMetric(task, new SelectorDimFilter("dim1t", "barbar", null), "metric1").longValue()); } else { Assert.assertNull(sumMetric(task, new SelectorDimFilter("dim1t", "barbar", null), "metric1")); } Assert.assertEquals(3, sumMetric(task, null, "met1").longValue()); awaitHandoffs(); for (DataSegment publishedSegment : publishedSegments) { Pair<Executor, Runnable> executorRunnablePair = handOffCallbacks.get( new SegmentDescriptor( publishedSegment.getInterval(), publishedSegment.getVersion(), publishedSegment.getShardSpec().getPartitionNum() ) ); Assert.assertNotNull( publishedSegment + " missing from handoff callbacks: " + handOffCallbacks, executorRunnablePair ); // Simulate handoff. executorRunnablePair.lhs.execute(executorRunnablePair.rhs); } handOffCallbacks.clear(); // Wait for the task to finish. final TaskStatus taskStatus = statusFuture.get(); Assert.assertEquals(TaskState.SUCCESS, taskStatus.getStatusCode()); } @Test(timeout = 60_000L) public void testReportParseExceptionsOnBadMetric() throws Exception { expectPublishedSegments(0); final AppenderatorDriverRealtimeIndexTask task = makeRealtimeTask(null, true); final ListenableFuture<TaskStatus> statusFuture = runTask(task); // Wait for firehose to show up, it starts off null. while (task.getFirehose() == null) { Thread.sleep(50); } final TestFirehose firehose = (TestFirehose) task.getFirehose(); firehose.addRows( ImmutableList.of( ImmutableMap.of("t", 2000000L, "dim1", "foo", "met1", "1"), ImmutableMap.of("t", 3000000L, "dim1", "foo", "met1", "foo"), ImmutableMap.of("t", now.minus(new Period("P1D")).getMillis(), "dim1", "foo", "met1", "foo"), ImmutableMap.of("t", 4000000L, "dim2", "bar", "met1", 2.0) ) ); // Stop the firehose, this will drain out existing events. firehose.close(); // Wait for the task to finish. TaskStatus status = statusFuture.get(); Assert.assertTrue(status.getErrorMsg() .contains("java.lang.RuntimeException: Max parse exceptions exceeded, terminating task...")); IngestionStatsAndErrorsTaskReportData reportData = getTaskReportData(); Map<String, Object> expectedUnparseables = ImmutableMap.of( RowIngestionMeters.BUILD_SEGMENTS, Collections.singletonList( "Found unparseable columns in row: [MapBasedInputRow{timestamp=1970-01-01T00:50:00.000Z, event={t=3000000, dim1=foo, met1=foo}, dimensions=[dim1, dim2, dim1t, dimLong, dimFloat]}], exceptions: [Unable to parse value[foo] for field[met1],]" ) ); Assert.assertEquals(expectedUnparseables, reportData.getUnparseableEvents()); } @Test(timeout = 60_000L) public void testNoReportParseExceptions() throws Exception { expectPublishedSegments(1); final AppenderatorDriverRealtimeIndexTask task = makeRealtimeTask( null, TransformSpec.NONE, false, 0, true, null, 1 ); final ListenableFuture<TaskStatus> statusFuture = runTask(task); // Wait for firehose to show up, it starts off null. while (task.getFirehose() == null) { Thread.sleep(50); } final TestFirehose firehose = (TestFirehose) task.getFirehose(); firehose.addRows( Arrays.asList( // Good row- will be processed. ImmutableMap.of("t", now.getMillis(), "dim1", "foo", "met1", "1"), // Null row- will be thrown away. null, // Bad metric- will count as processed, but that particular metric won't update. ImmutableMap.of("t", now.getMillis(), "dim1", "foo", "met1", "foo"), // Bad row- will be unparseable. ImmutableMap.of("dim1", "foo", "met1", 2.0, FAIL_DIM, "x"), // Good row- will be processed. ImmutableMap.of("t", now.getMillis(), "dim2", "bar", "met1", 2.0) ) ); // Stop the firehose, this will drain out existing events. firehose.close(); // Wait for publish. Collection<DataSegment> publishedSegments = awaitSegments(); DataSegment publishedSegment = Iterables.getOnlyElement(publishedSegments); // Check metrics. Assert.assertEquals(2, task.getRowIngestionMeters().getProcessed()); Assert.assertEquals(1, task.getRowIngestionMeters().getProcessedWithError()); Assert.assertEquals(0, task.getRowIngestionMeters().getThrownAway()); Assert.assertEquals(2, task.getRowIngestionMeters().getUnparseable()); // Do some queries. Assert.assertEquals(3, sumMetric(task, null, "rows").longValue()); Assert.assertEquals(3, sumMetric(task, null, "met1").longValue()); awaitHandoffs(); // Simulate handoff. for (Map.Entry<SegmentDescriptor, Pair<Executor, Runnable>> entry : handOffCallbacks.entrySet()) { final Pair<Executor, Runnable> executorRunnablePair = entry.getValue(); Assert.assertEquals( new SegmentDescriptor( publishedSegment.getInterval(), publishedSegment.getVersion(), publishedSegment.getShardSpec().getPartitionNum() ), entry.getKey() ); executorRunnablePair.lhs.execute(executorRunnablePair.rhs); } handOffCallbacks.clear(); Map<String, Object> expectedMetrics = ImmutableMap.of( RowIngestionMeters.BUILD_SEGMENTS, ImmutableMap.of( RowIngestionMeters.PROCESSED, 2, RowIngestionMeters.PROCESSED_WITH_ERROR, 1, RowIngestionMeters.UNPARSEABLE, 2, RowIngestionMeters.THROWN_AWAY, 0 ) ); // Wait for the task to finish. final TaskStatus taskStatus = statusFuture.get(); Assert.assertEquals(TaskState.SUCCESS, taskStatus.getStatusCode()); IngestionStatsAndErrorsTaskReportData reportData = getTaskReportData(); Assert.assertEquals(expectedMetrics, reportData.getRowStats()); } @Test(timeout = 60_000L) public void testMultipleParseExceptionsSuccess() throws Exception { expectPublishedSegments(1); final AppenderatorDriverRealtimeIndexTask task = makeRealtimeTask(null, TransformSpec.NONE, false, 0, true, 10, 10); final ListenableFuture<TaskStatus> statusFuture = runTask(task); // Wait for firehose to show up, it starts off null. while (task.getFirehose() == null) { Thread.sleep(50); } final TestFirehose firehose = (TestFirehose) task.getFirehose(); firehose.addRows( Arrays.asList( // Good row- will be processed. ImmutableMap.of("t", 1521251960729L, "dim1", "foo", "met1", "1"), // Null row- will be thrown away. null, // Bad metric- will count as processed, but that particular metric won't update. ImmutableMap.of("t", 1521251960729L, "dim1", "foo", "met1", "foo"), // Bad long dim- will count as processed, but bad dims will get default values ImmutableMap.of( "t", 1521251960729L, "dim1", "foo", "dimLong", "notnumber", "dimFloat", "notnumber", "met1", "foo" ), // Bad row- will be unparseable. ImmutableMap.of("dim1", "foo", "met1", 2.0, FAIL_DIM, "x"), // Good row- will be processed. ImmutableMap.of("t", 1521251960729L, "dim2", "bar", "met1", 2.0) ) ); // Stop the firehose, this will drain out existing events. firehose.close(); // Wait for publish. Collection<DataSegment> publishedSegments = awaitSegments(); DataSegment publishedSegment = Iterables.getOnlyElement(publishedSegments); // Check metrics. Assert.assertEquals(2, task.getRowIngestionMeters().getProcessed()); Assert.assertEquals(2, task.getRowIngestionMeters().getProcessedWithError()); Assert.assertEquals(0, task.getRowIngestionMeters().getThrownAway()); Assert.assertEquals(2, task.getRowIngestionMeters().getUnparseable()); // Do some queries. Assert.assertEquals(4, sumMetric(task, null, "rows").longValue()); Assert.assertEquals(3, sumMetric(task, null, "met1").longValue()); awaitHandoffs(); // Simulate handoff. for (Map.Entry<SegmentDescriptor, Pair<Executor, Runnable>> entry : handOffCallbacks.entrySet()) { final Pair<Executor, Runnable> executorRunnablePair = entry.getValue(); Assert.assertEquals( new SegmentDescriptor( publishedSegment.getInterval(), publishedSegment.getVersion(), publishedSegment.getShardSpec().getPartitionNum() ), entry.getKey() ); executorRunnablePair.lhs.execute(executorRunnablePair.rhs); } handOffCallbacks.clear(); Map<String, Object> expectedMetrics = ImmutableMap.of( RowIngestionMeters.BUILD_SEGMENTS, ImmutableMap.of( RowIngestionMeters.PROCESSED, 2, RowIngestionMeters.PROCESSED_WITH_ERROR, 2, RowIngestionMeters.UNPARSEABLE, 2, RowIngestionMeters.THROWN_AWAY, 0 ) ); // Wait for the task to finish. final TaskStatus taskStatus = statusFuture.get(); Assert.assertEquals(TaskState.SUCCESS, taskStatus.getStatusCode()); IngestionStatsAndErrorsTaskReportData reportData = getTaskReportData(); Assert.assertEquals(expectedMetrics, reportData.getRowStats()); Map<String, Object> expectedUnparseables = ImmutableMap.of( RowIngestionMeters.BUILD_SEGMENTS, Arrays.asList( "Unparseable timestamp found! Event: {dim1=foo, met1=2.0, __fail__=x}", "Found unparseable columns in row: [MapBasedInputRow{timestamp=2018-03-17T01:59:20.729Z, event={t=1521251960729, dim1=foo, dimLong=notnumber, dimFloat=notnumber, met1=foo}, dimensions=[dim1, dim2, dim1t, dimLong, dimFloat]}], exceptions: [could not convert value [notnumber] to long,could not convert value [notnumber] to float,Unable to parse value[foo] for field[met1],]", "Found unparseable columns in row: [MapBasedInputRow{timestamp=2018-03-17T01:59:20.729Z, event={t=1521251960729, dim1=foo, met1=foo}, dimensions=[dim1, dim2, dim1t, dimLong, dimFloat]}], exceptions: [Unable to parse value[foo] for field[met1],]", "Unparseable timestamp found! Event: null" ) ); Assert.assertEquals(expectedUnparseables, reportData.getUnparseableEvents()); Assert.assertEquals(IngestionState.COMPLETED, reportData.getIngestionState()); } @Test(timeout = 60_000L) public void testMultipleParseExceptionsFailure() throws Exception { expectPublishedSegments(1); final AppenderatorDriverRealtimeIndexTask task = makeRealtimeTask(null, TransformSpec.NONE, false, 0, true, 3, 10); final ListenableFuture<TaskStatus> statusFuture = runTask(task); // Wait for firehose to show up, it starts off null. while (task.getFirehose() == null) { Thread.sleep(50); } final TestFirehose firehose = (TestFirehose) task.getFirehose(); firehose.addRows( Arrays.asList( // Good row- will be processed. ImmutableMap.of("t", 1521251960729L, "dim1", "foo", "met1", "1"), // Null row- will be thrown away. null, // Bad metric- will count as processed, but that particular metric won't update. ImmutableMap.of("t", 1521251960729L, "dim1", "foo", "met1", "foo"), // Bad long dim- will count as processed, but bad dims will get default values ImmutableMap.of( "t", 1521251960729L, "dim1", "foo", "dimLong", "notnumber", "dimFloat", "notnumber", "met1", "foo" ), // Bad row- will be unparseable. ImmutableMap.of("dim1", "foo", "met1", 2.0, FAIL_DIM, "x"), // Good row- will be processed. ImmutableMap.of("t", 1521251960729L, "dim2", "bar", "met1", 2.0) ) ); // Stop the firehose, this will drain out existing events. firehose.close(); // Wait for the task to finish. final TaskStatus taskStatus = statusFuture.get(); Assert.assertEquals(TaskState.FAILED, taskStatus.getStatusCode()); Assert.assertTrue(taskStatus.getErrorMsg().contains("Max parse exceptions exceeded, terminating task...")); IngestionStatsAndErrorsTaskReportData reportData = getTaskReportData(); Map<String, Object> expectedMetrics = ImmutableMap.of( RowIngestionMeters.BUILD_SEGMENTS, ImmutableMap.of( RowIngestionMeters.PROCESSED, 1, RowIngestionMeters.PROCESSED_WITH_ERROR, 2, RowIngestionMeters.UNPARSEABLE, 2, RowIngestionMeters.THROWN_AWAY, 0 ) ); Assert.assertEquals(expectedMetrics, reportData.getRowStats()); Map<String, Object> expectedUnparseables = ImmutableMap.of( RowIngestionMeters.BUILD_SEGMENTS, Arrays.asList( "Unparseable timestamp found! Event: {dim1=foo, met1=2.0, __fail__=x}", "Found unparseable columns in row: [MapBasedInputRow{timestamp=2018-03-17T01:59:20.729Z, event={t=1521251960729, dim1=foo, dimLong=notnumber, dimFloat=notnumber, met1=foo}, dimensions=[dim1, dim2, dim1t, dimLong, dimFloat]}], exceptions: [could not convert value [notnumber] to long,could not convert value [notnumber] to float,Unable to parse value[foo] for field[met1],]", "Found unparseable columns in row: [MapBasedInputRow{timestamp=2018-03-17T01:59:20.729Z, event={t=1521251960729, dim1=foo, met1=foo}, dimensions=[dim1, dim2, dim1t, dimLong, dimFloat]}], exceptions: [Unable to parse value[foo] for field[met1],]", "Unparseable timestamp found! Event: null" ) ); Assert.assertEquals(expectedUnparseables, reportData.getUnparseableEvents()); Assert.assertEquals(IngestionState.BUILD_SEGMENTS, reportData.getIngestionState()); } @Test(timeout = 60_000L) public void testRestore() throws Exception { expectPublishedSegments(0); final AppenderatorDriverRealtimeIndexTask task1 = makeRealtimeTask(null); final DataSegment publishedSegment; // First run: { final ListenableFuture<TaskStatus> statusFuture = runTask(task1); // Wait for firehose to show up, it starts off null. while (task1.getFirehose() == null) { Thread.sleep(50); } final TestFirehose firehose = (TestFirehose) task1.getFirehose(); firehose.addRows( ImmutableList.of( ImmutableMap.of("t", now.getMillis(), "dim1", "foo") ) ); // Trigger graceful shutdown. task1.stopGracefully(); // Wait for the task to finish. The status doesn't really matter, but we'll check it anyway. final TaskStatus taskStatus = statusFuture.get(); Assert.assertEquals(TaskState.SUCCESS, taskStatus.getStatusCode()); // Nothing should be published. Assert.assertTrue(publishedSegments.isEmpty()); } // Second run: { expectPublishedSegments(1); final AppenderatorDriverRealtimeIndexTask task2 = makeRealtimeTask(task1.getId()); final ListenableFuture<TaskStatus> statusFuture = runTask(task2); // Wait for firehose to show up, it starts off null. while (task2.getFirehose() == null) { Thread.sleep(50); } // Do a query, at this point the previous data should be loaded. Assert.assertEquals(1, sumMetric(task2, null, "rows").longValue()); final TestFirehose firehose = (TestFirehose) task2.getFirehose(); firehose.addRows( ImmutableList.of( ImmutableMap.of("t", now.getMillis(), "dim2", "bar") ) ); // Stop the firehose, this will drain out existing events. firehose.close(); Collection<DataSegment> publishedSegments = awaitSegments(); publishedSegment = Iterables.getOnlyElement(publishedSegments); // Do a query. Assert.assertEquals(2, sumMetric(task2, null, "rows").longValue()); awaitHandoffs(); // Simulate handoff. for (Map.Entry<SegmentDescriptor, Pair<Executor, Runnable>> entry : handOffCallbacks.entrySet()) { final Pair<Executor, Runnable> executorRunnablePair = entry.getValue(); Assert.assertEquals( new SegmentDescriptor( publishedSegment.getInterval(), publishedSegment.getVersion(), publishedSegment.getShardSpec().getPartitionNum() ), entry.getKey() ); executorRunnablePair.lhs.execute(executorRunnablePair.rhs); } handOffCallbacks.clear(); // Wait for the task to finish. final TaskStatus taskStatus = statusFuture.get(); Assert.assertEquals(TaskState.SUCCESS, taskStatus.getStatusCode()); } } @Test(timeout = 60_000L) public void testRestoreAfterHandoffAttemptDuringShutdown() throws Exception { final AppenderatorDriverRealtimeIndexTask task1 = makeRealtimeTask(null); final DataSegment publishedSegment; // First run: { expectPublishedSegments(1); final ListenableFuture<TaskStatus> statusFuture = runTask(task1); // Wait for firehose to show up, it starts off null. while (task1.getFirehose() == null) { Thread.sleep(50); } final TestFirehose firehose = (TestFirehose) task1.getFirehose(); firehose.addRows( ImmutableList.of( ImmutableMap.of("t", now.getMillis(), "dim1", "foo") ) ); // Stop the firehose, this will trigger a finishJob. firehose.close(); Collection<DataSegment> publishedSegments = awaitSegments(); publishedSegment = Iterables.getOnlyElement(publishedSegments); // Do a query. Assert.assertEquals(1, sumMetric(task1, null, "rows").longValue()); // Trigger graceful shutdown. task1.stopGracefully(); // Wait for the task to finish. The status doesn't really matter. while (!statusFuture.isDone()) { Thread.sleep(50); } } // Second run: { expectPublishedSegments(1); final AppenderatorDriverRealtimeIndexTask task2 = makeRealtimeTask(task1.getId()); final ListenableFuture<TaskStatus> statusFuture = runTask(task2); // Wait for firehose to show up, it starts off null. while (task2.getFirehose() == null) { Thread.sleep(50); } // Stop the firehose again, this will start another handoff. final TestFirehose firehose = (TestFirehose) task2.getFirehose(); // Stop the firehose, this will trigger a finishJob. firehose.close(); awaitHandoffs(); // Simulate handoff. for (Map.Entry<SegmentDescriptor, Pair<Executor, Runnable>> entry : handOffCallbacks.entrySet()) { final Pair<Executor, Runnable> executorRunnablePair = entry.getValue(); Assert.assertEquals( new SegmentDescriptor( publishedSegment.getInterval(), publishedSegment.getVersion(), publishedSegment.getShardSpec().getPartitionNum() ), entry.getKey() ); executorRunnablePair.lhs.execute(executorRunnablePair.rhs); } handOffCallbacks.clear(); // Wait for the task to finish. final TaskStatus taskStatus = statusFuture.get(); Assert.assertEquals(TaskState.SUCCESS, taskStatus.getStatusCode()); } } @Test(timeout = 60_000L) public void testRestoreCorruptData() throws Exception { final AppenderatorDriverRealtimeIndexTask task1 = makeRealtimeTask(null); // First run: { expectPublishedSegments(0); final ListenableFuture<TaskStatus> statusFuture = runTask(task1); // Wait for firehose to show up, it starts off null. while (task1.getFirehose() == null) { Thread.sleep(50); } final TestFirehose firehose = (TestFirehose) task1.getFirehose(); firehose.addRows( ImmutableList.of( ImmutableMap.of("t", now.getMillis(), "dim1", "foo") ) ); // Trigger graceful shutdown. task1.stopGracefully(); // Wait for the task to finish. The status doesn't really matter, but we'll check it anyway. final TaskStatus taskStatus = statusFuture.get(); Assert.assertEquals(TaskState.SUCCESS, taskStatus.getStatusCode()); // Nothing should be published. Assert.assertTrue(publishedSegments.isEmpty()); } Optional<File> optional = FileUtils.listFiles(baseDir, null, true).stream() .filter(f -> f.getName().equals("00000.smoosh")) .findFirst(); Assert.assertTrue("Could not find smoosh file", optional.isPresent()); // Corrupt the data: final File smooshFile = optional.get(); Files.write(smooshFile.toPath(), StringUtils.toUtf8("oops!")); // Second run: { expectPublishedSegments(0); final AppenderatorDriverRealtimeIndexTask task2 = makeRealtimeTask(task1.getId()); final ListenableFuture<TaskStatus> statusFuture = runTask(task2); // Wait for the task to finish. TaskStatus status = statusFuture.get(); Map<String, Object> expectedMetrics = ImmutableMap.of( RowIngestionMeters.BUILD_SEGMENTS, ImmutableMap.of( RowIngestionMeters.PROCESSED_WITH_ERROR, 0, RowIngestionMeters.PROCESSED, 0, RowIngestionMeters.UNPARSEABLE, 0, RowIngestionMeters.THROWN_AWAY, 0 ) ); IngestionStatsAndErrorsTaskReportData reportData = getTaskReportData(); Assert.assertEquals(expectedMetrics, reportData.getRowStats()); Assert.assertTrue(status.getErrorMsg() .contains("java.lang.IllegalArgumentException\n\tat java.nio.Buffer.position")); } } @Test(timeout = 60_000L) public void testStopBeforeStarting() throws Exception { expectPublishedSegments(0); final AppenderatorDriverRealtimeIndexTask task1 = makeRealtimeTask(null); task1.stopGracefully(); final ListenableFuture<TaskStatus> statusFuture = runTask(task1); // Wait for the task to finish. final TaskStatus taskStatus = statusFuture.get(); Assert.assertEquals(TaskState.SUCCESS, taskStatus.getStatusCode()); } private ListenableFuture<TaskStatus> runTask(final Task task) { try { taskStorage.insert(task, TaskStatus.running(task.getId())); } catch (EntryExistsException e) { // suppress } taskLockbox.syncFromStorage(); final TaskToolbox toolbox = taskToolboxFactory.build(task); return taskExec.submit( () -> { try { if (task.isReady(toolbox.getTaskActionClient())) { return task.run(toolbox); } else { throw new ISE("Task is not ready"); } } catch (Exception e) { log.warn(e, "Task failed"); throw e; } } ); } private AppenderatorDriverRealtimeIndexTask makeRealtimeTask(final String taskId) { return makeRealtimeTask( taskId, TransformSpec.NONE, true, 0, true, 0, 1 ); } private AppenderatorDriverRealtimeIndexTask makeRealtimeTask( final String taskId, final Integer maxRowsPerSegment, final Long maxTotalRows ) { return makeRealtimeTask( taskId, TransformSpec.NONE, true, 0, true, 0, 1, maxRowsPerSegment, maxTotalRows ); } private AppenderatorDriverRealtimeIndexTask makeRealtimeTask(final String taskId, boolean reportParseExceptions) { return makeRealtimeTask( taskId, TransformSpec.NONE, reportParseExceptions, 0, true, null, 1 ); } private AppenderatorDriverRealtimeIndexTask makeRealtimeTask( final String taskId, final TransformSpec transformSpec, final boolean reportParseExceptions, final long handoffTimeout, final Boolean logParseExceptions, final Integer maxParseExceptions, final Integer maxSavedParseExceptions ) { return makeRealtimeTask( taskId, transformSpec, reportParseExceptions, handoffTimeout, logParseExceptions, maxParseExceptions, maxSavedParseExceptions, 1000, null ); } private AppenderatorDriverRealtimeIndexTask makeRealtimeTask( final String taskId, final TransformSpec transformSpec, final boolean reportParseExceptions, final long handoffTimeout, final Boolean logParseExceptions, final Integer maxParseExceptions, final Integer maxSavedParseExceptions, final Integer maxRowsPerSegment, final Long maxTotalRows ) { ObjectMapper objectMapper = new DefaultObjectMapper(); DataSchema dataSchema = new DataSchema( "test_ds", TestHelper.makeJsonMapper().convertValue( new MapInputRowParser( new TimeAndDimsParseSpec( new TimestampSpec("t", "auto", null), new DimensionsSpec( ImmutableList.of( new StringDimensionSchema("dim1"), new StringDimensionSchema("dim2"), new StringDimensionSchema("dim1t"), new LongDimensionSchema("dimLong"), new FloatDimensionSchema("dimFloat") ), null, null ) ) ), JacksonUtils.TYPE_REFERENCE_MAP_STRING_OBJECT ), new AggregatorFactory[]{new CountAggregatorFactory("rows"), new LongSumAggregatorFactory("met1", "met1")}, new UniformGranularitySpec(Granularities.DAY, Granularities.NONE, null), transformSpec, objectMapper ); RealtimeIOConfig realtimeIOConfig = new RealtimeIOConfig( new TestFirehoseFactory(), null, null ); RealtimeAppenderatorTuningConfig tuningConfig = new RealtimeAppenderatorTuningConfig( 1000, null, maxRowsPerSegment, maxTotalRows, null, null, null, null, null, reportParseExceptions, handoffTimeout, null, null, logParseExceptions, maxParseExceptions, maxSavedParseExceptions ); return new AppenderatorDriverRealtimeIndexTask( taskId, null, new RealtimeAppenderatorIngestionSpec(dataSchema, realtimeIOConfig, tuningConfig), null, null, AuthTestUtils.TEST_AUTHORIZER_MAPPER, rowIngestionMetersFactory ) { @Override protected boolean isFirehoseDrainableByClosing(FirehoseFactory firehoseFactory) { return true; } }; } private void expectPublishedSegments(int count) { segmentLatch = new CountDownLatch(count); handoffLatch = new CountDownLatch(count); } private Collection<DataSegment> awaitSegments() throws InterruptedException { Assert.assertTrue( "Timed out waiting for segments to be published", segmentLatch.await(1, TimeUnit.MINUTES) ); return publishedSegments; } private void awaitHandoffs() throws InterruptedException { Assert.assertTrue( "Timed out waiting for segments to be handed off", handoffLatch.await(1, TimeUnit.MINUTES) ); } private void makeToolboxFactory(final File directory) { taskStorage = new HeapMemoryTaskStorage(new TaskStorageConfig(null)); taskLockbox = new TaskLockbox(taskStorage); publishedSegments = new CopyOnWriteArrayList<>(); ObjectMapper mapper = new DefaultObjectMapper(); mapper.registerSubtypes(LinearShardSpec.class); mapper.registerSubtypes(NumberedShardSpec.class); IndexerSQLMetadataStorageCoordinator mdc = new IndexerSQLMetadataStorageCoordinator( mapper, derbyConnectorRule.metadataTablesConfigSupplier().get(), derbyConnectorRule.getConnector() ) { @Override public Set<DataSegment> announceHistoricalSegments(Set<DataSegment> segments) throws IOException { Set<DataSegment> result = super.announceHistoricalSegments(segments); Assert.assertFalse( "Segment latch not initialized, did you forget to call expectPublishSegments?", segmentLatch == null ); publishedSegments.addAll(result); segments.forEach(s -> segmentLatch.countDown()); return result; } @Override public SegmentPublishResult announceHistoricalSegments( Set<DataSegment> segments, DataSourceMetadata startMetadata, DataSourceMetadata endMetadata ) throws IOException { SegmentPublishResult result = super.announceHistoricalSegments(segments, startMetadata, endMetadata); Assert.assertFalse( "Segment latch not initialized, did you forget to call expectPublishSegments?", segmentLatch == null ); publishedSegments.addAll(result.getSegments()); result.getSegments().forEach(s -> segmentLatch.countDown()); return result; } }; final TaskConfig taskConfig = new TaskConfig(directory.getPath(), null, null, 50000, null, false, null, null); final TaskActionToolbox taskActionToolbox = new TaskActionToolbox( taskLockbox, taskStorage, mdc, emitter, EasyMock.createMock(SupervisorManager.class), new Counters() ); final TaskActionClientFactory taskActionClientFactory = new LocalTaskActionClientFactory( taskStorage, taskActionToolbox, new TaskAuditLogConfig(false) ); IntervalChunkingQueryRunnerDecorator queryRunnerDecorator = new IntervalChunkingQueryRunnerDecorator( null, null, null ) { @Override public <T> QueryRunner<T> decorate( QueryRunner<T> delegate, QueryToolChest<T, ? extends Query<T>> toolChest ) { return delegate; } }; final QueryRunnerFactoryConglomerate conglomerate = new DefaultQueryRunnerFactoryConglomerate( ImmutableMap.of( TimeseriesQuery.class, new TimeseriesQueryRunnerFactory( new TimeseriesQueryQueryToolChest(queryRunnerDecorator), new TimeseriesQueryEngine(), (query, future) -> { // do nothing } ) ) ); handOffCallbacks = new ConcurrentHashMap<>(); final SegmentHandoffNotifierFactory handoffNotifierFactory = dataSource -> new SegmentHandoffNotifier() { @Override public boolean registerSegmentHandoffCallback( SegmentDescriptor descriptor, Executor exec, Runnable handOffRunnable ) { handOffCallbacks.put(descriptor, new Pair<>(exec, handOffRunnable)); handoffLatch.countDown(); return true; } @Override public void start() { //Noop } @Override public void close() { //Noop } }; final TestUtils testUtils = new TestUtils(); rowIngestionMetersFactory = testUtils.getRowIngestionMetersFactory(); SegmentLoaderConfig segmentLoaderConfig = new SegmentLoaderConfig() { @Override public List<StorageLocationConfig> getLocations() { return Lists.newArrayList(); } }; taskToolboxFactory = new TaskToolboxFactory( taskConfig, taskActionClientFactory, emitter, new TestDataSegmentPusher(), new TestDataSegmentKiller(), null, // DataSegmentMover null, // DataSegmentArchiver new TestDataSegmentAnnouncer(), EasyMock.createNiceMock(DataSegmentServerAnnouncer.class), handoffNotifierFactory, () -> conglomerate, MoreExecutors.sameThreadExecutor(), // queryExecutorService EasyMock.createMock(MonitorScheduler.class), new SegmentLoaderFactory( new SegmentLoaderLocalCacheManager(null, segmentLoaderConfig, testUtils.getTestObjectMapper()) ), testUtils.getTestObjectMapper(), testUtils.getTestIndexIO(), MapCache.create(1024), new CacheConfig(), new CachePopulatorStats(), testUtils.getTestIndexMergerV9(), EasyMock.createNiceMock(DruidNodeAnnouncer.class), EasyMock.createNiceMock(DruidNode.class), new LookupNodeService("tier"), new DataNodeService("tier", 1000, ServerType.INDEXER_EXECUTOR, 0), new TaskReportFileWriter(reportsFile) ); } @Nullable public Long sumMetric(final Task task, final DimFilter filter, final String metric) { // Do a query. TimeseriesQuery query = Druids.newTimeseriesQueryBuilder() .dataSource("test_ds") .filters(filter) .aggregators( ImmutableList.of( new LongSumAggregatorFactory(metric, metric) ) ).granularity(Granularities.ALL) .intervals("2000/3000") .build(); List<Result<TimeseriesResultValue>> results = task.getQueryRunner(query).run(QueryPlus.wrap(query), ImmutableMap.of()).toList(); if (results.isEmpty()) { return 0L; } else { return results.get(0).getValue().getLongMetric(metric); } } private IngestionStatsAndErrorsTaskReportData getTaskReportData() throws IOException { Map<String, TaskReport> taskReports = objectMapper.readValue( reportsFile, new TypeReference<Map<String, TaskReport>>() { } ); return IngestionStatsAndErrorsTaskReportData.getPayloadFromTaskReports( taskReports ); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sling.engine.impl.helper; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.Dictionary; import java.util.Enumeration; import java.util.EventListener; import java.util.Hashtable; import java.util.Map; import java.util.Set; import javax.servlet.Filter; import javax.servlet.FilterRegistration; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; import javax.servlet.ServletRegistration.Dynamic; import javax.servlet.SessionCookieConfig; import javax.servlet.SessionTrackingMode; import javax.servlet.descriptor.JspConfigDescriptor; import org.apache.sling.engine.impl.SlingMainServlet; import org.apache.sling.engine.impl.request.SlingRequestDispatcher; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceRegistration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The <code>SlingServletContext</code> class is the <code>ServletContext</code> * which is registered as a service usable by servlets and helpers inside Sling. * Most methods just call into the servlet context in which the * {@link SlingMainServlet} is running. * <dl> * <dt><b>MIME Type Mapping</b></dt> * <dd>Just forwards to the servlet context of the {@link SlingMainServlet} for * MIME type mapping.</dd> * <dt><b>Resources</b></dt> * <dd>This class provides access to the resources in the web application by * means of the respective resource accessor methods. These are not the same * resources as available through the <code>ResourceResolver</code>.</dd> * <dt><b>Request Dispatcher</b></dt> * <dd>The {@link #getRequestDispatcher(String)} method returns a * {@link SlingRequestDispatcher} which may dispatch a request inside sling * without going through the servlet container. The * {@link #getNamedDispatcher(String)} method returns a servlet container * request dispatcher which always goes through the servlet container.</dd> * <dt><b>Parameters and Attributes</b></dt> * <dd>Initialization parameters and context attributes are shared with the * servlet context in which the {@link SlingMainServlet} is running.</dd> * <dt><b>Logging</b></dt> * <dd>Logging is diverted to a logger whose name is the fully qualified name of * this class.</dd> * </dl> * <p> * This class implements the Servlet API 3.0 {@code ServletContext} interface. */ public class SlingServletContext implements ServletContext { /** default log */ private final Logger log = LoggerFactory.getLogger(getClass()); /** The {@link SlingMainServlet} to which some calls are delegated */ private final SlingMainServlet slingMainServlet; /** * The service registration of this service as ServletContext * @see #SlingServletContext(SlingMainServlet) * @see #dispose() */ private final ServiceRegistration registration; /** * Creates an instance of this class delegating some methods to the given * {@link SlingMainServlet}. In addition the new instance is registered as * a<code>ServletContext</code>. * <p> * This method must only be called <b>after</b> the sling main servlet * has been fully initialized. Otherwise the {@link #getServletContext()} * method may cause a {@link NullPointerException} ! * @see #dispose() */ public SlingServletContext(final BundleContext bundleContext, final SlingMainServlet slingMainServlet) { this.slingMainServlet = slingMainServlet; Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put(Constants.SERVICE_PID, getClass().getName()); props.put(Constants.SERVICE_DESCRIPTION, "Apache Sling ServletContext"); props.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation"); props.put("name", "org.apache.sling"); // property to identify this context registration = bundleContext.registerService( ServletContext.class.getName(), this, props); } /** * Unregisters this servlet context as a service (if registered at all) * <p> * This method must be called <b>before</b> the sling main servlet * is destroyed. Otherwise the {@link #getServletContext()} method may * cause a {@link NullPointerException} ! * @see #SlingServletContext(SlingMainServlet) */ public void dispose() { if (registration != null) { registration.unregister(); } } // ---------- Web App configuration ---------------------------------------- /** * Returns the name of the servlet context in which Sling is configured. * This method calls on the <code>ServletContext</code> in which the * {@link SlingMainServlet} is running. */ @Override public String getServletContextName() { ServletContext delegatee = getServletContext(); if (delegatee != null) { return delegatee.getServletContextName(); } return null; } /** Returns the context path of the web application. (Servlet API 2.5) */ @Override public String getContextPath() { ServletContext delegatee = getServletContext(); if (delegatee != null) { return delegatee.getContextPath(); } return null; } /** * Returns the init-param of the servlet context in which Sling is * configured. This method calls on the <code>ServletContext</code> in * which the {@link SlingMainServlet} is running. */ @Override public String getInitParameter(String name) { ServletContext delegatee = getServletContext(); if (delegatee != null) { return delegatee.getInitParameter(name); } return null; } /** * Returns the names of the init-params of the servlet context in which * Sling is configured. This method calls on the <code>ServletContext</code> * in which the {@link SlingMainServlet} is running. */ @Override public Enumeration<String> getInitParameterNames() { ServletContext delegatee = getServletContext(); if (delegatee != null) { return delegatee.getInitParameterNames(); } return null; } // ---------- attributes --------------------------------------------------- /** * Returns the named servlet context attribute. This method calls on the * <code>ServletContext</code> in which the {@link SlingMainServlet} is * running. */ @Override public Object getAttribute(String name) { ServletContext delegatee = getServletContext(); if (delegatee != null) { return delegatee.getAttribute(name); } return null; } /** * Returns the names of all servlet context attributes. This method calls on * the <code>ServletContext</code> in which the {@link SlingMainServlet} * is running. */ @Override public Enumeration<String> getAttributeNames() { ServletContext delegatee = getServletContext(); if (delegatee != null) { return delegatee.getAttributeNames(); } return Collections.enumeration(Collections.<String>emptyList()); } /** * Removes the named servlet context attribute. This method calls on the * <code>ServletContext</code> in which the {@link SlingMainServlet} is * running. */ @Override public void removeAttribute(String name) { ServletContext delegatee = getServletContext(); if (delegatee != null) { delegatee.removeAttribute(name); } } /** * Sets the name servlet context attribute to the requested value. This * method calls on the <code>ServletContext</code> in which the * {@link SlingMainServlet} is running. */ @Override public void setAttribute(String name, Object object) { ServletContext delegatee = getServletContext(); if (delegatee != null) { delegatee.setAttribute(name, object); } } // ---------- Servlet Container information -------------------------------- /** * Returns the Sling server info string. This is not the same server info * string as returned by the servlet context in which Sling is configured. */ @Override public String getServerInfo() { return slingMainServlet.getServerInfo(); } /** * Returns the major version number of the Servlet API supported by the * servlet container in which Sling is running. This method calls on the * <code>ServletContext</code> in which the {@link SlingMainServlet} is * running. */ @Override public int getMajorVersion() { ServletContext delegatee = getServletContext(); if (delegatee != null) { return delegatee.getMajorVersion(); } return 3; // hard coded major version as fall back } /** * Returns the minor version number of the Servlet API supported by the * servlet container in which Sling is running. This method calls on the * <code>ServletContext</code> in which the {@link SlingMainServlet} is * running. */ @Override public int getMinorVersion() { ServletContext delegatee = getServletContext(); if (delegatee != null) { return delegatee.getMinorVersion(); } return 0; // hard coded minor version as fall back } // ---------- MIME type mapping -------------------------------------------- /** * Returns a MIME type for the extension of the given file name. This method * calls on the <code>ServletContext</code> in which the * {@link SlingMainServlet} is running. */ @Override public String getMimeType(String file) { ServletContext delegatee = getServletContext(); if (delegatee != null) { return delegatee.getMimeType(file); } return null; } // ---------- Request Dispatcher ------------------------------------------- /** * Returns a {@link SlingRequestDispatcher} for the given path if not * <code>null</code>. Otherwise <code>null</code> is returned. */ @Override public RequestDispatcher getRequestDispatcher(String path) { // return no dispatcher if content is null if (path == null) { log.error("getRequestDispatcher: No path, cannot create request dispatcher"); return null; } return new SlingRequestDispatcher(path, null); } /** * Returns a servlet container request dispatcher for the named servlet. * This method calls on the <code>ServletContext</code> in which the * {@link SlingMainServlet} is running. */ @Override public RequestDispatcher getNamedDispatcher(String name) { ServletContext delegatee = getServletContext(); if (delegatee != null) { return delegatee.getNamedDispatcher(name); } return null; } // ---------- Resource Access ---------------------------------------------- /** * Returns the URI for the given path. This method calls on the * <code>ServletContext</code> in which the {@link SlingMainServlet} is * running. */ @Override public URL getResource(String path) throws MalformedURLException { ServletContext delegatee = getServletContext(); if (delegatee != null) { return delegatee.getResource(path); } return null; } /** * Returns an input stream to the given path. This method calls on the * <code>ServletContext</code> in which the {@link SlingMainServlet} is * running. */ @Override public InputStream getResourceAsStream(String path) { ServletContext delegatee = getServletContext(); if (delegatee != null) { return delegatee.getResourceAsStream(path); } return null; } /** * Returns a set of names for path entries considered children of the given * path. This method calls on the <code>ServletContext</code> in which the * {@link SlingMainServlet} is running. */ @Override public Set<String> getResourcePaths(String parentPath) { ServletContext delegatee = getServletContext(); if (delegatee != null) { return delegatee.getResourcePaths(parentPath); } return null; } /** * Returns the real file inside the web application to which the given path * maps or <code>null</code> if no such file exists. This method calls on * the <code>ServletContext</code> in which the {@link SlingMainServlet} * is running. */ @Override public String getRealPath(String path) { ServletContext delegatee = getServletContext(); if (delegatee != null) { return delegatee.getRealPath(path); } return null; } // ---------- logging ------------------------------------------------------ /** Logs the message and optional throwable at error level to the logger */ @Override public void log(String message, Throwable throwable) { log.error(message, throwable); } /** Logs the message at info level to the logger */ @Override public void log(String message) { log.info(message); } /** Logs the message and optional exception at error level to the logger */ @SuppressWarnings("deprecation") @Override @Deprecated public void log(Exception exception, String message) { log(message, exception); } // ---------- foreign Servlets --------------------------------------------- /** * Returns the servlet context from the servlet container in which sling is * running. This method calls on the <code>ServletContext</code> in which * the {@link SlingMainServlet} is running. */ @Override public ServletContext getContext(String uripath) { ServletContext delegatee = getServletContext(); if (delegatee != null) { ServletContext otherContext = delegatee.getContext(uripath); if (otherContext != null && otherContext != delegatee) { return wrapServletContext(otherContext); } } return null; } /** Returns <code>null</code> as defined in Servlet API 2.4 */ @SuppressWarnings("deprecation") @Override @Deprecated public Servlet getServlet(String name) { return null; } /** Returns an empty enumeration as defined in Servlet API 2.4 */ @SuppressWarnings("deprecation") @Override @Deprecated public Enumeration<String> getServletNames() { return Collections.enumeration(Collections.<String>emptyList()); } /** Returns an empty enumeration as defined in Servlet API 2.4 */ @SuppressWarnings("deprecation") @Override @Deprecated public Enumeration<Servlet> getServlets() { return Collections.enumeration(Collections.<Servlet>emptyList()); } @Override public int getEffectiveMajorVersion() { ServletContext delegatee = getServletContext(); if (delegatee != null) { return delegatee.getEffectiveMajorVersion(); } return 3; } @Override public int getEffectiveMinorVersion() { ServletContext delegatee = getServletContext(); if (delegatee != null) { return delegatee.getEffectiveMinorVersion(); } return 0; } @Override public boolean setInitParameter(String name, String value) { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } @Override public SessionCookieConfig getSessionCookieConfig() { // result in NPE if context is not set anymore return getServletContext().getSessionCookieConfig(); } @Override public void setSessionTrackingModes(Set<SessionTrackingMode> sessionTrackingModes) { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } @Override public Set<SessionTrackingMode> getDefaultSessionTrackingModes() { // result in NPE if context is not set anymore return getServletContext().getDefaultSessionTrackingModes(); } @Override public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() { // result in NPE if context is not set anymore return getServletContext().getEffectiveSessionTrackingModes(); } @Override public JspConfigDescriptor getJspConfigDescriptor() { // result in NPE if context is not set anymore return getServletContext().getJspConfigDescriptor(); } @Override public ClassLoader getClassLoader() { // we don't allow access to any class loader here since we are // running in the OSGi Framework and we don't want code to fiddle // with class laoders obtained from the ServletContext throw new SecurityException(); } @Override public void declareRoles(String... roleNames) { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } // Servlet API 3.0, Section 4.4 Configuration methods @Override public Dynamic addServlet(String servletName, String className) { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } @Override public Dynamic addServlet(String servletName, Servlet servlet) { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } @Override public Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } @Override public <T extends Servlet> T createServlet(Class<T> clazz) { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } @Override public ServletRegistration getServletRegistration(String servletName) { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } @Override public Map<String, ? extends ServletRegistration> getServletRegistrations() { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } @Override public javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, String className) { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } @Override public javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, Filter filter) { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } @Override public javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } @Override public <T extends Filter> T createFilter(Class<T> clazz) { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } @Override public FilterRegistration getFilterRegistration(String filterName) { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } @Override public Map<String, ? extends FilterRegistration> getFilterRegistrations() { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } @Override public void addListener(String className) { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } @Override public <T extends EventListener> void addListener(T t) { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } @Override public void addListener(Class<? extends EventListener> listenerClass) { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } @Override public <T extends EventListener> T createListener(Class<T> clazz) { // only supported in ServletContextListener.contextInitialized or // ServletContainerInitializer.onStartuo throw new IllegalStateException(); } // ---------- internal ----------------------------------------------------- /** * Returns the real servlet context of the servlet container in which the * Sling Servlet is running. */ protected ServletContext getServletContext() { return slingMainServlet.getServletContext(); } protected ServletContext wrapServletContext(ServletContext context) { return new ExternalServletContextWrapper(context); } }
package com.tinkerpop.blueprints.pgm.impls.neo4j; import com.tinkerpop.blueprints.pgm.*; import com.tinkerpop.blueprints.pgm.impls.neo4j.util.Neo4jGraphEdgeSequence; import com.tinkerpop.blueprints.pgm.impls.neo4j.util.Neo4jVertexSequence; import com.tinkerpop.blueprints.pgm.util.AutomaticIndexHelper; import org.neo4j.graphdb.*; import org.neo4j.graphdb.index.IndexManager; import org.neo4j.kernel.EmbeddedGraphDatabase; import java.io.File; import java.util.*; /** * A Blueprints implementation of the graph database Neo4j (http://neo4j.org) * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class Neo4jGraph implements TransactionalGraph, IndexableGraph { private GraphDatabaseService rawGraph; private String directory; private Transaction tx; private Mode mode = Mode.AUTOMATIC; protected Map<String, Neo4jIndex> indices = new HashMap<String, Neo4jIndex>(); protected Map<String, Neo4jAutomaticIndex> autoIndices = new HashMap<String, Neo4jAutomaticIndex>(); public Neo4jGraph(final String directory) { this(directory, null); } public Neo4jGraph(final String directory, final Map<String, String> configuration) { this.directory = directory; boolean fresh = !new File(this.directory).exists(); try { if (null != configuration) this.rawGraph = new EmbeddedGraphDatabase(this.directory, configuration); else this.rawGraph = new EmbeddedGraphDatabase(this.directory); if (fresh) { // remove reference node try { this.removeVertex(this.getVertex(0)); } catch (Exception e) { } this.createAutomaticIndex(Index.VERTICES, Neo4jVertex.class, null); this.createAutomaticIndex(Index.EDGES, Neo4jEdge.class, null); } else { this.loadIndices(); } } catch (RuntimeException e) { if (this.rawGraph != null) this.rawGraph.shutdown(); throw e; } catch (Exception e) { if (this.rawGraph != null) this.rawGraph.shutdown(); throw new RuntimeException(e.getMessage(), e); } } public Neo4jGraph(final GraphDatabaseService rawGraph) { this.rawGraph = rawGraph; this.loadIndices(); } private void loadIndices() { final IndexManager manager = this.rawGraph.index(); for (final String indexName : manager.nodeIndexNames()) { final org.neo4j.graphdb.index.Index<Node> neo4jIndex = manager.forNodes(indexName); final String type = manager.getConfiguration(neo4jIndex).get(Neo4jTokens.BLUEPRINTS_TYPE); if (null != type && type.equals(Index.Type.AUTOMATIC.toString())) this.createAutomaticIndex(indexName, Neo4jVertex.class, null); else this.createManualIndex(indexName, Neo4jVertex.class); } for (final String indexName : manager.relationshipIndexNames()) { final org.neo4j.graphdb.index.Index<Relationship> neo4jIndex = manager.forRelationships(indexName); final String type = manager.getConfiguration(neo4jIndex).get(Neo4jTokens.BLUEPRINTS_TYPE); if (null != type && type.equals(Index.Type.AUTOMATIC.toString())) this.createAutomaticIndex(indexName, Neo4jEdge.class, null); else this.createManualIndex(indexName, Neo4jEdge.class); } } public <T extends Element> Index<T> createManualIndex(final String indexName, final Class<T> indexClass) { if (this.indices.containsKey(indexName)) throw new RuntimeException("Index already exists: " + indexName); Neo4jIndex index = new Neo4jIndex(indexName, indexClass, this); this.indices.put(index.getIndexName(), index); return index; } public <T extends Element> AutomaticIndex<T> createAutomaticIndex(final String indexName, final Class<T> indexClass, Set<String> keys) { if (this.indices.containsKey(indexName)) throw new RuntimeException("Index already exists: " + indexName); Neo4jAutomaticIndex index = new Neo4jAutomaticIndex(indexName, indexClass, this, keys); this.autoIndices.put(index.getIndexName(), index); this.indices.put(index.getIndexName(), index); return index; } public <T extends Element> Index<T> getIndex(final String indexName, final Class<T> indexClass) { Index index = this.indices.get(indexName); // todo: be sure to do code for multiple connections interacting with db if (null == index) throw new RuntimeException("No such index exists: " + indexName); else if (indexClass.isAssignableFrom(index.getIndexClass())) return (Index<T>) index; else throw new RuntimeException("Can not convert " + index.getIndexClass() + " to " + indexClass); } public void dropIndex(final String indexName) { try { this.autoStartTransaction(); this.rawGraph.index().forNodes(indexName).delete(); this.rawGraph.index().forRelationships(indexName).delete(); this.autoStopTransaction(Conclusion.SUCCESS); } catch (RuntimeException e) { this.autoStopTransaction(TransactionalGraph.Conclusion.FAILURE); throw e; } catch (Exception e) { this.autoStopTransaction(TransactionalGraph.Conclusion.FAILURE); throw new RuntimeException(e.getMessage(), e); } this.indices.remove(indexName); this.autoIndices.remove(indexName); } protected Iterable<Neo4jAutomaticIndex> getAutoIndices() { return autoIndices.values(); } public Iterable<Index<? extends Element>> getIndices() { List<Index<? extends Element>> list = new ArrayList<Index<? extends Element>>(); for (Index index : this.indices.values()) { list.add(index); } return list; } public Vertex addVertex(final Object id) { try { this.autoStartTransaction(); final Vertex vertex = new Neo4jVertex(this.rawGraph.createNode(), this); this.autoStopTransaction(Conclusion.SUCCESS); return vertex; } catch (RuntimeException e) { this.autoStopTransaction(TransactionalGraph.Conclusion.FAILURE); throw e; } catch (Exception e) { this.autoStopTransaction(TransactionalGraph.Conclusion.FAILURE); throw new RuntimeException(e.getMessage(), e); } } public Vertex getVertex(final Object id) { if (null == id) return null; try { Long longId = Double.valueOf(id.toString()).longValue(); Node node = this.rawGraph.getNodeById(longId); return new Neo4jVertex(node, this); } catch (NotFoundException e) { return null; } catch (NumberFormatException e) { throw new RuntimeException("Neo4j vertex ids must be convertible to a long value", e); } } public Iterable<Vertex> getVertices() { return new Neo4jVertexSequence(this.rawGraph.getAllNodes(), this); } public Iterable<Edge> getEdges() { return new Neo4jGraphEdgeSequence(this.rawGraph.getAllNodes(), this); } public void removeVertex(final Vertex vertex) { final Long id = (Long) vertex.getId(); final Node node = this.rawGraph.getNodeById(id); if (null != node) { try { AutomaticIndexHelper.removeElement(this, vertex); this.autoStartTransaction(); for (final Edge edge : vertex.getInEdges()) { ((Relationship) ((Neo4jEdge) edge).getRawElement()).delete(); } for (final Edge edge : vertex.getOutEdges()) { ((Relationship) ((Neo4jEdge) edge).getRawElement()).delete(); } node.delete(); this.autoStopTransaction(Conclusion.SUCCESS); } catch (RuntimeException e) { this.autoStopTransaction(TransactionalGraph.Conclusion.FAILURE); throw e; } catch (Exception e) { this.autoStopTransaction(TransactionalGraph.Conclusion.FAILURE); throw new RuntimeException(e.getMessage(), e); } } } public Edge addEdge(final Object id, final Vertex outVertex, final Vertex inVertex, final String label) { final Node outNode = ((Neo4jVertex) outVertex).getRawVertex(); final Node inNode = ((Neo4jVertex) inVertex).getRawVertex(); try { this.autoStartTransaction(); final Relationship relationship = outNode.createRelationshipTo(inNode, DynamicRelationshipType.withName(label)); final Edge edge = new Neo4jEdge(relationship, this, true); this.autoStopTransaction(Conclusion.SUCCESS); return edge; } catch (RuntimeException e) { this.autoStopTransaction(TransactionalGraph.Conclusion.FAILURE); throw e; } catch (Exception e) { this.autoStopTransaction(TransactionalGraph.Conclusion.FAILURE); throw new RuntimeException(e.getMessage(), e); } } public Edge getEdge(final Object id) { if (null == id) return null; try { final Long longId = Double.valueOf(id.toString()).longValue(); final Relationship relationship = this.rawGraph.getRelationshipById(longId); return new Neo4jEdge(relationship, this); } catch (NotFoundException e) { return null; } catch (NumberFormatException e) { throw new RuntimeException("Neo4j edge ids must be convertible to a long value", e); } } public void removeEdge(final Edge edge) { try { AutomaticIndexHelper.removeElement(this, edge); this.autoStartTransaction(); ((Relationship) ((Neo4jEdge) edge).getRawElement()).delete(); this.autoStopTransaction(Conclusion.SUCCESS); } catch (RuntimeException e) { this.autoStopTransaction(TransactionalGraph.Conclusion.FAILURE); throw e; } catch (Exception e) { this.autoStopTransaction(TransactionalGraph.Conclusion.FAILURE); throw new RuntimeException(e.getMessage(), e); } } public void startTransaction() { if (Mode.AUTOMATIC == this.mode) throw new RuntimeException(TransactionalGraph.TURN_OFF_MESSAGE); if (this.tx == null) this.tx = this.rawGraph.beginTx(); else throw new RuntimeException(TransactionalGraph.NESTED_MESSAGE); } public void stopTransaction(final Conclusion conclusion) { if (Mode.AUTOMATIC == this.mode) throw new RuntimeException(TransactionalGraph.TURN_OFF_MESSAGE); if (null == this.tx) throw new RuntimeException("There is no active transaction to stop"); if (conclusion == Conclusion.SUCCESS) { this.tx.success(); } else { this.tx.failure(); } this.tx.finish(); this.tx = null; } public void setTransactionMode(final Mode mode) { if (null != this.tx) { this.tx.success(); this.tx.finish(); this.tx = null; } this.mode = mode; } public Mode getTransactionMode() { return this.mode; } public void shutdown() { if (null != this.tx) { try { this.tx.failure(); this.tx.finish(); this.tx = null; } catch (TransactionFailureException e) { } } this.rawGraph.shutdown(); } public void clear() { for (Vertex vertex : this.getVertices()) { this.removeVertex(vertex); } for (Index index : this.getIndices()) { this.dropIndex(index.getIndexName()); } } protected void autoStartTransaction() { if (getTransactionMode() == Mode.AUTOMATIC) { if (this.tx == null) this.tx = this.rawGraph.beginTx(); else throw new RuntimeException(TransactionalGraph.NESTED_MESSAGE); } } protected void autoStopTransaction(final Conclusion conclusion) { if (getTransactionMode() == Mode.AUTOMATIC) { if (conclusion == Conclusion.SUCCESS) this.tx.success(); else this.tx.failure(); this.tx.finish(); this.tx = null; } } public GraphDatabaseService getRawGraph() { return this.rawGraph; } public String toString() { return "neo4jgraph[" + this.rawGraph + "]"; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v10/enums/extension_setting_device.proto package com.google.ads.googleads.v10.enums; /** * <pre> * Container for enum describing extension setting device types. * </pre> * * Protobuf type {@code google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum} */ public final class ExtensionSettingDeviceEnum extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum) ExtensionSettingDeviceEnumOrBuilder { private static final long serialVersionUID = 0L; // Use ExtensionSettingDeviceEnum.newBuilder() to construct. private ExtensionSettingDeviceEnum(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ExtensionSettingDeviceEnum() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new ExtensionSettingDeviceEnum(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ExtensionSettingDeviceEnum( 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.ads.googleads.v10.enums.ExtensionSettingDeviceProto.internal_static_google_ads_googleads_v10_enums_ExtensionSettingDeviceEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v10.enums.ExtensionSettingDeviceProto.internal_static_google_ads_googleads_v10_enums_ExtensionSettingDeviceEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum.class, com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum.Builder.class); } /** * <pre> * Possible device types for an extension setting. * </pre> * * Protobuf enum {@code google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum.ExtensionSettingDevice} */ public enum ExtensionSettingDevice implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> * Not specified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ UNSPECIFIED(0), /** * <pre> * The value is unknown in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ UNKNOWN(1), /** * <pre> * Mobile. The extensions in the extension setting will only serve on * mobile devices. * </pre> * * <code>MOBILE = 2;</code> */ MOBILE(2), /** * <pre> * Desktop. The extensions in the extension setting will only serve on * desktop devices. * </pre> * * <code>DESKTOP = 3;</code> */ DESKTOP(3), UNRECOGNIZED(-1), ; /** * <pre> * Not specified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ public static final int UNSPECIFIED_VALUE = 0; /** * <pre> * The value is unknown in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ public static final int UNKNOWN_VALUE = 1; /** * <pre> * Mobile. The extensions in the extension setting will only serve on * mobile devices. * </pre> * * <code>MOBILE = 2;</code> */ public static final int MOBILE_VALUE = 2; /** * <pre> * Desktop. The extensions in the extension setting will only serve on * desktop devices. * </pre> * * <code>DESKTOP = 3;</code> */ public static final int DESKTOP_VALUE = 3; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static ExtensionSettingDevice valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static ExtensionSettingDevice forNumber(int value) { switch (value) { case 0: return UNSPECIFIED; case 1: return UNKNOWN; case 2: return MOBILE; case 3: return DESKTOP; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<ExtensionSettingDevice> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< ExtensionSettingDevice> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<ExtensionSettingDevice>() { public ExtensionSettingDevice findValueByNumber(int number) { return ExtensionSettingDevice.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum.getDescriptor().getEnumTypes().get(0); } private static final ExtensionSettingDevice[] VALUES = values(); public static ExtensionSettingDevice valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private ExtensionSettingDevice(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum.ExtensionSettingDevice) } 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.ads.googleads.v10.enums.ExtensionSettingDeviceEnum)) { return super.equals(obj); } com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum other = (com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum) 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.ads.googleads.v10.enums.ExtensionSettingDeviceEnum parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum 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.ads.googleads.v10.enums.ExtensionSettingDeviceEnum parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum 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.ads.googleads.v10.enums.ExtensionSettingDeviceEnum parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum 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.ads.googleads.v10.enums.ExtensionSettingDeviceEnum parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum 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.ads.googleads.v10.enums.ExtensionSettingDeviceEnum 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> * Container for enum describing extension setting device types. * </pre> * * Protobuf type {@code google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum) com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnumOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v10.enums.ExtensionSettingDeviceProto.internal_static_google_ads_googleads_v10_enums_ExtensionSettingDeviceEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v10.enums.ExtensionSettingDeviceProto.internal_static_google_ads_googleads_v10_enums_ExtensionSettingDeviceEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum.class, com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum.Builder.class); } // Construct using com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum.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.ads.googleads.v10.enums.ExtensionSettingDeviceProto.internal_static_google_ads_googleads_v10_enums_ExtensionSettingDeviceEnum_descriptor; } @java.lang.Override public com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum getDefaultInstanceForType() { return com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum build() { com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum buildPartial() { com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum result = new com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum(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.ads.googleads.v10.enums.ExtensionSettingDeviceEnum) { return mergeFrom((com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum other) { if (other == com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum.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.ads.googleads.v10.enums.ExtensionSettingDeviceEnum parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum) 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.ads.googleads.v10.enums.ExtensionSettingDeviceEnum) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum) private static final com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum(); } public static com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ExtensionSettingDeviceEnum> PARSER = new com.google.protobuf.AbstractParser<ExtensionSettingDeviceEnum>() { @java.lang.Override public ExtensionSettingDeviceEnum parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ExtensionSettingDeviceEnum(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ExtensionSettingDeviceEnum> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ExtensionSettingDeviceEnum> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v10.enums.ExtensionSettingDeviceEnum getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
// // ======================================================================== // Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.websocket.servlet; import java.net.HttpCookie; import java.net.InetSocketAddress; import java.net.URISyntaxException; import java.security.Principal; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.eclipse.jetty.websocket.api.UpgradeRequest; import org.eclipse.jetty.websocket.api.extensions.ExtensionConfig; import org.eclipse.jetty.websocket.api.util.WSURI; /** * Servlet specific {@link UpgradeRequest} implementation. */ public class ServletUpgradeRequest extends UpgradeRequest { private final UpgradeHttpServletRequest request; public ServletUpgradeRequest(HttpServletRequest httpRequest) throws URISyntaxException { super(WSURI.toWebsocket(httpRequest.getRequestURL(), httpRequest.getQueryString())); this.request = new UpgradeHttpServletRequest(httpRequest); // Parse protocols. Enumeration<String> requestProtocols = request.getHeaders("Sec-WebSocket-Protocol"); if (requestProtocols != null) { List<String> protocols = new ArrayList<>(2); while (requestProtocols.hasMoreElements()) { String candidate = requestProtocols.nextElement(); Collections.addAll(protocols, parseProtocols(candidate)); } setSubProtocols(protocols); } // Parse extensions. Enumeration<String> e = request.getHeaders("Sec-WebSocket-Extensions"); setExtensions(ExtensionConfig.parseEnum(e)); // Copy cookies. Cookie[] requestCookies = request.getCookies(); if (requestCookies != null) { List<HttpCookie> cookies = new ArrayList<>(); for (Cookie requestCookie : requestCookies) { HttpCookie cookie = new HttpCookie(requestCookie.getName(), requestCookie.getValue()); // No point handling domain/path/expires/secure/httponly on client request cookies cookies.add(cookie); } setCookies(cookies); } setHeaders(request.getHeaders()); // Copy parameters. Map<String, String[]> requestParams = request.getParameterMap(); if (requestParams != null) { Map<String, List<String>> params = new HashMap<>(requestParams.size()); for (Map.Entry<String, String[]> entry : requestParams.entrySet()) params.put(entry.getKey(), Arrays.asList(entry.getValue())); setParameterMap(params); } setSession(request.getSession(false)); setHttpVersion(request.getProtocol()); setMethod(request.getMethod()); } public X509Certificate[] getCertificates() { return (X509Certificate[])request.getAttribute("javax.servlet.request.X509Certificate"); } /** * Return the underlying HttpServletRequest that existed at Upgrade time. * <p/> * Note: many features of the HttpServletRequest are invalid when upgraded, * especially ones that deal with body content, streams, readers, and responses. * * @return a limited version of the underlying HttpServletRequest */ public HttpServletRequest getHttpServletRequest() { return request; } /** * Equivalent to {@link HttpServletRequest#getLocalAddr()} * * @return the local address */ public String getLocalAddress() { return request.getLocalAddr(); } /** * Equivalent to {@link HttpServletRequest#getLocalName()} * * @return the local host name */ public String getLocalHostName() { return request.getLocalName(); } /** * Equivalent to {@link HttpServletRequest#getLocalPort()} * * @return the local port */ public int getLocalPort() { return request.getLocalPort(); } /** * Return a {@link InetSocketAddress} for the local socket. * <p/> * Warning: this can cause a DNS lookup * * @return the local socket address */ public InetSocketAddress getLocalSocketAddress() { return new InetSocketAddress(getLocalAddress(), getLocalPort()); } /** * Equivalent to {@link HttpServletRequest#getLocale()} * * @return the preferred <code>Locale</code> for the client */ public Locale getLocale() { return request.getLocale(); } /** * Equivalent to {@link HttpServletRequest#getLocales()} * * @return an Enumeration of preferred Locale objects */ public Enumeration<Locale> getLocales() { return request.getLocales(); } /** * @deprecated use {@link #getUserPrincipal()} instead */ @Deprecated public Principal getPrincipal() { return getUserPrincipal(); } /** * Equivalent to {@link HttpServletRequest#getUserPrincipal()} */ public Principal getUserPrincipal() { return request.getUserPrincipal(); } /** * Equivalent to {@link HttpServletRequest#getRemoteAddr()} * * @return the remote address */ public String getRemoteAddress() { return request.getRemoteAddr(); } /** * Equivalent to {@link HttpServletRequest#getRemoteHost()} * * @return the remote host name */ public String getRemoteHostName() { return request.getRemoteHost(); } /** * Equivalent to {@link HttpServletRequest#getRemotePort()} * * @return the remote port */ public int getRemotePort() { return request.getRemotePort(); } /** * Return a {@link InetSocketAddress} for the remote socket. * <p/> * Warning: this can cause a DNS lookup * * @return the remote socket address */ public InetSocketAddress getRemoteSocketAddress() { return new InetSocketAddress(getRemoteAddress(), getRemotePort()); } public Map<String, Object> getServletAttributes() { return request.getAttributes(); } public Map<String, List<String>> getServletParameters() { return getParameterMap(); } /** * Return the HttpSession if it exists. * <p/> * Note: this is equivalent to {@link HttpServletRequest#getSession(boolean)} * and will not create a new HttpSession. */ @Override public HttpSession getSession() { return request.getSession(false); } public void setServletAttribute(String name, Object value) { request.setAttribute(name, value); } public Object getServletAttribute(String name) { return request.getAttribute(name); } public boolean isUserInRole(String role) { return request.isUserInRole(role); } public String getRequestPath() { // Since this can be called from a filter, we need to be smart about determining the target request path. String contextPath = request.getContextPath(); String requestPath = request.getRequestURI(); if (requestPath.startsWith(contextPath)) requestPath = requestPath.substring(contextPath.length()); return requestPath; } private String[] parseProtocols(String protocol) { if (protocol == null) return new String[0]; protocol = protocol.trim(); if (protocol.length() == 0) return new String[0]; return protocol.split("\\s*,\\s*"); } public void complete() { request.complete(); } }
/** * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.core.api.util.collect; import org.junit.Before; import org.junit.Test; import org.springframework.beans.BeanUtils; import java.lang.reflect.Method; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; import static org.junit.Assert.*; /** * This class tests the PropertyTreeTest methods. */ public class PropertyTreeTest { private static final String KNOWN_SIMPLE_KEY = "simple"; private static final String KNOWN_SIMPLE_VALUE = "simple value"; private static final String KNOWN_COMPLEX_KEY = "known.complex.key"; private static final String KNOWN_COMPLEX_VALUE = "known complex value"; private static final int MIXED_COUNT = 13; PropertiesMap.PropertyTree tree; @Before public void setUp() throws Exception { tree = new PropertiesMap.PropertyTree(); } // entrySet @Test public void testEntrySet_readwrite() { Set entrySet = tree.entrySet(); boolean failedAsExpected = false; try { entrySet.clear(); } catch (UnsupportedOperationException e) { failedAsExpected = true; } assertTrue(failedAsExpected); } @Test public void testEntrySet_emptyTree() { Set entrySet = tree.entrySet(); assertTrue(entrySet.isEmpty()); } @Test public void testEntrySet_oneSimpleKey() { setOneSimpleKey(); Set entrySet = tree.entrySet(); assertEquals(1, entrySet.size()); boolean foundSimple = false; for (Iterator i = entrySet.iterator(); i.hasNext();) { Map.Entry e = (Map.Entry) i.next(); if (e.getKey().equals(KNOWN_SIMPLE_KEY)) { foundSimple = true; assertEquals(e.getValue(), KNOWN_SIMPLE_VALUE); } } assertTrue(foundSimple); } @Test public void testEntrySet_oneComplexKey() { setOneComplexKey(); Set entrySet = tree.entrySet(); assertEquals(1, entrySet.size()); boolean foundComplex = false; for (Iterator i = entrySet.iterator(); i.hasNext();) { Map.Entry e = (Map.Entry) i.next(); if (e.getKey().equals(KNOWN_COMPLEX_KEY)) { foundComplex = true; assertEquals(e.getValue(), KNOWN_COMPLEX_VALUE); } } assertTrue(foundComplex); } @Test public void testEntrySet_manyMixedKeys() { setManyMixedKeys(); Set entrySet = tree.entrySet(); assertEquals(MIXED_COUNT, entrySet.size()); boolean foundSimple = false; boolean foundComplex = false; for (Iterator i = entrySet.iterator(); i.hasNext();) { Map.Entry e = (Map.Entry) i.next(); if (e.getKey().equals(KNOWN_SIMPLE_KEY)) { foundSimple = true; assertEquals(e.getValue(), KNOWN_SIMPLE_VALUE); } else if (e.getKey().equals(KNOWN_COMPLEX_KEY)) { foundComplex = true; assertEquals(e.getValue(), KNOWN_COMPLEX_VALUE); } } assertTrue(foundSimple); assertTrue(foundComplex); } // size() @Test public void testSize_emptyTree() { assertEquals(0, tree.size()); } @Test public void testSize_oneSimpleKey() { setOneSimpleKey(); assertEquals(1, tree.size()); } @Test public void testSize_oneComplexKey() { setOneComplexKey(); assertEquals(1, tree.size()); } @Test public void testSize_manyMixedKeys() { setManyMixedKeys(); assertEquals(MIXED_COUNT, tree.size()); } // isEmpty @Test public void testIsEmpty_emptyTree() { assertTrue(tree.isEmpty()); } @Test public void testIsEmpty_oneSimpleKey() { setOneSimpleKey(); assertFalse(tree.isEmpty()); } @Test public void testIsEmpty_oneComplexKey() { setOneComplexKey(); assertFalse(tree.isEmpty()); } @Test public void testIsEmpty_manyMixedKeys() { setManyMixedKeys(); assertFalse(tree.isEmpty()); } // values @Test public void testValues_readwrite() { Collection values = tree.values(); boolean failedAsExpected = false; try { values.clear(); } catch (UnsupportedOperationException e) { failedAsExpected = true; } assertTrue(failedAsExpected); } @Test public void testValues_emptyTree() { Collection values = tree.values(); assertTrue(values.isEmpty()); } @Test public void testValues_oneSimpleKey() { setOneSimpleKey(); Collection values = tree.values(); assertEquals(1, values.size()); assertTrue(values.contains(KNOWN_SIMPLE_VALUE)); } @Test public void testValues_oneComplexKey() { setOneComplexKey(); Collection values = tree.values(); assertEquals(1, values.size()); assertTrue(values.contains(KNOWN_COMPLEX_VALUE)); } @Test public void testValues_manyMixedKeys() { setManyMixedKeys(); Collection values = tree.values(); assertEquals(MIXED_COUNT, values.size()); assertTrue(values.contains(KNOWN_SIMPLE_VALUE)); assertTrue(values.contains(KNOWN_COMPLEX_VALUE)); } // keySet @Test public void testKeySet_readwrite() { Set keys = tree.keySet(); boolean failedAsExpected = false; try { keys.clear(); } catch (UnsupportedOperationException e) { failedAsExpected = true; } assertTrue(failedAsExpected); } @Test public void testKeySet_emptyTree() { Set keys = tree.keySet(); assertTrue(keys.isEmpty()); } @Test public void testKeySet_oneSimpleKey() { setOneSimpleKey(); Set keys = tree.keySet(); assertEquals(1, keys.size()); assertTrue(keys.contains(KNOWN_SIMPLE_KEY)); } @Test public void testKeySet_oneComplexKey() { setOneComplexKey(); Set keys = tree.keySet(); assertEquals(1, keys.size()); assertTrue(keys.contains(KNOWN_COMPLEX_KEY)); } @Test public void testKeySet_manyMixedKeys() { setManyMixedKeys(); Set keys = tree.keySet(); assertEquals(MIXED_COUNT, keys.size()); assertTrue(keys.contains(KNOWN_SIMPLE_KEY)); assertTrue(keys.contains(KNOWN_COMPLEX_KEY)); } // containsKey @Test public void testContainsKey_invalidKey() { boolean failedAsExpected = false; try { assertFalse(tree.containsKey(null)); } catch (IllegalArgumentException e) { failedAsExpected = true; } assertTrue(failedAsExpected); } @Test public void testContainsKey_emptyTree() { assertFalse(tree.containsKey(KNOWN_SIMPLE_KEY)); } @Test public void testContainsKey_unknownKey() { setManyMixedKeys(); assertFalse(tree.containsKey("hopefully unknown key")); } @Test public void testContainsKey_oneSimpleKey() { setOneSimpleKey(); assertTrue(tree.containsKey(KNOWN_SIMPLE_KEY)); } @Test public void testContainsKey_oneComplexKey() { setOneComplexKey(); assertTrue(tree.containsKey(KNOWN_COMPLEX_KEY)); } @Test public void testContainsKey_manyMixedKeys() { setManyMixedKeys(); assertTrue(tree.containsKey(KNOWN_SIMPLE_KEY)); assertTrue(tree.containsKey(KNOWN_COMPLEX_KEY)); } // containsValue @Test public void testContainsValue_invalidValue() { boolean failedAsExpected = false; try { assertFalse(tree.containsValue(null)); } catch (IllegalArgumentException e) { failedAsExpected = true; } assertTrue(failedAsExpected); } @Test public void testContainsValue_emptyTree() { assertFalse(tree.containsValue(KNOWN_SIMPLE_VALUE)); } @Test public void testContainsValue_unknownValue() { setManyMixedKeys(); assertFalse(tree.containsValue("hopefully unknown value")); } @Test public void testContainsValue_oneSimpleKey() { setOneSimpleKey(); assertTrue(tree.containsValue(KNOWN_SIMPLE_VALUE)); } @Test public void testContainsValue_oneComplexKey() { setOneComplexKey(); assertTrue(tree.containsValue(KNOWN_COMPLEX_VALUE)); } @Test public void testContainsValue_manyMixedKeys() { setManyMixedKeys(); assertTrue(tree.containsValue(KNOWN_SIMPLE_VALUE)); assertTrue(tree.containsValue(KNOWN_COMPLEX_VALUE)); } // get @Test public void testGet_invalidKey() { boolean failedAsExpected = false; try { tree.get(null); } catch (IllegalArgumentException e) { failedAsExpected = true; } assertTrue(failedAsExpected); } @Test public void testGet_unknownKey() { setManyMixedKeys(); assertNull(tree.get("hopefully unknown key")); } @Test public void testGet_oneSimpleKey() { setOneSimpleKey(); assertEquals(KNOWN_SIMPLE_VALUE, tree.get(KNOWN_SIMPLE_KEY).toString()); } @Test public void testGet_oneComplexKey() { setOneComplexKey(); assertEquals(KNOWN_COMPLEX_VALUE, tree.get(KNOWN_COMPLEX_KEY).toString()); } @Test public void testGet_manyMixedKeys() { setManyMixedKeys(); assertEquals(KNOWN_SIMPLE_VALUE, tree.get(KNOWN_SIMPLE_KEY).toString()); assertEquals(KNOWN_COMPLEX_VALUE, tree.get(KNOWN_COMPLEX_KEY).toString()); } @Test public void testGet_chainedGet() throws Exception { setManyMixedKeys(); String value = ((PropertiesMap.PropertyTree) ((PropertiesMap.PropertyTree) tree.get("known")).get("complex")).get("key").toString(); assertNotNull(value); assertEquals(KNOWN_COMPLEX_VALUE, value); } /* * As close a simulation as possible of how the JSTL variable-reference will actually be implemented. */ @Test public void testGet_jstlGet() throws Exception { setManyMixedKeys(); Class[] getParamTypes = { Object.class }; Object level1 = tree.get("known"); Method m1 = BeanUtils.findMethod(level1.getClass(), "get", getParamTypes); Object level2 = m1.invoke(level1, new Object[] { "complex" }); Method m2 = BeanUtils.findMethod(level2.getClass(), "get", getParamTypes); Object level3 = m2.invoke(level2, new Object[] { "key" }); String value = level3.toString(); assertNotNull(value); assertEquals(KNOWN_COMPLEX_VALUE, value); } // unsupported operations @Test public void testClear() { setManyMixedKeys(); boolean failedAsExpected = false; try { tree.clear(); } catch (UnsupportedOperationException e) { failedAsExpected = true; } assertTrue(failedAsExpected); } @Test public void testPut() { setManyMixedKeys(); boolean failedAsExpected = false; try { tree.put("meaningless", "entry"); } catch (UnsupportedOperationException e) { failedAsExpected = true; } assertTrue(failedAsExpected); } @Test public void testPutAll() { setManyMixedKeys(); Properties p = new Properties(); p.setProperty("meaningless", "value"); boolean failedAsExpected = false; try { tree.putAll(p); } catch (UnsupportedOperationException e) { failedAsExpected = true; } assertTrue(failedAsExpected); } @Test public void testRemove() { setManyMixedKeys(); boolean failedAsExpected = false; try { tree.remove(KNOWN_SIMPLE_KEY); } catch (UnsupportedOperationException e) { failedAsExpected = true; } assertTrue(failedAsExpected); } // support methods private void setOneSimpleKey() { Properties p = new Properties(); p.setProperty(KNOWN_SIMPLE_KEY, KNOWN_SIMPLE_VALUE); tree = new PropertiesMap.PropertyTree(p); } private void setOneComplexKey() { Properties p = new Properties(); p.setProperty(KNOWN_COMPLEX_KEY, KNOWN_COMPLEX_VALUE); tree = new PropertiesMap.PropertyTree(p); } private void setManyMixedKeys() { Properties p = new Properties(); p.setProperty(KNOWN_SIMPLE_KEY, KNOWN_SIMPLE_VALUE); p.setProperty(KNOWN_COMPLEX_KEY, KNOWN_COMPLEX_VALUE); p.setProperty("a", "a"); p.setProperty("b.b", "bb"); p.setProperty("b.c", "cb"); p.setProperty("c.b.c", "cbc"); p.setProperty("c.b.d", "dbc"); p.setProperty("c.c.a", "acc"); p.setProperty("a.c.b", "bca"); p.setProperty("a.c.c", "cca"); p.setProperty("b.a", "ab"); p.setProperty("b", "b"); p.setProperty("d", "d"); tree = new PropertiesMap.PropertyTree(p); } }
package com.plugplayer.plugplayer.upnp; import java.io.FileNotFoundException; import java.io.InputStream; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import org.cybergarage.http.HTTP; import org.cybergarage.http.HTTPRequest; import org.cybergarage.http.HTTPServer; import org.cybergarage.net.HostInterface; import org.cybergarage.upnp.ControlPoint; import org.cybergarage.upnp.Device; import org.cybergarage.upnp.Service; import org.cybergarage.upnp.UPnP; import org.cybergarage.upnp.device.DeviceChangeListener; import org.cybergarage.upnp.device.NotifyListener; import org.cybergarage.upnp.device.SearchResponseListener; import org.cybergarage.upnp.event.EventListener; import org.cybergarage.upnp.ssdp.SSDPPacket; import org.cybergarage.xml.Node; import org.cybergarage.xml.Parser; import org.cybergarage.xml.ParserException; import android.app.Activity; import android.content.SharedPreferences; import android.os.AsyncTask; import android.util.Log; import com.android.vending.licensing.util.Base64; import com.plugplayer.plugplayer.activities.MainActivity; import com.plugplayer.plugplayer.activities.SettingsEditor; import com.plugplayer.plugplayer.utils.StateList; import com.plugplayer.plugplayer.utils.StateMap; public class PlugPlayerControlPoint implements EventListener, NotifyListener, SearchResponseListener, DeviceChangeListener, MediaDeviceListener { private static PlugPlayerControlPoint instance = null; public static PlugPlayerControlPoint getInstance() { return instance; } private final List<ControlPointListener> listeners; private Renderer currentRenderer = null; private Server currentServer = null; private final Map<String, MediaDevice> subscriptionMap; final ControlPoint controlPoint; private List<Renderer> rendererList; private List<Server> serverList; private boolean isStarted = false; protected static interface AndroidRendererFactory { Renderer create(); } protected static AndroidRendererFactory androidRendererFactory = new AndroidRendererFactory() { public Renderer create() { return new AndroidRenderer(); } }; protected static interface AndroidServerFactory { Server[] create(); } protected static AndroidServerFactory androidServerFactory = new AndroidServerFactory() { public Server[] create() { return new Server[] { new AndroidServer(), new MP3TunesServer() }; // return new Server[] { new MP3TunesServer() }; } }; public PlugPlayerControlPoint() { HostInterface.USE_ONLY_IPV4_ADDR = true; // HostInterface.USE_LOOPBACK_ADDR = true; HTTP.setChunkSize( 128 * 1024 ); instance = this; rendererList = new ArrayList<Renderer>(); serverList = new ArrayList<Server>(); listeners = new ArrayList<ControlPointListener>(); subscriptionMap = new HashMap<String, MediaDevice>(); addRenderer( androidRendererFactory.create() ); Server[] builtInServers = androidServerFactory.create(); if ( builtInServers != null ) for ( Server s : builtInServers ) addServer( s ); controlPoint = new ControlPoint(); controlPoint.addNotifyListener( this ); controlPoint.addEventListener( this ); controlPoint.addSearchResponseListener( this ); controlPoint.addDeviceChangeListener( this ); controlPoint.setNMPRMode( true ); } public void toState( StateMap state ) { int currentRendererIndex = -1; if ( getCurrentRenderer() != null ) currentRendererIndex = getRendererList().indexOf( getCurrentRenderer() ); int currentServerIndex = -1; if ( getCurrentServer() != null ) currentServerIndex = getServerList().indexOf( getCurrentServer() ); state.setName( "ControlPoint" ); state.setValue( "currentRendererIndex", currentRendererIndex ); state.setValue( "currentServerIndex", currentServerIndex ); StateList rendererListState = new StateList(); for ( Renderer r : rendererList ) { StateMap rendererState = new StateMap(); r.toState( rendererState ); rendererListState.add( rendererState ); } state.setList( "rendererList", rendererListState ); StateList serverListState = new StateList(); for ( Server s : serverList ) { StateMap serverState = new StateMap(); s.toState( serverState ); serverListState.add( serverState ); } state.setList( "serverList", serverListState ); } public static PlugPlayerControlPoint createFromState( StateMap state ) { PlugPlayerControlPoint rval = new PlugPlayerControlPoint(); rval.fromState( state ); return rval; } protected static interface RendererStateFactory { Renderer rendererFromState( StateMap rendererState ); } protected static RendererStateFactory rendererStateFactory = new RendererStateFactory() { public Renderer rendererFromState( StateMap rendererState ) { if ( rendererState.getName().equals( AndroidRenderer.STATENAME ) ) return AndroidRenderer.createFromState( rendererState ); if ( rendererState.getName().equals( UPNPRenderer.STATENAME ) ) return UPNPRenderer.createFromState( rendererState ); if ( rendererState.getName().equals( LinnCaraRenderer.STATENAME ) ) return LinnCaraRenderer.createFromState( rendererState ); if ( rendererState.getName().equals( LinnDavaarRenderer.STATENAME ) ) return LinnDavaarRenderer.createFromState( rendererState ); return null; } }; protected static interface ServerStateFactory { Server serverFromState( StateMap serverState ); } protected static ServerStateFactory serverStateFactory = new ServerStateFactory() { public Server serverFromState( StateMap serverState ) { if ( serverState.getName().equals( AndroidServer.STATENAME ) ) return AndroidServer.createFromState( serverState ); if ( serverState.getName().equals( MP3TunesServer.STATENAME ) ) return MP3TunesServer.createFromState( serverState ); if ( serverState.getName().equals( UPNPServer.STATENAME ) ) return UPNPServer.createFromState( serverState ); return null; } }; public void fromState( StateMap state ) { StateList rendererListState = state.getList( "rendererList" ); rendererList = new ArrayList<Renderer>(); synchronized ( rendererList ) { rendererList.clear(); for ( StateMap rendererState : rendererListState ) { Renderer r = rendererStateFactory.rendererFromState( rendererState ); if ( r != null ) { r.addMediaDeviceListener( this ); rendererList.add( r ); } } } // if ( rendererList.isEmpty() || !(rendererList.get( 0 ) instanceof AndroidRenderer) ) // throw new RuntimeException( "Bad State" ); StateList serverListState = state.getList( "serverList" ); serverList = new ArrayList<Server>(); synchronized ( serverList ) { serverList.clear(); for ( StateMap serverState : serverListState ) { Server s = serverStateFactory.serverFromState( serverState ); if ( s != null ) { s.addMediaDeviceListener( this ); serverList.add( s ); } } } int currentRendererIndex = state.getValue( "currentRendererIndex", -1 ); if ( currentRendererIndex >= 0 && currentRendererIndex < getRendererList().size() ) { Renderer r = getRendererList().get( currentRendererIndex ); r.updateAlive(); if ( r.isAlive() ) setCurrentRenderer( r ); if ( currentRenderer == null ) for ( Renderer renderer : getRendererList() ) { renderer.updateAlive(); if ( renderer.isAlive() ) { setCurrentRenderer( renderer ); break; } } } int currentServerIndex = state.getValue( "currentServerIndex", -1 ); if ( currentServerIndex >= 0 && currentServerIndex < getServerList().size() ) { Server s = getServerList().get( currentServerIndex ); s.updateAlive(); if ( s.isAlive() ) setCurrentServer( s ); if ( currentServer == null ) for ( Server server : getServerList() ) { server.updateAlive(); if ( server.isAlive() ) { setCurrentServer( server ); break; } } } } private MediaDevice getDeviceByUSN( String USN ) { if ( USN != null ) { synchronized ( serverList ) { for ( Server s : serverList ) if ( s.getUDN().length() > 0 && USN.startsWith( s.getUDN() ) ) return s; } synchronized ( rendererList ) { for ( Renderer r : rendererList ) if ( USN.startsWith( r.getUDN() ) ) return r; } } return null; } private boolean haveServerDevice( Device dev ) { final SharedPreferences preferences = MainActivity.me.getSharedPreferences( SettingsEditor.ADVANCED_SETTINGS, Activity.MODE_PRIVATE ); boolean discovery = preferences.getBoolean( SettingsEditor.DEVICE_DISCOVERY, true ); synchronized ( serverList ) { for ( Server s : serverList ) if ( s.getUDN().equals( dev.getUDN() ) ) { if ( !discovery ) { if ( s.getLocation().equals( dev.getLocation() ) ) { return true; } } else { return true; } } } return false; } private boolean haveRendererDevice( Device dev ) { final SharedPreferences preferences = MainActivity.me.getSharedPreferences( SettingsEditor.ADVANCED_SETTINGS, Activity.MODE_PRIVATE ); boolean discovery = preferences.getBoolean( SettingsEditor.DEVICE_DISCOVERY, true ); synchronized ( rendererList ) { for ( Renderer r : rendererList ) if ( r.getUDN().equals( dev.getUDN() ) ) { if ( !discovery ) { if ( r.getLocation().equals( dev.getLocation() ) ) { return true; } } else { return true; } } else if ( r instanceof LinnRenderer && dev.getUDN().equals( ((LinnRenderer)r).getOtherUDN() ) ) return true; } return false; } public interface DeviceFactory { MediaDevice createDevice( Device dev ); } protected static DeviceFactory rendererFactory = new DeviceFactory() { public MediaDevice createDevice( Device dev ) { MediaDevice device = LinnDavaarRenderer.createDevice( dev ); if ( device == null ) device = LinnCaraRenderer.createDevice( dev ); if ( device == null ) device = UPNPRenderer.createDevice( dev ); return device; } }; protected static DeviceFactory serverFactory = new DeviceFactory() { public MediaDevice createDevice( Device dev ) { MediaDevice device = UPNPServer.createDevice( dev ); return device; } }; public boolean localRendererAddr( String descriptionURL ) { if ( descriptionURL != null && AndroidRenderer.rendererDevice != null ) { for ( int i = 0; i < AndroidRenderer.rendererDevice.getHTTPServerList().size(); ++i ) { HTTPServer s = AndroidRenderer.rendererDevice.getHTTPServerList().getHTTPServer( i ); String addr = s.getBindAddress() + ":" + s.getBindPort(); if ( descriptionURL.contains( addr ) ) return true; } } return false; } public boolean localServerAddr( String descriptionURL ) { if ( descriptionURL != null && AndroidServer.serverDevice != null ) { for ( int i = 0; i < AndroidServer.serverDevice.getHTTPServerList().size(); ++i ) { HTTPServer s = AndroidServer.serverDevice.getHTTPServerList().getHTTPServer( i ); String addr = s.getBindAddress() + ":" + s.getBindPort(); if ( descriptionURL.contains( addr ) ) return true; } } return false; } public void addDevice( Device dev ) { if ( dev == null ) return; if ( !haveRendererDevice( dev ) ) { MediaDevice device = rendererFactory.createDevice( dev ); if ( device != null ) { Log.i( "MIT_DBG", "inside addDevice(dev), created MediaDevice=" + device.toString() ); if ( localRendererAddr( device.getLocation() ) ) { // XXX This should never happen, but it has! } else { device.setAlive( true ); addRenderer( (Renderer)device ); } } else { Log.i( "MIT_DBG", "inside addDevice(dev), device == null" ); } } else { Log.i( "MIT_DBG", "inside addDevice(dev), device already exist, so updateservices for devUDN=" + dev.getUDN() ); MediaDevice device = getDeviceByUSN( dev.getUDN() ); if ( device != null && !(device instanceof AndroidRenderer) && dev.getLocation() != null && (device.getLocation() == null || !device.getLocation().equals( dev.getLocation() )) ) { device.updateServices( dev ); device.setAlive( true ); deviceUpdated( device ); } } if ( !haveServerDevice( dev ) ) { MediaDevice device = serverFactory.createDevice( dev ); Log.i( "MIT_DBG", "inside addDevice(dev), device has ServerDevice" ); if ( device != null ) { if ( localServerAddr( device.getLocation() ) ) { // XXX This should never happen, but it has! } else { device.setAlive( true ); addServer( (Server)device ); } } } else { MediaDevice device = getDeviceByUSN( dev.getUDN() ); if ( device != null && !(device instanceof AndroidServer) && dev.getLocation() != null && (device.getLocation() == null || !device.getLocation().equals( dev.getLocation() )) ) { device.updateServices( dev ); device.setAlive( true ); deviceUpdated( device ); } } } public void deviceAdded( Device dev ) { Log.i( android.util.PlugPlayerUtil.DBG_TAG, "deviceAdded() PPCP" ); final SharedPreferences preferences = MainActivity.me.getSharedPreferences( SettingsEditor.ADVANCED_SETTINGS, Activity.MODE_PRIVATE ); if ( !preferences.getBoolean( SettingsEditor.DEVICE_DISCOVERY, true ) ) { Log.i( android.util.PlugPlayerUtil.DBG_TAG, "deviceAdded():DeviceDiscovery is false so return:PPCP" ); return; } Log.i( android.util.PlugPlayerUtil.DBG_TAG, "deviceAdded() DeviceDiscovery is true so call addDevice():PPCP" ); addDevice( dev ); } public void deviceUpdated( Device dev ) { // Just make sure we have this device already if we are doing discovery Log.i( android.util.PlugPlayerUtil.DBG_TAG, "deviceUpdated() Just make sure we have this device already if we are doing discovery:PPCP" ); deviceAdded( dev ); } public void deviceRemoved( Device dev ) { // XXX TODO: Mark device as not alive and pick a new one if this one was active // MediaDevice d = getDeviceByUSN( dev.getUDN() ); // if ( d != null ) // { // // } } public void deviceSearchResponseReceived( SSDPPacket ssdpPacket ) { Log.i( android.util.PlugPlayerUtil.DBG_TAG, "deviceSearchResponseReceived() SSDPPacket = " + ssdpPacket.toString() ); final SharedPreferences preferences = MainActivity.me.getSharedPreferences( SettingsEditor.ADVANCED_SETTINGS, Activity.MODE_PRIVATE ); if ( !preferences.getBoolean( SettingsEditor.DEVICE_DISCOVERY, true ) ) return; Device dev = null; String newLocation = ssdpPacket.getLocation(); if ( newLocation != null && newLocation.length() > 0 ) dev = PlugPlayerControlPoint.deviceFromLocation( newLocation, 1 ); if ( dev != null ) dev.setSSDPPacket( ssdpPacket ); addDevice( dev ); } public void deviceUpdated( MediaDevice d ) { Log.i( android.util.PlugPlayerUtil.DBG_TAG, "deviceUpdated() MediaDevice=" + d.toString() ); if ( d == currentServer || d == currentRenderer ) { d.setActive( false, false ); d.setActive( true, false ); } if ( d instanceof Renderer ) { for ( ControlPointListener listener : getListenersCopy() ) { Log.i( android.util.PlugPlayerUtil.DBG_TAG, "deviceUpdated() calling mediaRendererListChanged()=" + listener.toString() ); listener.mediaRendererListChanged(); } } else { for ( ControlPointListener listener : getListenersCopy() ) { Log.i( android.util.PlugPlayerUtil.DBG_TAG, "deviceUpdated() calling mediaServerListChanged()=" + listener.toString() ); listener.mediaServerListChanged(); } } } public void deviceNotifyReceived( SSDPPacket ssdpPacket ) { Log.i( android.util.PlugPlayerUtil.DBG_TAG, "deviceNotifyReceived()" ); final SharedPreferences preferences = MainActivity.me.getSharedPreferences( SettingsEditor.ADVANCED_SETTINGS, Activity.MODE_PRIVATE ); if ( !preferences.getBoolean( SettingsEditor.DEVICE_DISCOVERY, true ) ) { Log.i( android.util.PlugPlayerUtil.DBG_TAG, "inside deviceNotifyReceived(), pref.DEVICE_DISCOVERY is false, so return" ); return; } if ( ssdpPacket.isRootDevice() == true && !ssdpPacket.getUSN().equals( "" ) ) { MediaDevice d = getDeviceByUSN( ssdpPacket.getUSN() ); if ( d == null ) return; if ( ssdpPacket.isAlive() == true ) { String newLocation = ssdpPacket.getLocation(); if ( newLocation != null && d.getLocation() != null && !d.getLocation().equals( newLocation ) ) { Device dev = PlugPlayerControlPoint.deviceFromLocation( newLocation, d.getSearchTimeout() ); if ( dev != null ) d.updateServices( dev ); } if ( !d.isAlive() ) { // d.setAlive( true ); d.updateAlive(); if ( d instanceof Renderer ) { for ( ControlPointListener listener : getListenersCopy() ) { Log.i( android.util.PlugPlayerUtil.DBG_TAG, "deviceNotifyReceived() calling mediaRendererListChanged()=" + listener.toString() ); listener.mediaRendererListChanged(); } } else { for ( ControlPointListener listener : getListenersCopy() ) listener.mediaServerListChanged(); } } } else if ( ssdpPacket.isByeBye() == true && d.isAlive() ) { // Log.d( MainActivity.appName, "Got bye bye from: " + d.getName() ); d.setAlive( false ); if ( d instanceof Renderer ) { synchronized ( rendererList ) { if ( d == currentRenderer ) { Renderer newRenderer = null; for ( Renderer r : rendererList ) if ( r.isAlive() ) { newRenderer = r; break; } setCurrentRenderer( newRenderer ); } } for ( ControlPointListener listener : getListenersCopy() ) listener.mediaRendererListChanged(); } else { if ( d == currentServer ) { currentServer = null; synchronized ( serverList ) { Server newServer = null; for ( Server s : serverList ) if ( s.isAlive() ) { newServer = s; break; } setCurrentServer( newServer ); } } for ( ControlPointListener listener : getListenersCopy() ) listener.mediaServerListChanged(); } } } } public static Device deviceFromInputStream( InputStream descriptionStream, String location ) throws ParserException { Parser parser = UPnP.getXMLParser(); Node rootNode = parser.parse( descriptionStream ); Node devNode = rootNode.getNode( Device.ELEM_NAME ); Device rootDev = new Device( rootNode, devNode ); String data = "Location: " + location; SSDPPacket ssdpPacket = new SSDPPacket( data.getBytes(), data.getBytes().length ); String localAddr = HostInterface.getHostAddress( 0 ); ssdpPacket.setLocalAddress( localAddr ); rootDev.setSSDPPacket( ssdpPacket ); // PlugPlayerControlPoint.getInstance().controlPoint.addDevice( rootNode ); return rootDev; } public boolean addDevice( String location ) { Device d = deviceFromLocation( location, 2 ); if ( d != null ) { addDevice( d ); return true; } else return false; } public static Device deviceFromLocation( String location, int searchTimeout ) { URL locationUrl; try { locationUrl = new URL( location ); // Check to make sure we can connect to this without blocking for a minute try { URLConnection connection = locationUrl.openConnection(); connection.setRequestProperty( "User-Agent", HTTPRequest.UserAgent ); String userInfo = locationUrl.getUserInfo(); if ( userInfo != null ) { String authStringEnc = Base64.encode( userInfo.getBytes() ); connection.setRequestProperty( "Authorization", "Basic " + authStringEnc ); } connection.setConnectTimeout( searchTimeout * 1000 ); connection.connect(); Device rootDev = deviceFromInputStream( connection.getInputStream(), location ); return rootDev; } catch ( SocketTimeoutException e ) { return null; } } catch ( FileNotFoundException e ) { // e.printStackTrace(); return null; } catch ( Exception e ) { Log.e( MainActivity.appName, "Couln't create device at '" + location + "'", e ); return null; } } public void addControlPointListener( ControlPointListener listener ) { synchronized ( listeners ) { listeners.add( listener ); } } public void removeControlPointListener( ControlPointListener listener ) { synchronized ( listeners ) { listeners.remove( listener ); } } public void removeDevice( MediaDevice d ) { if ( d instanceof Renderer ) removeRenderer( (Renderer)d ); else removeServer( (Server)d ); } private void addServer( Server device ) { final SharedPreferences preferences = MainActivity.me.getSharedPreferences( SettingsEditor.ADVANCED_SETTINGS, Activity.MODE_PRIVATE ); boolean discovery = preferences.getBoolean( SettingsEditor.DEVICE_DISCOVERY, true ); if ( device == null ) return; synchronized ( serverList ) { for ( Server server : serverList ) if ( server.getUDN().equals( device.getUDN() ) ) { if ( !discovery ) { if ( server.getLocation().equals( device.getLocation() ) ) { return; } } else { return; } } device.addMediaDeviceListener( this ); serverList.add( device ); Log.i( "MIT_DBG", "inside addServer(dev),added to serverList=" + serverList.toString() ); } for ( ControlPointListener listener : getListenersCopy() ) listener.mediaServerListChanged(); if ( getCurrentServer() == null ) { device.updateAlive(); if ( device.isAlive() ) setCurrentServer( device ); } } private void removeServer( Server device ) { device.removeMediaDeviceListener( this ); synchronized ( serverList ) { serverList.remove( device ); } for ( ControlPointListener listener : getListenersCopy() ) listener.mediaServerListChanged(); if ( getCurrentServer() == device ) setCurrentServer( null ); } public List<Server> getServerList() { return serverList; } public Server getCurrentServer() { return currentServer; } public void setCurrentServer( Server device ) { if ( currentServer == device ) return; if ( currentServer != null ) currentServer.setActive( false, false ); Server oldServer = currentServer; currentServer = device; for ( ControlPointListener listener : getListenersCopy() ) listener.mediaServerChanged( currentServer, oldServer ); if ( isStarted && currentServer != null ) currentServer.setActive( true, false ); } private void addRenderer( Renderer device ) { final SharedPreferences preferences = MainActivity.me.getSharedPreferences( SettingsEditor.ADVANCED_SETTINGS, Activity.MODE_PRIVATE ); boolean discovery = preferences.getBoolean( SettingsEditor.DEVICE_DISCOVERY, true ); if ( device == null ) return; synchronized ( rendererList ) { for ( Renderer renderer : rendererList ) if ( renderer.getUDN().equals( device.getUDN() ) ) { if ( !discovery ) { if ( renderer.getLocation().equals( device.getLocation() ) ) { return; } } else { return; } } device.addMediaDeviceListener( this ); rendererList.add( device ); Log.i( "MIT_DBG", "inside addRendererdev,added to rendererList (size =" + rendererList.size() + " )=" + rendererList.toString() ); } for ( ControlPointListener listener : getListenersCopy() ) { Log.i( android.util.PlugPlayerUtil.DBG_TAG, "calling mediaRendererChanged()from addRenderer : PPControlPoint: PP" ); listener.mediaRendererListChanged(); } if ( getCurrentRenderer() == null ) { device.updateAlive(); if ( device.isAlive() ) setCurrentRenderer( device ); } } public void removeRenderer( Renderer device ) { device.removeMediaDeviceListener( this ); synchronized ( serverList ) { rendererList.remove( device ); for ( ControlPointListener listener : getListenersCopy() ) listener.mediaRendererListChanged(); if ( getCurrentRenderer() == device ) setCurrentRenderer( rendererList.get( 0 ) ); } } public List<Renderer> getRendererList() { return rendererList; } public Renderer getCurrentRenderer() { return currentRenderer; } public void setCurrentRenderer( Renderer device ) { if ( currentRenderer == device ) return; if ( currentRenderer != null ) currentRenderer.setActive( false, false ); Renderer oldRenderer = currentRenderer; currentRenderer = device; for ( ControlPointListener listener : getListenersCopy() ) { Log.i( android.util.PlugPlayerUtil.DBG_TAG, "calling mediaRendererChanged()from setCurrentRenderer (old = curr) of PPControlPoint: PP" ); listener.mediaRendererChanged( currentRenderer, oldRenderer ); } if ( isStarted && currentRenderer != null ) currentRenderer.setActive( true, false ); } private List<ControlPointListener> getListenersCopy() { List<ControlPointListener> listenersCopy = null; synchronized ( listeners ) { listenersCopy = new ArrayList<ControlPointListener>( listeners ); } return listenersCopy; } public void search() { Log.i( android.util.PlugPlayerUtil.DBG_TAG, "inside PPCP search" ); controlPoint.search(); } public void checkAliveSync() { boolean rendererListChanged = false; ArrayList<Renderer> renderersCopy; synchronized ( getRendererList() ) { renderersCopy = new ArrayList<Renderer>( getRendererList() ); } for ( Renderer renderer : renderersCopy ) { rendererListChanged = rendererListChanged || renderer.updateAlive(); if ( renderer == getCurrentRenderer() && renderer.isAlive() == false ) setCurrentRenderer( null ); } if ( getCurrentRenderer() == null ) { for ( Renderer renderer : getRendererList() ) if ( renderer.isAlive() ) setCurrentRenderer( renderer ); } if ( rendererListChanged ) for ( ControlPointListener listener : getListenersCopy() ) listener.mediaRendererListChanged(); boolean serverListChanged = false; ArrayList<Server> serversCopy; synchronized ( getServerList() ) { serversCopy = new ArrayList<Server>( getServerList() ); } for ( Server server : serversCopy ) serverListChanged = serverListChanged || server.updateAlive(); if ( serverListChanged ) for ( ControlPointListener listener : getListenersCopy() ) listener.mediaServerListChanged(); if ( getCurrentServer() == null ) { for ( Server server : getServerList() ) if ( server.isAlive() ) setCurrentServer( server ); } } public void checkAlive() { new AsyncTask<Object, Object, Object>() { @Override protected Object doInBackground( Object... arg0 ) { checkAliveSync(); return null; } }.execute( (Object)null ); } public void eventNotifyReceived( String uuid, long seq, String varName, String value ) { // Log.i( MainActivity.appName, "Event recieved: " + uuid + " : " + varName + "," + value ); MediaDevice mediaDevice = subscriptionMap.get( uuid ); if ( mediaDevice != null ) mediaDevice.eventNotifyReceived( uuid, seq, varName, value ); else Log.e( MainActivity.appName, "Got event for device we won't know about: " + uuid ); } public void subscribe( MediaDevice device, Service service ) { boolean subRet = controlPoint.subscribe( service, 1800 ); if ( subRet == true ) { String sid = service.getSID(); subscriptionMap.put( sid, device ); } } public void unsubscribe( MediaDevice device, Service service ) { String sid = service.getSID(); boolean subRet = controlPoint.unsubscribe( service ); if ( subRet == true ) { subscriptionMap.remove( sid ); } } Timer timer = null; public void start() { Log.i( android.util.PlugPlayerUtil.DBG_TAG, "PPcontrolPoint start()" ); if ( controlPoint != null ) { controlPoint.start(); isStarted = true; if ( currentRenderer != null ) currentRenderer.setActive( true, false ); if ( currentServer != null ) currentServer.setActive( true, false ); timer = new Timer(); timer.schedule( new TimerTask() { @Override public void run() { Log.i( android.util.PlugPlayerUtil.DBG_TAG, "PPcontrolPoint start()->run()" ); search(); checkAliveSync(); } }, 0, 15 * 1000 ); } } public void stop( boolean hardStop ) { if ( controlPoint != null ) { if ( timer != null ) timer.cancel(); timer = null; if ( currentRenderer != null ) currentRenderer.setActive( false, hardStop ); if ( currentServer != null ) currentServer.setActive( false, hardStop ); controlPoint.stop(); isStarted = true; } } public void error( String message ) { for ( ControlPointListener listener : getListenersCopy() ) listener.onErrorFromDevice( message ); try { throw new RuntimeException(); } catch ( Exception e ) { Log.e( MainActivity.appName, message, e ); } } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.sql.planner.optimizations; import com.facebook.presto.Session; import com.facebook.presto.connector.system.GlobalSystemConnector; import com.facebook.presto.execution.QueryManagerConfig.ExchangeMaterializationStrategy; import com.facebook.presto.execution.warnings.WarningCollector; import com.facebook.presto.metadata.Metadata; import com.facebook.presto.spi.GroupingProperty; import com.facebook.presto.spi.LocalProperty; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.SortingProperty; import com.facebook.presto.spi.plan.AggregationNode; import com.facebook.presto.spi.plan.Assignments; import com.facebook.presto.spi.plan.FilterNode; import com.facebook.presto.spi.plan.LimitNode; import com.facebook.presto.spi.plan.PlanNode; import com.facebook.presto.spi.plan.PlanNodeIdAllocator; import com.facebook.presto.spi.plan.ProjectNode; import com.facebook.presto.spi.plan.TableScanNode; import com.facebook.presto.spi.plan.TopNNode; import com.facebook.presto.spi.plan.ValuesNode; import com.facebook.presto.spi.relation.RowExpression; import com.facebook.presto.spi.relation.VariableReferenceExpression; import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.analyzer.FeaturesConfig.PartialMergePushdownStrategy; import com.facebook.presto.sql.parser.SqlParser; import com.facebook.presto.sql.planner.ExpressionDomainTranslator; import com.facebook.presto.sql.planner.LiteralEncoder; import com.facebook.presto.sql.planner.Partitioning; import com.facebook.presto.sql.planner.PartitioningHandle; import com.facebook.presto.sql.planner.PartitioningScheme; import com.facebook.presto.sql.planner.PlanVariableAllocator; import com.facebook.presto.sql.planner.TypeProvider; import com.facebook.presto.sql.planner.optimizations.PreferredProperties.PartitioningProperties; import com.facebook.presto.sql.planner.plan.ApplyNode; import com.facebook.presto.sql.planner.plan.ChildReplacer; import com.facebook.presto.sql.planner.plan.DistinctLimitNode; import com.facebook.presto.sql.planner.plan.EnforceSingleRowNode; import com.facebook.presto.sql.planner.plan.ExchangeNode; import com.facebook.presto.sql.planner.plan.ExchangeNode.Scope; import com.facebook.presto.sql.planner.plan.ExplainAnalyzeNode; import com.facebook.presto.sql.planner.plan.GroupIdNode; import com.facebook.presto.sql.planner.plan.IndexJoinNode; import com.facebook.presto.sql.planner.plan.IndexSourceNode; import com.facebook.presto.sql.planner.plan.InternalPlanVisitor; import com.facebook.presto.sql.planner.plan.JoinNode; import com.facebook.presto.sql.planner.plan.LateralJoinNode; import com.facebook.presto.sql.planner.plan.MarkDistinctNode; import com.facebook.presto.sql.planner.plan.OutputNode; import com.facebook.presto.sql.planner.plan.RowNumberNode; import com.facebook.presto.sql.planner.plan.SemiJoinNode; import com.facebook.presto.sql.planner.plan.SortNode; import com.facebook.presto.sql.planner.plan.SpatialJoinNode; import com.facebook.presto.sql.planner.plan.StatisticsWriterNode; import com.facebook.presto.sql.planner.plan.TableFinishNode; import com.facebook.presto.sql.planner.plan.TableWriterNode; import com.facebook.presto.sql.planner.plan.TopNRowNumberNode; import com.facebook.presto.sql.planner.plan.UnionNode; import com.facebook.presto.sql.planner.plan.UnnestNode; import com.facebook.presto.sql.planner.plan.WindowNode; import com.facebook.presto.sql.tree.Expression; import com.facebook.presto.sql.tree.SymbolReference; import com.google.common.annotations.VisibleForTesting; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.ComparisonChain; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.SetMultimap; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import static com.facebook.presto.SystemSessionProperties.getExchangeMaterializationStrategy; import static com.facebook.presto.SystemSessionProperties.getHashPartitionCount; import static com.facebook.presto.SystemSessionProperties.getPartialMergePushdownStrategy; import static com.facebook.presto.SystemSessionProperties.getPartitioningProviderCatalog; import static com.facebook.presto.SystemSessionProperties.isColocatedJoinEnabled; import static com.facebook.presto.SystemSessionProperties.isDistributedIndexJoinEnabled; import static com.facebook.presto.SystemSessionProperties.isDistributedSortEnabled; import static com.facebook.presto.SystemSessionProperties.isForceSingleNodeOutput; import static com.facebook.presto.SystemSessionProperties.isRedistributeWrites; import static com.facebook.presto.SystemSessionProperties.isScaleWriters; import static com.facebook.presto.SystemSessionProperties.preferStreamingOperators; import static com.facebook.presto.operator.aggregation.AggregationUtils.hasSingleNodeExecutionPreference; import static com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED; import static com.facebook.presto.spi.plan.LimitNode.Step.PARTIAL; import static com.facebook.presto.sql.planner.FragmentTableScanCounter.getNumberOfTableScans; import static com.facebook.presto.sql.planner.FragmentTableScanCounter.hasMultipleTableScans; import static com.facebook.presto.sql.planner.PlannerUtils.toVariableReference; import static com.facebook.presto.sql.planner.SystemPartitioningHandle.FIXED_ARBITRARY_DISTRIBUTION; import static com.facebook.presto.sql.planner.SystemPartitioningHandle.FIXED_HASH_DISTRIBUTION; import static com.facebook.presto.sql.planner.SystemPartitioningHandle.SCALED_WRITER_DISTRIBUTION; import static com.facebook.presto.sql.planner.SystemPartitioningHandle.SINGLE_DISTRIBUTION; import static com.facebook.presto.sql.planner.SystemPartitioningHandle.isCompatibleSystemPartitioning; import static com.facebook.presto.sql.planner.iterative.rule.PickTableLayout.pushPredicateIntoTableScan; import static com.facebook.presto.sql.planner.optimizations.ActualProperties.Global.partitionedOn; import static com.facebook.presto.sql.planner.optimizations.ActualProperties.Global.singleStreamPartition; import static com.facebook.presto.sql.planner.optimizations.LocalProperties.grouped; import static com.facebook.presto.sql.planner.plan.ExchangeNode.Scope.REMOTE_MATERIALIZED; import static com.facebook.presto.sql.planner.plan.ExchangeNode.Scope.REMOTE_STREAMING; import static com.facebook.presto.sql.planner.plan.ExchangeNode.Type.GATHER; import static com.facebook.presto.sql.planner.plan.ExchangeNode.Type.REPARTITION; import static com.facebook.presto.sql.planner.plan.ExchangeNode.gatheringExchange; import static com.facebook.presto.sql.planner.plan.ExchangeNode.mergingExchange; import static com.facebook.presto.sql.planner.plan.ExchangeNode.partitionedExchange; import static com.facebook.presto.sql.planner.plan.ExchangeNode.replicatedExchange; import static com.facebook.presto.sql.planner.plan.ExchangeNode.roundRobinExchange; import static com.facebook.presto.sql.relational.OriginalExpressionUtils.castToExpression; import static com.facebook.presto.sql.tree.BooleanLiteral.TRUE_LITERAL; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Verify.verify; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Iterables.getOnlyElement; import static java.lang.String.format; import static java.util.stream.Collectors.toList; public class AddExchanges implements PlanOptimizer { private final SqlParser parser; private final Metadata metadata; private final ExpressionDomainTranslator domainTranslator; public AddExchanges(Metadata metadata, SqlParser parser) { this.metadata = metadata; this.domainTranslator = new ExpressionDomainTranslator(new LiteralEncoder(metadata.getBlockEncodingSerde())); this.parser = parser; } @Override public PlanNode optimize(PlanNode plan, Session session, TypeProvider types, PlanVariableAllocator variableAllocator, PlanNodeIdAllocator idAllocator, WarningCollector warningCollector) { PlanWithProperties result = plan.accept(new Rewriter(idAllocator, variableAllocator, session), PreferredProperties.any()); return result.getNode(); } private class Rewriter extends InternalPlanVisitor<PlanWithProperties, PreferredProperties> { private final PlanNodeIdAllocator idAllocator; private final PlanVariableAllocator variableAllocator; private final TypeProvider types; private final Session session; private final boolean distributedIndexJoins; private final boolean preferStreamingOperators; private final boolean redistributeWrites; private final boolean scaleWriters; private final PartialMergePushdownStrategy partialMergePushdownStrategy; private final String partitioningProviderCatalog; private final int hashPartitionCount; private final ExchangeMaterializationStrategy exchangeMaterializationStrategy; public Rewriter(PlanNodeIdAllocator idAllocator, PlanVariableAllocator variableAllocator, Session session) { this.idAllocator = idAllocator; this.variableAllocator = variableAllocator; this.types = variableAllocator.getTypes(); this.session = session; this.distributedIndexJoins = isDistributedIndexJoinEnabled(session); this.redistributeWrites = isRedistributeWrites(session); this.scaleWriters = isScaleWriters(session); this.partialMergePushdownStrategy = getPartialMergePushdownStrategy(session); this.preferStreamingOperators = preferStreamingOperators(session); this.partitioningProviderCatalog = getPartitioningProviderCatalog(session); this.hashPartitionCount = getHashPartitionCount(session); this.exchangeMaterializationStrategy = getExchangeMaterializationStrategy(session); } @Override public PlanWithProperties visitPlan(PlanNode node, PreferredProperties preferredProperties) { return rebaseAndDeriveProperties(node, planChild(node, preferredProperties)); } @Override public PlanWithProperties visitProject(ProjectNode node, PreferredProperties preferredProperties) { Map<VariableReferenceExpression, VariableReferenceExpression> identities = computeIdentityTranslations(node.getAssignments(), types); PreferredProperties translatedPreferred = preferredProperties.translate(symbol -> Optional.ofNullable(identities.get(symbol))); return rebaseAndDeriveProperties(node, planChild(node, translatedPreferred)); } @Override public PlanWithProperties visitOutput(OutputNode node, PreferredProperties preferredProperties) { PlanWithProperties child = planChild(node, PreferredProperties.undistributed()); if (!child.getProperties().isSingleNode() && isForceSingleNodeOutput(session)) { child = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE_STREAMING, child.getNode()), child.getProperties()); } return rebaseAndDeriveProperties(node, child); } @Override public PlanWithProperties visitEnforceSingleRow(EnforceSingleRowNode node, PreferredProperties preferredProperties) { PlanWithProperties child = planChild(node, PreferredProperties.any()); if (!child.getProperties().isSingleNode()) { child = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE_STREAMING, child.getNode()), child.getProperties()); } return rebaseAndDeriveProperties(node, child); } @Override public PlanWithProperties visitAggregation(AggregationNode node, PreferredProperties parentPreferredProperties) { Set<VariableReferenceExpression> partitioningRequirement = ImmutableSet.copyOf(node.getGroupingKeys()); boolean preferSingleNode = hasSingleNodeExecutionPreference(node, metadata.getFunctionManager()); PreferredProperties preferredProperties = preferSingleNode ? PreferredProperties.undistributed() : PreferredProperties.any(); if (!node.getGroupingKeys().isEmpty()) { preferredProperties = PreferredProperties.partitionedWithLocal(partitioningRequirement, grouped(node.getGroupingKeys())) .mergeWithParent(parentPreferredProperties); } PlanWithProperties child = planChild(node, preferredProperties); if (child.getProperties().isSingleNode()) { // If already unpartitioned, just drop the single aggregation back on return rebaseAndDeriveProperties(node, child); } if (preferSingleNode) { child = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE_STREAMING, child.getNode()), child.getProperties()); } else if (!child.getProperties().isStreamPartitionedOn(partitioningRequirement) && !child.getProperties().isNodePartitionedOn(partitioningRequirement)) { child = withDerivedProperties( partitionedExchange( idAllocator.getNextId(), selectExchangeScopeForPartitionedRemoteExchange(child.getNode(), false), child.getNode(), createPartitioning(node.getGroupingKeys()), node.getHashVariable()), child.getProperties()); } return rebaseAndDeriveProperties(node, child); } @Override public PlanWithProperties visitGroupId(GroupIdNode node, PreferredProperties preferredProperties) { PreferredProperties childPreference = preferredProperties.translate(translateGroupIdVariables(node)); PlanWithProperties child = planChild(node, childPreference); return rebaseAndDeriveProperties(node, child); } private Function<VariableReferenceExpression, Optional<VariableReferenceExpression>> translateGroupIdVariables(GroupIdNode node) { return variable -> { if (node.getAggregationArguments().contains(variable)) { return Optional.of(variable); } if (node.getCommonGroupingColumns().contains(variable)) { return Optional.of((node.getGroupingColumns().get(variable))); } return Optional.empty(); }; } @Override public PlanWithProperties visitMarkDistinct(MarkDistinctNode node, PreferredProperties preferredProperties) { PreferredProperties preferredChildProperties = PreferredProperties.partitionedWithLocal(ImmutableSet.copyOf(node.getDistinctVariables()), grouped(node.getDistinctVariables())) .mergeWithParent(preferredProperties); PlanWithProperties child = node.getSource().accept(this, preferredChildProperties); if (child.getProperties().isSingleNode() || !child.getProperties().isStreamPartitionedOn(node.getDistinctVariables())) { child = withDerivedProperties( partitionedExchange( idAllocator.getNextId(), selectExchangeScopeForPartitionedRemoteExchange(child.getNode(), false), child.getNode(), createPartitioning(node.getDistinctVariables()), node.getHashVariable()), child.getProperties()); } return rebaseAndDeriveProperties(node, child); } @Override public PlanWithProperties visitWindow(WindowNode node, PreferredProperties preferredProperties) { List<LocalProperty<VariableReferenceExpression>> desiredProperties = new ArrayList<>(); if (!node.getPartitionBy().isEmpty()) { desiredProperties.add(new GroupingProperty<>(node.getPartitionBy())); } node.getOrderingScheme().ifPresent(orderingScheme -> orderingScheme.getOrderByVariables().stream() .map(variable -> new SortingProperty<>(variable, orderingScheme.getOrdering(variable))) .forEach(desiredProperties::add)); PlanWithProperties child = planChild( node, PreferredProperties.partitionedWithLocal(ImmutableSet.copyOf(node.getPartitionBy()), desiredProperties) .mergeWithParent(preferredProperties)); if (!child.getProperties().isStreamPartitionedOn(node.getPartitionBy()) && !child.getProperties().isNodePartitionedOn(node.getPartitionBy())) { if (node.getPartitionBy().isEmpty()) { child = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE_STREAMING, child.getNode()), child.getProperties()); } else { child = withDerivedProperties( partitionedExchange( idAllocator.getNextId(), selectExchangeScopeForPartitionedRemoteExchange(child.getNode(), false), child.getNode(), createPartitioning(node.getPartitionBy()), node.getHashVariable()), child.getProperties()); } } return rebaseAndDeriveProperties(node, child); } @Override public PlanWithProperties visitRowNumber(RowNumberNode node, PreferredProperties preferredProperties) { if (node.getPartitionBy().isEmpty()) { PlanWithProperties child = planChild(node, PreferredProperties.undistributed()); if (!child.getProperties().isSingleNode()) { child = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE_STREAMING, child.getNode()), child.getProperties()); } return rebaseAndDeriveProperties(node, child); } PlanWithProperties child = planChild( node, PreferredProperties.partitionedWithLocal(ImmutableSet.copyOf(node.getPartitionBy()), grouped(node.getPartitionBy())) .mergeWithParent(preferredProperties)); // TODO: add config option/session property to force parallel plan if child is unpartitioned and window has a PARTITION BY clause if (!child.getProperties().isStreamPartitionedOn(node.getPartitionBy()) && !child.getProperties().isNodePartitionedOn(node.getPartitionBy())) { child = withDerivedProperties( partitionedExchange( idAllocator.getNextId(), selectExchangeScopeForPartitionedRemoteExchange(child.getNode(), false), child.getNode(), createPartitioning(node.getPartitionBy()), node.getHashVariable()), child.getProperties()); } // TODO: streaming return rebaseAndDeriveProperties(node, child); } @Override public PlanWithProperties visitTopNRowNumber(TopNRowNumberNode node, PreferredProperties preferredProperties) { PreferredProperties preferredChildProperties; Function<PlanNode, PlanNode> addExchange; if (node.getPartitionBy().isEmpty()) { preferredChildProperties = PreferredProperties.any(); addExchange = partial -> gatheringExchange(idAllocator.getNextId(), REMOTE_STREAMING, partial); } else { preferredChildProperties = PreferredProperties.partitionedWithLocal(ImmutableSet.copyOf(node.getPartitionBy()), grouped(node.getPartitionBy())) .mergeWithParent(preferredProperties); addExchange = partial -> partitionedExchange( idAllocator.getNextId(), selectExchangeScopeForPartitionedRemoteExchange(partial, false), partial, createPartitioning(node.getPartitionBy()), node.getHashVariable()); } PlanWithProperties child = planChild(node, preferredChildProperties); if (!child.getProperties().isStreamPartitionedOn(node.getPartitionBy()) && !child.getProperties().isNodePartitionedOn(node.getPartitionBy())) { // add exchange + push function to child child = withDerivedProperties( new TopNRowNumberNode( idAllocator.getNextId(), child.getNode(), node.getSpecification(), node.getRowNumberVariable(), node.getMaxRowCountPerPartition(), true, node.getHashVariable()), child.getProperties()); child = withDerivedProperties(addExchange.apply(child.getNode()), child.getProperties()); } return rebaseAndDeriveProperties(node, child); } @Override public PlanWithProperties visitTopN(TopNNode node, PreferredProperties preferredProperties) { PlanWithProperties child; switch (node.getStep()) { case SINGLE: case FINAL: child = planChild(node, PreferredProperties.undistributed()); if (!child.getProperties().isSingleNode()) { child = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE_STREAMING, child.getNode()), child.getProperties()); } break; case PARTIAL: child = planChild(node, PreferredProperties.any()); break; default: throw new UnsupportedOperationException(format("Unsupported step for TopN [%s]", node.getStep())); } return rebaseAndDeriveProperties(node, child); } @Override public PlanWithProperties visitSort(SortNode node, PreferredProperties preferredProperties) { PlanWithProperties child = planChild(node, PreferredProperties.undistributed()); if (child.getProperties().isSingleNode()) { // current plan so far is single node, so local properties are effectively global properties // skip the SortNode if the local properties guarantee ordering on Sort keys // TODO: This should be extracted as a separate optimizer once the planner is able to reason about the ordering of each operator List<LocalProperty<VariableReferenceExpression>> desiredProperties = new ArrayList<>(); for (VariableReferenceExpression variable : node.getOrderingScheme().getOrderByVariables()) { desiredProperties.add(new SortingProperty<>(variable, node.getOrderingScheme().getOrdering(variable))); } if (LocalProperties.match(child.getProperties().getLocalProperties(), desiredProperties).stream() .noneMatch(Optional::isPresent)) { return child; } } if (isDistributedSortEnabled(session)) { child = planChild(node, PreferredProperties.any()); // insert round robin exchange to eliminate skewness issues PlanNode source = roundRobinExchange(idAllocator.getNextId(), REMOTE_STREAMING, child.getNode()); return withDerivedProperties( mergingExchange( idAllocator.getNextId(), REMOTE_STREAMING, new SortNode( idAllocator.getNextId(), source, node.getOrderingScheme(), true), node.getOrderingScheme()), child.getProperties()); } if (!child.getProperties().isSingleNode()) { child = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE_STREAMING, child.getNode()), child.getProperties()); } return rebaseAndDeriveProperties(node, child); } @Override public PlanWithProperties visitLimit(LimitNode node, PreferredProperties preferredProperties) { PlanWithProperties child = planChild(node, PreferredProperties.any()); if (!child.getProperties().isSingleNode()) { child = withDerivedProperties( new LimitNode(idAllocator.getNextId(), child.getNode(), node.getCount(), PARTIAL), child.getProperties()); child = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE_STREAMING, child.getNode()), child.getProperties()); } return rebaseAndDeriveProperties(node, child); } @Override public PlanWithProperties visitDistinctLimit(DistinctLimitNode node, PreferredProperties preferredProperties) { PlanWithProperties child = planChild(node, PreferredProperties.any()); if (!child.getProperties().isSingleNode()) { child = withDerivedProperties( gatheringExchange( idAllocator.getNextId(), REMOTE_STREAMING, new DistinctLimitNode(idAllocator.getNextId(), child.getNode(), node.getLimit(), true, node.getDistinctVariables(), node.getHashVariable())), child.getProperties()); } return rebaseAndDeriveProperties(node, child); } @Override public PlanWithProperties visitFilter(FilterNode node, PreferredProperties preferredProperties) { if (node.getSource() instanceof TableScanNode) { return planTableScan((TableScanNode) node.getSource(), castToExpression(node.getPredicate())); } return rebaseAndDeriveProperties(node, planChild(node, preferredProperties)); } @Override public PlanWithProperties visitTableScan(TableScanNode node, PreferredProperties preferredProperties) { return planTableScan(node, TRUE_LITERAL); } @Override public PlanWithProperties visitTableWriter(TableWriterNode node, PreferredProperties preferredProperties) { PlanWithProperties source = node.getSource().accept(this, preferredProperties); Optional<PartitioningScheme> partitioningScheme = node.getPartitioningScheme(); if (!partitioningScheme.isPresent()) { if (scaleWriters) { partitioningScheme = Optional.of(new PartitioningScheme(Partitioning.create(SCALED_WRITER_DISTRIBUTION, ImmutableList.of()), source.getNode().getOutputVariables())); } else if (redistributeWrites) { partitioningScheme = Optional.of(new PartitioningScheme(Partitioning.create(FIXED_ARBITRARY_DISTRIBUTION, ImmutableList.of()), source.getNode().getOutputVariables())); } } if (partitioningScheme.isPresent() && // TODO: Deprecate compatible table partitioning !source.getProperties().isCompatibleTablePartitioningWith(partitioningScheme.get().getPartitioning(), false, metadata, session) && !(source.getProperties().isRefinedPartitioningOver(partitioningScheme.get().getPartitioning(), false, metadata, session) && canPushdownPartialMerge(source.getNode(), partialMergePushdownStrategy))) { source = withDerivedProperties( partitionedExchange( idAllocator.getNextId(), REMOTE_STREAMING, source.getNode(), partitioningScheme.get()), source.getProperties()); } return rebaseAndDeriveProperties(node, source); } private PlanWithProperties planTableScan(TableScanNode node, Expression predicate) { PlanNode plan = pushPredicateIntoTableScan(node, predicate, true, session, types, idAllocator, metadata, parser, domainTranslator); // TODO: Support selecting layout with best local property once connector can participate in query optimization. return new PlanWithProperties(plan, derivePropertiesRecursively(plan)); } @Override public PlanWithProperties visitValues(ValuesNode node, PreferredProperties preferredProperties) { return new PlanWithProperties( node, ActualProperties.builder() .global(singleStreamPartition()) .build()); } @Override public PlanWithProperties visitExplainAnalyze(ExplainAnalyzeNode node, PreferredProperties preferredProperties) { PlanWithProperties child = planChild(node, PreferredProperties.any()); // if the child is already a gathering exchange, don't add another if ((child.getNode() instanceof ExchangeNode) && ((ExchangeNode) child.getNode()).getType() == ExchangeNode.Type.GATHER) { return rebaseAndDeriveProperties(node, child); } // Always add an exchange because ExplainAnalyze should be in its own stage child = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE_STREAMING, child.getNode()), child.getProperties()); return rebaseAndDeriveProperties(node, child); } @Override public PlanWithProperties visitStatisticsWriterNode(StatisticsWriterNode node, PreferredProperties context) { PlanWithProperties child = planChild(node, PreferredProperties.any()); // if the child is already a gathering exchange, don't add another if ((child.getNode() instanceof ExchangeNode) && ((ExchangeNode) child.getNode()).getType().equals(GATHER)) { return rebaseAndDeriveProperties(node, child); } if (!child.getProperties().isCoordinatorOnly()) { child = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE_STREAMING, child.getNode()), child.getProperties()); } return rebaseAndDeriveProperties(node, child); } @Override public PlanWithProperties visitTableFinish(TableFinishNode node, PreferredProperties preferredProperties) { PlanWithProperties child = planChild(node, PreferredProperties.any()); // if the child is already a gathering exchange, don't add another if ((child.getNode() instanceof ExchangeNode) && ((ExchangeNode) child.getNode()).getType().equals(GATHER)) { return rebaseAndDeriveProperties(node, child); } if (!child.getProperties().isCoordinatorOnly()) { child = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE_STREAMING, child.getNode()), child.getProperties()); } return rebaseAndDeriveProperties(node, child); } private <T> SetMultimap<T, T> createMapping(List<T> keys, List<T> values) { checkArgument(keys.size() == values.size(), "Inputs must have the same size"); ImmutableSetMultimap.Builder<T, T> builder = ImmutableSetMultimap.builder(); for (int i = 0; i < keys.size(); i++) { builder.put(keys.get(i), values.get(i)); } return builder.build(); } private <T> Function<T, Optional<T>> createTranslator(SetMultimap<T, T> inputToOutput) { return input -> inputToOutput.get(input).stream().findAny(); } private <T> Function<T, T> createDirectTranslator(SetMultimap<T, T> inputToOutput) { return input -> inputToOutput.get(input).iterator().next(); } @Override public PlanWithProperties visitJoin(JoinNode node, PreferredProperties preferredProperties) { List<VariableReferenceExpression> leftVariables = node.getCriteria().stream() .map(JoinNode.EquiJoinClause::getLeft) .collect(toImmutableList()); List<VariableReferenceExpression> rightVariables = node.getCriteria().stream() .map(JoinNode.EquiJoinClause::getRight) .collect(toImmutableList()); JoinNode.DistributionType distributionType = node.getDistributionType().orElseThrow(() -> new IllegalArgumentException("distributionType not yet set")); if (distributionType == JoinNode.DistributionType.REPLICATED) { PlanWithProperties left = node.getLeft().accept(this, PreferredProperties.any()); // use partitioned join if probe side is naturally partitioned on join symbols (e.g: because of aggregation) if (!node.getCriteria().isEmpty() && left.getProperties().isNodePartitionedOn(leftVariables) && !left.getProperties().isSingleNode()) { return planPartitionedJoin(node, leftVariables, rightVariables, left); } return planReplicatedJoin(node, left); } else { return planPartitionedJoin(node, leftVariables, rightVariables); } } private PlanWithProperties planPartitionedJoin(JoinNode node, List<VariableReferenceExpression> leftVariables, List<VariableReferenceExpression> rightVariables) { return planPartitionedJoin(node, leftVariables, rightVariables, node.getLeft().accept(this, PreferredProperties.partitioned(ImmutableSet.copyOf(leftVariables)))); } private PlanWithProperties planPartitionedJoin(JoinNode node, List<VariableReferenceExpression> leftVariables, List<VariableReferenceExpression> rightVariables, PlanWithProperties left) { SetMultimap<VariableReferenceExpression, VariableReferenceExpression> rightToLeft = createMapping(rightVariables, leftVariables); SetMultimap<VariableReferenceExpression, VariableReferenceExpression> leftToRight = createMapping(leftVariables, rightVariables); PlanWithProperties right; if (left.getProperties().isNodePartitionedOn(leftVariables) && !left.getProperties().isSingleNode()) { Partitioning rightPartitioning = left.getProperties().translateVariable(createTranslator(leftToRight)).getNodePartitioning().get(); right = node.getRight().accept(this, PreferredProperties.partitioned(rightPartitioning)); if (!right.getProperties().isCompatibleTablePartitioningWith(left.getProperties(), rightToLeft::get, metadata, session) && // TODO: Deprecate compatible table partitioning !(right.getProperties().isRefinedPartitioningOver(left.getProperties(), rightToLeft::get, metadata, session) && canPushdownPartialMerge(right.getNode(), partialMergePushdownStrategy))) { right = withDerivedProperties( partitionedExchange( idAllocator.getNextId(), selectExchangeScopeForPartitionedRemoteExchange(right.getNode(), false), right.getNode(), new PartitioningScheme(rightPartitioning, right.getNode().getOutputVariables())), right.getProperties()); } } else { right = node.getRight().accept(this, PreferredProperties.partitioned(ImmutableSet.copyOf(rightVariables))); if (right.getProperties().isNodePartitionedOn(rightVariables) && !right.getProperties().isSingleNode()) { Partitioning leftPartitioning = right.getProperties().translateVariable(createTranslator(rightToLeft)).getNodePartitioning().get(); left = withDerivedProperties( partitionedExchange( idAllocator.getNextId(), selectExchangeScopeForPartitionedRemoteExchange(left.getNode(), false), left.getNode(), new PartitioningScheme(leftPartitioning, left.getNode().getOutputVariables())), left.getProperties()); } else { left = withDerivedProperties( partitionedExchange( idAllocator.getNextId(), selectExchangeScopeForPartitionedRemoteExchange(left.getNode(), false), left.getNode(), createPartitioning(leftVariables), Optional.empty()), left.getProperties()); right = withDerivedProperties( partitionedExchange( idAllocator.getNextId(), selectExchangeScopeForPartitionedRemoteExchange(right.getNode(), false), right.getNode(), createPartitioning(rightVariables), Optional.empty()), right.getProperties()); } } // TODO: Deprecate compatible table partitioning verify(left.getProperties().isCompatibleTablePartitioningWith(right.getProperties(), leftToRight::get, metadata, session) || (right.getProperties().isRefinedPartitioningOver(left.getProperties(), rightToLeft::get, metadata, session) && canPushdownPartialMerge(right.getNode(), partialMergePushdownStrategy))); // if colocated joins are disabled, force redistribute when using a custom partitioning if (!isColocatedJoinEnabled(session) && hasMultipleTableScans(left.getNode(), right.getNode())) { Partitioning rightPartitioning = left.getProperties().translateVariable(createTranslator(leftToRight)).getNodePartitioning().get(); right = withDerivedProperties( partitionedExchange( idAllocator.getNextId(), selectExchangeScopeForPartitionedRemoteExchange(right.getNode(), false), right.getNode(), new PartitioningScheme(rightPartitioning, right.getNode().getOutputVariables())), right.getProperties()); } return buildJoin(node, left, right, JoinNode.DistributionType.PARTITIONED); } private PlanWithProperties planReplicatedJoin(JoinNode node, PlanWithProperties left) { // Broadcast Join PlanWithProperties right = node.getRight().accept(this, PreferredProperties.any()); if (left.getProperties().isSingleNode()) { if (!right.getProperties().isSingleNode() || (!isColocatedJoinEnabled(session) && hasMultipleTableScans(left.getNode(), right.getNode()))) { right = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE_STREAMING, right.getNode()), right.getProperties()); } } else { right = withDerivedProperties( replicatedExchange(idAllocator.getNextId(), REMOTE_STREAMING, right.getNode()), right.getProperties()); } return buildJoin(node, left, right, JoinNode.DistributionType.REPLICATED); } private PlanWithProperties buildJoin(JoinNode node, PlanWithProperties newLeft, PlanWithProperties newRight, JoinNode.DistributionType newDistributionType) { JoinNode result = new JoinNode(node.getId(), node.getType(), newLeft.getNode(), newRight.getNode(), node.getCriteria(), node.getOutputVariables(), node.getFilter(), node.getLeftHashVariable(), node.getRightHashVariable(), Optional.of(newDistributionType)); return new PlanWithProperties(result, deriveProperties(result, ImmutableList.of(newLeft.getProperties(), newRight.getProperties()))); } @Override public PlanWithProperties visitSpatialJoin(SpatialJoinNode node, PreferredProperties preferredProperties) { SpatialJoinNode.DistributionType distributionType = node.getDistributionType(); PlanWithProperties left = node.getLeft().accept(this, PreferredProperties.any()); PlanWithProperties right = node.getRight().accept(this, PreferredProperties.any()); if (distributionType == SpatialJoinNode.DistributionType.REPLICATED) { if (left.getProperties().isSingleNode()) { if (!right.getProperties().isSingleNode()) { right = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE_STREAMING, right.getNode()), right.getProperties()); } } else { right = withDerivedProperties( replicatedExchange(idAllocator.getNextId(), REMOTE_STREAMING, right.getNode()), right.getProperties()); } } else { left = withDerivedProperties( partitionedExchange(idAllocator.getNextId(), REMOTE_STREAMING, left.getNode(), createPartitioning(ImmutableList.of(node.getLeftPartitionVariable().get())), Optional.empty()), left.getProperties()); right = withDerivedProperties( partitionedExchange(idAllocator.getNextId(), REMOTE_STREAMING, right.getNode(), createPartitioning(ImmutableList.of(node.getRightPartitionVariable().get())), Optional.empty()), right.getProperties()); } PlanNode newJoinNode = node.replaceChildren(ImmutableList.of(left.getNode(), right.getNode())); return new PlanWithProperties(newJoinNode, deriveProperties(newJoinNode, ImmutableList.of(left.getProperties(), right.getProperties()))); } @Override public PlanWithProperties visitUnnest(UnnestNode node, PreferredProperties preferredProperties) { PreferredProperties translatedPreferred = preferredProperties.translate(variable -> node.getReplicateVariables().contains(variable) ? Optional.of(variable) : Optional.empty()); return rebaseAndDeriveProperties(node, planChild(node, translatedPreferred)); } @Override public PlanWithProperties visitSemiJoin(SemiJoinNode node, PreferredProperties preferredProperties) { PlanWithProperties source; PlanWithProperties filteringSource; SemiJoinNode.DistributionType distributionType = node.getDistributionType().orElseThrow(() -> new IllegalArgumentException("distributionType not yet set")); if (distributionType == SemiJoinNode.DistributionType.PARTITIONED) { List<VariableReferenceExpression> sourceVariables = ImmutableList.of(node.getSourceJoinVariable()); List<VariableReferenceExpression> filteringSourceVariables = ImmutableList.of(node.getFilteringSourceJoinVariable()); SetMultimap<VariableReferenceExpression, VariableReferenceExpression> sourceToFiltering = createMapping(sourceVariables, filteringSourceVariables); SetMultimap<VariableReferenceExpression, VariableReferenceExpression> filteringToSource = createMapping(filteringSourceVariables, sourceVariables); source = node.getSource().accept(this, PreferredProperties.partitioned(ImmutableSet.copyOf(sourceVariables))); if (source.getProperties().isNodePartitionedOn(sourceVariables) && !source.getProperties().isSingleNode()) { Partitioning filteringPartitioning = source.getProperties().translateVariable(createTranslator(sourceToFiltering)).getNodePartitioning().get(); filteringSource = node.getFilteringSource().accept(this, PreferredProperties.partitionedWithNullsAndAnyReplicated(filteringPartitioning)); // TODO: Deprecate compatible table partitioning if (!source.getProperties().withReplicatedNulls(true).isCompatibleTablePartitioningWith(filteringSource.getProperties(), sourceToFiltering::get, metadata, session) && !(filteringSource.getProperties().withReplicatedNulls(true).isRefinedPartitioningOver(source.getProperties(), filteringToSource::get, metadata, session) && canPushdownPartialMerge(filteringSource.getNode(), partialMergePushdownStrategy))) { filteringSource = withDerivedProperties( partitionedExchange(idAllocator.getNextId(), REMOTE_STREAMING, filteringSource.getNode(), new PartitioningScheme( filteringPartitioning, filteringSource.getNode().getOutputVariables(), Optional.empty(), true, Optional.empty())), filteringSource.getProperties()); } } else { filteringSource = node.getFilteringSource().accept(this, PreferredProperties.partitionedWithNullsAndAnyReplicated(ImmutableSet.copyOf(filteringSourceVariables))); if (filteringSource.getProperties().isNodePartitionedOn(filteringSourceVariables, true) && !filteringSource.getProperties().isSingleNode()) { Partitioning sourcePartitioning = filteringSource.getProperties().translateVariable(createTranslator(filteringToSource)).getNodePartitioning().get(); source = withDerivedProperties( partitionedExchange(idAllocator.getNextId(), REMOTE_STREAMING, source.getNode(), new PartitioningScheme(sourcePartitioning, source.getNode().getOutputVariables())), source.getProperties()); } else { source = withDerivedProperties( partitionedExchange( idAllocator.getNextId(), REMOTE_STREAMING, source.getNode(), createPartitioning(sourceVariables), Optional.empty()), source.getProperties()); filteringSource = withDerivedProperties( partitionedExchange(idAllocator.getNextId(), REMOTE_STREAMING, filteringSource.getNode(), createPartitioning(filteringSourceVariables), Optional.empty(), true), filteringSource.getProperties()); } } verify(source.getProperties().withReplicatedNulls(true).isCompatibleTablePartitioningWith(filteringSource.getProperties(), sourceToFiltering::get, metadata, session) || // TODO: Deprecate compatible table partitioning (filteringSource.getProperties().withReplicatedNulls(true).isRefinedPartitioningOver(source.getProperties(), filteringToSource::get, metadata, session) && canPushdownPartialMerge(filteringSource.getNode(), partialMergePushdownStrategy))); // if colocated joins are disabled, force redistribute when using a custom partitioning if (!isColocatedJoinEnabled(session) && hasMultipleTableScans(source.getNode(), filteringSource.getNode())) { Partitioning filteringPartitioning = source.getProperties().translateVariable(createTranslator(sourceToFiltering)).getNodePartitioning().get(); filteringSource = withDerivedProperties( partitionedExchange(idAllocator.getNextId(), REMOTE_STREAMING, filteringSource.getNode(), new PartitioningScheme( filteringPartitioning, filteringSource.getNode().getOutputVariables(), Optional.empty(), true, Optional.empty())), filteringSource.getProperties()); } } else { source = node.getSource().accept(this, PreferredProperties.any()); // Delete operator works fine even if TableScans on the filtering (right) side is not co-located with itself. It only cares about the corresponding TableScan, // which is always on the source (left) side. Therefore, hash-partitioned semi-join is always allowed on the filtering side. filteringSource = node.getFilteringSource().accept(this, PreferredProperties.any()); // make filtering source match requirements of source if (source.getProperties().isSingleNode()) { if (!filteringSource.getProperties().isSingleNode() || (!isColocatedJoinEnabled(session) && hasMultipleTableScans(source.getNode(), filteringSource.getNode()))) { filteringSource = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE_STREAMING, filteringSource.getNode()), filteringSource.getProperties()); } } else { filteringSource = withDerivedProperties( replicatedExchange(idAllocator.getNextId(), REMOTE_STREAMING, filteringSource.getNode()), filteringSource.getProperties()); } } return rebaseAndDeriveProperties(node, ImmutableList.of(source, filteringSource)); } @Override public PlanWithProperties visitIndexJoin(IndexJoinNode node, PreferredProperties preferredProperties) { List<VariableReferenceExpression> joinColumns = node.getCriteria().stream() .map(IndexJoinNode.EquiJoinClause::getProbe) .collect(toImmutableList()); // Only prefer grouping on join columns if no parent local property preferences List<LocalProperty<VariableReferenceExpression>> desiredLocalProperties = preferredProperties.getLocalProperties().isEmpty() ? grouped(joinColumns) : ImmutableList.of(); PlanWithProperties probeSource = node.getProbeSource().accept(this, PreferredProperties.partitionedWithLocal(ImmutableSet.copyOf(joinColumns), desiredLocalProperties) .mergeWithParent(preferredProperties)); ActualProperties probeProperties = probeSource.getProperties(); PlanWithProperties indexSource = node.getIndexSource().accept(this, PreferredProperties.any()); // TODO: allow repartitioning if unpartitioned to increase parallelism if (shouldRepartitionForIndexJoin(joinColumns, preferredProperties, probeProperties)) { probeSource = withDerivedProperties( partitionedExchange(idAllocator.getNextId(), REMOTE_STREAMING, probeSource.getNode(), createPartitioning(joinColumns), node.getProbeHashVariable()), probeProperties); } // TODO: if input is grouped, create streaming join // index side is really a nested-loops plan, so don't add exchanges PlanNode result = ChildReplacer.replaceChildren(node, ImmutableList.of(probeSource.getNode(), node.getIndexSource())); return new PlanWithProperties(result, deriveProperties(result, ImmutableList.of(probeSource.getProperties(), indexSource.getProperties()))); } private boolean shouldRepartitionForIndexJoin(List<VariableReferenceExpression> joinColumns, PreferredProperties parentPreferredProperties, ActualProperties probeProperties) { // See if distributed index joins are enabled if (!distributedIndexJoins) { return false; } // No point in repartitioning if the plan is not distributed if (probeProperties.isSingleNode()) { return false; } Optional<PartitioningProperties> parentPartitioningPreferences = parentPreferredProperties.getGlobalProperties() .flatMap(PreferredProperties.Global::getPartitioningProperties); // Disable repartitioning if it would disrupt a parent's partitioning preference when streaming is enabled boolean parentAlreadyPartitionedOnChild = parentPartitioningPreferences .map(partitioning -> probeProperties.isStreamPartitionedOn(partitioning.getPartitioningColumns())) .orElse(false); if (preferStreamingOperators && parentAlreadyPartitionedOnChild) { return false; } // Otherwise, repartition if we need to align with the join columns if (!probeProperties.isStreamPartitionedOn(joinColumns)) { return true; } // If we are already partitioned on the join columns because the data has been forced effectively into one stream, // then we should repartition if that would make a difference (from the single stream state). return probeProperties.isEffectivelySingleStream() && probeProperties.isStreamRepartitionEffective(joinColumns); } @Override public PlanWithProperties visitIndexSource(IndexSourceNode node, PreferredProperties preferredProperties) { return new PlanWithProperties( node, ActualProperties.builder() .global(singleStreamPartition()) .build()); } private Function<VariableReferenceExpression, Optional<VariableReferenceExpression>> outputToInputTranslator(UnionNode node, int sourceIndex, TypeProvider types) { return variable -> Optional.of(node.getVariableMapping().get(variable).get(sourceIndex)); } private Partitioning selectUnionPartitioning(UnionNode node, PartitioningProperties parentPreference) { // Use the parent's requested partitioning if available if (parentPreference.getPartitioning().isPresent()) { return parentPreference.getPartitioning().get(); } // Try planning the children to see if any of them naturally produce a partitioning (for now, just select the first) boolean nullsAndAnyReplicated = parentPreference.isNullsAndAnyReplicated(); for (int sourceIndex = 0; sourceIndex < node.getSources().size(); sourceIndex++) { PreferredProperties.PartitioningProperties childPartitioning = parentPreference.translateVariable(outputToInputTranslator(node, sourceIndex, types)).get(); PreferredProperties childPreferred = PreferredProperties.builder() .global(PreferredProperties.Global.distributed(childPartitioning.withNullsAndAnyReplicated(nullsAndAnyReplicated))) .build(); PlanWithProperties child = node.getSources().get(sourceIndex).accept(this, childPreferred); // Don't select a single node partitioning so that we maintain query parallelism // Theoretically, if all children are single partitioned on the same node we could choose a single // partitioning, but as this only applies to a union of two values nodes, it isn't worth the added complexity if (child.getProperties().isNodePartitionedOn(childPartitioning.getPartitioningColumns(), nullsAndAnyReplicated) && !child.getProperties().isSingleNode()) { Function<VariableReferenceExpression, Optional<VariableReferenceExpression>> childToParent = createTranslator(createMapping( node.sourceOutputLayout(sourceIndex), node.getOutputVariables())); return child.getProperties().translateVariable(childToParent).getNodePartitioning().get(); } } // Otherwise, choose an arbitrary partitioning over the columns return createPartitioning(ImmutableList.copyOf(parentPreference.getPartitioningColumns())); } @Override public PlanWithProperties visitUnion(UnionNode node, PreferredProperties parentPreference) { Optional<PreferredProperties.Global> parentPartitioningPreference = parentPreference.getGlobalProperties(); // case 1: parent provides preferred distributed partitioning if (parentPartitioningPreference.isPresent() && parentPartitioningPreference.get().isDistributed() && parentPartitioningPreference.get().getPartitioningProperties().isPresent()) { PartitioningProperties parentPartitioningProperties = parentPartitioningPreference.get().getPartitioningProperties().get(); boolean nullsAndAnyReplicated = parentPartitioningProperties.isNullsAndAnyReplicated(); Partitioning desiredParentPartitioning = selectUnionPartitioning(node, parentPartitioningProperties); ImmutableList.Builder<PlanNode> partitionedSources = ImmutableList.builder(); ImmutableListMultimap.Builder<VariableReferenceExpression, VariableReferenceExpression> outputToSourcesMapping = ImmutableListMultimap.builder(); for (int sourceIndex = 0; sourceIndex < node.getSources().size(); sourceIndex++) { Partitioning childPartitioning = desiredParentPartitioning.translateVariable(createDirectTranslator(createMapping( node.getOutputVariables(), node.sourceOutputLayout(sourceIndex)))); PreferredProperties childPreferred = PreferredProperties.builder() .global(PreferredProperties.Global.distributed(PartitioningProperties.partitioned(childPartitioning) .withNullsAndAnyReplicated(nullsAndAnyReplicated))) .build(); PlanWithProperties source = node.getSources().get(sourceIndex).accept(this, childPreferred); // TODO: Deprecate compatible table partitioning if (!source.getProperties().isCompatibleTablePartitioningWith(childPartitioning, nullsAndAnyReplicated, metadata, session) && !(source.getProperties().isRefinedPartitioningOver(childPartitioning, nullsAndAnyReplicated, metadata, session) && canPushdownPartialMerge(source.getNode(), partialMergePushdownStrategy))) { source = withDerivedProperties( partitionedExchange( idAllocator.getNextId(), selectExchangeScopeForPartitionedRemoteExchange(source.getNode(), nullsAndAnyReplicated), source.getNode(), new PartitioningScheme( childPartitioning, source.getNode().getOutputVariables(), Optional.empty(), nullsAndAnyReplicated, Optional.empty())), source.getProperties()); } partitionedSources.add(source.getNode()); for (int column = 0; column < node.getOutputVariables().size(); column++) { outputToSourcesMapping.put(node.getOutputVariables().get(column), node.sourceOutputLayout(sourceIndex).get(column)); } } UnionNode newNode = new UnionNode( node.getId(), partitionedSources.build(), outputToSourcesMapping.build()); return new PlanWithProperties( newNode, ActualProperties.builder() .global(partitionedOn(desiredParentPartitioning, Optional.of(desiredParentPartitioning))) .build() .withReplicatedNulls(parentPartitioningProperties.isNullsAndAnyReplicated())); } // case 2: parent doesn't provide preferred distributed partitioning, this could be one of the following cases: // * parentPartitioningPreference is Optional.empty() // * parentPartitioningPreference is present, but is single node distribution // * parentPartitioningPreference is present and is distributed, but does not have an explicit partitioning preference // first, classify children into single node and distributed List<PlanNode> singleNodeChildren = new ArrayList<>(); List<List<VariableReferenceExpression>> singleNodeOutputLayouts = new ArrayList<>(); List<PlanNode> distributedChildren = new ArrayList<>(); List<List<VariableReferenceExpression>> distributedOutputLayouts = new ArrayList<>(); for (int i = 0; i < node.getSources().size(); i++) { PlanWithProperties child = node.getSources().get(i).accept(this, PreferredProperties.any()); if (child.getProperties().isSingleNode()) { singleNodeChildren.add(child.getNode()); singleNodeOutputLayouts.add(node.sourceOutputLayout(i)); } else { distributedChildren.add(child.getNode()); // union may drop or duplicate symbols from the input so we must provide an exact mapping distributedOutputLayouts.add(node.sourceOutputLayout(i)); } } PlanNode result; if (!distributedChildren.isEmpty() && singleNodeChildren.isEmpty()) { // parent does not have preference or prefers some partitioning without any explicit partitioning - just use // children partitioning and don't GATHER partitioned inputs // TODO: add FIXED_ARBITRARY_DISTRIBUTION support on non empty singleNodeChildren if (!parentPartitioningPreference.isPresent() || parentPartitioningPreference.get().isDistributed()) { return arbitraryDistributeUnion(node, distributedChildren, distributedOutputLayouts); } // add a gathering exchange above partitioned inputs result = new ExchangeNode( idAllocator.getNextId(), GATHER, REMOTE_STREAMING, new PartitioningScheme(Partitioning.create(SINGLE_DISTRIBUTION, ImmutableList.of()), node.getOutputVariables()), distributedChildren, distributedOutputLayouts, Optional.empty()); } else if (!singleNodeChildren.isEmpty()) { if (!distributedChildren.isEmpty()) { // add a gathering exchange above partitioned inputs and fold it into the set of unpartitioned inputs // NOTE: new symbols for ExchangeNode output are required in order to keep plan logically correct with new local union below List<VariableReferenceExpression> exchangeOutputLayout = node.getOutputVariables().stream() .map(variableAllocator::newVariable) .collect(toImmutableList()); result = new ExchangeNode( idAllocator.getNextId(), GATHER, REMOTE_STREAMING, new PartitioningScheme(Partitioning.create(SINGLE_DISTRIBUTION, ImmutableList.of()), exchangeOutputLayout), distributedChildren, distributedOutputLayouts, Optional.empty()); singleNodeChildren.add(result); // TODO use result.getOutputVariable() after symbol to variable refactoring is done. This is a temporary hack since we know the value should be exchangeOutputLayout. singleNodeOutputLayouts.add(exchangeOutputLayout); } ImmutableListMultimap.Builder<VariableReferenceExpression, VariableReferenceExpression> mappings = ImmutableListMultimap.builder(); for (int i = 0; i < node.getOutputVariables().size(); i++) { for (List<VariableReferenceExpression> outputLayout : singleNodeOutputLayouts) { mappings.put(node.getOutputVariables().get(i), outputLayout.get(i)); } } // add local union for all unpartitioned inputs result = new UnionNode(node.getId(), singleNodeChildren, mappings.build()); } else { throw new IllegalStateException("both singleNodeChildren distributedChildren are empty"); } return new PlanWithProperties( result, ActualProperties.builder() .global(singleStreamPartition()) .build()); } private PlanWithProperties arbitraryDistributeUnion( UnionNode node, List<PlanNode> distributedChildren, List<List<VariableReferenceExpression>> distributedOutputLayouts) { // TODO: can we insert LOCAL exchange for one child SOURCE distributed and another HASH distributed? if (getNumberOfTableScans(distributedChildren) == 0 && isSameOrSystemCompatiblePartitions(extractRemoteExchangePartitioningHandles(distributedChildren))) { // No source distributed child, we can use insert LOCAL exchange // TODO: if all children have the same partitioning, pass this partitioning to the parent // instead of "arbitraryPartition". return new PlanWithProperties(node.replaceChildren(distributedChildren)); } else { // Presto currently can not execute stage that has multiple table scans, so in that case // we have to insert REMOTE exchange with FIXED_ARBITRARY_DISTRIBUTION instead of local exchange return new PlanWithProperties( new ExchangeNode( idAllocator.getNextId(), REPARTITION, REMOTE_STREAMING, new PartitioningScheme(Partitioning.create(FIXED_ARBITRARY_DISTRIBUTION, ImmutableList.of()), node.getOutputVariables()), distributedChildren, distributedOutputLayouts, Optional.empty())); } } @Override public PlanWithProperties visitApply(ApplyNode node, PreferredProperties preferredProperties) { throw new IllegalStateException("Unexpected node: " + node.getClass().getName()); } @Override public PlanWithProperties visitLateralJoin(LateralJoinNode node, PreferredProperties preferredProperties) { throw new IllegalStateException("Unexpected node: " + node.getClass().getName()); } private PlanWithProperties planChild(PlanNode node, PreferredProperties preferredProperties) { return getOnlyElement(node.getSources()).accept(this, preferredProperties); } private PlanWithProperties rebaseAndDeriveProperties(PlanNode node, PlanWithProperties child) { return withDerivedProperties( ChildReplacer.replaceChildren(node, ImmutableList.of(child.getNode())), child.getProperties()); } private PlanWithProperties rebaseAndDeriveProperties(PlanNode node, List<PlanWithProperties> children) { PlanNode result = node.replaceChildren( children.stream() .map(PlanWithProperties::getNode) .collect(toList())); return new PlanWithProperties(result, deriveProperties(result, children.stream().map(PlanWithProperties::getProperties).collect(toList()))); } private PlanWithProperties withDerivedProperties(PlanNode node, ActualProperties inputProperties) { return new PlanWithProperties(node, deriveProperties(node, inputProperties)); } private ActualProperties deriveProperties(PlanNode result, ActualProperties inputProperties) { return deriveProperties(result, ImmutableList.of(inputProperties)); } private ActualProperties deriveProperties(PlanNode result, List<ActualProperties> inputProperties) { // TODO: move this logic to PlanSanityChecker once PropertyDerivations.deriveProperties fully supports local exchanges ActualProperties outputProperties = PropertyDerivations.deriveProperties(result, inputProperties, metadata, session, types, parser); verify(result instanceof SemiJoinNode || inputProperties.stream().noneMatch(ActualProperties::isNullsAndAnyReplicated) || outputProperties.isNullsAndAnyReplicated(), "SemiJoinNode is the only node that can strip null replication"); return outputProperties; } private ActualProperties derivePropertiesRecursively(PlanNode result) { return PropertyDerivations.derivePropertiesRecursively(result, metadata, session, types, parser); } private Partitioning createPartitioning(List<VariableReferenceExpression> partitioningColumns) { // TODO: Use SystemTablesMetadata instead of introducing a special case if (GlobalSystemConnector.NAME.equals(partitioningProviderCatalog)) { return Partitioning.create(FIXED_HASH_DISTRIBUTION, ImmutableList.copyOf(partitioningColumns)); } List<Type> partitioningTypes = partitioningColumns.stream() .map(VariableReferenceExpression::getType) .collect(toImmutableList()); try { PartitioningHandle partitioningHandle = metadata.getPartitioningHandleForExchange(session, partitioningProviderCatalog, hashPartitionCount, partitioningTypes); return Partitioning.create(partitioningHandle, partitioningColumns); } catch (PrestoException e) { if (e.getErrorCode().equals(NOT_SUPPORTED.toErrorCode())) { throw new PrestoException( NOT_SUPPORTED, format( "Catalog \"%s\" cannot be used as a partitioning provider: %s", partitioningProviderCatalog, e.getMessage()), e); } throw e; } } // TODO: refactor this method into ExchangeNode#partitionedExchange once // materialized exchange is supported for all nodes. private Scope selectExchangeScopeForPartitionedRemoteExchange(PlanNode exchangeSource, boolean nullsAndAnyReplicated) { if (nullsAndAnyReplicated || exchangeSource.getOutputVariables().isEmpty()) { // materialized remote exchange is not supported when // * replicateNullsAndAny is needed // * materializing 0 columns input is not supported return REMOTE_STREAMING; } switch (exchangeMaterializationStrategy) { case ALL: return REMOTE_MATERIALIZED; case NONE: return REMOTE_STREAMING; default: throw new IllegalStateException("Unexpected exchange materialization strategy: " + exchangeMaterializationStrategy); } } } private boolean canPushdownPartialMerge(PlanNode node, PartialMergePushdownStrategy strategy) { switch (strategy) { case NONE: return false; case PUSH_THROUGH_LOW_MEMORY_OPERATORS: return canPushdownPartialMergeThroughLowMemoryOperators(node); default: throw new UnsupportedOperationException("Unsupported PartialMergePushdownStrategy: " + strategy); } } private boolean canPushdownPartialMergeThroughLowMemoryOperators(PlanNode node) { if (node instanceof TableScanNode) { return true; } if (node instanceof ExchangeNode && ((ExchangeNode) node).getScope() == REMOTE_MATERIALIZED) { return true; } // Don't pushdown partial merge through join and aggregations // since execution might requires more distributed memory. if (node instanceof JoinNode || node instanceof AggregationNode || node instanceof SemiJoinNode) { return false; } return node.getSources().stream() .allMatch(this::canPushdownPartialMergeThroughLowMemoryOperators); } public static Map<VariableReferenceExpression, VariableReferenceExpression> computeIdentityTranslations(Assignments assignments, TypeProvider types) { Map<VariableReferenceExpression, VariableReferenceExpression> outputToInput = new HashMap<>(); for (Map.Entry<VariableReferenceExpression, RowExpression> assignment : assignments.getMap().entrySet()) { if (castToExpression(assignment.getValue()) instanceof SymbolReference) { outputToInput.put(assignment.getKey(), toVariableReference(castToExpression(assignment.getValue()), types)); } } return outputToInput; } @VisibleForTesting static Comparator<ActualProperties> streamingExecutionPreference(PreferredProperties preferred) { // Calculating the matches can be a bit expensive, so cache the results between comparisons LoadingCache<List<LocalProperty<VariableReferenceExpression>>, List<Optional<LocalProperty<VariableReferenceExpression>>>> matchCache = CacheBuilder.newBuilder() .build(CacheLoader.from(actualProperties -> LocalProperties.match(actualProperties, preferred.getLocalProperties()))); return (actual1, actual2) -> { List<Optional<LocalProperty<VariableReferenceExpression>>> matchLayout1 = matchCache.getUnchecked(actual1.getLocalProperties()); List<Optional<LocalProperty<VariableReferenceExpression>>> matchLayout2 = matchCache.getUnchecked(actual2.getLocalProperties()); return ComparisonChain.start() .compareTrueFirst(hasLocalOptimization(preferred.getLocalProperties(), matchLayout1), hasLocalOptimization(preferred.getLocalProperties(), matchLayout2)) .compareTrueFirst(meetsPartitioningRequirements(preferred, actual1), meetsPartitioningRequirements(preferred, actual2)) .compare(matchLayout1, matchLayout2, matchedLayoutPreference()) .result(); }; } private static <T> boolean hasLocalOptimization(List<LocalProperty<T>> desiredLayout, List<Optional<LocalProperty<T>>> matchResult) { checkArgument(desiredLayout.size() == matchResult.size()); if (matchResult.isEmpty()) { return false; } // Optimizations can be applied if the first LocalProperty has been modified in the match in any way return !matchResult.get(0).equals(Optional.of(desiredLayout.get(0))); } private static boolean meetsPartitioningRequirements(PreferredProperties preferred, ActualProperties actual) { if (!preferred.getGlobalProperties().isPresent()) { return true; } PreferredProperties.Global preferredGlobal = preferred.getGlobalProperties().get(); if (!preferredGlobal.isDistributed()) { return actual.isSingleNode(); } if (!preferredGlobal.getPartitioningProperties().isPresent()) { return !actual.isSingleNode(); } return actual.isStreamPartitionedOn(preferredGlobal.getPartitioningProperties().get().getPartitioningColumns()); } // Prefer the match result that satisfied the most requirements private static <T> Comparator<List<Optional<LocalProperty<T>>>> matchedLayoutPreference() { return (matchLayout1, matchLayout2) -> { Iterator<Optional<LocalProperty<T>>> match1Iterator = matchLayout1.iterator(); Iterator<Optional<LocalProperty<T>>> match2Iterator = matchLayout2.iterator(); while (match1Iterator.hasNext() && match2Iterator.hasNext()) { Optional<LocalProperty<T>> match1 = match1Iterator.next(); Optional<LocalProperty<T>> match2 = match2Iterator.next(); if (match1.isPresent() && match2.isPresent()) { return Integer.compare(match1.get().getColumns().size(), match2.get().getColumns().size()); } else if (match1.isPresent()) { return 1; } else if (match2.isPresent()) { return -1; } } checkState(!match1Iterator.hasNext() && !match2Iterator.hasNext()); // Should be the same size return 0; }; } @VisibleForTesting static class PlanWithProperties { private final PlanNode node; private final ActualProperties properties; public PlanWithProperties(PlanNode node) { this(node, ActualProperties.builder().build()); } public PlanWithProperties(PlanNode node, ActualProperties properties) { this.node = node; this.properties = properties; } public PlanNode getNode() { return node; } public ActualProperties getProperties() { return properties; } } private static boolean isSameOrSystemCompatiblePartitions(List<PartitioningHandle> partitioningHandles) { for (int i = 0; i < partitioningHandles.size() - 1; i++) { PartitioningHandle first = partitioningHandles.get(i); PartitioningHandle second = partitioningHandles.get(i + 1); if (!first.equals(second) && !isCompatibleSystemPartitioning(first, second)) { return false; } } return true; } private static List<PartitioningHandle> extractRemoteExchangePartitioningHandles(List<PlanNode> nodes) { ImmutableList.Builder<PartitioningHandle> handles = ImmutableList.builder(); nodes.forEach(node -> node.accept(new ExchangePartitioningHandleExtractor(), handles)); return handles.build(); } private static class ExchangePartitioningHandleExtractor extends InternalPlanVisitor<Void, ImmutableList.Builder<PartitioningHandle>> { @Override public Void visitExchange(ExchangeNode node, ImmutableList.Builder<PartitioningHandle> handles) { checkArgument(node.getScope().isRemote(), "scope is expected to be remote: %s", node.getScope()); handles.add(node.getPartitioningScheme().getPartitioning().getHandle()); return null; } @Override public Void visitPlan(PlanNode node, ImmutableList.Builder<PartitioningHandle> handles) { for (PlanNode source : node.getSources()) { source.accept(this, handles); } return null; } } }
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.iotsitewise.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotsitewise-2019-12-02/DeleteTimeSeries" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteTimeSeriesRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The alias that identifies the time series. * </p> */ private String alias; /** * <p> * The ID of the asset in which the asset property was created. * </p> */ private String assetId; /** * <p> * The ID of the asset property. * </p> */ private String propertyId; /** * <p> * A unique case-sensitive identifier that you can provide to ensure the idempotency of the request. Don't reuse * this client token if a new idempotent request is required. * </p> */ private String clientToken; /** * <p> * The alias that identifies the time series. * </p> * * @param alias * The alias that identifies the time series. */ public void setAlias(String alias) { this.alias = alias; } /** * <p> * The alias that identifies the time series. * </p> * * @return The alias that identifies the time series. */ public String getAlias() { return this.alias; } /** * <p> * The alias that identifies the time series. * </p> * * @param alias * The alias that identifies the time series. * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteTimeSeriesRequest withAlias(String alias) { setAlias(alias); return this; } /** * <p> * The ID of the asset in which the asset property was created. * </p> * * @param assetId * The ID of the asset in which the asset property was created. */ public void setAssetId(String assetId) { this.assetId = assetId; } /** * <p> * The ID of the asset in which the asset property was created. * </p> * * @return The ID of the asset in which the asset property was created. */ public String getAssetId() { return this.assetId; } /** * <p> * The ID of the asset in which the asset property was created. * </p> * * @param assetId * The ID of the asset in which the asset property was created. * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteTimeSeriesRequest withAssetId(String assetId) { setAssetId(assetId); return this; } /** * <p> * The ID of the asset property. * </p> * * @param propertyId * The ID of the asset property. */ public void setPropertyId(String propertyId) { this.propertyId = propertyId; } /** * <p> * The ID of the asset property. * </p> * * @return The ID of the asset property. */ public String getPropertyId() { return this.propertyId; } /** * <p> * The ID of the asset property. * </p> * * @param propertyId * The ID of the asset property. * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteTimeSeriesRequest withPropertyId(String propertyId) { setPropertyId(propertyId); return this; } /** * <p> * A unique case-sensitive identifier that you can provide to ensure the idempotency of the request. Don't reuse * this client token if a new idempotent request is required. * </p> * * @param clientToken * A unique case-sensitive identifier that you can provide to ensure the idempotency of the request. Don't * reuse this client token if a new idempotent request is required. */ public void setClientToken(String clientToken) { this.clientToken = clientToken; } /** * <p> * A unique case-sensitive identifier that you can provide to ensure the idempotency of the request. Don't reuse * this client token if a new idempotent request is required. * </p> * * @return A unique case-sensitive identifier that you can provide to ensure the idempotency of the request. Don't * reuse this client token if a new idempotent request is required. */ public String getClientToken() { return this.clientToken; } /** * <p> * A unique case-sensitive identifier that you can provide to ensure the idempotency of the request. Don't reuse * this client token if a new idempotent request is required. * </p> * * @param clientToken * A unique case-sensitive identifier that you can provide to ensure the idempotency of the request. Don't * reuse this client token if a new idempotent request is required. * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteTimeSeriesRequest withClientToken(String clientToken) { setClientToken(clientToken); 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 (getAlias() != null) sb.append("Alias: ").append(getAlias()).append(","); if (getAssetId() != null) sb.append("AssetId: ").append(getAssetId()).append(","); if (getPropertyId() != null) sb.append("PropertyId: ").append(getPropertyId()).append(","); if (getClientToken() != null) sb.append("ClientToken: ").append(getClientToken()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteTimeSeriesRequest == false) return false; DeleteTimeSeriesRequest other = (DeleteTimeSeriesRequest) obj; if (other.getAlias() == null ^ this.getAlias() == null) return false; if (other.getAlias() != null && other.getAlias().equals(this.getAlias()) == false) return false; if (other.getAssetId() == null ^ this.getAssetId() == null) return false; if (other.getAssetId() != null && other.getAssetId().equals(this.getAssetId()) == false) return false; if (other.getPropertyId() == null ^ this.getPropertyId() == null) return false; if (other.getPropertyId() != null && other.getPropertyId().equals(this.getPropertyId()) == false) return false; if (other.getClientToken() == null ^ this.getClientToken() == null) return false; if (other.getClientToken() != null && other.getClientToken().equals(this.getClientToken()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAlias() == null) ? 0 : getAlias().hashCode()); hashCode = prime * hashCode + ((getAssetId() == null) ? 0 : getAssetId().hashCode()); hashCode = prime * hashCode + ((getPropertyId() == null) ? 0 : getPropertyId().hashCode()); hashCode = prime * hashCode + ((getClientToken() == null) ? 0 : getClientToken().hashCode()); return hashCode; } @Override public DeleteTimeSeriesRequest clone() { return (DeleteTimeSeriesRequest) super.clone(); } }
/* * Copyright 2011 gitblit.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.gitblit.wicket.pages; import java.io.Serializable; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.wicket.Component; import org.apache.wicket.PageParameters; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.link.ExternalLink; import org.apache.wicket.markup.html.panel.Fragment; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.protocol.http.RequestUtils; import org.apache.wicket.request.target.basic.RedirectRequestTarget; import org.eclipse.jgit.diff.DiffEntry.ChangeType; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import com.gitblit.Constants; import com.gitblit.GitBlit; import com.gitblit.Keys; import com.gitblit.PagesServlet; import com.gitblit.SyndicationServlet; import com.gitblit.models.ProjectModel; import com.gitblit.models.RefModel; import com.gitblit.models.RepositoryModel; import com.gitblit.models.SubmoduleModel; import com.gitblit.models.UserModel; import com.gitblit.utils.ArrayUtils; import com.gitblit.utils.JGitUtils; import com.gitblit.utils.StringUtils; import com.gitblit.utils.TicgitUtils; import com.gitblit.wicket.GitBlitWebSession; import com.gitblit.wicket.PageRegistration; import com.gitblit.wicket.PageRegistration.OtherPageLink; import com.gitblit.wicket.SessionlessForm; import com.gitblit.wicket.WicketUtils; import com.gitblit.wicket.panels.LinkPanel; import com.gitblit.wicket.panels.NavigationPanel; import com.gitblit.wicket.panels.RefsPanel; public abstract class RepositoryPage extends BasePage { protected final String projectName; protected final String repositoryName; protected final String objectId; private transient Repository r; private RepositoryModel m; private Map<String, SubmoduleModel> submodules; private final Map<String, PageRegistration> registeredPages; private boolean showAdmin; private boolean isOwner; public RepositoryPage(PageParameters params) { super(params); repositoryName = WicketUtils.getRepositoryName(params); String root =StringUtils.getFirstPathElement(repositoryName); if (StringUtils.isEmpty(root)) { projectName = GitBlit.getString(Keys.web.repositoryRootGroupName, "main"); } else { projectName = root; } objectId = WicketUtils.getObject(params); if (StringUtils.isEmpty(repositoryName)) { error(MessageFormat.format(getString("gb.repositoryNotSpecifiedFor"), getPageName()), true); } if (!getRepositoryModel().hasCommits) { setResponsePage(EmptyRepositoryPage.class, params); } if (getRepositoryModel().isCollectingGarbage) { error(MessageFormat.format(getString("gb.busyCollectingGarbage"), getRepositoryModel().name), true); } if (objectId != null) { RefModel branch = null; if ((branch = JGitUtils.getBranch(getRepository(), objectId)) != null) { UserModel user = GitBlitWebSession.get().getUser(); if (user == null) { // workaround until get().getUser() is reviewed throughout the app user = UserModel.ANONYMOUS; } boolean canAccess = user.canView(getRepositoryModel(), branch.reference.getName()); if (!canAccess) { error(getString("gb.accessDenied"), true); } } } // register the available page links for this page and user registeredPages = registerPages(); // standard page links List<PageRegistration> pages = new ArrayList<PageRegistration>(registeredPages.values()); NavigationPanel navigationPanel = new NavigationPanel("navPanel", getClass(), pages); add(navigationPanel); add(new ExternalLink("syndication", SyndicationServlet.asLink(getRequest() .getRelativePathPrefixToContextRoot(), repositoryName, null, 0))); // add floating search form SearchForm searchForm = new SearchForm("searchForm", repositoryName); add(searchForm); searchForm.setTranslatedAttributes(); // set stateless page preference setStatelessHint(true); } private Map<String, PageRegistration> registerPages() { PageParameters params = null; if (!StringUtils.isEmpty(repositoryName)) { params = WicketUtils.newRepositoryParameter(repositoryName); } Map<String, PageRegistration> pages = new LinkedHashMap<String, PageRegistration>(); // standard links pages.put("repositories", new PageRegistration("gb.repositories", RepositoriesPage.class)); pages.put("summary", new PageRegistration("gb.summary", SummaryPage.class, params)); pages.put("log", new PageRegistration("gb.log", LogPage.class, params)); pages.put("branches", new PageRegistration("gb.branches", BranchesPage.class, params)); pages.put("tags", new PageRegistration("gb.tags", TagsPage.class, params)); pages.put("tree", new PageRegistration("gb.tree", TreePage.class, params)); if (GitBlit.getBoolean(Keys.web.allowForking, true)) { pages.put("forks", new PageRegistration("gb.forks", ForksPage.class, params)); } // conditional links Repository r = getRepository(); RepositoryModel model = getRepositoryModel(); // per-repository extra page links if (model.useTickets && TicgitUtils.getTicketsBranch(r) != null) { pages.put("tickets", new PageRegistration("gb.tickets", TicketsPage.class, params)); } if (model.useDocs) { pages.put("docs", new PageRegistration("gb.docs", DocsPage.class, params)); } if (JGitUtils.getPagesBranch(r) != null) { OtherPageLink pagesLink = new OtherPageLink("gb.pages", PagesServlet.asLink( getRequest().getRelativePathPrefixToContextRoot(), repositoryName, null)); pages.put("pages", pagesLink); } // Conditionally add edit link showAdmin = false; if (GitBlit.getBoolean(Keys.web.authenticateAdminPages, true)) { boolean allowAdmin = GitBlit.getBoolean(Keys.web.allowAdministration, false); showAdmin = allowAdmin && GitBlitWebSession.get().canAdmin(); } else { showAdmin = GitBlit.getBoolean(Keys.web.allowAdministration, false); } isOwner = GitBlitWebSession.get().isLoggedIn() && (model.isOwner(GitBlitWebSession.get() .getUsername())); if (showAdmin || isOwner) { pages.put("edit", new PageRegistration("gb.edit", EditRepositoryPage.class, params)); } return pages; } protected boolean allowForkControls() { return GitBlit.getBoolean(Keys.web.allowForking, true); } @Override protected void setupPage(String repositoryName, String pageName) { String projectName = StringUtils.getFirstPathElement(repositoryName); ProjectModel project = GitBlit.self().getProjectModel(projectName); if (project.isUserProject()) { // user-as-project add(new LinkPanel("projectTitle", null, project.getDisplayName(), UserPage.class, WicketUtils.newUsernameParameter(project.name.substring(1)))); } else { // project add(new LinkPanel("projectTitle", null, project.name, ProjectPage.class, WicketUtils.newProjectParameter(project.name))); } String name = StringUtils.stripDotGit(repositoryName); if (!StringUtils.isEmpty(projectName) && name.startsWith(projectName)) { name = name.substring(projectName.length() + 1); } add(new LinkPanel("repositoryName", null, name, SummaryPage.class, WicketUtils.newRepositoryParameter(repositoryName))); add(new Label("pageName", pageName).setRenderBodyOnly(true)); UserModel user = GitBlitWebSession.get().getUser(); if (user == null) { user = UserModel.ANONYMOUS; } // indicate origin repository RepositoryModel model = getRepositoryModel(); if (StringUtils.isEmpty(model.originRepository)) { add(new Label("originRepository").setVisible(false)); } else { RepositoryModel origin = GitBlit.self().getRepositoryModel(model.originRepository); if (origin == null) { // no origin repository add(new Label("originRepository").setVisible(false)); } else if (!user.canView(origin)) { // show origin repository without link Fragment forkFrag = new Fragment("originRepository", "originFragment", this); forkFrag.add(new Label("originRepository", StringUtils.stripDotGit(model.originRepository))); add(forkFrag); } else { // link to origin repository Fragment forkFrag = new Fragment("originRepository", "originFragment", this); forkFrag.add(new LinkPanel("originRepository", null, StringUtils.stripDotGit(model.originRepository), SummaryPage.class, WicketUtils.newRepositoryParameter(model.originRepository))); add(forkFrag); } } // show sparkleshare folder icon if (model.isSparkleshared()) { add(WicketUtils.newImage("repositoryIcon", "folder_star_32x32.png", getString("gb.isSparkleshared"))); } else { add(WicketUtils.newClearPixel("repositoryIcon").setVisible(false)); } if (getRepositoryModel().isBare) { add(new Label("workingCopyIndicator").setVisible(false)); } else { Fragment wc = new Fragment("workingCopyIndicator", "workingCopyFragment", this); Label lbl = new Label("workingCopy", getString("gb.workingCopy")); WicketUtils.setHtmlTooltip(lbl, getString("gb.workingCopyWarning")); wc.add(lbl); add(wc); } // fork controls if (!allowForkControls() || user == null || !user.isAuthenticated) { // must be logged-in to fork, hide all fork controls add(new ExternalLink("forkLink", "").setVisible(false)); add(new ExternalLink("myForkLink", "").setVisible(false)); add(new Label("forksProhibitedIndicator").setVisible(false)); } else { String fork = GitBlit.self().getFork(user.username, model.name); boolean hasFork = fork != null; boolean canFork = user.canFork(model); if (hasFork || !canFork) { // user not allowed to fork or fork already exists or repo forbids forking add(new ExternalLink("forkLink", "").setVisible(false)); if (user.canFork() && !model.allowForks) { // show forks prohibited indicator Fragment wc = new Fragment("forksProhibitedIndicator", "forksProhibitedFragment", this); Label lbl = new Label("forksProhibited", getString("gb.forksProhibited")); WicketUtils.setHtmlTooltip(lbl, getString("gb.forksProhibitedWarning")); wc.add(lbl); add(wc); } else { // can not fork, no need for forks prohibited indicator add(new Label("forksProhibitedIndicator").setVisible(false)); } if (hasFork && !fork.equals(model.name)) { // user has fork, view my fork link String url = getRequestCycle().urlFor(SummaryPage.class, WicketUtils.newRepositoryParameter(fork)).toString(); add(new ExternalLink("myForkLink", url)); } else { // no fork, hide view my fork link add(new ExternalLink("myForkLink", "").setVisible(false)); } } else if (canFork) { // can fork and we do not have one add(new Label("forksProhibitedIndicator").setVisible(false)); add(new ExternalLink("myForkLink", "").setVisible(false)); String url = getRequestCycle().urlFor(ForkPage.class, WicketUtils.newRepositoryParameter(model.name)).toString(); add(new ExternalLink("forkLink", url)); } } super.setupPage(repositoryName, pageName); } protected void addSyndicationDiscoveryLink() { add(WicketUtils.syndicationDiscoveryLink(SyndicationServlet.getTitle(repositoryName, objectId), SyndicationServlet.asLink(getRequest() .getRelativePathPrefixToContextRoot(), repositoryName, objectId, 0))); } protected Repository getRepository() { if (r == null) { Repository r = GitBlit.self().getRepository(repositoryName); if (r == null) { error(getString("gb.canNotLoadRepository") + " " + repositoryName, true); return null; } this.r = r; } return r; } protected RepositoryModel getRepositoryModel() { if (m == null) { RepositoryModel model = GitBlit.self().getRepositoryModel( GitBlitWebSession.get().getUser(), repositoryName); if (model == null) { if (GitBlit.self().hasRepository(repositoryName, true)) { // has repository, but unauthorized authenticationError(getString("gb.unauthorizedAccessForRepository") + " " + repositoryName); } else { // does not have repository error(getString("gb.canNotLoadRepository") + " " + repositoryName, true); } return null; } m = model; } return m; } protected RevCommit getCommit() { RevCommit commit = JGitUtils.getCommit(r, objectId); if (commit == null) { error(MessageFormat.format(getString("gb.failedToFindCommit"), objectId, repositoryName, getPageName()), true); } getSubmodules(commit); return commit; } private Map<String, SubmoduleModel> getSubmodules(RevCommit commit) { if (submodules == null) { submodules = new HashMap<String, SubmoduleModel>(); for (SubmoduleModel model : JGitUtils.getSubmodules(r, commit.getTree())) { submodules.put(model.path, model); } } return submodules; } protected SubmoduleModel getSubmodule(String path) { SubmoduleModel model = submodules.get(path); if (model == null) { // undefined submodule?! model = new SubmoduleModel(path.substring(path.lastIndexOf('/') + 1), path, path); model.hasSubmodule = false; model.gitblitPath = model.name; return model; } else { // extract the repository name from the clone url List<String> patterns = GitBlit.getStrings(Keys.git.submoduleUrlPatterns); String submoduleName = StringUtils.extractRepositoryPath(model.url, patterns.toArray(new String[0])); // determine the current path for constructing paths relative // to the current repository String currentPath = ""; if (repositoryName.indexOf('/') > -1) { currentPath = repositoryName.substring(0, repositoryName.lastIndexOf('/') + 1); } // try to locate the submodule repository // prefer bare to non-bare names List<String> candidates = new ArrayList<String>(); // relative candidates.add(currentPath + StringUtils.stripDotGit(submoduleName)); candidates.add(candidates.get(candidates.size() - 1) + ".git"); // relative, no subfolder if (submoduleName.lastIndexOf('/') > -1) { String name = submoduleName.substring(submoduleName.lastIndexOf('/') + 1); candidates.add(currentPath + StringUtils.stripDotGit(name)); candidates.add(currentPath + candidates.get(candidates.size() - 1) + ".git"); } // absolute candidates.add(StringUtils.stripDotGit(submoduleName)); candidates.add(candidates.get(candidates.size() - 1) + ".git"); // absolute, no subfolder if (submoduleName.lastIndexOf('/') > -1) { String name = submoduleName.substring(submoduleName.lastIndexOf('/') + 1); candidates.add(StringUtils.stripDotGit(name)); candidates.add(candidates.get(candidates.size() - 1) + ".git"); } // create a unique, ordered set of candidate paths Set<String> paths = new LinkedHashSet<String>(candidates); for (String candidate : paths) { if (GitBlit.self().hasRepository(candidate)) { model.hasSubmodule = true; model.gitblitPath = candidate; return model; } } // we do not have a copy of the submodule, but we need a path model.gitblitPath = candidates.get(0); return model; } } protected String getShortObjectId(String objectId) { return objectId.substring(0, GitBlit.getInteger(Keys.web.shortCommitIdLength, 6)); } protected void addRefs(Repository r, RevCommit c) { add(new RefsPanel("refsPanel", repositoryName, c, JGitUtils.getAllRefs(r, getRepositoryModel().showRemoteBranches))); } protected void addFullText(String wicketId, String text, boolean substituteRegex) { String html = StringUtils.escapeForHtml(text, true); if (substituteRegex) { html = GitBlit.self().processCommitMessage(repositoryName, text); } else { html = StringUtils.breakLinesForHtml(html); } add(new Label(wicketId, html).setEscapeModelStrings(false)); } protected abstract String getPageName(); protected Component createPersonPanel(String wicketId, PersonIdent identity, Constants.SearchType searchType) { String name = identity == null ? "" : identity.getName(); String address = identity == null ? "" : identity.getEmailAddress(); name = StringUtils.removeNewlines(name); address = StringUtils.removeNewlines(address); boolean showEmail = GitBlit.getBoolean(Keys.web.showEmailAddresses, false); if (!showEmail || StringUtils.isEmpty(name) || StringUtils.isEmpty(address)) { String value = name; if (StringUtils.isEmpty(value)) { if (showEmail) { value = address; } else { value = getString("gb.missingUsername"); } } Fragment partial = new Fragment(wicketId, "partialPersonIdent", this); LinkPanel link = new LinkPanel("personName", "list", value, GitSearchPage.class, WicketUtils.newSearchParameter(repositoryName, objectId, value, searchType)); setPersonSearchTooltip(link, value, searchType); partial.add(link); return partial; } else { Fragment fullPerson = new Fragment(wicketId, "fullPersonIdent", this); LinkPanel nameLink = new LinkPanel("personName", "list", name, GitSearchPage.class, WicketUtils.newSearchParameter(repositoryName, objectId, name, searchType)); setPersonSearchTooltip(nameLink, name, searchType); fullPerson.add(nameLink); LinkPanel addressLink = new LinkPanel("personAddress", "hidden-phone list", "<" + address + ">", GitSearchPage.class, WicketUtils.newSearchParameter(repositoryName, objectId, address, searchType)); setPersonSearchTooltip(addressLink, address, searchType); fullPerson.add(addressLink); return fullPerson; } } protected void setPersonSearchTooltip(Component component, String value, Constants.SearchType searchType) { if (searchType.equals(Constants.SearchType.AUTHOR)) { WicketUtils.setHtmlTooltip(component, getString("gb.searchForAuthor") + " " + value); } else if (searchType.equals(Constants.SearchType.COMMITTER)) { WicketUtils.setHtmlTooltip(component, getString("gb.searchForCommitter") + " " + value); } } protected void setChangeTypeTooltip(Component container, ChangeType type) { switch (type) { case ADD: WicketUtils.setHtmlTooltip(container, getString("gb.addition")); break; case COPY: case RENAME: WicketUtils.setHtmlTooltip(container, getString("gb.rename")); break; case DELETE: WicketUtils.setHtmlTooltip(container, getString("gb.deletion")); break; case MODIFY: WicketUtils.setHtmlTooltip(container, getString("gb.modification")); break; } } @Override protected void onBeforeRender() { // dispose of repository object if (r != null) { r.close(); r = null; } // setup page header and footer setupPage(repositoryName, "/ " + getPageName()); super.onBeforeRender(); } protected PageParameters newRepositoryParameter() { return WicketUtils.newRepositoryParameter(repositoryName); } protected PageParameters newCommitParameter() { return WicketUtils.newObjectParameter(repositoryName, objectId); } protected PageParameters newCommitParameter(String commitId) { return WicketUtils.newObjectParameter(repositoryName, commitId); } public boolean isShowAdmin() { return showAdmin; } public boolean isOwner() { return isOwner; } private class SearchForm extends SessionlessForm<Void> implements Serializable { private static final long serialVersionUID = 1L; private final String repositoryName; private final IModel<String> searchBoxModel = new Model<String>(""); private final IModel<Constants.SearchType> searchTypeModel = new Model<Constants.SearchType>( Constants.SearchType.COMMIT); public SearchForm(String id, String repositoryName) { super(id, RepositoryPage.this.getClass(), RepositoryPage.this.getPageParameters()); this.repositoryName = repositoryName; DropDownChoice<Constants.SearchType> searchType = new DropDownChoice<Constants.SearchType>( "searchType", Arrays.asList(Constants.SearchType.values())); searchType.setModel(searchTypeModel); add(searchType.setVisible(GitBlit.getBoolean(Keys.web.showSearchTypeSelection, false))); TextField<String> searchBox = new TextField<String>("searchBox", searchBoxModel); add(searchBox); } void setTranslatedAttributes() { WicketUtils.setHtmlTooltip(get("searchType"), getString("gb.searchTypeTooltip")); WicketUtils.setHtmlTooltip(get("searchBox"), MessageFormat.format(getString("gb.searchTooltip"), repositoryName)); WicketUtils.setInputPlaceholder(get("searchBox"), getString("gb.search")); } @Override public void onSubmit() { Constants.SearchType searchType = searchTypeModel.getObject(); String searchString = searchBoxModel.getObject(); if (searchString == null) { return; } for (Constants.SearchType type : Constants.SearchType.values()) { if (searchString.toLowerCase().startsWith(type.name().toLowerCase() + ":")) { searchType = type; searchString = searchString.substring(type.name().toLowerCase().length() + 1) .trim(); break; } } Class<? extends BasePage> searchPageClass = GitSearchPage.class; RepositoryModel model = GitBlit.self().getRepositoryModel(repositoryName); if (GitBlit.getBoolean(Keys.web.allowLuceneIndexing, true) && !ArrayUtils.isEmpty(model.indexedBranches)) { // this repository is Lucene-indexed searchPageClass = LuceneSearchPage.class; } // use an absolute url to workaround Wicket-Tomcat problems with // mounted url parameters (issue-111) PageParameters params = WicketUtils.newSearchParameter(repositoryName, null, searchString, searchType); String relativeUrl = urlFor(searchPageClass, params).toString(); String absoluteUrl = RequestUtils.toAbsolutePath(relativeUrl); getRequestCycle().setRequestTarget(new RedirectRequestTarget(absoluteUrl)); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.spi.security.authorization.accesscontrol; import java.security.Principal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import javax.jcr.AccessDeniedException; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.security.AccessControlException; import javax.jcr.security.AccessControlPolicy; import javax.jcr.security.AccessControlPolicyIterator; import javax.jcr.security.Privilege; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.apache.jackrabbit.api.security.JackrabbitAccessControlPolicy; import org.apache.jackrabbit.api.security.authorization.PrivilegeManager; import org.apache.jackrabbit.oak.api.ContentSession; import org.apache.jackrabbit.oak.api.Root; import org.apache.jackrabbit.oak.api.Tree; import org.apache.jackrabbit.oak.namepath.NamePathMapper; import org.apache.jackrabbit.oak.spi.security.Context; import org.apache.jackrabbit.oak.spi.security.SecurityProvider; import org.apache.jackrabbit.oak.spi.security.authentication.AuthInfoImpl; import org.apache.jackrabbit.oak.spi.security.authorization.AuthorizationConfiguration; import org.apache.jackrabbit.oak.spi.security.authorization.permission.EmptyPermissionProvider; import org.apache.jackrabbit.oak.spi.security.authorization.permission.OpenPermissionProvider; import org.apache.jackrabbit.oak.spi.security.authorization.permission.Permissions; import org.apache.jackrabbit.oak.spi.security.principal.EveryonePrincipal; import org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConfiguration; import org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConstants; import org.jetbrains.annotations.NotNull; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class AbstractAccessControlManagerTest extends AbstractAccessControlTest { private static final String WSP_NAME = "wspName"; public static final String TEST_PREFIX = "jr"; private final String testName = TEST_PREFIX + ":testRoot"; private final String testPath = '/' + testName; private final String nonExistingPath = "/not/existing"; private final Set<Principal> testPrincipals = ImmutableSet.of(testPrincipal); private Privilege[] testPrivileges; private Privilege[] allPrivileges; private AbstractAccessControlManager acMgr; private PrivilegeManager privilegeManager; private AuthorizationConfiguration authorizationConfiguration; private SecurityProvider securityProvider; private ContentSession cs; @Before public void before() throws Exception { testPrivileges = new Privilege[] {mockPrivilege("priv1"), mockPrivilege("priv2")}; allPrivileges = new Privilege[] {mockPrivilege(PrivilegeConstants.JCR_ALL)}; cs = Mockito.mock(ContentSession.class); when(cs.getWorkspaceName()).thenReturn(WSP_NAME); when(cs.getAuthInfo()).thenReturn(new AuthInfoImpl(null, ImmutableMap.of(), testPrincipals)); when(root.getContentSession()).thenReturn(cs); Tree nonExistingTree = Mockito.mock(Tree.class); when(nonExistingTree.exists()).thenReturn(false); when(root.getTree(nonExistingPath)).thenReturn(nonExistingTree); Tree existingTree = Mockito.mock(Tree.class); when(existingTree.exists()).thenReturn(true); when(root.getTree(testPath)).thenReturn(existingTree); Tree rootTree = Mockito.mock(Tree.class); when(rootTree.exists()).thenReturn(true); when(root.getTree("/")).thenReturn(rootTree); privilegeManager = Mockito.mock(PrivilegeManager.class); when(privilegeManager.getRegisteredPrivileges()).thenReturn(testPrivileges); when(privilegeManager.getPrivilege("priv1")).thenReturn(testPrivileges[0]); when(privilegeManager.getPrivilege("priv2")).thenReturn(testPrivileges[1]); when(privilegeManager.getPrivilege(PrivilegeConstants.JCR_ALL)).thenReturn(allPrivileges[0]); PrivilegeConfiguration privilegeConfiguration = Mockito.mock(PrivilegeConfiguration.class); when(privilegeConfiguration.getPrivilegeManager(root, getNamePathMapper())).thenReturn(privilegeManager); authorizationConfiguration = Mockito.mock(AuthorizationConfiguration.class); when(authorizationConfiguration.getPermissionProvider(root, WSP_NAME, getEveryonePrincipalSet())).thenReturn(EmptyPermissionProvider.getInstance()); when(authorizationConfiguration.getPermissionProvider(root, WSP_NAME, testPrincipals)).thenReturn(OpenPermissionProvider.getInstance()); when(authorizationConfiguration.getPermissionProvider(root, WSP_NAME, ImmutableSet.of())).thenReturn(EmptyPermissionProvider.getInstance()); when(authorizationConfiguration.getContext()).thenReturn(Context.DEFAULT); securityProvider = Mockito.mock(SecurityProvider.class); when(securityProvider.getConfiguration(PrivilegeConfiguration.class)).thenReturn(privilegeConfiguration); when(securityProvider.getConfiguration(AuthorizationConfiguration.class)).thenReturn(authorizationConfiguration); acMgr = createAccessControlManager(root, getNamePathMapper()); } private AbstractAccessControlManager createAccessControlManager(@NotNull Root root, @NotNull NamePathMapper namePathMapper) { return new TestAcMgr(root, namePathMapper, securityProvider); } private static List<String> getInvalidPaths() { List<String> invalid = new ArrayList<>(); invalid.add(""); invalid.add("../../jcr:testRoot"); invalid.add("jcr:testRoot"); invalid.add("jcr:test/Root"); invalid.add("./jcr:testRoot"); return invalid; } private static Privilege mockPrivilege(@NotNull String name) { Privilege p = Mockito.mock(Privilege.class); when(p.getName()).thenReturn(name); return p; } private static Set<Principal> getEveryonePrincipalSet() { return ImmutableSet.<Principal>of(EveryonePrincipal.getInstance()); } //--------------------------------------------------- protected methods >--- @Test public void testGetConfig() { assertSame(authorizationConfiguration, acMgr.getConfig()); } @Test public void testGetRoot() { assertSame(root, createAccessControlManager(root, getNamePathMapper()).getRoot()); } @Test public void testGetLatestRoot() { assertNotSame(root, createAccessControlManager(root, getNamePathMapper()).getLatestRoot()); } @Test public void testGetNamePathMapper() { assertSame(getNamePathMapper(), createAccessControlManager(root, getNamePathMapper()).getNamePathMapper()); } @Test public void testGetPrivilegeManager() { assertSame(privilegeManager, acMgr.getPrivilegeManager()); } @Test public void testGetOakPathNull() throws Exception { assertNull(acMgr.getOakPath(null)); } @Test(expected = RepositoryException.class) public void testGetOakPathNotAbsolute() throws Exception { acMgr.getOakPath("a/rel/path"); } @Test(expected = RepositoryException.class) public void testGetOakPathInvalid() throws Exception { NamePathMapper np = new NamePathMapper.Default() { @Override public String getOakPath(String jcrPath) { // mock failing conversion from jcr to oak path return null; } }; createAccessControlManager(root, np).getOakPath("/any/abs/path"); } @Test public void testGetTreeTestPath() throws Exception { assertNotNull(acMgr.getTree(testPath, Permissions.NO_PERMISSION, false)); assertNotNull(acMgr.getTree(testPath, Permissions.NO_PERMISSION, true)); } @Test(expected = PathNotFoundException.class) public void testGetTreeNonExstingPath() throws Exception { acMgr.getTree(nonExistingPath, Permissions.NO_PERMISSION, false); } @Test public void testGetTreeNullPath() throws Exception { assertNotNull(acMgr.getTree(null, Permissions.NO_PERMISSION, false)); } @Test public void testGetTreeNullPathCheckPermission() throws Exception { assertNotNull(acMgr.getTree(null, Permissions.ALL, false)); } @Test(expected = AccessControlException.class) public void testGetTreeDefinesAcContent() throws Exception { Context ctx = new Context.Default() { @Override public boolean definesTree(@NotNull Tree tree) { return true; } }; when(authorizationConfiguration.getContext()).thenReturn(ctx); acMgr.getTree(testPath, Permissions.NO_PERMISSION, true); } @Test(expected = AccessDeniedException.class) public void testGetTreeDefinesNoAccess() throws Exception { when(cs.getAuthInfo()).thenReturn(new AuthInfoImpl(null, ImmutableMap.of(), getEveryonePrincipalSet())); AbstractAccessControlManager mgr = createAccessControlManager(root, getNamePathMapper()); mgr.getTree(testPath, Permissions.ALL, true); } //---------------------------------------------< getSupportedPrivileges >--- @Test public void testGetSupportedPrivileges() throws Exception { List<Privilege> allPrivileges = Arrays.asList(privilegeManager.getRegisteredPrivileges()); Privilege[] supported = acMgr.getSupportedPrivileges(testPath); assertNotNull(supported); assertEquals(allPrivileges.size(), supported.length); assertTrue(allPrivileges.containsAll(Arrays.asList(supported))); } @Test public void testGetSupportedPrivilegesInvalidPath() { for (String path : getInvalidPaths()) { try { acMgr.getSupportedPrivileges(path); fail("Expects valid node path, found: " + path); } catch (RepositoryException e) { // success } } } @Test(expected = PathNotFoundException.class) public void testGetSupportedPrivilegesNonExistingPath() throws Exception { acMgr.getSupportedPrivileges(nonExistingPath); } //--------------------------------------------------< privilegeFromName >--- @Test public void testPrivilegeFromName() throws Exception { List<Privilege> allPrivileges = Arrays.asList(privilegeManager.getRegisteredPrivileges()); for (Privilege privilege : allPrivileges) { Privilege p = acMgr.privilegeFromName(privilege.getName()); assertEquals(privilege, p); } } //------------------------------------------------------< hasPrivileges >--- @Test public void testHasNullPrivileges() throws Exception { assertTrue(acMgr.hasPrivileges(testPath, null)); } @Test public void testHasEmptyPrivileges() throws Exception { assertTrue(acMgr.hasPrivileges(testPath, new Privilege[0])); } @Test(expected = PathNotFoundException.class) public void testHasPrivilegesNonExistingNodePath() throws Exception { acMgr.hasPrivileges(nonExistingPath, testPrivileges); } @Test(expected = PathNotFoundException.class) public void testHasPrivilegesNonExistingNodePathEveryoneSet() throws Exception { acMgr.hasPrivileges(nonExistingPath, getEveryonePrincipalSet(), testPrivileges); } @Test(expected = PathNotFoundException.class) public void testHasPrivilegesNonExistingNodePathEmptyPrincipalSet() throws Exception { acMgr.hasPrivileges(nonExistingPath, ImmutableSet.<Principal>of(), testPrivileges); } @Test public void testHasPrivilegesInvalidPaths() { for (String path : getInvalidPaths()) { try { acMgr.hasPrivileges(path, testPrivileges); fail("AccessControlManager#hasPrivileges for node that doesn't exist should fail."); } catch (RepositoryException e) { // success } } } @Test public void testHasPrivileges() throws Exception { assertTrue(acMgr.hasPrivileges(testPath, allPrivileges)); } @Test public void testHasPrivilegesSessionSet() throws Exception { assertTrue(acMgr.hasPrivileges(testPath, testPrincipals, allPrivileges)); } @Test public void testHasPrivilegesInvalidPathsEveryoneSet() { for (String path : getInvalidPaths()) { try { acMgr.hasPrivileges(path, ImmutableSet.<Principal>of(EveryonePrincipal.getInstance()), testPrivileges); fail("AccessControlManager#hasPrivileges for node that doesn't exist should fail."); } catch (RepositoryException e) { // success } } } @Test public void testHasRepoPrivileges() throws Exception { assertTrue(acMgr.hasPrivileges(null, testPrivileges)); } @Test public void testHasRepoPrivilegesEveryoneSet() throws Exception { assertFalse(acMgr.hasPrivileges(null, getEveryonePrincipalSet(), testPrivileges)); } @Test public void testHasRepoPrivilegesEmptyPrincipalSet() throws Exception { assertFalse(acMgr.hasPrivileges(null, ImmutableSet.<Principal>of(), testPrivileges)); } //------------------------------------------------------< getPrivileges >--- @Test(expected = PathNotFoundException.class) public void testGetPrivilegesNonExistingNodePath() throws Exception { acMgr.getPrivileges(nonExistingPath); } @Test(expected = PathNotFoundException.class) public void testGetPrivilegesNonExistingNodePathEmptyPrincipalSet() throws Exception { acMgr.getPrivileges(nonExistingPath, ImmutableSet.<Principal>of()); } @Test public void testGetPrivilegesInvalidPaths() { for (String path : getInvalidPaths()) { try { acMgr.getPrivileges(path); fail("AccessControlManager#getPrivileges for node that doesn't exist should fail."); } catch (RepositoryException e) { // success } } for (String path : getInvalidPaths()) { try { acMgr.getPrivileges(path, Collections.singleton(testPrincipal)); fail("AccessControlManager#getPrivileges for node that doesn't exist should fail."); } catch (RepositoryException e) { // success } } for (String path : getInvalidPaths()) { try { acMgr.getPrivileges(path, ImmutableSet.<Principal>of()); fail("AccessControlManager#getPrivileges for node that doesn't exist should fail."); } catch (RepositoryException e) { // success } } } @Test public void testGetPrivileges() throws Exception { assertArrayEquals(allPrivileges, acMgr.getPrivileges(testPath)); } @Test public void testGetPrivilegesEveronePrincipalSet() throws Exception { assertArrayEquals(new Privilege[0], acMgr.getPrivileges(testPath, getEveryonePrincipalSet())); } @Test public void testGetPrivilegesEmptyPrincipalSet() throws Exception { assertArrayEquals(new Privilege[0], acMgr.getPrivileges(testPath, ImmutableSet.<Principal>of())); } @Test public void testGetPrivilegesSessionPrincipalSet() throws Exception { AbstractAccessControlManager mgr = spy(acMgr); Privilege[] privileges = mgr.getPrivileges(testPath, testPrincipals); assertArrayEquals(acMgr.getPrivileges(testPath), privileges); // getPrivileges(String,Set) for the principals attached to the content session, // must result in forwarding the call to getPrivilege(String) verify(mgr, times(1)).getPrivileges(testPath); } @Test public void testGetRepoPrivileges() throws Exception { assertArrayEquals(allPrivileges, acMgr.getPrivileges(null)); } @Test public void testGetRepoPrivilegesEveryonePrincipalSet() throws Exception { assertArrayEquals(new Privilege[0], acMgr.getPrivileges(null, getEveryonePrincipalSet())); } @Test public void testGetRepoPrivilegesEmptyPrincipalSet() throws Exception { assertArrayEquals(new Privilege[0], acMgr.getPrivileges(null, ImmutableSet.<Principal>of())); } private class TestAcMgr extends AbstractAccessControlManager { protected TestAcMgr(@NotNull Root root, @NotNull NamePathMapper namePathMapper, @NotNull SecurityProvider securityProvider) { super(root, namePathMapper, securityProvider); } @NotNull @Override public JackrabbitAccessControlPolicy[] getApplicablePolicies(@NotNull Principal principal) { throw new UnsupportedOperationException(); } @NotNull @Override public JackrabbitAccessControlPolicy[] getPolicies(@NotNull Principal principal) { throw new UnsupportedOperationException(); } @NotNull @Override public AccessControlPolicy[] getEffectivePolicies(@NotNull Set<Principal> set) { throw new UnsupportedOperationException(); } @Override public AccessControlPolicy[] getPolicies(String absPath) { throw new UnsupportedOperationException(); } @Override public AccessControlPolicy[] getEffectivePolicies(String absPath) { throw new UnsupportedOperationException(); } @Override public AccessControlPolicyIterator getApplicablePolicies(String absPath) { throw new UnsupportedOperationException(); } @Override public void setPolicy(String absPath, AccessControlPolicy policy) { throw new UnsupportedOperationException(); } @Override public void removePolicy(String absPath, AccessControlPolicy policy) { throw new UnsupportedOperationException(); } } }
package org.jboss.resteasy.test.cdi.injection.resource; import org.jboss.resteasy.test.cdi.util.Utilities; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.ejb.Stateful; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import java.util.HashMap; import java.util.logging.Logger; @Stateful @RequestScoped public class ReverseInjectionEJBHolder implements ReverseInjectionEJBHolderRemote, ReverseInjectionEJBHolderLocal { public static final String SLE = "sle"; public static final String SFDE = "sfde"; public static final String SFRE = "sfre"; public static final String SFAE = "sfae"; public static final String SLI = "sli"; public static final String SFDI = "sfdi"; public static final String SFRI = "sfri"; public static final String SFAI = "sfai"; public static final String SLI_SECRET = "sliSecret"; public static final String SFDI_SECRET = "sfdiSecret"; public static final String SFRI_SECRET = "sfriSecret"; public static final String SFAI_SECRET = "sfaiSecret"; private static HashMap<String, Object> store = new HashMap<String, Object>(); @Inject private Logger log; @Inject private Utilities utilities; @Inject int secret; @EJB private StatelessEJBwithJaxRsComponentsInterface sle; @EJB private StatefulDependentScopedEJBwithJaxRsComponentsInterface sfde; @EJB private StatefulRequestScopedEJBwithJaxRsComponentsInterface sfre; @EJB private StatefulApplicationScopedEJBwithJaxRsComponentsInterface sfae; @Inject private StatelessEJBwithJaxRsComponentsInterface sli; @Inject private StatefulDependentScopedEJBwithJaxRsComponentsInterface sfdi; @Inject private StatefulRequestScopedEJBwithJaxRsComponentsInterface sfri; @Inject private StatefulApplicationScopedEJBwithJaxRsComponentsInterface sfai; @Inject private CDIInjectionBookResource resource; @PostConstruct public void postConstruct() { log.info(this + " secret: " + secret); } @Override public boolean testScopes() { log.info(""); log.info("entering ReverseInjectionEJBHolder.testScopes()"); log.info("resource scope: " + utilities.getScope(CDIInjectionBookResource.class)); log.info("ReverseInjectionEJBHolder scope: " + utilities.getScope(ReverseInjectionEJBHolder.class)); log.info("ReverseInjectionEJBHolderLocal scope: " + utilities.getScope(ReverseInjectionEJBHolderLocal.class)); log.info("ReverseInjectionEJBHolderRemote scope: " + utilities.getScope(ReverseInjectionEJBHolderRemote.class)); log.info("StatelessEJBwithJaxRsComponents scope: " + utilities.getScope(StatelessEJBwithJaxRsComponents.class)); log.info("StatelessEJBwithJaxRsComponentsInterface scope: " + utilities.getScope(StatelessEJBwithJaxRsComponentsInterface.class)); log.info("StatefulDependentScopedEJBwithJaxRsComponents scope: " + utilities.getScope(StatefulDependentScopedEJBwithJaxRsComponents.class)); log.info("StatefulDependentScopedEJBwithJaxRsComponentsInterface scope: " + utilities.getScope(StatefulDependentScopedEJBwithJaxRsComponentsInterface.class)); log.info("StatefulRequestScopedEJBwithJaxRsComponents scope: " + utilities.getScope(StatefulRequestScopedEJBwithJaxRsComponents.class)); log.info("StatefulRequestScopedEJBwithJaxRsComponentsInterface scope: " + utilities.getScope(StatefulRequestScopedEJBwithJaxRsComponentsInterface.class)); log.info("StatefulApplicationScopedEJBwithJaxRsComponents scope: " + utilities.getScope(StatefulApplicationScopedEJBwithJaxRsComponents.class)); log.info("StatefulApplicationScopedEJBwithJaxRsComponentsInterface scope: " + utilities.getScope(StatefulApplicationScopedEJBwithJaxRsComponentsInterface.class)); return utilities.isDependentScoped(StatelessEJBwithJaxRsComponentsInterface.class) && utilities.isDependentScoped(StatefulDependentScopedEJBwithJaxRsComponentsInterface.class) && utilities.isRequestScoped(StatefulRequestScopedEJBwithJaxRsComponentsInterface.class) && utilities.isApplicationScoped(StatefulApplicationScopedEJBwithJaxRsComponentsInterface.class); } @Override public void setup() { log.info(""); log.info("entering ReverseInjectionEJBHolder.setup()"); resource.getSet().add(new CDIInjectionBook("Disappearing Book")); store.put("sle", sle); store.put("sfde", sfde); store.put("sfre", sfre); store.put("sfae", sfae); store.put("sli", sli); store.put("sfdi", sfdi); store.put("sfri", sfri); store.put("sfai", sfai); store.put("sli.secret", sli.theSecret()); store.put("sfdi.secret", sfdi.theSecret()); store.put("sfri.secret", sfri.theSecret()); store.put("sfai.secret", sfai.theSecret()); sleSetup(); sfdeSetup(); sfreSetup(); sfaeSetup(); sliSetup(); sfdiSetup(); sfriSetup(); sfaiSetup(); } @Override public boolean test() { log.info(""); log.info("entering ReverseInjectionEJBHolder.test()"); boolean result = true; result &= resource.getSet().isEmpty(); // @TODO inject singleton // @TODO inject by setter method result &= store.get("sle").equals(sle); // EJB spec 3.4.7.1 result &= !store.get("sfde").equals(sfde); // EJB spec 3.4.7.2, 16.2.1 result &= !store.get("sfre").equals(sfre); // EJB spec 3.4.7.2, 16.2.1 result &= !store.get("sfae").equals(sfae); // EJB spec 3.4.7.2, 16.2.1 // result &= !(store.get("sle") == sle); // EJB spec 16.2.1 result &= !(store.get("sfde") == sfde); // EJB spec 16.2.1 result &= !(store.get("sfre") == sfre); // EJB spec 16.2.1 result &= !(store.get("sfae") == sfae); // EJB spec 16.2.1 // Unlike the EJB spec, the CDI spec does not explicitly specify the semantics of the equality or inequality // of injected objects. In fact, it explicitly forbids calling the java.lang.Object.equals() function on injected // objects [CDI spec, section 5.4.2]. It does specify that the first reference to an injectible object in a given // context should result in a new contextual reference or a new contextual instance [CDI spec, section 6.5.3], // but it doesn't seem to specify the precise semantics of "new". In the weld reference implementation, // there seem to be three variations, at least with respect to injected EJBs: // // 1. It could be a new proxy for an existing object, or // 2. a new proxy for a new object, or // 3. a reused proxy for a new object. // // In this test, we find that // // 1. An SLSB (which necessarily has dependent pseudo-scope) is treated according to case 1. // 2. An SFSB with dependent scope is treated according to case 2. // 3. An SFSB with request scope is treated according to case 3. // // This behavior seems to be consistent with the semantics of EJBs: // // 1. All instances of a given SLSB class are considered equal, and SLSB target objects are reused (case 1). // 2. All instances of a given SFSB class are considered unequal, and SFSBs are always recreated (cases 2 and 3). // // For this test, we consider inequality, in cases where we expect a new object in a new scope, to mean // // 1. a new proxy for SLSBs, and // 2. a new target object for SFSBs. // // N.B. If an SLSB is reused, and it is a contextual object (i.e., created by CDI), then, though some fields might // remain the same, all fields annotated with @Inject should be processed accordingly. // log.info("sli: == stored sli: " + (sli == store.get("sli"))); log.info("sfdi: == stored sfdi: " + (sfdi == store.get("sfdi"))); log.info("sfri: == stored sfri: " + (sfri == store.get("sfri"))); log.info("sfai: == stored sfai: " + (sfai == store.get("sfai"))); log.info("sli.secret: == stored sli.secret: " + (sli.theSecret() == Integer.class.cast(store.get("sli.secret")))); log.info("sfdi.secret: == stored sfdi.secret: " + (sfdi.theSecret() == Integer.class.cast(store.get("sfdi.secret")))); log.info("sfri.secret: == stored sfri.secret: " + (sfri.theSecret() == Integer.class.cast(store.get("sfri.secret")))); log.info("sfai.secret: == stored sfai.secret: " + (sfai.theSecret() == Integer.class.cast(store.get("sfai.secret")))); result &= (sli != store.get("sli")); result &= (sfdi.theSecret() != Integer.class.cast(store.get("sfdi.secret"))); result &= (sfri.theSecret() != Integer.class.cast(store.get("sfri.secret"))); // The CDI spec requires that a single application scoped object of a given class should exist for the // lifetime of the application. It seems reasonable to expect // // 1. that a proxy for that object obtained by @Inject should be reused throughout the lifetime of the application, and // 2. that the target of that proxy should remain the same throughout the lifetime of the application. result &= (sfai == store.get("sfai") && sfai.theSecret() == Integer.class.cast(store.get("sfai.secret"))); result &= sleTest(); result &= sfdeTest(); result &= sfreTest(); result &= sfaeTest(); result &= sliTest(); result &= sfdiTest(); result &= sfriTest(); result &= sfaiTest(); return result; } @Override public void sleSetup() { sle.setUp(SLE); } @Override public boolean sleTest() { return sle.test(SLE); } @Override public void sfdeSetup() { sfde.setUp(SFDE); } @Override public boolean sfdeTest() { return sfde.test(SFDE); } @Override public void sfreSetup() { sfre.setUp(SFRE); } @Override public boolean sfreTest() { return sfre.test(SFRE); } @Override public void sfaeSetup() { sfae.setUp(SFAE); } @Override public boolean sfaeTest() { return sfae.test(SFAE); } @Override public void sliSetup() { sli.setUp(SLI); } @Override public boolean sliTest() { return sli.test(SLI); } @Override public void sfdiSetup() { sfdi.setUp(SFDI); } @Override public boolean sfdiTest() { return sfdi.test(SFDI); } @Override public void sfriSetup() { sfri.setUp(SFRI); } @Override public boolean sfriTest() { return sfri.test(SFRI); } @Override public void sfaiSetup() { sfai.setUp(SFAI); } @Override public boolean sfaiTest() { return sfai.test(SFAI); } @Override public boolean theSame(ReverseInjectionEJBHolderLocal that) { log.info("this secret: " + secret); log.info("that secret: " + that.theSecret()); return this.secret == that.theSecret(); } @Override public int theSecret() { return secret; } }