gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/* * Copyright (c) 1997 - 2016 * Actelion Pharmaceuticals Ltd. * Gewerbestrasse 16 * CH-4123 Allschwil, Switzerland * * 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 the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package com.actelion.research.chem.prediction; import com.actelion.research.chem.AtomTypeCalculator; import com.actelion.research.chem.Molecule; import com.actelion.research.chem.StereoMolecule; import java.text.DecimalFormat; import java.text.NumberFormat; public class SolubilityPredictor { public static final float cSolubilityUnknown = -999; private static final long[] cAtomType = { 0x80002L, 0x80004L, 0x80009L, 0x8000dL, 0x90002L, 0x90003L, 0x90004L, 0x90005L, 0x90008L, 0x90009L, 0x9000dL, 0x9000eL, 0xa8002L, 0xa8003L, 0xa8004L, 0xa8009L, 0xa800dL, 0xc8002L, 0xc8003L, 0xc8004L, 0xc8005L, 0xc8008L, 0xc8009L, 0x110002L, 0x110003L, 0x110004L, 0x110008L, 0x128004L, 0x148004L, 0x148008L, 0x190002L, 0x190003L, 0x1090002L, 0x1090003L, 0x1090004L, 0x1090005L, 0x1090008L, 0x1090009L, 0x109000dL, 0x109000eL, 0x10a8002L, 0x40080004L, 0x48080002L, 0x48080004L, 0x48090002L, 0x48090003L, 0x48090004L, 0x48090008L, 0x4809000cL, 0x54080002L, 0x54090002L, 0x54090003L, 0x54090004L, 0x54090008L, 0x540a8002L, 0x540a8008L, 0x540a800cL, 0x64090002L, 0x64090003L, 0x64090004L, 0x64090008L, 0x6409000cL, 0x640a8002L, 0x640a8003L, 0x640a8004L, 0x640c8002L, 0x640c8003L, 0x640c8004L, 0x640c8008L, 0x88090002L, 0x88090003L, 0x880a8002L, 0x880a8003L, 0x880c8002L, 0x880c8003L, 0x94090002L, 0x94090003L, 0x940a8002L, 0x940a8003L, 0xa4128002L, 0xc8090002L, 0xd4090002L, 0xd40a8002L, 0xd40c8002L, 0x809010002L, 0x809010003L, 0x809010004L, 0x809010008L, 0x815010002L, 0x815010003L, 0x815010004L, 0x815010008L, 0x815028002L, 0x815028003L, 0x815028004L, 0x825010002L, 0x825010003L, 0x825028002L, 0x848090002L, 0x848090003L, 0x848090004L, 0x848090008L, 0x8480a8002L, 0x8480a8003L, 0x8480a8004L, 0x8480c8002L, 0x8480c8003L, 0x8480c8004L, 0x8480c8008L, 0x848110002L, 0x848110003L, 0x848128002L, 0x848128003L, 0x84812800eL, 0x848190002L, 0x849090002L, 0x849090003L, 0x849090004L, 0x849090008L, 0x854080002L, 0x854090002L, 0x8540a8002L, 0x8540c8002L, 0x855090002L, 0x24048090002L, 0x24048090003L, 0x2a048090002L, 0x2a048090003L, 0x2a054090002L, 0x2a054090003L, 0x2a0540a8002L, 0x32048090002L, 0x32048090003L, 0x32054090002L, 0x320540a8002L, 0x32064090002L, 0x320640c8002L, 0x320640c8003L, 0x44048090002L, 0x44054090002L, 0x44054090003L, 0x440540a8002L, 0x44064090002L, 0x440640a8002L, 0x440640c8002L, 0x4a048090002L, 0x4a048090008L, 0x4a054090002L, 0x4a054090003L, 0x4a0540a8002L, 0x4a0540a8003L, 0x4a0540a8007L, 0x4a0540a8008L, 0x4a064090002L, 0x4a064090008L, 0x4a0640a8002L, 0x4a0640c8002L, 0x52054090002L, 0x520540a8002L, 0x520640a8002L, 0x520640c8002L, 0x404808090002L, 0x404808090003L, 0x4048080a8002L, 0x4048080c8002L, 0x404809010002L, 0x404809010003L, 0x40a808090002L, 0x40a808090003L, 0x40a8080a8002L, 0x40a8080c8002L, 0x40a8080c8003L, 0x40a809010002L, 0x40a809010003L, 0x40a814090002L, 0x40a814090003L, 0x40a8140a8002L, 0x40a8140c8002L, 0x40a815010002L, 0x40a815028002L, 0x412808090002L, 0x4128080a8002L, 0x4128080c8002L, 0x412809010002L, 0x412814090002L, 0x4128140a8002L, 0x4128140c8002L, 0x412815010002L, 0x424048090002L, 0x424048090003L, 0x424054090002L, 0x424054090003L, 0x4240540a8002L, 0x424064090002L, 0x424064090003L, 0x4240640a8002L, 0x4240640c8002L, 0x4240640c8003L, 0x424088090002L, 0x4240880a8002L, 0x4240880c8002L, 0x4240880c8008L, 0x424094090002L, 0x424094090008L, 0x4240940a8002L, 0x4240940a8007L, 0x4240940c8002L, 0x42409412800eL, 0x424809010002L, 0x424815010002L, 0x424815010003L, 0x424815028002L, 0x424815028003L, 0x424848090002L, 0x424848090003L, 0x4248480a8002L, 0x4248480a8003L, 0x424848110002L, 0x424848128002L, 0x424849090002L, 0x42a048090002L, 0x42a054090002L, 0x42a088090002L, 0x42a094090002L, 0x42a0940a8002L, 0x12024048090002L, 0x15024048090002L, 0x15024048090003L, 0x1502a048090002L, 0x1502a054090002L, 0x1502a0540a8002L, 0x19024048090002L, 0x1902a048090002L, 0x1902a054090002L, 0x1902a0540a8002L, 0x19032048090002L, 0x19032054090002L, 0x190320540a8002L, 0x19032064090002L, 0x190320640a8002L, 0x190320640c8002L, 0x25024048090007L, 0x2502a048090007L, 0x2502a054090007L, 0x2502a0540a8007L, 0x25032054090007L, 0x250320540a8007L, 0x250320640a8007L, 0x250320640c8007L, 0x2504a048090008L, 0x2504a054090008L, 0x2504a0540a8008L, 0x2504a064090008L, 0x2504a0640a8008L, 0x2902a054090007L, 0x212024048090002L, 0x21202a048090002L, 0x21202a054090002L, 0x21202a0540a8002L, 0x212032048090002L, 0x2120320640c8002L, 0x21204a0540a8007L, 0x21204a094090008L, 0x21204a0940a8008L, 0x21204a0940c8008L, 0x212424048090002L, 0x212424054090002L, 0x2124240540a8002L, 0x212424848090002L, 0x2124248480a8002L, 0x2124248480c8002L }; private static final float[] cIncrement = { -0.19f, 1.27f, -0.701f, 2.691f, -0.227f, 0.03f, 0.106f, -0.476f, -0.447f, -0.191f, -0.333f, 0.086f, 0.247f, -0.062f, 0.016f, 0.387f, 0.235f, -0.432f, -0.903f, 0.39f, 0.581f, 4.524f, -0.635f, -0.28f, 0.77f, -0.05f, 1.087f, 0.192f, 0.196f, -0.52f, 0.542f, 0.363f, 0.792f, 0.592f, 0.964f, 0.354f, -0.685f, -0.315f, -0.413f, -0.595f, 0.22f, -1.432f, -2.254f, 0.44f, -0.27f, -0.133f, -0.269f, 0.267f, 0.572f, -0.568f, 0.174f, -0.185f, -0.235f, -0.17f, -0.181f, -0.342f, -0.348f, -0.437f, -0.804f, -0.412f, -0.215f, -0.625f, -0.831f, 0.497f, -0.431f, -1.331f, 0.507f, -0.632f, -0.599f, -0.156f, -0.353f, -0.164f, -0.441f, -0.497f, -1.06f, 0.115f, -0.225f, -0.154f, -0.031f, -1.574f, -1.093f, -0.738f, -0.45f, -0.556f, -0.181f, 2.384f, 1.75f, -1.666f, -1.066f, 1.327f, 0.803f, -1.505f, -2.537f, -0.17f, 0.149f, 0.521f, 2.905f, -0.252f, 0.86f, 0.361f, 0.403f, 0.005f, 1.146f, 0.936f, -0.3f, 0.209f, -0.583f, -0.024f, -0.01f, 0.611f, 0.486f, 0.862f, -0.035f, -0.596f, 1.161f, 1.647f, 0.844f, 0.125f, 0.142f, -0.171f, 0.442f, 0.088f, 3.066f, 1.652f, -0.203f, -0.018f, 0.023f, 0.073f, 0.254f, 0.554f, 0.595f, -0.406f, -0.637f, -0.174f, -0.101f, -0.543f, -2.406f, -3.292f, -0.053f, -0.193f, 1.85f, -1.261f, -0.656f, -0.73f, -0.938f, 0.128f, 1.154f, 0.242f, -0.529f, -0.278f, -0.802f, 0.912f, -1.381f, 0.463f, 1.074f, -0.628f, -0.962f, -1.832f, -1.499f, -2.116f, -2.207f, -1.317f, 2.501f, -0.849f, -0.602f, -0.622f, 2.122f, -2.226f, 0.913f, -2.259f, -1.25f, 1.394f, -1.402f, 2.073f, -2.957f, 0.291f, -3.476f, -2.727f, -3.132f, -2.12f, -0.725f, -0.297f, 0.083f, 0.347f, -1.425f, -1.66f, -1.282f, -1.265f, 0.719f, 0.138f, 1.302f, 0.859f, 1.359f, 0.659f, -0.94f, 0.9f, 0.319f, -2.571f, 1.109f, 0.972f, 1.653f, 2.602f, 0.729f, 1.066f, 1.067f, -0.311f, 0.031f, -0.203f, -0.681f, -1.258f, 1.07f, -3.096f, -0.228f, 1.933f, 0.119f, 2.108f, 0.113f, 1.628f, 1.308f, 3.336f, 0.754f, -0.465f, -0.397f, 0.077f, -0.479f, -0.153f, 0.141f, 2.135f, 0.234f, 0.461f, 0.67f, -0.361f, -1.039f, -0.483f, 0.137f, -0.768f, -0.511f, 3.424f, -0.855f, -0.585f, -1.567f, 3.343f, 1.84f, 0.389f, 1.122f, 1.63f, 1.335f, 0.366f, -0.557f, 0.432f, 0.204f, 0.882f, 0.466f, -0.458f, 0.404f, 0.657f, 1.115f, 1.976f, 1.786f, -0.036f, -1.05f, 1.045f, 0.044f, 1.033f, -1.08f, 2.539f, 2.235f, 2.29f, 3.121f, 3.932f, 2.75f }; public SolubilityPredictor() { } public float assessSolubility(StereoMolecule mol) { float logS = -0.530f; mol.normalizeAmbiguousBonds(); mol.ensureHelperArrays(Molecule.cHelperRings); for (int atom=0; atom<mol.getAtoms(); atom++) { long type = -1; try { type = AtomTypeCalculator.getAtomType(mol, atom, AtomTypeCalculator.cPropertiesForSolubility); } catch (Exception e) {} for (int i =0; i<cIncrement.length; i++) { if (cAtomType[i] == type) { logS += cIncrement[i]; break; } } } return logS; } public ParameterizedStringList getDetail(StereoMolecule mol) { ParameterizedStringList detail = new ParameterizedStringList(); detail.add("Solubility values are estimated applying an atom-type based increment system.", ParameterizedStringList.cStringTypeText); detail.add("Atom-types are 64-bit numbers describing atoms and their near surrounding.", ParameterizedStringList.cStringTypeText); detail.add("Recognized atom types and their contributions are:", ParameterizedStringList.cStringTypeText); detail.add("Base value = -0.530", ParameterizedStringList.cStringTypeText); int count[] = new int[cIncrement.length]; if (mol != null) { mol.normalizeAmbiguousBonds(); mol.ensureHelperArrays(Molecule.cHelperRings); for (int atom=0; atom<mol.getAtoms(); atom++) { long type = -1; try { type = AtomTypeCalculator.getAtomType(mol, atom, AtomTypeCalculator.cPropertiesForSolubility); } catch (Exception e) {} for (int i =0; i<cIncrement.length; i++) { if (cAtomType[i] == type) { count[i]++; break; } } } } NumberFormat formatter = new DecimalFormat("#0.000"); for (int i=0; i<cIncrement.length; i++) if (count[i] != 0) detail.add(""+count[i]+" * "+ formatter.format(cIncrement[i]) +" AtomType: 0x" +Long.toHexString(cAtomType[i]), ParameterizedStringList.cStringTypeText); return detail; } }
/* * 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.execution.scheduler; import com.facebook.presto.OutputBuffers.OutputBufferId; import com.facebook.presto.client.NodeVersion; import com.facebook.presto.connector.ConnectorId; import com.facebook.presto.execution.LocationFactory; import com.facebook.presto.execution.MockRemoteTaskFactory; import com.facebook.presto.execution.MockRemoteTaskFactory.MockRemoteTask; import com.facebook.presto.execution.NodeTaskMap; import com.facebook.presto.execution.RemoteTask; import com.facebook.presto.execution.SqlStageExecution; import com.facebook.presto.execution.StageId; import com.facebook.presto.execution.TestSqlTaskManager.MockLocationFactory; import com.facebook.presto.metadata.InMemoryNodeManager; import com.facebook.presto.metadata.InternalNodeManager; import com.facebook.presto.metadata.PrestoNode; import com.facebook.presto.metadata.TableHandle; import com.facebook.presto.spi.ConnectorSplit; import com.facebook.presto.spi.ConnectorSplitSource; import com.facebook.presto.spi.FixedSplitSource; import com.facebook.presto.spi.Node; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.QueryId; import com.facebook.presto.spi.predicate.TupleDomain; import com.facebook.presto.split.ConnectorAwareSplitSource; import com.facebook.presto.split.SplitSource; import com.facebook.presto.sql.planner.Partitioning; import com.facebook.presto.sql.planner.PartitioningScheme; import com.facebook.presto.sql.planner.PlanFragment; import com.facebook.presto.sql.planner.StageExecutionPlan; import com.facebook.presto.sql.planner.Symbol; import com.facebook.presto.sql.planner.TestingColumnHandle; import com.facebook.presto.sql.planner.TestingTableHandle; import com.facebook.presto.sql.planner.plan.JoinNode; import com.facebook.presto.sql.planner.plan.PlanFragmentId; import com.facebook.presto.sql.planner.plan.PlanNodeId; import com.facebook.presto.sql.planner.plan.RemoteSourceNode; import com.facebook.presto.sql.planner.plan.TableScanNode; import com.facebook.presto.testing.TestingSplit; import com.facebook.presto.testing.TestingTransactionHandle; import com.facebook.presto.util.FinalizerService; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import static com.facebook.presto.OutputBuffers.BufferType.PARTITIONED; import static com.facebook.presto.OutputBuffers.createInitialEmptyOutputBuffers; import static com.facebook.presto.SessionTestUtils.TEST_SESSION; import static com.facebook.presto.spi.StandardErrorCode.NO_NODES_AVAILABLE; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static com.facebook.presto.sql.planner.SystemPartitioningHandle.SINGLE_DISTRIBUTION; import static com.facebook.presto.sql.planner.SystemPartitioningHandle.SOURCE_DISTRIBUTION; import static com.facebook.presto.sql.planner.plan.JoinNode.Type.INNER; import static io.airlift.concurrent.Threads.daemonThreadsNamed; import static java.lang.Integer.min; import static java.util.Objects.requireNonNull; import static java.util.concurrent.Executors.newCachedThreadPool; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; public class TestSourcePartitionedScheduler { public static final OutputBufferId OUT = new OutputBufferId(0); private static final ConnectorId CONNECTOR_ID = new ConnectorId("connector_id"); private final ExecutorService executor = newCachedThreadPool(daemonThreadsNamed("stageExecutor-%s")); private final LocationFactory locationFactory = new MockLocationFactory(); private final InMemoryNodeManager nodeManager = new InMemoryNodeManager(); private final FinalizerService finalizerService = new FinalizerService(); public TestSourcePartitionedScheduler() { nodeManager.addNode(CONNECTOR_ID, new PrestoNode("other1", URI.create("http://127.0.0.1:11"), NodeVersion.UNKNOWN, false), new PrestoNode("other2", URI.create("http://127.0.0.1:12"), NodeVersion.UNKNOWN, false), new PrestoNode("other3", URI.create("http://127.0.0.1:13"), NodeVersion.UNKNOWN, false)); } @BeforeClass public void setUp() { finalizerService.start(); } @AfterClass public void destroyExecutor() { executor.shutdownNow(); finalizerService.destroy(); } @Test public void testScheduleNoSplits() throws Exception { StageExecutionPlan plan = createPlan(createFixedSplitSource(0, TestingSplit::createRemoteSplit)); NodeTaskMap nodeTaskMap = new NodeTaskMap(finalizerService); SqlStageExecution stage = createSqlStageExecution(plan, nodeTaskMap); SourcePartitionedScheduler scheduler = getSourcePartitionedScheduler(plan, stage, nodeManager, nodeTaskMap, 1); ScheduleResult scheduleResult = scheduler.schedule(); assertTrue(scheduleResult.isFinished()); assertTrue(scheduleResult.getBlocked().isDone()); assertTrue(scheduleResult.getNewTasks().isEmpty()); stage.abort(); } @Test public void testScheduleSplitsOneAtATime() throws Exception { StageExecutionPlan plan = createPlan(createFixedSplitSource(60, TestingSplit::createRemoteSplit)); NodeTaskMap nodeTaskMap = new NodeTaskMap(finalizerService); SqlStageExecution stage = createSqlStageExecution(plan, nodeTaskMap); SourcePartitionedScheduler scheduler = getSourcePartitionedScheduler(plan, stage, nodeManager, nodeTaskMap, 1); for (int i = 0; i < 60; i++) { ScheduleResult scheduleResult = scheduler.schedule(); // only finishes when last split is fetched assertEquals(scheduleResult.isFinished(), i == 59); // never blocks assertTrue(scheduleResult.getBlocked().isDone()); // first three splits create new tasks assertEquals(scheduleResult.getNewTasks().size(), i < 3 ? 1 : 0); assertEquals(stage.getAllTasks().size(), i < 3 ? i + 1 : 3); assertPartitionedSplitCount(stage, min(i + 1, 60)); } for (RemoteTask remoteTask : stage.getAllTasks()) { assertEquals(remoteTask.getPartitionedSplitCount(), 20); } stage.abort(); } @Test public void testScheduleSplitsBatched() throws Exception { StageExecutionPlan plan = createPlan(createFixedSplitSource(60, TestingSplit::createRemoteSplit)); NodeTaskMap nodeTaskMap = new NodeTaskMap(finalizerService); SqlStageExecution stage = createSqlStageExecution(plan, nodeTaskMap); SourcePartitionedScheduler scheduler = getSourcePartitionedScheduler(plan, stage, nodeManager, nodeTaskMap, 7); for (int i = 0; i <= (60 / 7); i++) { ScheduleResult scheduleResult = scheduler.schedule(); // finishes when last split is fetched assertEquals(scheduleResult.isFinished(), i == (60 / 7)); // never blocks assertTrue(scheduleResult.getBlocked().isDone()); // first three splits create new tasks assertEquals(scheduleResult.getNewTasks().size(), i == 0 ? 3 : 0); assertEquals(stage.getAllTasks().size(), 3); assertPartitionedSplitCount(stage, min((i + 1) * 7, 60)); } for (RemoteTask remoteTask : stage.getAllTasks()) { assertEquals(remoteTask.getPartitionedSplitCount(), 20); } stage.abort(); } @Test public void testScheduleSplitsBlock() throws Exception { StageExecutionPlan plan = createPlan(createFixedSplitSource(80, TestingSplit::createRemoteSplit)); NodeTaskMap nodeTaskMap = new NodeTaskMap(finalizerService); SqlStageExecution stage = createSqlStageExecution(plan, nodeTaskMap); SourcePartitionedScheduler scheduler = getSourcePartitionedScheduler(plan, stage, nodeManager, nodeTaskMap, 1); // schedule first 60 splits, which will cause the scheduler to block for (int i = 0; i <= 60; i++) { ScheduleResult scheduleResult = scheduler.schedule(); assertFalse(scheduleResult.isFinished()); // blocks at 20 per node assertEquals(scheduleResult.getBlocked().isDone(), i != 60); // first three splits create new tasks assertEquals(scheduleResult.getNewTasks().size(), i < 3 ? 1 : 0); assertEquals(stage.getAllTasks().size(), i < 3 ? i + 1 : 3); assertPartitionedSplitCount(stage, min(i + 1, 60)); } for (RemoteTask remoteTask : stage.getAllTasks()) { assertEquals(remoteTask.getPartitionedSplitCount(), 20); } // todo rewrite MockRemoteTask to fire a tate transition when splits are cleared, and then validate blocked future completes // drop the 20 splits from one node ((MockRemoteTask) stage.getAllTasks().get(0)).clearSplits(); // schedule remaining 20 splits for (int i = 0; i < 20; i++) { ScheduleResult scheduleResult = scheduler.schedule(); // finishes when last split is fetched assertEquals(scheduleResult.isFinished(), i == 19); // does not block again assertTrue(scheduleResult.getBlocked().isDone()); // no additional tasks will be created assertEquals(scheduleResult.getNewTasks().size(), 0); assertEquals(stage.getAllTasks().size(), 3); // we dropped 20 splits so start at 40 and count to 60 assertPartitionedSplitCount(stage, min(i + 41, 60)); } for (RemoteTask remoteTask : stage.getAllTasks()) { assertEquals(remoteTask.getPartitionedSplitCount(), 20); } stage.abort(); } @Test public void testScheduleSlowSplitSource() throws Exception { QueuedSplitSource queuedSplitSource = new QueuedSplitSource(TestingSplit::createRemoteSplit); StageExecutionPlan plan = createPlan(queuedSplitSource); NodeTaskMap nodeTaskMap = new NodeTaskMap(finalizerService); SqlStageExecution stage = createSqlStageExecution(plan, nodeTaskMap); SourcePartitionedScheduler scheduler = getSourcePartitionedScheduler(plan, stage, nodeManager, nodeTaskMap, 1); // schedule with no splits - will block ScheduleResult scheduleResult = scheduler.schedule(); assertFalse(scheduleResult.isFinished()); assertFalse(scheduleResult.getBlocked().isDone()); assertEquals(scheduleResult.getNewTasks().size(), 0); assertEquals(stage.getAllTasks().size(), 0); queuedSplitSource.addSplits(1); assertTrue(scheduleResult.getBlocked().isDone()); } @Test public void testNoNodes() throws Exception { try { NodeTaskMap nodeTaskMap = new NodeTaskMap(finalizerService); InMemoryNodeManager nodeManager = new InMemoryNodeManager(); NodeScheduler nodeScheduler = new NodeScheduler(new LegacyNetworkTopology(), nodeManager, new NodeSchedulerConfig().setIncludeCoordinator(false), nodeTaskMap); StageExecutionPlan plan = createPlan(createFixedSplitSource(20, TestingSplit::createRemoteSplit)); SqlStageExecution stage = createSqlStageExecution(plan, nodeTaskMap); SourcePartitionedScheduler scheduler = new SourcePartitionedScheduler( stage, Iterables.getOnlyElement(plan.getSplitSources().keySet()), Iterables.getOnlyElement(plan.getSplitSources().values()), new DynamicSplitPlacementPolicy(nodeScheduler.createNodeSelector(CONNECTOR_ID), stage::getAllTasks), 2); scheduler.schedule(); fail("expected PrestoException"); } catch (PrestoException e) { assertEquals(e.getErrorCode(), NO_NODES_AVAILABLE.toErrorCode()); } } @Test public void testBalancedSplitAssignment() throws Exception { // use private node manager so we can add a node later InMemoryNodeManager nodeManager = new InMemoryNodeManager(); nodeManager.addNode(CONNECTOR_ID, new PrestoNode("other1", URI.create("http://127.0.0.1:11"), NodeVersion.UNKNOWN, false), new PrestoNode("other2", URI.create("http://127.0.0.1:12"), NodeVersion.UNKNOWN, false), new PrestoNode("other3", URI.create("http://127.0.0.1:13"), NodeVersion.UNKNOWN, false)); NodeTaskMap nodeTaskMap = new NodeTaskMap(finalizerService); // Schedule 15 splits - there are 3 nodes, each node should get 5 splits StageExecutionPlan firstPlan = createPlan(createFixedSplitSource(15, TestingSplit::createRemoteSplit)); SqlStageExecution firstStage = createSqlStageExecution(firstPlan, nodeTaskMap); SourcePartitionedScheduler firstScheduler = getSourcePartitionedScheduler(firstPlan, firstStage, nodeManager, nodeTaskMap, 200); ScheduleResult scheduleResult = firstScheduler.schedule(); assertTrue(scheduleResult.isFinished()); assertTrue(scheduleResult.getBlocked().isDone()); assertEquals(scheduleResult.getNewTasks().size(), 3); assertEquals(firstStage.getAllTasks().size(), 3); for (RemoteTask remoteTask : firstStage.getAllTasks()) { assertEquals(remoteTask.getPartitionedSplitCount(), 5); } // Add new node Node additionalNode = new PrestoNode("other4", URI.create("http://127.0.0.1:14"), NodeVersion.UNKNOWN, false); nodeManager.addNode(CONNECTOR_ID, additionalNode); // Schedule 5 splits in another query. Since the new node does not have any splits, all 5 splits are assigned to the new node StageExecutionPlan secondPlan = createPlan(createFixedSplitSource(5, TestingSplit::createRemoteSplit)); SqlStageExecution secondStage = createSqlStageExecution(secondPlan, nodeTaskMap); SourcePartitionedScheduler secondScheduler = getSourcePartitionedScheduler(secondPlan, secondStage, nodeManager, nodeTaskMap, 200); scheduleResult = secondScheduler.schedule(); assertTrue(scheduleResult.isFinished()); assertTrue(scheduleResult.getBlocked().isDone()); assertEquals(scheduleResult.getNewTasks().size(), 1); assertEquals(secondStage.getAllTasks().size(), 1); RemoteTask task = secondStage.getAllTasks().get(0); assertEquals(task.getPartitionedSplitCount(), 5); firstStage.abort(); secondStage.abort(); } @Test public void testBlockCausesFullSchedule() throws Exception { NodeTaskMap nodeTaskMap = new NodeTaskMap(finalizerService); // Schedule 60 splits - filling up all nodes StageExecutionPlan firstPlan = createPlan(createFixedSplitSource(60, TestingSplit::createRemoteSplit)); SqlStageExecution firstStage = createSqlStageExecution(firstPlan, nodeTaskMap); SourcePartitionedScheduler firstScheduler = getSourcePartitionedScheduler(firstPlan, firstStage, nodeManager, nodeTaskMap, 200); ScheduleResult scheduleResult = firstScheduler.schedule(); assertTrue(scheduleResult.isFinished()); assertTrue(scheduleResult.getBlocked().isDone()); assertEquals(scheduleResult.getNewTasks().size(), 3); assertEquals(firstStage.getAllTasks().size(), 3); for (RemoteTask remoteTask : firstStage.getAllTasks()) { assertEquals(remoteTask.getPartitionedSplitCount(), 20); } // Schedule more splits in another query, which will block since all nodes are full StageExecutionPlan secondPlan = createPlan(createFixedSplitSource(5, TestingSplit::createRemoteSplit)); SqlStageExecution secondStage = createSqlStageExecution(secondPlan, nodeTaskMap); SourcePartitionedScheduler secondScheduler = getSourcePartitionedScheduler(secondPlan, secondStage, nodeManager, nodeTaskMap, 200); scheduleResult = secondScheduler.schedule(); assertFalse(scheduleResult.isFinished()); assertTrue(scheduleResult.getBlocked().isDone()); assertEquals(scheduleResult.getNewTasks().size(), 3); assertEquals(secondStage.getAllTasks().size(), 3); for (RemoteTask remoteTask : secondStage.getAllTasks()) { assertEquals(remoteTask.getPartitionedSplitCount(), 0); } firstStage.abort(); secondStage.abort(); } private static void assertPartitionedSplitCount(SqlStageExecution stage, int expectedPartitionedSplitCount) { assertEquals(stage.getAllTasks().stream().mapToInt(RemoteTask::getPartitionedSplitCount).sum(), expectedPartitionedSplitCount); } private static SourcePartitionedScheduler getSourcePartitionedScheduler( StageExecutionPlan plan, SqlStageExecution stage, InternalNodeManager nodeManager, NodeTaskMap nodeTaskMap, int splitBatchSize) { NodeSchedulerConfig nodeSchedulerConfig = new NodeSchedulerConfig() .setIncludeCoordinator(false) .setMaxSplitsPerNode(20) .setMaxPendingSplitsPerTask(0); NodeScheduler nodeScheduler = new NodeScheduler(new LegacyNetworkTopology(), nodeManager, nodeSchedulerConfig, nodeTaskMap); PlanNodeId sourceNode = Iterables.getOnlyElement(plan.getSplitSources().keySet()); SplitSource splitSource = Iterables.getOnlyElement(plan.getSplitSources().values()); SplitPlacementPolicy placementPolicy = new DynamicSplitPlacementPolicy(nodeScheduler.createNodeSelector(splitSource.getConnectorId()), stage::getAllTasks); return new SourcePartitionedScheduler(stage, sourceNode, splitSource, placementPolicy, splitBatchSize); } private static StageExecutionPlan createPlan(ConnectorSplitSource splitSource) { Symbol symbol = new Symbol("column"); // table scan with splitCount splits PlanNodeId tableScanNodeId = new PlanNodeId("plan_id"); TableScanNode tableScan = new TableScanNode( tableScanNodeId, new TableHandle(CONNECTOR_ID, new TestingTableHandle()), ImmutableList.of(symbol), ImmutableMap.of(symbol, new TestingColumnHandle("column")), Optional.empty(), TupleDomain.all(), null); RemoteSourceNode remote = new RemoteSourceNode(new PlanNodeId("remote_id"), new PlanFragmentId("plan_fragment_id"), ImmutableList.of()); PlanFragment testFragment = new PlanFragment( new PlanFragmentId("plan_id"), new JoinNode(new PlanNodeId("join_id"), INNER, tableScan, remote, ImmutableList.of(), ImmutableList.<Symbol>builder() .addAll(tableScan.getOutputSymbols()) .addAll(remote.getOutputSymbols()) .build(), Optional.empty(), Optional.empty(), Optional.empty()), ImmutableMap.of(symbol, VARCHAR), SOURCE_DISTRIBUTION, ImmutableList.of(tableScanNodeId), new PartitioningScheme(Partitioning.create(SINGLE_DISTRIBUTION, ImmutableList.of()), ImmutableList.of(symbol))); return new StageExecutionPlan( testFragment, ImmutableMap.of(tableScanNodeId, new ConnectorAwareSplitSource(CONNECTOR_ID, TestingTransactionHandle.create(), splitSource)), ImmutableList.of()); } private static ConnectorSplitSource createFixedSplitSource(int splitCount, Supplier<ConnectorSplit> splitFactory) { ImmutableList.Builder<ConnectorSplit> splits = ImmutableList.builder(); for (int i = 0; i < splitCount; i++) { splits.add(splitFactory.get()); } return new FixedSplitSource(splits.build()); } private SqlStageExecution createSqlStageExecution(StageExecutionPlan tableScanPlan, NodeTaskMap nodeTaskMap) { StageId stageId = new StageId(new QueryId("query"), 0); SqlStageExecution stage = new SqlStageExecution(stageId, locationFactory.createStageLocation(stageId), tableScanPlan.getFragment(), new MockRemoteTaskFactory(executor), TEST_SESSION, true, nodeTaskMap, executor, new SplitSchedulerStats()); stage.setOutputBuffers(createInitialEmptyOutputBuffers(PARTITIONED) .withBuffer(OUT, 0) .withNoMoreBufferIds()); return stage; } private static class QueuedSplitSource implements ConnectorSplitSource { private final Supplier<ConnectorSplit> splitFactory; private final LinkedBlockingQueue<ConnectorSplit> queue = new LinkedBlockingQueue<>(); private CompletableFuture<?> notEmptyFuture = new CompletableFuture<>(); private boolean closed; public QueuedSplitSource(Supplier<ConnectorSplit> splitFactory) { this.splitFactory = requireNonNull(splitFactory, "splitFactory is null"); } synchronized void addSplits(int count) { if (closed) { return; } for (int i = 0; i < count; i++) { queue.add(splitFactory.get()); notEmptyFuture.complete(null); } } @Override public synchronized CompletableFuture<List<ConnectorSplit>> getNextBatch(int maxSize) { return notEmptyFuture.thenApply(x -> getBatch(maxSize)); } private synchronized List<ConnectorSplit> getBatch(int maxSize) { // take up to maxSize elements from the queue List<ConnectorSplit> elements = new ArrayList<>(maxSize); queue.drainTo(elements, maxSize); // if the queue is empty and the current future is finished, create a new one so // a new readers can be notified when the queue has elements to read if (queue.isEmpty() && !closed) { if (notEmptyFuture.isDone()) { notEmptyFuture = new CompletableFuture<>(); } } return ImmutableList.copyOf(elements); } @Override public synchronized boolean isFinished() { return closed && queue.isEmpty(); } @Override public synchronized void close() { closed = true; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.builder.endpoint.dsl; import java.util.Map; import javax.annotation.Generated; import org.apache.camel.ExchangePattern; import org.apache.camel.builder.EndpointConsumerBuilder; import org.apache.camel.builder.EndpointProducerBuilder; import org.apache.camel.builder.endpoint.AbstractEndpointBuilder; import org.apache.camel.spi.ExceptionHandler; /** * Capture changes from a MongoDB database. * * Generated by camel build tools - do NOT edit this file! */ @Generated("org.apache.camel.maven.packaging.EndpointDslMojo") public interface DebeziumMongodbEndpointBuilderFactory { /** * Builder for endpoint for the Debezium MongoDB Connector component. */ public interface DebeziumMongodbEndpointBuilder extends EndpointConsumerBuilder { default AdvancedDebeziumMongodbEndpointBuilder advanced() { return (AdvancedDebeziumMongodbEndpointBuilder) this; } /** * Additional properties for debezium components in case they can't be * set directly on the camel configurations (e.g: setting Kafka Connect * properties needed by Debezium engine, for example setting * KafkaOffsetBackingStore), the properties have to be prefixed with * additionalProperties.. E.g: * additionalProperties.transactional.id=12345&additionalProperties.schema.registry.url=http://localhost:8811/avro. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the * additionalProperties(String, Object) method to add a value (call the * method multiple times to set more values). * * Group: common */ default DebeziumMongodbEndpointBuilder additionalProperties( String key, Object value) { doSetMultiValueProperty("additionalProperties", "additionalProperties." + key, value); return this; } /** * Additional properties for debezium components in case they can't be * set directly on the camel configurations (e.g: setting Kafka Connect * properties needed by Debezium engine, for example setting * KafkaOffsetBackingStore), the properties have to be prefixed with * additionalProperties.. E.g: * additionalProperties.transactional.id=12345&additionalProperties.schema.registry.url=http://localhost:8811/avro. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the * additionalProperties(String, Object) method to add a value (call the * method multiple times to set more values). * * Group: common */ default DebeziumMongodbEndpointBuilder additionalProperties(Map values) { doSetMultiValueProperties("additionalProperties", "additionalProperties.", values); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions occurred while the consumer is trying to * pickup incoming messages, or the likes, will now be processed as a * message and handled by the routing Error Handler. By default the * consumer will use the org.apache.camel.spi.ExceptionHandler to deal * with exceptions, that will be logged at WARN or ERROR level and * ignored. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer */ default DebeziumMongodbEndpointBuilder bridgeErrorHandler( boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions occurred while the consumer is trying to * pickup incoming messages, or the likes, will now be processed as a * message and handled by the routing Error Handler. By default the * consumer will use the org.apache.camel.spi.ExceptionHandler to deal * with exceptions, that will be logged at WARN or ERROR level and * ignored. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer */ default DebeziumMongodbEndpointBuilder bridgeErrorHandler( String bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * The Converter class that should be used to serialize and deserialize * key data for offsets. The default is JSON converter. * * The option is a: <code>java.lang.String</code> type. * * Default: org.apache.kafka.connect.json.JsonConverter * Group: consumer */ default DebeziumMongodbEndpointBuilder internalKeyConverter( String internalKeyConverter) { doSetProperty("internalKeyConverter", internalKeyConverter); return this; } /** * The Converter class that should be used to serialize and deserialize * value data for offsets. The default is JSON converter. * * The option is a: <code>java.lang.String</code> type. * * Default: org.apache.kafka.connect.json.JsonConverter * Group: consumer */ default DebeziumMongodbEndpointBuilder internalValueConverter( String internalValueConverter) { doSetProperty("internalValueConverter", internalValueConverter); return this; } /** * The name of the Java class of the commit policy. It defines when * offsets commit has to be triggered based on the number of events * processed and the time elapsed since the last commit. This class must * implement the interface 'OffsetCommitPolicy'. The default is a * periodic commit policy based upon time intervals. * * The option is a: <code>java.lang.String</code> type. * * Default: * io.debezium.embedded.spi.OffsetCommitPolicy.PeriodicCommitOffsetPolicy * Group: consumer */ default DebeziumMongodbEndpointBuilder offsetCommitPolicy( String offsetCommitPolicy) { doSetProperty("offsetCommitPolicy", offsetCommitPolicy); return this; } /** * Maximum number of milliseconds to wait for records to flush and * partition offset data to be committed to offset storage before * cancelling the process and restoring the offset data to be committed * in a future attempt. The default is 5 seconds. * * The option is a: <code>long</code> type. * * Default: 5s * Group: consumer */ default DebeziumMongodbEndpointBuilder offsetCommitTimeoutMs( long offsetCommitTimeoutMs) { doSetProperty("offsetCommitTimeoutMs", offsetCommitTimeoutMs); return this; } /** * Maximum number of milliseconds to wait for records to flush and * partition offset data to be committed to offset storage before * cancelling the process and restoring the offset data to be committed * in a future attempt. The default is 5 seconds. * * The option will be converted to a <code>long</code> type. * * Default: 5s * Group: consumer */ default DebeziumMongodbEndpointBuilder offsetCommitTimeoutMs( String offsetCommitTimeoutMs) { doSetProperty("offsetCommitTimeoutMs", offsetCommitTimeoutMs); return this; } /** * Interval at which to try committing offsets. The default is 1 minute. * * The option is a: <code>long</code> type. * * Default: 60s * Group: consumer */ default DebeziumMongodbEndpointBuilder offsetFlushIntervalMs( long offsetFlushIntervalMs) { doSetProperty("offsetFlushIntervalMs", offsetFlushIntervalMs); return this; } /** * Interval at which to try committing offsets. The default is 1 minute. * * The option will be converted to a <code>long</code> type. * * Default: 60s * Group: consumer */ default DebeziumMongodbEndpointBuilder offsetFlushIntervalMs( String offsetFlushIntervalMs) { doSetProperty("offsetFlushIntervalMs", offsetFlushIntervalMs); return this; } /** * The name of the Java class that is responsible for persistence of * connector offsets. * * The option is a: <code>java.lang.String</code> type. * * Default: org.apache.kafka.connect.storage.FileOffsetBackingStore * Group: consumer */ default DebeziumMongodbEndpointBuilder offsetStorage( String offsetStorage) { doSetProperty("offsetStorage", offsetStorage); return this; } /** * Path to file where offsets are to be stored. Required when * offset.storage is set to the FileOffsetBackingStore. * * The option is a: <code>java.lang.String</code> type. * * Group: consumer */ default DebeziumMongodbEndpointBuilder offsetStorageFileName( String offsetStorageFileName) { doSetProperty("offsetStorageFileName", offsetStorageFileName); return this; } /** * The number of partitions used when creating the offset storage topic. * Required when offset.storage is set to the 'KafkaOffsetBackingStore'. * * The option is a: <code>int</code> type. * * Group: consumer */ default DebeziumMongodbEndpointBuilder offsetStoragePartitions( int offsetStoragePartitions) { doSetProperty("offsetStoragePartitions", offsetStoragePartitions); return this; } /** * The number of partitions used when creating the offset storage topic. * Required when offset.storage is set to the 'KafkaOffsetBackingStore'. * * The option will be converted to a <code>int</code> type. * * Group: consumer */ default DebeziumMongodbEndpointBuilder offsetStoragePartitions( String offsetStoragePartitions) { doSetProperty("offsetStoragePartitions", offsetStoragePartitions); return this; } /** * Replication factor used when creating the offset storage topic. * Required when offset.storage is set to the KafkaOffsetBackingStore. * * The option is a: <code>int</code> type. * * Group: consumer */ default DebeziumMongodbEndpointBuilder offsetStorageReplicationFactor( int offsetStorageReplicationFactor) { doSetProperty("offsetStorageReplicationFactor", offsetStorageReplicationFactor); return this; } /** * Replication factor used when creating the offset storage topic. * Required when offset.storage is set to the KafkaOffsetBackingStore. * * The option will be converted to a <code>int</code> type. * * Group: consumer */ default DebeziumMongodbEndpointBuilder offsetStorageReplicationFactor( String offsetStorageReplicationFactor) { doSetProperty("offsetStorageReplicationFactor", offsetStorageReplicationFactor); return this; } /** * The name of the Kafka topic where offsets are to be stored. Required * when offset.storage is set to the KafkaOffsetBackingStore. * * The option is a: <code>java.lang.String</code> type. * * Group: consumer */ default DebeziumMongodbEndpointBuilder offsetStorageTopic( String offsetStorageTopic) { doSetProperty("offsetStorageTopic", offsetStorageTopic); return this; } /** * Description is not available here, please check Debezium website for * corresponding key 'collection.blacklist' description. * * The option is a: <code>java.lang.String</code> type. * * Group: mongodb */ default DebeziumMongodbEndpointBuilder collectionBlacklist( String collectionBlacklist) { doSetProperty("collectionBlacklist", collectionBlacklist); return this; } /** * The collections for which changes are to be captured. * * The option is a: <code>java.lang.String</code> type. * * Group: mongodb */ default DebeziumMongodbEndpointBuilder collectionWhitelist( String collectionWhitelist) { doSetProperty("collectionWhitelist", collectionWhitelist); return this; } /** * The initial delay when trying to reconnect to a primary after a * connection cannot be made or when no primary is available. Defaults * to 1 second (1000 ms). * * The option is a: <code>long</code> type. * * Default: 1s * Group: mongodb */ default DebeziumMongodbEndpointBuilder connectBackoffInitialDelayMs( long connectBackoffInitialDelayMs) { doSetProperty("connectBackoffInitialDelayMs", connectBackoffInitialDelayMs); return this; } /** * The initial delay when trying to reconnect to a primary after a * connection cannot be made or when no primary is available. Defaults * to 1 second (1000 ms). * * The option will be converted to a <code>long</code> type. * * Default: 1s * Group: mongodb */ default DebeziumMongodbEndpointBuilder connectBackoffInitialDelayMs( String connectBackoffInitialDelayMs) { doSetProperty("connectBackoffInitialDelayMs", connectBackoffInitialDelayMs); return this; } /** * The maximum delay when trying to reconnect to a primary after a * connection cannot be made or when no primary is available. Defaults * to 120 second (120,000 ms). * * The option is a: <code>long</code> type. * * Default: 2m * Group: mongodb */ default DebeziumMongodbEndpointBuilder connectBackoffMaxDelayMs( long connectBackoffMaxDelayMs) { doSetProperty("connectBackoffMaxDelayMs", connectBackoffMaxDelayMs); return this; } /** * The maximum delay when trying to reconnect to a primary after a * connection cannot be made or when no primary is available. Defaults * to 120 second (120,000 ms). * * The option will be converted to a <code>long</code> type. * * Default: 2m * Group: mongodb */ default DebeziumMongodbEndpointBuilder connectBackoffMaxDelayMs( String connectBackoffMaxDelayMs) { doSetProperty("connectBackoffMaxDelayMs", connectBackoffMaxDelayMs); return this; } /** * Maximum number of failed connection attempts to a replica set primary * before an exception occurs and task is aborted. Defaults to 16, which * with the defaults for 'connect.backoff.initial.delay.ms' and * 'connect.backoff.max.delay.ms' results in just over 20 minutes of * attempts before failing. * * The option is a: <code>int</code> type. * * Default: 16 * Group: mongodb */ default DebeziumMongodbEndpointBuilder connectMaxAttempts( int connectMaxAttempts) { doSetProperty("connectMaxAttempts", connectMaxAttempts); return this; } /** * Maximum number of failed connection attempts to a replica set primary * before an exception occurs and task is aborted. Defaults to 16, which * with the defaults for 'connect.backoff.initial.delay.ms' and * 'connect.backoff.max.delay.ms' results in just over 20 minutes of * attempts before failing. * * The option will be converted to a <code>int</code> type. * * Default: 16 * Group: mongodb */ default DebeziumMongodbEndpointBuilder connectMaxAttempts( String connectMaxAttempts) { doSetProperty("connectMaxAttempts", connectMaxAttempts); return this; } /** * Optional list of custom converters that would be used instead of * default ones. The converters are defined using '.type' config option * and configured using options '.'. * * The option is a: <code>java.lang.String</code> type. * * Group: mongodb */ default DebeziumMongodbEndpointBuilder converters(String converters) { doSetProperty("converters", converters); return this; } /** * The databases for which changes are to be excluded. * * The option is a: <code>java.lang.String</code> type. * * Group: mongodb */ default DebeziumMongodbEndpointBuilder databaseBlacklist( String databaseBlacklist) { doSetProperty("databaseBlacklist", databaseBlacklist); return this; } /** * The path to the file that will be used to record the database * history. * * The option is a: <code>java.lang.String</code> type. * * Group: mongodb */ default DebeziumMongodbEndpointBuilder databaseHistoryFileFilename( String databaseHistoryFileFilename) { doSetProperty("databaseHistoryFileFilename", databaseHistoryFileFilename); return this; } /** * The databases for which changes are to be captured. * * The option is a: <code>java.lang.String</code> type. * * Group: mongodb */ default DebeziumMongodbEndpointBuilder databaseWhitelist( String databaseWhitelist) { doSetProperty("databaseWhitelist", databaseWhitelist); return this; } /** * Specify how failures during processing of events (i.e. when * encountering a corrupted event) should be handled, including:'fail' * (the default) an exception indicating the problematic event and its * position is raised, causing the connector to be stopped; 'warn' the * problematic event and its position will be logged and the event will * be skipped;'ignore' the problematic event will be skipped. * * The option is a: <code>java.lang.String</code> type. * * Default: fail * Group: mongodb */ default DebeziumMongodbEndpointBuilder eventProcessingFailureHandlingMode( String eventProcessingFailureHandlingMode) { doSetProperty("eventProcessingFailureHandlingMode", eventProcessingFailureHandlingMode); return this; } /** * Description is not available here, please check Debezium website for * corresponding key 'field.blacklist' description. * * The option is a: <code>java.lang.String</code> type. * * Group: mongodb */ default DebeziumMongodbEndpointBuilder fieldBlacklist( String fieldBlacklist) { doSetProperty("fieldBlacklist", fieldBlacklist); return this; } /** * Description is not available here, please check Debezium website for * corresponding key 'field.renames' description. * * The option is a: <code>java.lang.String</code> type. * * Group: mongodb */ default DebeziumMongodbEndpointBuilder fieldRenames(String fieldRenames) { doSetProperty("fieldRenames", fieldRenames); return this; } /** * Length of an interval in milli-seconds in in which the connector * periodically sends heartbeat messages to a heartbeat topic. Use 0 to * disable heartbeat messages. Disabled by default. * * The option is a: <code>int</code> type. * * Default: 0ms * Group: mongodb */ default DebeziumMongodbEndpointBuilder heartbeatIntervalMs( int heartbeatIntervalMs) { doSetProperty("heartbeatIntervalMs", heartbeatIntervalMs); return this; } /** * Length of an interval in milli-seconds in in which the connector * periodically sends heartbeat messages to a heartbeat topic. Use 0 to * disable heartbeat messages. Disabled by default. * * The option will be converted to a <code>int</code> type. * * Default: 0ms * Group: mongodb */ default DebeziumMongodbEndpointBuilder heartbeatIntervalMs( String heartbeatIntervalMs) { doSetProperty("heartbeatIntervalMs", heartbeatIntervalMs); return this; } /** * The prefix that is used to name heartbeat topics.Defaults to * __debezium-heartbeat. * * The option is a: <code>java.lang.String</code> type. * * Default: __debezium-heartbeat * Group: mongodb */ default DebeziumMongodbEndpointBuilder heartbeatTopicsPrefix( String heartbeatTopicsPrefix) { doSetProperty("heartbeatTopicsPrefix", heartbeatTopicsPrefix); return this; } /** * Maximum number of threads used to perform an initial sync of the * collections in a replica set. Defaults to 1. * * The option is a: <code>int</code> type. * * Default: 1 * Group: mongodb */ default DebeziumMongodbEndpointBuilder initialSyncMaxThreads( int initialSyncMaxThreads) { doSetProperty("initialSyncMaxThreads", initialSyncMaxThreads); return this; } /** * Maximum number of threads used to perform an initial sync of the * collections in a replica set. Defaults to 1. * * The option will be converted to a <code>int</code> type. * * Default: 1 * Group: mongodb */ default DebeziumMongodbEndpointBuilder initialSyncMaxThreads( String initialSyncMaxThreads) { doSetProperty("initialSyncMaxThreads", initialSyncMaxThreads); return this; } /** * Maximum size of each batch of source records. Defaults to 2048. * * The option is a: <code>int</code> type. * * Default: 2048 * Group: mongodb */ default DebeziumMongodbEndpointBuilder maxBatchSize(int maxBatchSize) { doSetProperty("maxBatchSize", maxBatchSize); return this; } /** * Maximum size of each batch of source records. Defaults to 2048. * * The option will be converted to a <code>int</code> type. * * Default: 2048 * Group: mongodb */ default DebeziumMongodbEndpointBuilder maxBatchSize(String maxBatchSize) { doSetProperty("maxBatchSize", maxBatchSize); return this; } /** * Maximum size of the queue for change events read from the database * log but not yet recorded or forwarded. Defaults to 8192, and should * always be larger than the maximum batch size. * * The option is a: <code>int</code> type. * * Default: 8192 * Group: mongodb */ default DebeziumMongodbEndpointBuilder maxQueueSize(int maxQueueSize) { doSetProperty("maxQueueSize", maxQueueSize); return this; } /** * Maximum size of the queue for change events read from the database * log but not yet recorded or forwarded. Defaults to 8192, and should * always be larger than the maximum batch size. * * The option will be converted to a <code>int</code> type. * * Default: 8192 * Group: mongodb */ default DebeziumMongodbEndpointBuilder maxQueueSize(String maxQueueSize) { doSetProperty("maxQueueSize", maxQueueSize); return this; } /** * Database containing user credentials. * * The option is a: <code>java.lang.String</code> type. * * Default: admin * Group: mongodb */ default DebeziumMongodbEndpointBuilder mongodbAuthsource( String mongodbAuthsource) { doSetProperty("mongodbAuthsource", mongodbAuthsource); return this; } /** * The hostname and port pairs (in the form 'host' or 'host:port') of * the MongoDB server(s) in the replica set. * * The option is a: <code>java.lang.String</code> type. * * Group: mongodb */ default DebeziumMongodbEndpointBuilder mongodbHosts(String mongodbHosts) { doSetProperty("mongodbHosts", mongodbHosts); return this; } /** * Specifies whether the addresses in 'hosts' are seeds that should be * used to discover all members of the cluster or replica set ('true'), * or whether the address(es) in 'hosts' should be used as is ('false'). * The default is 'true'. * * The option is a: <code>boolean</code> type. * * Default: true * Group: mongodb */ default DebeziumMongodbEndpointBuilder mongodbMembersAutoDiscover( boolean mongodbMembersAutoDiscover) { doSetProperty("mongodbMembersAutoDiscover", mongodbMembersAutoDiscover); return this; } /** * Specifies whether the addresses in 'hosts' are seeds that should be * used to discover all members of the cluster or replica set ('true'), * or whether the address(es) in 'hosts' should be used as is ('false'). * The default is 'true'. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: mongodb */ default DebeziumMongodbEndpointBuilder mongodbMembersAutoDiscover( String mongodbMembersAutoDiscover) { doSetProperty("mongodbMembersAutoDiscover", mongodbMembersAutoDiscover); return this; } /** * Unique name that identifies the MongoDB replica set or cluster and * all recorded offsets, andthat is used as a prefix for all schemas and * topics. Each distinct MongoDB installation should have a separate * namespace and monitored by at most one Debezium connector. * * The option is a: <code>java.lang.String</code> type. * * Required: true * Group: mongodb */ default DebeziumMongodbEndpointBuilder mongodbName(String mongodbName) { doSetProperty("mongodbName", mongodbName); return this; } /** * Password to be used when connecting to MongoDB, if necessary. * * The option is a: <code>java.lang.String</code> type. * * Required: true * Group: mongodb */ default DebeziumMongodbEndpointBuilder mongodbPassword( String mongodbPassword) { doSetProperty("mongodbPassword", mongodbPassword); return this; } /** * Frequency in seconds to look for new, removed, or changed replica * sets. Defaults to 30 seconds. * * The option is a: <code>int</code> type. * * Default: 30 * Group: mongodb */ default DebeziumMongodbEndpointBuilder mongodbPollIntervalSec( int mongodbPollIntervalSec) { doSetProperty("mongodbPollIntervalSec", mongodbPollIntervalSec); return this; } /** * Frequency in seconds to look for new, removed, or changed replica * sets. Defaults to 30 seconds. * * The option will be converted to a <code>int</code> type. * * Default: 30 * Group: mongodb */ default DebeziumMongodbEndpointBuilder mongodbPollIntervalSec( String mongodbPollIntervalSec) { doSetProperty("mongodbPollIntervalSec", mongodbPollIntervalSec); return this; } /** * Should connector use SSL to connect to MongoDB instances. * * The option is a: <code>boolean</code> type. * * Default: false * Group: mongodb */ default DebeziumMongodbEndpointBuilder mongodbSslEnabled( boolean mongodbSslEnabled) { doSetProperty("mongodbSslEnabled", mongodbSslEnabled); return this; } /** * Should connector use SSL to connect to MongoDB instances. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: mongodb */ default DebeziumMongodbEndpointBuilder mongodbSslEnabled( String mongodbSslEnabled) { doSetProperty("mongodbSslEnabled", mongodbSslEnabled); return this; } /** * Whether invalid host names are allowed when using SSL. If true the * connection will not prevent man-in-the-middle attacks. * * The option is a: <code>boolean</code> type. * * Default: false * Group: mongodb */ default DebeziumMongodbEndpointBuilder mongodbSslInvalidHostnameAllowed( boolean mongodbSslInvalidHostnameAllowed) { doSetProperty("mongodbSslInvalidHostnameAllowed", mongodbSslInvalidHostnameAllowed); return this; } /** * Whether invalid host names are allowed when using SSL. If true the * connection will not prevent man-in-the-middle attacks. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: mongodb */ default DebeziumMongodbEndpointBuilder mongodbSslInvalidHostnameAllowed( String mongodbSslInvalidHostnameAllowed) { doSetProperty("mongodbSslInvalidHostnameAllowed", mongodbSslInvalidHostnameAllowed); return this; } /** * Database user for connecting to MongoDB, if necessary. * * The option is a: <code>java.lang.String</code> type. * * Group: mongodb */ default DebeziumMongodbEndpointBuilder mongodbUser(String mongodbUser) { doSetProperty("mongodbUser", mongodbUser); return this; } /** * Frequency in milliseconds to wait for new change events to appear * after receiving no events. Defaults to 500ms. * * The option is a: <code>long</code> type. * * Default: 500ms * Group: mongodb */ default DebeziumMongodbEndpointBuilder pollIntervalMs( long pollIntervalMs) { doSetProperty("pollIntervalMs", pollIntervalMs); return this; } /** * Frequency in milliseconds to wait for new change events to appear * after receiving no events. Defaults to 500ms. * * The option will be converted to a <code>long</code> type. * * Default: 500ms * Group: mongodb */ default DebeziumMongodbEndpointBuilder pollIntervalMs( String pollIntervalMs) { doSetProperty("pollIntervalMs", pollIntervalMs); return this; } /** * Enables transaction metadata extraction together with event counting. * * The option is a: <code>boolean</code> type. * * Default: false * Group: mongodb */ default DebeziumMongodbEndpointBuilder provideTransactionMetadata( boolean provideTransactionMetadata) { doSetProperty("provideTransactionMetadata", provideTransactionMetadata); return this; } /** * Enables transaction metadata extraction together with event counting. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: mongodb */ default DebeziumMongodbEndpointBuilder provideTransactionMetadata( String provideTransactionMetadata) { doSetProperty("provideTransactionMetadata", provideTransactionMetadata); return this; } /** * Whether field names will be sanitized to Avro naming conventions. * * The option is a: <code>boolean</code> type. * * Default: false * Group: mongodb */ default DebeziumMongodbEndpointBuilder sanitizeFieldNames( boolean sanitizeFieldNames) { doSetProperty("sanitizeFieldNames", sanitizeFieldNames); return this; } /** * Whether field names will be sanitized to Avro naming conventions. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: mongodb */ default DebeziumMongodbEndpointBuilder sanitizeFieldNames( String sanitizeFieldNames) { doSetProperty("sanitizeFieldNames", sanitizeFieldNames); return this; } /** * The comma-separated list of operations to skip during streaming, * defined as: 'i' for inserts; 'u' for updates; 'd' for deletes. By * default, no operations will be skipped. * * The option is a: <code>java.lang.String</code> type. * * Group: mongodb */ default DebeziumMongodbEndpointBuilder skippedOperations( String skippedOperations) { doSetProperty("skippedOperations", skippedOperations); return this; } /** * The number of milliseconds to delay before a snapshot will begin. * * The option is a: <code>long</code> type. * * Default: 0ms * Group: mongodb */ default DebeziumMongodbEndpointBuilder snapshotDelayMs( long snapshotDelayMs) { doSetProperty("snapshotDelayMs", snapshotDelayMs); return this; } /** * The number of milliseconds to delay before a snapshot will begin. * * The option will be converted to a <code>long</code> type. * * Default: 0ms * Group: mongodb */ default DebeziumMongodbEndpointBuilder snapshotDelayMs( String snapshotDelayMs) { doSetProperty("snapshotDelayMs", snapshotDelayMs); return this; } /** * The maximum number of records that should be loaded into memory while * performing a snapshot. * * The option is a: <code>int</code> type. * * Group: mongodb */ default DebeziumMongodbEndpointBuilder snapshotFetchSize( int snapshotFetchSize) { doSetProperty("snapshotFetchSize", snapshotFetchSize); return this; } /** * The maximum number of records that should be loaded into memory while * performing a snapshot. * * The option will be converted to a <code>int</code> type. * * Group: mongodb */ default DebeziumMongodbEndpointBuilder snapshotFetchSize( String snapshotFetchSize) { doSetProperty("snapshotFetchSize", snapshotFetchSize); return this; } /** * The criteria for running a snapshot upon startup of the connector. * Options include: 'initial' (the default) to specify the connector * should always perform an initial sync when required; 'never' to * specify the connector should never perform an initial sync. * * The option is a: <code>java.lang.String</code> type. * * Default: initial * Group: mongodb */ default DebeziumMongodbEndpointBuilder snapshotMode(String snapshotMode) { doSetProperty("snapshotMode", snapshotMode); return this; } /** * A version of the format of the publicly visible source part in the * message. * * The option is a: <code>java.lang.String</code> type. * * Default: v2 * Group: mongodb */ default DebeziumMongodbEndpointBuilder sourceStructVersion( String sourceStructVersion) { doSetProperty("sourceStructVersion", sourceStructVersion); return this; } /** * Whether delete operations should be represented by a delete event and * a subsquenttombstone event (true) or only by a delete event (false). * Emitting the tombstone event (the default behavior) allows Kafka to * completely delete all events pertaining to the given key once the * source record got deleted. * * The option is a: <code>boolean</code> type. * * Default: false * Group: mongodb */ default DebeziumMongodbEndpointBuilder tombstonesOnDelete( boolean tombstonesOnDelete) { doSetProperty("tombstonesOnDelete", tombstonesOnDelete); return this; } /** * Whether delete operations should be represented by a delete event and * a subsquenttombstone event (true) or only by a delete event (false). * Emitting the tombstone event (the default behavior) allows Kafka to * completely delete all events pertaining to the given key once the * source record got deleted. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: mongodb */ default DebeziumMongodbEndpointBuilder tombstonesOnDelete( String tombstonesOnDelete) { doSetProperty("tombstonesOnDelete", tombstonesOnDelete); return this; } } /** * Advanced builder for endpoint for the Debezium MongoDB Connector * component. */ public interface AdvancedDebeziumMongodbEndpointBuilder extends EndpointConsumerBuilder { default DebeziumMongodbEndpointBuilder basic() { return (DebeziumMongodbEndpointBuilder) this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option is a: <code>org.apache.camel.spi.ExceptionHandler</code> * type. * * Group: consumer (advanced) */ default AdvancedDebeziumMongodbEndpointBuilder exceptionHandler( ExceptionHandler exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option will be converted to a * <code>org.apache.camel.spi.ExceptionHandler</code> type. * * Group: consumer (advanced) */ default AdvancedDebeziumMongodbEndpointBuilder exceptionHandler( String exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option is a: <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) */ default AdvancedDebeziumMongodbEndpointBuilder exchangePattern( ExchangePattern exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option will be converted to a * <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) */ default AdvancedDebeziumMongodbEndpointBuilder exchangePattern( String exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * Whether the endpoint should use basic property binding (Camel 2.x) or * the newer property binding with additional capabilities. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedDebeziumMongodbEndpointBuilder basicPropertyBinding( boolean basicPropertyBinding) { doSetProperty("basicPropertyBinding", basicPropertyBinding); return this; } /** * Whether the endpoint should use basic property binding (Camel 2.x) or * the newer property binding with additional capabilities. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedDebeziumMongodbEndpointBuilder basicPropertyBinding( String basicPropertyBinding) { doSetProperty("basicPropertyBinding", basicPropertyBinding); return this; } /** * Sets whether synchronous processing should be strictly used, or Camel * is allowed to use asynchronous processing (if supported). * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedDebeziumMongodbEndpointBuilder synchronous( boolean synchronous) { doSetProperty("synchronous", synchronous); return this; } /** * Sets whether synchronous processing should be strictly used, or Camel * is allowed to use asynchronous processing (if supported). * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedDebeziumMongodbEndpointBuilder synchronous( String synchronous) { doSetProperty("synchronous", synchronous); return this; } } public interface DebeziumMongodbBuilders { /** * Debezium MongoDB Connector (camel-debezium-mongodb) * Capture changes from a MongoDB database. * * Category: database,nosql * Since: 3.0 * Maven coordinates: org.apache.camel:camel-debezium-mongodb * * Syntax: <code>debezium-mongodb:name</code> * * Path parameter: name (required) * Unique name for the connector. Attempting to register again with the * same name will fail. * * @param path name */ default DebeziumMongodbEndpointBuilder debeziumMongodb(String path) { return DebeziumMongodbEndpointBuilderFactory.endpointBuilder("debezium-mongodb", path); } /** * Debezium MongoDB Connector (camel-debezium-mongodb) * Capture changes from a MongoDB database. * * Category: database,nosql * Since: 3.0 * Maven coordinates: org.apache.camel:camel-debezium-mongodb * * Syntax: <code>debezium-mongodb:name</code> * * Path parameter: name (required) * Unique name for the connector. Attempting to register again with the * same name will fail. * * @param componentName to use a custom component name for the endpoint * instead of the default name * @param path name */ default DebeziumMongodbEndpointBuilder debeziumMongodb( String componentName, String path) { return DebeziumMongodbEndpointBuilderFactory.endpointBuilder(componentName, path); } } static DebeziumMongodbEndpointBuilder endpointBuilder( String componentName, String path) { class DebeziumMongodbEndpointBuilderImpl extends AbstractEndpointBuilder implements DebeziumMongodbEndpointBuilder, AdvancedDebeziumMongodbEndpointBuilder { public DebeziumMongodbEndpointBuilderImpl(String path) { super(componentName, path); } } return new DebeziumMongodbEndpointBuilderImpl(path); } }
/* ************************************************************************ # # DivConq # # http://divconq.com/ # # Copyright: # Copyright 2014 eTimeline, LLC. All rights reserved. # # License: # See the license.txt file in the project's top-level directory for details. # # Authors: # * Andy White # ************************************************************************ */ package divconq.schema; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import divconq.util.StringUtil; import divconq.xml.XAttribute; import divconq.xml.XElement; public class DatabaseSchema { protected SchemaManager man = null; protected HashMap<String, DbProc> procs = new HashMap<String, DbProc>(); protected HashMap<String, DbComposer> composers = new HashMap<String, DbComposer>(); protected HashMap<String, DbCollector> collectors = new HashMap<String, DbCollector>(); protected HashMap<String, List<DbTrigger>> triggers = new HashMap<String, List<DbTrigger>>(); protected HashMap<String, DbTable> tables = new HashMap<String, DbTable>(); public Collection<DbProc> getProcedures() { return this.procs.values(); } public Collection<DbComposer> getComposers() { return this.composers.values(); } public Collection<DbCollector> getCollectors() { return this.collectors.values(); } //public Collection<DbTable> getTables() { // return this.tables.values(); //} public DatabaseSchema(SchemaManager man) { this.man = man; } public void load(Schema schema, XElement db) { for (XElement dtel : db.selectAll("Table")) { String id = dtel.getAttribute("Id"); if (StringUtil.isEmpty(id)) continue; DbTable tab = this.tables.get(id); if (tab == null) { tab = new DbTable(); tab.name = id; this.tables.put(id, tab); } DataType dt = this.man.knownTypes().get(id); if (dt != null) dt.load(dtel); else { dt = this.man.loadDataType(schema, dtel); XElement autoSchema = new XElement("Table", new XElement("Field", new XAttribute("Name", "Id"), new XAttribute("Type", "Id") ), new XElement("Field", new XAttribute("Name", "Retired"), new XAttribute("Type", "Boolean") ), new XElement("Field", new XAttribute("Name", "From"), new XAttribute("Type", "BigDateTime"), new XAttribute("Indexed", "True") ), new XElement("Field", new XAttribute("Name", "To"), new XAttribute("Type", "BigDateTime"), new XAttribute("Indexed", "True") ), new XElement("Field", new XAttribute("Name", "Tags"), new XAttribute("Type", "dcTinyString"), new XAttribute("List", "True") ) ); // automatically add Id, Retired, etc to tables dt.load(autoSchema); for (XElement fel : autoSchema.selectAll("Field")) tab.addField(fel, dt); } for (XElement fel : dtel.selectAll("Field")) tab.addField(fel, dt); } for (XElement secel : db.selectAll("Secure")) { String[] tags = secel.hasAttribute("Tags") ? secel.getAttribute("Tags").split(",") : new String[] { "Guest", "User" }; for (XElement procel : secel.selectAll("Procedure")) { String sname = procel.getAttribute("Name"); if (StringUtil.isEmpty(sname)) continue; DbProc opt = new DbProc(); opt.name = sname; opt.execute = procel.getAttribute("Execute"); opt.securityTags = tags; this.procs.put(sname, opt); XElement req = procel.find("Request", "ListRequest", "RecRequest"); if (req != null) opt.request = this.man.loadDataType(schema, req); XElement resp = procel.find("Response", "ListResponse", "RecResponse"); if (resp != null) opt.response = this.man.loadDataType(schema, resp); } for (XElement procel : secel.selectAll("Composer")) { String sname = procel.getAttribute("Name"); if (StringUtil.isEmpty(sname)) continue; DbComposer opt = new DbComposer(); opt.name = sname; opt.execute = procel.getAttribute("Execute"); opt.securityTags = tags; this.composers.put(sname, opt); } for (XElement procel : secel.selectAll("Collector")) { String sname = procel.getAttribute("Name"); if (StringUtil.isEmpty(sname)) continue; DbCollector opt = new DbCollector(); opt.name = sname; opt.execute = procel.getAttribute("Execute"); opt.securityTags = tags; this.collectors.put(sname, opt); } } for (XElement procel : db.selectAll("Trigger")) { String sname = procel.getAttribute("Table"); if (StringUtil.isEmpty(sname)) continue; DbTrigger opt = new DbTrigger(); opt.op = procel.getAttribute("Operation"); opt.execute = procel.getAttribute("Execute"); opt.table = sname; List<DbTrigger> ll = this.triggers.get(sname); if (ll == null) { ll = new ArrayList<>(); this.triggers.put(sname, ll); } ll.add(opt); } } public void compile() { for (DbProc s : this.procs.values()) { if (s.request != null) s.request.compile(); if (s.response != null) s.response.compile(); } for (DbTable t : this.tables.values()) t.compile(this.man); } public DataType getProcRequestType(String name) { DbProc proc = this.getProc(name); if (proc != null) return proc.request; return null; } public DataType getProcResponseType(String name) { DbProc proc = this.getProc(name); if (proc != null) return proc.response; return null; } public DbTable getTable(String table) { if (StringUtil.isEmpty(table)) return null; return this.tables.get(table); } public DbField getField(String table, String field) { if (StringUtil.isEmpty(table) || StringUtil.isEmpty(field)) return null; DbTable tbl = this.tables.get(table); if (tbl != null) return tbl.fields.get(field); return null; } public boolean hasTable(String table) { if (StringUtil.isEmpty(table)) return false; return this.tables.containsKey(table); } // returns a copy list, you (caller) can own the list public List<DbTrigger> getTriggers(String table, String operation) { if (StringUtil.isEmpty(table) || StringUtil.isEmpty(operation)) return null; List<DbTrigger> ret = new ArrayList<>(); List<DbTrigger> tbl = this.triggers.get(table); if (tbl != null) for (DbTrigger t : tbl) if (t.op.equals(operation)) ret.add(t); return ret; } // returns a copy list, you (caller) can own the list public List<DbTable> getTables() { return new ArrayList<>(this.tables.values()); } // returns a copy list, you (caller) can own the list public List<DbField> getFields(String table) { if (StringUtil.isEmpty(table)) return null; DbTable tbl = this.tables.get(table); if (tbl == null) return null; return new ArrayList<>(tbl.fields.values()); } public DbProc getProc(String name) { if (StringUtil.isEmpty(name)) return null; return this.procs.get(name); } public DbComposer getComposer(String name) { if (StringUtil.isEmpty(name)) return null; return this.composers.get(name); } public DbCollector getCollector(String name) { if (StringUtil.isEmpty(name)) return null; return this.collectors.get(name); } }
/* Copyright (c) 2008, University of Oslo, Norway * 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 University of Oslo nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package vtk.web.display.tags; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Required; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import vtk.repository.Path; import vtk.repository.Resource; import vtk.repository.resourcetype.ResourceTypeDefinition; import vtk.web.RequestContext; import vtk.web.display.listing.ListingPager; import vtk.web.display.listing.ListingPagingLink; import vtk.web.referencedata.Link; import vtk.web.search.Listing; import vtk.web.search.SearchComponent; import vtk.web.service.Service; import vtk.web.service.URL; import vtk.web.tags.RepositoryTagElementsDataProvider; import vtk.web.tags.TagElement; import vtk.web.tags.TagsHelper; public class TagsController implements Controller { private int defaultPageLimit = 20; private String viewName; private SearchComponent searchComponent; private Map<String, Service> alternativeRepresentations; private RepositoryTagElementsDataProvider tagElementsProvider; private TagsHelper tagsHelper; private String customDisplayResourceType; private String customDisplayImport; public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> model = new HashMap<>(); RequestContext requestContext = RequestContext.getRequestContext(request); String token = requestContext.getSecurityToken(); Resource resource = tagsHelper.getScopedResource(token, request); String tag = request.getParameter(TagsHelper.TAG_PARAMETER); List<ResourceTypeDefinition> resourceTypes = tagsHelper.getResourceTypes(request); boolean displayScope = tagsHelper.getDisplayScope(request); String overrideResourceTypeTitle = request.getParameter(TagsHelper.OVERRIDE_RESOURCE_TYPE_TITLE_PARAMETER); /* List all known tags for the current collection */ if (!StringUtils.isBlank(tag)) { model.put(TagsHelper.TAG_PARAMETER, tag); handleSingleTag(request, tag, resource, model, resourceTypes, displayScope, overrideResourceTypeTitle); } else { handleAllTags(request, token, resource, model, resourceTypes, overrideResourceTypeTitle, displayScope); } // Resolve Title String title = tagsHelper.getTitle(request, resource, tag, false); model.put("title", title); // Add scope up url Link scopeUpLink = tagsHelper.getScopeUpUrl(request, resource, model, tag, resourceTypes, displayScope, true); model.put(TagsHelper.SCOPE_UP_MODEL_KEY, scopeUpLink); model.put("requestURL", requestContext.getRequestURL()); if (customDisplayResourceType != null && customDisplayImport != null) { model.put("customDisplayResourceType", customDisplayResourceType); model.put("customDisplayImport", customDisplayImport); } return new ModelAndView(viewName, model); } private void handleSingleTag(HttpServletRequest request, String tag, Resource resource, Map<String, Object> model, List<ResourceTypeDefinition> resourceTypes, boolean displayScope, String overrideResourceTypeTitle) throws Exception { // Setting the default page limit int pageLimit = defaultPageLimit; int page = ListingPager.getPage(request, ListingPager.UPCOMING_PAGE_PARAM); int limit = pageLimit; int totalHits = 0; Listing listing = searchComponent.execute(request, resource, page, limit, 0); List<String> sortFieldParams = null; if (listing != null) { totalHits = listing.getTotalHits(); sortFieldParams = listing.getSortFieldParams(); } if (resourceTypes != null && resourceTypes.size() == 1) { model.put(TagsHelper.RESOURCE_TYPE_MODEL_KEY, resourceTypes.get(0).getName()); } RequestContext requestContext = RequestContext.getRequestContext(request); Service service = requestContext.getService(); URL baseURL = service.urlConstructor(requestContext.getRequestURL()) .withURI(resource.getURI()) .constructURL(); tagsHelper.processUrl(baseURL, tag, resourceTypes, sortFieldParams, displayScope, overrideResourceTypeTitle); Optional<ListingPager.Pagination> pagination = ListingPager.pagination(totalHits, pageLimit, baseURL, page); if (pagination.isPresent()) { List<ListingPagingLink> urls = pagination.get().pageThroughLinks(); model.put("pageThroughUrls", urls); } model.put("listing", listing); model.put("searchComponents", Collections.singletonList(listing)); model.put("page", page); if (alternativeRepresentations != null) { Set<Object> alt = new HashSet<>(); for (String contentType : alternativeRepresentations.keySet()) { try { Service altService = alternativeRepresentations.get(contentType); URL url = altService.urlConstructor(requestContext.getRequestURL()) .withURI(resource.getURI()) .constructURL(); tagsHelper.processUrl(url, tag, resourceTypes, sortFieldParams, displayScope, overrideResourceTypeTitle); String title = altService.getName(); org.springframework.web.servlet.support.RequestContext rc = new org.springframework.web.servlet.support.RequestContext( request); title = rc.getMessage(altService.getName(), new Object[] { resource.getTitle() }, altService.getName()); Map<String, Object> m = new HashMap<>(); m.put("title", title); m.put("url", url); m.put("contentType", contentType); alt.add(m); model.put("alternativeRepresentations", alt); } catch (Throwable t) { } } } } private void handleAllTags(HttpServletRequest request, String token, Resource resource, Map<String, Object> model, List<ResourceTypeDefinition> resourceTypes, String overrideResourceTypeTitle, boolean displayScope) throws Exception { Path scopeUri = resource.getURI(); List<TagElement> tagElements = tagElementsProvider .getTagElements(request, scopeUri, token, 1, 1, Integer.MAX_VALUE, 1, resourceTypes, null, overrideResourceTypeTitle, displayScope); model.put("tagElements", tagElements); } public void setDefaultPageLimit(int defaultPageLimit) { if (defaultPageLimit <= 0) throw new IllegalArgumentException("Argument must be a positive integer"); this.defaultPageLimit = defaultPageLimit; } @Required public void setSearchComponent(SearchComponent searchComponent) { this.searchComponent = searchComponent; } @Required public void setViewName(String viewName) { this.viewName = viewName; } public void setAlternativeRepresentations(Map<String, Service> alternativeRepresentations) { this.alternativeRepresentations = alternativeRepresentations; } public void setTagElementsProvider(RepositoryTagElementsDataProvider tagElementsProvider) { this.tagElementsProvider = tagElementsProvider; } @Required public void setTagsHelper(TagsHelper tagsHelper) { this.tagsHelper = tagsHelper; } public void setCustomDisplayResourceType(String customDisplayResourceType) { this.customDisplayResourceType = customDisplayResourceType; } public void setCustomDisplayImport(String customDisplayImport) { this.customDisplayImport = customDisplayImport; } }
/* * 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.security; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLException; import javax.net.ssl.TrustManagerFactory; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.io.util.File; /** * SslContextFactory for the <a href="">PEM standard</a> encoded PKCS#8 private keys and X509 certificates/public-keys. * It parses the key material based on the standard defined in the <a href="https://datatracker.ietf.org/doc/html/rfc7468">RFC 7468</a>. * It creates <a href="https://datatracker.ietf.org/doc/html/rfc5208">PKCS# 8</a> based private key and X509 certificate(s) * for the public key to build the required keystore and the truststore managers that are used for the SSL context creation. * Internally it builds Java {@link KeyStore} with <a href="https://datatracker.ietf.org/doc/html/rfc7292">PKCS# 12</a> <a href="https://docs.oracle.com/en/java/javase/11/docs/specs/security/standard-names.html#keystore-types">store type</a> * to be used for keystore and the truststore managers. * <p> * This factory also supports 'hot reloading' of the key material, the same way as defined by {@link FileBasedSslContextFactory}, * <b>if it is file based</b>. This factory ignores the existing 'store_type' configuration used for other file based store * types like JKS. * <p> * You can configure this factory with either inline PEM data or with the files having the required PEM data as shown * below, * * <b>Configuration: PEM keys/certs defined inline (mind the spaces in the YAML!)</b> * <pre> * client/server_encryption_options: * ssl_context_factory: * class_name: org.apache.cassandra.security.PEMBasedSslContextFactory * parameters: * private_key: | * -----BEGIN ENCRYPTED PRIVATE KEY----- OR -----BEGIN PRIVATE KEY----- * <your base64 encoded private key> * -----END ENCRYPTED PRIVATE KEY----- OR -----END PRIVATE KEY----- * -----BEGIN CERTIFICATE----- * <your base64 encoded certificate chain> * -----END CERTIFICATE----- * * private_key_password: "<your password if the private key is encrypted with a password>" * * trusted_certificates: | * -----BEGIN CERTIFICATE----- * <your base64 encoded certificate> * -----END CERTIFICATE----- * </pre> * * <b>Configuration: PEM keys/certs defined in files</b> * <pre> * client/server_encryption_options: * ssl_context_factory: * class_name: org.apache.cassandra.security.PEMBasedSslContextFactory * keystore: <file path to the keystore file in the PEM format with the private key and the certificate chain> * keystore_password: "<your password if the private key is encrypted with a password>" * truststore: <file path to the truststore file in the PEM format> * </pre> */ public final class PEMBasedSslContextFactory extends FileBasedSslContextFactory { public static final String DEFAULT_TARGET_STORETYPE = "PKCS12"; private static final Logger logger = LoggerFactory.getLogger(PEMBasedSslContextFactory.class); private String pemEncodedKey; private String keyPassword; private String pemEncodedCertificates; private boolean maybeFileBasedPrivateKey; private boolean maybeFileBasedTrustedCertificates; public PEMBasedSslContextFactory() { } public PEMBasedSslContextFactory(Map<String, Object> parameters) { super(parameters); pemEncodedKey = getString(ConfigKey.ENCODED_KEY.getKeyName()); keyPassword = getString(ConfigKey.KEY_PASSWORD.getKeyName()); if (StringUtils.isEmpty(keyPassword)) { keyPassword = keystore_password; } else if (!StringUtils.isEmpty(keystore_password) && !keyPassword.equals(keystore_password)) { throw new IllegalArgumentException("'keystore_password' and 'key_password' both configurations are given and the " + "values do not match"); } else { logger.warn("'keystore_password' and 'key_password' both are configured but since the values match it's " + "okay. Ideally you should only specify one of them."); } if (!StringUtils.isEmpty(truststore_password)) { logger.warn("PEM based truststore should not be using password. Ignoring the given value in " + "'truststore_password' configuration."); } pemEncodedCertificates = getString(ConfigKey.ENCODED_CERTIFICATES.getKeyName()); maybeFileBasedPrivateKey = StringUtils.isEmpty(pemEncodedKey); maybeFileBasedTrustedCertificates = StringUtils.isEmpty(pemEncodedCertificates); enforceSinglePrivateKeySource(); enforceSingleTurstedCertificatesSource(); } /** * Decides if this factory has a keystore defined - key material specified in files or inline to the configuration. * * @return {@code true} if there is a keystore defined; {@code false} otherwise */ @Override public boolean hasKeystore() { return maybeFileBasedPrivateKey ? keystoreFileExists() : !StringUtils.isEmpty(pemEncodedKey); } /** * Checks if the keystore file exists. * * @return {@code true} if keystore file exists; {@code false} otherwise */ private boolean keystoreFileExists() { return keystore != null && new File(keystore).exists(); } /** * Decides if this factory has a truststore defined - key material specified in files or inline to the * configuration. * * @return {@code true} if there is a truststore defined; {@code false} otherwise */ private boolean hasTruststore() { return maybeFileBasedTrustedCertificates ? truststoreFileExists() : !StringUtils.isEmpty(pemEncodedCertificates); } /** * Checks if the truststore file exists. * * @return {@code true} if truststore file exists; {@code false} otherwise */ private boolean truststoreFileExists() { return truststore != null && new File(truststore).exists(); } /** * This enables 'hot' reloading of the key/trust stores based on the last updated timestamps if they are file based. */ @Override public synchronized void initHotReloading() { List<HotReloadableFile> fileList = new ArrayList<>(); if (maybeFileBasedPrivateKey && hasKeystore()) { fileList.add(new HotReloadableFile(keystore)); } if (maybeFileBasedTrustedCertificates && hasTruststore()) { fileList.add(new HotReloadableFile(truststore)); } if (!fileList.isEmpty()) { hotReloadableFiles = fileList; } } /** * Builds required KeyManagerFactory from the PEM based keystore. It also checks for the PrivateKey's certificate's * expiry and logs {@code warning} for each expired PrivateKey's certitificate. * * @return KeyManagerFactory built from the PEM based keystore. * @throws SSLException if any issues encountered during the build process */ @Override protected KeyManagerFactory buildKeyManagerFactory() throws SSLException { try { if (hasKeystore()) { if (maybeFileBasedPrivateKey) { pemEncodedKey = readPEMFile(keystore); // read PEM from the file } KeyManagerFactory kmf = KeyManagerFactory.getInstance( algorithm == null ? KeyManagerFactory.getDefaultAlgorithm() : algorithm); KeyStore ks = buildKeyStore(); if (!checkedExpiry) { checkExpiredCerts(ks); checkedExpiry = true; } kmf.init(ks, keyPassword != null ? keyPassword.toCharArray() : null); return kmf; } else { throw new SSLException("Must provide keystore or private_key in configuration for PEMBasedSSlContextFactory"); } } catch (Exception e) { throw new SSLException("Failed to build key manager store for secure connections", e); } } /** * Builds TrustManagerFactory from the PEM based truststore. * * @return TrustManagerFactory from the PEM based truststore * @throws SSLException if any issues encountered during the build process */ @Override protected TrustManagerFactory buildTrustManagerFactory() throws SSLException { try { if (hasTruststore()) { if (maybeFileBasedTrustedCertificates) { pemEncodedCertificates = readPEMFile(truststore); // read PEM from the file } TrustManagerFactory tmf = TrustManagerFactory.getInstance( algorithm == null ? TrustManagerFactory.getDefaultAlgorithm() : algorithm); KeyStore ts = buildTrustStore(); tmf.init(ts); return tmf; } else { throw new SSLException("Must provide truststore or trusted_certificates in configuration for " + "PEMBasedSSlContextFactory"); } } catch (Exception e) { throw new SSLException("Failed to build trust manager store for secure connections", e); } } private String readPEMFile(String file) throws IOException { return new String(Files.readAllBytes(Paths.get(file))); } /** * Builds KeyStore object given the {@link #DEFAULT_TARGET_STORETYPE} out of the PEM formatted private key material. * It uses {@code cassandra-ssl-keystore} as the alias for the created key-entry. */ private KeyStore buildKeyStore() throws GeneralSecurityException, IOException { char[] keyPasswordArray = keyPassword != null ? keyPassword.toCharArray() : null; PrivateKey privateKey = PEMReader.extractPrivateKey(pemEncodedKey, keyPassword); Certificate[] certChainArray = PEMReader.extractCertificates(pemEncodedKey); if (certChainArray == null || certChainArray.length == 0) { throw new SSLException("Could not read any certificates for the certChain for the private key"); } KeyStore keyStore = KeyStore.getInstance(DEFAULT_TARGET_STORETYPE); keyStore.load(null, null); keyStore.setKeyEntry("cassandra-ssl-keystore", privateKey, keyPasswordArray, certChainArray); return keyStore; } /** * Builds KeyStore object given the {@link #DEFAULT_TARGET_STORETYPE} out of the PEM formatted certificates/public-key * material. * <p> * It uses {@code cassandra-ssl-trusted-cert-<numeric-id>} as the alias for the created certificate-entry. */ private KeyStore buildTrustStore() throws GeneralSecurityException, IOException { Certificate[] certChainArray = PEMReader.extractCertificates(pemEncodedCertificates); if (certChainArray == null || certChainArray.length == 0) { throw new SSLException("Could not read any certificates from the given PEM"); } KeyStore keyStore = KeyStore.getInstance(DEFAULT_TARGET_STORETYPE); keyStore.load(null, null); for (int i = 0; i < certChainArray.length; i++) { keyStore.setCertificateEntry("cassandra-ssl-trusted-cert-" + (i + 1), certChainArray[i]); } return keyStore; } /** * Enforces that the configuration specified a sole source of loading private keys - either {@code keystore} (the * actual file must exist) or {@code private_key}, not both. */ private void enforceSinglePrivateKeySource() { if (keystoreFileExists() && !StringUtils.isEmpty(pemEncodedKey)) { throw new IllegalArgumentException("Configuration must specify value for either keystore or private_key, " + "not both for PEMBasedSSlContextFactory"); } } /** * Enforces that the configuration specified a sole source of loading trusted certificates - either {@code * truststore} (actual file must exist) or {@code trusted_certificates}, not both. */ private void enforceSingleTurstedCertificatesSource() { if (truststoreFileExists() && !StringUtils.isEmpty(pemEncodedCertificates)) { throw new IllegalArgumentException("Configuration must specify value for either truststore or " + "trusted_certificates, not both for PEMBasedSSlContextFactory"); } } public enum ConfigKey { ENCODED_KEY("private_key"), KEY_PASSWORD("private_key_password"), ENCODED_CERTIFICATES("trusted_certificates"); final String keyName; ConfigKey(String keyName) { this.keyName = keyName; } String getKeyName() { return keyName; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.yarn; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.GlobalConfiguration; import org.apache.flink.configuration.JobManagerOptions; import org.apache.flink.configuration.ResourceManagerOptions; import org.apache.flink.runtime.client.JobClient; import org.apache.flink.runtime.taskexecutor.TaskManagerServices; import org.apache.flink.runtime.webmonitor.WebMonitorUtils; import org.apache.flink.test.testdata.WordCountData; import org.apache.flink.test.util.TestBaseUtils; import org.apache.flink.util.ExceptionUtils; import org.apache.flink.yarn.cli.FlinkYarnSessionCli; import org.apache.flink.yarn.configuration.YarnConfigOptions; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ArrayNode; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.protocolrecords.StopContainersRequest; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.client.api.YarnClient; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.security.NMTokenIdentifier; import org.apache.hadoop.yarn.server.nodemanager.NodeManager; import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler; import org.apache.log4j.Level; import org.junit.After; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import static junit.framework.TestCase.assertTrue; import static org.apache.flink.yarn.UtilsTest.addTestAppender; import static org.apache.flink.yarn.UtilsTest.checkForLogString; import static org.apache.flink.yarn.util.YarnTestUtils.getTestJarPath; import static org.junit.Assume.assumeTrue; /** * This test starts a MiniYARNCluster with a CapacityScheduler. * Is has, by default a queue called "default". The configuration here adds another queue: "qa-team". */ public class YARNSessionCapacitySchedulerITCase extends YarnTestBase { private static final Logger LOG = LoggerFactory.getLogger(YARNSessionCapacitySchedulerITCase.class); @BeforeClass public static void setup() { YARN_CONFIGURATION.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); YARN_CONFIGURATION.set("yarn.scheduler.capacity.root.queues", "default,qa-team"); YARN_CONFIGURATION.setInt("yarn.scheduler.capacity.root.default.capacity", 40); YARN_CONFIGURATION.setInt("yarn.scheduler.capacity.root.qa-team.capacity", 60); YARN_CONFIGURATION.set(YarnTestBase.TEST_CLUSTER_NAME_KEY, "flink-yarn-tests-capacityscheduler"); startYARNWithConfig(YARN_CONFIGURATION); } /** * Test regular operation, including command line parameter parsing. */ @Test public void testClientStartup() throws IOException { assumeTrue("The new mode does not start TMs upfront.", !isNewMode); LOG.info("Starting testClientStartup()"); runWithArgs(new String[]{"-j", flinkUberjar.getAbsolutePath(), "-t", flinkLibFolder.getAbsolutePath(), "-n", "1", "-jm", "768m", "-tm", "1024m", "-qu", "qa-team"}, "Number of connected TaskManagers changed to 1. Slots available: 1", null, RunTypes.YARN_SESSION, 0); LOG.info("Finished testClientStartup()"); } /** * Test per-job yarn cluster * * <p>This also tests the prefixed CliFrontend options for the YARN case * We also test if the requested parallelism of 2 is passed through. * The parallelism is requested at the YARN client (-ys). */ @Test public void perJobYarnCluster() throws IOException { LOG.info("Starting perJobYarnCluster()"); addTestAppender(JobClient.class, Level.INFO); File exampleJarLocation = getTestJarPath("BatchWordCount.jar"); runWithArgs(new String[]{"run", "-m", "yarn-cluster", "-yj", flinkUberjar.getAbsolutePath(), "-yt", flinkLibFolder.getAbsolutePath(), "-yn", "1", "-ys", "2", //test that the job is executed with a DOP of 2 "-yjm", "768m", "-ytm", "1024m", exampleJarLocation.getAbsolutePath()}, /* test succeeded after this string */ "Program execution finished", /* prohibited strings: (to verify the parallelism) */ // (we should see "DataSink (...) (1/2)" and "DataSink (...) (2/2)" instead) new String[]{"DataSink \\(.*\\) \\(1/1\\) switched to FINISHED"}, RunTypes.CLI_FRONTEND, 0, true); LOG.info("Finished perJobYarnCluster()"); } /** * Test per-job yarn cluster and memory calculations for off-heap use (see FLINK-7400) with the * same job as {@link #perJobYarnCluster()}. * * <p>This ensures that with (any) pre-allocated off-heap memory by us, there is some off-heap * memory remaining for Flink's libraries. Creating task managers will thus fail if no off-heap * memory remains. */ @Test public void perJobYarnClusterOffHeap() throws IOException { LOG.info("Starting perJobYarnCluster()"); addTestAppender(JobClient.class, Level.INFO); File exampleJarLocation = getTestJarPath("BatchWordCount.jar"); // set memory constraints (otherwise this is the same test as perJobYarnCluster() above) final long taskManagerMemoryMB = 1024; //noinspection NumericOverflow if the calculation of the total Java memory size overflows, default configuration parameters are wrong in the first place, so we can ignore this inspection final long networkBuffersMB = TaskManagerServices .calculateNetworkBufferMemory( (taskManagerMemoryMB - ResourceManagerOptions.CONTAINERIZED_HEAP_CUTOFF_MIN.defaultValue()) << 20, new Configuration()) >> 20; final long offHeapMemory = taskManagerMemoryMB - ResourceManagerOptions.CONTAINERIZED_HEAP_CUTOFF_MIN.defaultValue() // cutoff memory (will be added automatically) - networkBuffersMB // amount of memory used for network buffers - 100; // reserve something for the Java heap space runWithArgs(new String[]{"run", "-m", "yarn-cluster", "-yj", flinkUberjar.getAbsolutePath(), "-yt", flinkLibFolder.getAbsolutePath(), "-yn", "1", "-ys", "2", //test that the job is executed with a DOP of 2 "-yjm", "768m", "-ytm", taskManagerMemoryMB + "m", "-yD", "taskmanager.memory.off-heap=true", "-yD", "taskmanager.memory.size=" + offHeapMemory + "m", "-yD", "taskmanager.memory.preallocate=true", exampleJarLocation.getAbsolutePath()}, /* test succeeded after this string */ "Program execution finished", /* prohibited strings: (to verify the parallelism) */ // (we should see "DataSink (...) (1/2)" and "DataSink (...) (2/2)" instead) new String[]{"DataSink \\(.*\\) \\(1/1\\) switched to FINISHED"}, RunTypes.CLI_FRONTEND, 0, true); LOG.info("Finished perJobYarnCluster()"); } /** * Test TaskManager failure and also if the vcores are set correctly (see issue FLINK-2213). */ @Test(timeout = 100000) // timeout after 100 seconds public void testTaskManagerFailure() throws Exception { assumeTrue("The new mode does not start TMs upfront.", !isNewMode); LOG.info("Starting testTaskManagerFailure()"); Runner runner = startWithArgs(new String[]{"-j", flinkUberjar.getAbsolutePath(), "-t", flinkLibFolder.getAbsolutePath(), "-n", "1", "-jm", "768m", "-tm", "1024m", "-s", "3", // set the slots 3 to check if the vCores are set properly! "-nm", "customName", "-Dfancy-configuration-value=veryFancy", "-Dyarn.maximum-failed-containers=3", "-D" + YarnConfigOptions.VCORES.key() + "=2"}, "Number of connected TaskManagers changed to 1. Slots available: 3", RunTypes.YARN_SESSION); Assert.assertEquals(2, getRunningContainers()); // ------------------------ Test if JobManager web interface is accessible ------- final YarnClient yc = YarnClient.createYarnClient(); yc.init(YARN_CONFIGURATION); yc.start(); List<ApplicationReport> apps = yc.getApplications(EnumSet.of(YarnApplicationState.RUNNING)); Assert.assertEquals(1, apps.size()); // Only one running ApplicationReport app = apps.get(0); Assert.assertEquals("customName", app.getName()); String url = app.getTrackingUrl(); if (!url.endsWith("/")) { url += "/"; } if (!url.startsWith("http://")) { url = "http://" + url; } LOG.info("Got application URL from YARN {}", url); String response = TestBaseUtils.getFromHTTP(url + "taskmanagers/"); JsonNode parsedTMs = new ObjectMapper().readTree(response); ArrayNode taskManagers = (ArrayNode) parsedTMs.get("taskmanagers"); Assert.assertNotNull(taskManagers); Assert.assertEquals(1, taskManagers.size()); Assert.assertEquals(3, taskManagers.get(0).get("slotsNumber").asInt()); // get the configuration from webinterface & check if the dynamic properties from YARN show up there. String jsonConfig = TestBaseUtils.getFromHTTP(url + "jobmanager/config"); Map<String, String> parsedConfig = WebMonitorUtils.fromKeyValueJsonArray(jsonConfig); Assert.assertEquals("veryFancy", parsedConfig.get("fancy-configuration-value")); Assert.assertEquals("3", parsedConfig.get("yarn.maximum-failed-containers")); Assert.assertEquals("2", parsedConfig.get(YarnConfigOptions.VCORES.key())); // -------------- FLINK-1902: check if jobmanager hostname/port are shown in web interface // first, get the hostname/port String oC = outContent.toString(); Pattern p = Pattern.compile("Flink JobManager is now running on ([a-zA-Z0-9.-]+):([0-9]+)"); Matcher matches = p.matcher(oC); String hostname = null; String port = null; while (matches.find()) { hostname = matches.group(1).toLowerCase(); port = matches.group(2); } LOG.info("Extracted hostname:port: {} {}", hostname, port); Assert.assertEquals("unable to find hostname in " + jsonConfig, hostname, parsedConfig.get(JobManagerOptions.ADDRESS.key())); Assert.assertEquals("unable to find port in " + jsonConfig, port, parsedConfig.get(JobManagerOptions.PORT.key())); // test logfile access String logs = TestBaseUtils.getFromHTTP(url + "jobmanager/log"); Assert.assertTrue(logs.contains("Starting YARN ApplicationMaster")); Assert.assertTrue(logs.contains("Starting JobManager")); Assert.assertTrue(logs.contains("Starting JobManager Web Frontend")); // ------------------------ Kill container with TaskManager and check if vcores are set correctly ------- // find container id of taskManager: ContainerId taskManagerContainer = null; NodeManager nodeManager = null; UserGroupInformation remoteUgi = null; NMTokenIdentifier nmIdent = null; try { remoteUgi = UserGroupInformation.getCurrentUser(); } catch (IOException e) { LOG.warn("Unable to get curr user", e); Assert.fail(); } for (int nmId = 0; nmId < NUM_NODEMANAGERS; nmId++) { NodeManager nm = yarnCluster.getNodeManager(nmId); ConcurrentMap<ContainerId, Container> containers = nm.getNMContext().getContainers(); for (Map.Entry<ContainerId, Container> entry : containers.entrySet()) { String command = StringUtils.join(entry.getValue().getLaunchContext().getCommands(), " "); if (command.contains(YarnTaskManager.class.getSimpleName())) { taskManagerContainer = entry.getKey(); nodeManager = nm; nmIdent = new NMTokenIdentifier(taskManagerContainer.getApplicationAttemptId(), null, "", 0); // allow myself to do stuff with the container // remoteUgi.addCredentials(entry.getValue().getCredentials()); remoteUgi.addTokenIdentifier(nmIdent); } } sleep(500); } Assert.assertNotNull("Unable to find container with TaskManager", taskManagerContainer); Assert.assertNotNull("Illegal state", nodeManager); yc.stop(); List<ContainerId> toStop = new LinkedList<ContainerId>(); toStop.add(taskManagerContainer); StopContainersRequest scr = StopContainersRequest.newInstance(toStop); try { nodeManager.getNMContext().getContainerManager().stopContainers(scr); } catch (Throwable e) { LOG.warn("Error stopping container", e); Assert.fail("Error stopping container: " + e.getMessage()); } // stateful termination check: // wait until we saw a container being killed and AFTERWARDS a new one launched boolean ok = false; do { LOG.debug("Waiting for correct order of events. Output: {}", errContent.toString()); String o = errContent.toString(); int killedOff = o.indexOf("Container killed by the ApplicationMaster"); if (killedOff != -1) { o = o.substring(killedOff); ok = o.indexOf("Launching TaskManager") > 0; } sleep(1000); } while(!ok); // send "stop" command to command line interface runner.sendStop(); // wait for the thread to stop try { runner.join(); } catch (InterruptedException e) { LOG.warn("Interrupted while stopping runner", e); } LOG.warn("stopped"); // ----------- Send output to logger System.setOut(ORIGINAL_STDOUT); System.setErr(ORIGINAL_STDERR); oC = outContent.toString(); String eC = errContent.toString(); LOG.info("Sending stdout content through logger: \n\n{}\n\n", oC); LOG.info("Sending stderr content through logger: \n\n{}\n\n", eC); // ------ Check if everything happened correctly Assert.assertTrue("Expect to see failed container", eC.contains("New messages from the YARN cluster")); Assert.assertTrue("Expect to see failed container", eC.contains("Container killed by the ApplicationMaster")); Assert.assertTrue("Expect to see new container started", eC.contains("Launching TaskManager") && eC.contains("on host")); // cleanup auth for the subsequent tests. remoteUgi.getTokenIdentifiers().remove(nmIdent); LOG.info("Finished testTaskManagerFailure()"); } /** * Test deployment to non-existing queue & ensure that the system logs a WARN message * for the user. (Users had unexpected behavior of Flink on YARN because they mistyped the * target queue. With an error message, we can help users identifying the issue) */ @Test public void testNonexistingQueueWARNmessage() throws IOException { LOG.info("Starting testNonexistingQueueWARNmessage()"); addTestAppender(AbstractYarnClusterDescriptor.class, Level.WARN); try { runWithArgs(new String[]{"-j", flinkUberjar.getAbsolutePath(), "-t", flinkLibFolder.getAbsolutePath(), "-n", "1", "-jm", "768m", "-tm", "1024m", "-qu", "doesntExist"}, "to unknown queue: doesntExist", null, RunTypes.YARN_SESSION, 1); } catch (Exception e) { assertTrue(ExceptionUtils.findThrowableWithMessage(e, "to unknown queue: doesntExist").isPresent()); } checkForLogString("The specified queue 'doesntExist' does not exist. Available queues"); LOG.info("Finished testNonexistingQueueWARNmessage()"); } /** * Test per-job yarn cluster with the parallelism set at the CliFrontend instead of the YARN client. */ @Test public void perJobYarnClusterWithParallelism() throws IOException { LOG.info("Starting perJobYarnClusterWithParallelism()"); // write log messages to stdout as well, so that the runWithArgs() method // is catching the log output addTestAppender(JobClient.class, Level.INFO); File exampleJarLocation = getTestJarPath("BatchWordCount.jar"); runWithArgs(new String[]{"run", "-p", "2", //test that the job is executed with a DOP of 2 "-m", "yarn-cluster", "-yj", flinkUberjar.getAbsolutePath(), "-yt", flinkLibFolder.getAbsolutePath(), "-yn", "1", "-ys", "2", "-yjm", "768m", "-ytm", "1024m", exampleJarLocation.getAbsolutePath()}, /* test succeeded after this string */ "Program execution finished", /* prohibited strings: (we want to see "DataSink (...) (2/2) switched to FINISHED") */ new String[]{"DataSink \\(.*\\) \\(1/1\\) switched to FINISHED"}, RunTypes.CLI_FRONTEND, 0, true); LOG.info("Finished perJobYarnClusterWithParallelism()"); } /** * Test a fire-and-forget job submission to a YARN cluster. */ @Test(timeout = 60000) public void testDetachedPerJobYarnCluster() throws Exception { LOG.info("Starting testDetachedPerJobYarnCluster()"); File exampleJarLocation = getTestJarPath("BatchWordCount.jar"); testDetachedPerJobYarnClusterInternal(exampleJarLocation.getAbsolutePath()); LOG.info("Finished testDetachedPerJobYarnCluster()"); } /** * Test a fire-and-forget job submission to a YARN cluster. */ @Test(timeout = 60000) public void testDetachedPerJobYarnClusterWithStreamingJob() throws Exception { LOG.info("Starting testDetachedPerJobYarnClusterWithStreamingJob()"); File exampleJarLocation = getTestJarPath("StreamingWordCount.jar"); testDetachedPerJobYarnClusterInternal(exampleJarLocation.getAbsolutePath()); LOG.info("Finished testDetachedPerJobYarnClusterWithStreamingJob()"); } private void testDetachedPerJobYarnClusterInternal(String job) throws Exception { YarnClient yc = YarnClient.createYarnClient(); yc.init(YARN_CONFIGURATION); yc.start(); // get temporary folder for writing output of wordcount example File tmpOutFolder = null; try { tmpOutFolder = tmp.newFolder(); } catch (IOException e) { throw new RuntimeException(e); } // get temporary file for reading input data for wordcount example File tmpInFile; try { tmpInFile = tmp.newFile(); FileUtils.writeStringToFile(tmpInFile, WordCountData.TEXT); } catch (IOException e) { throw new RuntimeException(e); } Runner runner = startWithArgs(new String[]{ "run", "-m", "yarn-cluster", "-yj", flinkUberjar.getAbsolutePath(), "-yt", flinkLibFolder.getAbsolutePath(), "-yn", "1", "-yjm", "768m", // test if the cutoff is passed correctly (only useful when larger than the value // of containerized.heap-cutoff-min (default: 600MB) "-yD", "yarn.heap-cutoff-ratio=0.7", "-yD", "yarn.tags=test-tag", "-ytm", "1024m", "-ys", "2", // test requesting slots from YARN. "-p", "2", "--detached", job, "--input", tmpInFile.getAbsoluteFile().toString(), "--output", tmpOutFolder.getAbsoluteFile().toString()}, "Job has been submitted with JobID", RunTypes.CLI_FRONTEND); // it should usually be 2, but on slow machines, the number varies Assert.assertTrue("There should be at most 2 containers running", getRunningContainers() <= 2); // give the runner some time to detach for (int attempt = 0; runner.isAlive() && attempt < 5; attempt++) { try { Thread.sleep(500); } catch (InterruptedException e) { } } Assert.assertFalse("The runner should detach.", runner.isAlive()); LOG.info("CLI Frontend has returned, so the job is running"); // find out the application id and wait until it has finished. try { List<ApplicationReport> apps = yc.getApplications(EnumSet.of(YarnApplicationState.RUNNING)); ApplicationId tmpAppId; if (apps.size() == 1) { // Better method to find the right appId. But sometimes the app is shutting down very fast // Only one running tmpAppId = apps.get(0).getApplicationId(); LOG.info("waiting for the job with appId {} to finish", tmpAppId); // wait until the app has finished while (yc.getApplications(EnumSet.of(YarnApplicationState.RUNNING)).size() > 0) { sleep(500); } } else { // get appId by finding the latest finished appid apps = yc.getApplications(); Collections.sort(apps, new Comparator<ApplicationReport>() { @Override public int compare(ApplicationReport o1, ApplicationReport o2) { return o1.getApplicationId().compareTo(o2.getApplicationId()) * -1; } }); tmpAppId = apps.get(0).getApplicationId(); LOG.info("Selected {} as the last appId from {}", tmpAppId, Arrays.toString(apps.toArray())); } final ApplicationId id = tmpAppId; // now it has finished. // check the output files. File[] listOfOutputFiles = tmpOutFolder.listFiles(); Assert.assertNotNull("Taskmanager output not found", listOfOutputFiles); LOG.info("The job has finished. TaskManager output files found in {}", tmpOutFolder); // read all output files in output folder to one output string String content = ""; for (File f:listOfOutputFiles) { if (f.isFile()) { content += FileUtils.readFileToString(f) + "\n"; } } //String content = FileUtils.readFileToString(taskmanagerOut); // check for some of the wordcount outputs. Assert.assertTrue("Expected string 'da 5' or '(all,2)' not found in string '" + content + "'", content.contains("da 5") || content.contains("(da,5)") || content.contains("(all,2)")); Assert.assertTrue("Expected string 'der 29' or '(mind,1)' not found in string'" + content + "'", content.contains("der 29") || content.contains("(der,29)") || content.contains("(mind,1)")); // check if the heap size for the TaskManager was set correctly File jobmanagerLog = YarnTestBase.findFile("..", new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.contains("jobmanager.log") && dir.getAbsolutePath().contains(id.toString()); } }); Assert.assertNotNull("Unable to locate JobManager log", jobmanagerLog); content = FileUtils.readFileToString(jobmanagerLog); // TM was started with 1024 but we cut off 70% (NOT THE DEFAULT VALUE) String expected = "Starting TaskManagers"; Assert.assertTrue("Expected string '" + expected + "' not found in JobManager log: '" + jobmanagerLog + "'", content.contains(expected)); expected = " (2/2) (attempt #0) to "; Assert.assertTrue("Expected string '" + expected + "' not found in JobManager log." + "This string checks that the job has been started with a parallelism of 2. Log contents: '" + jobmanagerLog + "'", content.contains(expected)); // make sure the detached app is really finished. LOG.info("Checking again that app has finished"); ApplicationReport rep; do { sleep(500); rep = yc.getApplicationReport(id); LOG.info("Got report {}", rep); } while (rep.getYarnApplicationState() == YarnApplicationState.RUNNING); verifyApplicationTags(rep); } finally { //cleanup the yarn-properties file String confDirPath = System.getenv("FLINK_CONF_DIR"); File configDirectory = new File(confDirPath); LOG.info("testDetachedPerJobYarnClusterInternal: Using configuration directory " + configDirectory.getAbsolutePath()); // load the configuration LOG.info("testDetachedPerJobYarnClusterInternal: Trying to load configuration file"); Configuration configuration = GlobalConfiguration.loadConfiguration(configDirectory.getAbsolutePath()); try { File yarnPropertiesFile = FlinkYarnSessionCli.getYarnPropertiesLocation(configuration.getValue(YarnConfigOptions.PROPERTIES_FILE_LOCATION)); if (yarnPropertiesFile.exists()) { LOG.info("testDetachedPerJobYarnClusterInternal: Cleaning up temporary Yarn address reference: {}", yarnPropertiesFile.getAbsolutePath()); yarnPropertiesFile.delete(); } } catch (Exception e) { LOG.warn("testDetachedPerJobYarnClusterInternal: Exception while deleting the JobManager address file", e); } try { LOG.info("testDetachedPerJobYarnClusterInternal: Closing the yarn client"); yc.stop(); } catch (Exception e) { LOG.warn("testDetachedPerJobYarnClusterInternal: Exception while close the yarn client", e); } } } /** * Ensures that the YARN application tags were set properly. * * <p>Since YARN application tags were only added in Hadoop 2.4, but Flink still supports Hadoop 2.3, reflection is * required to invoke the methods. If the method does not exist, this test passes. */ private void verifyApplicationTags(final ApplicationReport report) throws InvocationTargetException, IllegalAccessException { final Method applicationTagsMethod; Class<ApplicationReport> clazz = ApplicationReport.class; try { // this method is only supported by Hadoop 2.4.0 onwards applicationTagsMethod = clazz.getMethod("getApplicationTags"); } catch (NoSuchMethodException e) { // only verify the tags if the method exists return; } @SuppressWarnings("unchecked") Set<String> applicationTags = (Set<String>) applicationTagsMethod.invoke(report); Assert.assertEquals(Collections.singleton("test-tag"), applicationTags); } @After public void checkForProhibitedLogContents() { ensureNoProhibitedStringInLogFiles(PROHIBITED_STRINGS, WHITELISTED_STRINGS); } }
package uk.nhs.ciao.transport.dts; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.ExchangePattern; import org.apache.camel.Message; import org.apache.camel.ProducerTemplate; import org.apache.camel.Route; import org.apache.camel.builder.PredicateBuilder; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.impl.DefaultExchange; import org.apache.camel.impl.DefaultMessage; import org.apache.camel.impl.DefaultProducerTemplate; import org.apache.camel.util.FileUtil; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PropertiesLoaderUtils; import uk.nhs.ciao.camel.CamelApplication; import uk.nhs.ciao.camel.CamelApplicationRunner; import uk.nhs.ciao.camel.CamelApplicationRunner.AsyncExecution; import uk.nhs.ciao.camel.CamelUtils; import uk.nhs.ciao.configuration.CIAOConfig; import uk.nhs.ciao.configuration.impl.MemoryCipProperties; import uk.nhs.ciao.docs.parser.Document; import uk.nhs.ciao.docs.parser.ParsedDocument; import uk.nhs.ciao.docs.parser.route.InProgressFolderManagerRoute.EventType; import uk.nhs.ciao.docs.parser.route.InProgressFolderManagerRoute.Header; import uk.nhs.ciao.dts.AddressType; import uk.nhs.ciao.dts.ControlFile; import uk.nhs.ciao.dts.Event; import uk.nhs.ciao.dts.MessageType; import uk.nhs.ciao.dts.Status; import uk.nhs.ciao.dts.StatusRecord; import uk.nhs.ciao.transport.itk.envelope.DistributionEnvelope; import uk.nhs.ciao.transport.itk.envelope.DistributionEnvelope.ManifestItem; import uk.nhs.ciao.transport.itk.envelope.InfrastructureResponse; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.google.common.collect.Maps; /** * Tests for the ciao-transport-dts CIP application */ public class DTSTransportApplicationTest { private static final Logger LOGGER = LoggerFactory.getLogger(DTSTransportApplication.class); private static final String CIP_NAME = "ciao-transport-dts"; @Rule public Timeout globalTimeout = Timeout.seconds(30); private ExecutorService executorService; private DTSTransportApplication application; private AsyncExecution execution; private ObjectMapper objectMapper; private ProducerTemplate producerTemplate; @Before public void setup() throws Exception { final CIAOConfig ciaoConfig = setupCiaoConfig(); cleanDirectories(getDTSRootFolder(ciaoConfig)); application = new DTSTransportApplication(ciaoConfig); executorService = Executors.newSingleThreadExecutor(); objectMapper = new ObjectMapper(); } private CIAOConfig setupCiaoConfig() throws IOException { final MemoryCipProperties cipProperties = new MemoryCipProperties(CIP_NAME, "tests"); addProperties(cipProperties, CIP_NAME + ".properties"); addProperties(cipProperties, CIP_NAME + "-test.properties"); return new CIAOConfig(cipProperties); } private void addProperties(final MemoryCipProperties cipProperties, final String resourcePath) throws IOException { final Resource resource = new ClassPathResource(resourcePath); final Properties properties = PropertiesLoaderUtils.loadProperties(resource); cipProperties.addConfigValues(properties); } private void runApplication() throws Exception { LOGGER.info("About to start camel application"); execution = CamelApplicationRunner.runApplication(application, executorService); LOGGER.info("Camel application has started"); } @After public void tearDown() { final File dtsRootFolder = getDTSRootFolder(); try { stopApplication(); } finally { // Always stop the executor service executorService.shutdownNow(); cleanDirectories(dtsRootFolder); } } private File getDTSRootFolder() { try { final CIAOConfig config = CamelApplication.getConfig(getCamelContext()); return getDTSRootFolder(config); } catch (Exception e) { LOGGER.warn("Unable to find the DTS root folder", e); return null; } } private File getDTSRootFolder(final CIAOConfig config) { try { return config == null ? null : new File(config.getConfigValue("dts.rootFolder")); } catch (Exception e) { LOGGER.warn("Unable to find the DTS root folder", e); return null; } } private void cleanDirectories(final File rootFolder) { try { if (rootFolder != null && rootFolder.isDirectory()) { FileUtil.removeDir(rootFolder); } } catch (Exception e) { LOGGER.warn("Unable to clean directories", e); } } private void stopApplication() { if (execution == null) { return; } CamelUtils.stopQuietly(producerTemplate); final CamelContext context = getCamelContext(); try { LOGGER.info("About to stop camel application"); execution.getRunner().stop(); execution.getFuture().get(); // wait for task to complete LOGGER.info("Camel application has stopped"); } catch (Exception e) { LOGGER.warn("Exception while trying to stop camel application", e); } finally { if (context != null) { MockEndpoint.resetMocks(context); } } } private CamelContext getCamelContext() { if (execution == null) { return null; } final List<CamelContext> camelContexts = execution.getRunner().getCamelContexts(); return camelContexts.isEmpty() ? null : camelContexts.get(0); } private ProducerTemplate getProducerTemplate() throws Exception { if (producerTemplate == null) { producerTemplate = new DefaultProducerTemplate(getCamelContext()); producerTemplate.start(); } return producerTemplate; } @Test public void testApplicationStartsUsingSpringConfig() throws Exception { LOGGER.info("Checking the application starts via spring config"); runApplication(); assertNotNull(execution); assertFalse(execution.getRunner().getCamelContexts().isEmpty()); assertNotNull(getCamelContext()); } @SuppressWarnings("deprecation") @Test public void testApplicationProcessesAJsonDocument() throws Exception { LOGGER.info("Checking a parsable document"); runApplication(); final CamelContext context = getCamelContext(); // reroute the output for the folder manager into a mock for testing for (final Route route: Lists.newArrayList(context.getRoutes())) { if (route.getEndpoint().getEndpointUri().endsWith("in-progress-folder-manager")) { context.stopRoute(route.getId()); context.removeRoute(route.getId()); context.addRouteDefinition(route.getRouteContext().getRoute() .to("direct:rerouted-in-progress-folder-manager")); context.startRoute(route.getId()); break; } } context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { // Send an ack whenever a request is received from(context.resolvePropertyPlaceholders("file://{{dts.rootFolder}}/OUT?delete=true")) .choice() .when(PredicateBuilder.endsWith(header(Exchange.FILE_NAME), constant(".ctl"))) .log("***** Creating success response for ${header.CamelFileName}") .bean(new SuccessResponseBuilder()) .to(context.resolvePropertyPlaceholders("file://{{dts.rootFolder}}/SENT?tempPrefix=../sent-temp")) .endChoice() .end() .end(); from("direct:rerouted-in-progress-folder-manager") .filter(header(Header.EVENT_TYPE)) .log("***** Received event message from the InProgressFolderManager") .to("mock:in-progress-folder-manager"); } }); final MockEndpoint inProgressFileManager = MockEndpoint.resolve(context, "mock:in-progress-folder-manager"); inProgressFileManager.expectedMessageCount(2); // Send the initial document to JMS (returns before main processing begins) sendMessage("jms:queue:cda-documents", getExampleJson()); // Wait for ACK response to be processed by the main route MockEndpoint.assertIsSatisfied(5, TimeUnit.SECONDS, inProgressFileManager); final Message sendNotification = inProgressFileManager.getExchanges().get(1).getIn(); Assert.assertEquals(EventType.MESSAGE_SENT, sendNotification.getHeader(Header.EVENT_TYPE)); final ControlFile controlFile = sendNotification.getMandatoryBody(ControlFile.class); Assert.assertEquals(controlFile.getLocalId(), sendNotification.getHeader(Exchange.CORRELATION_ID)); } @Test public void testInfrastructureResponseIsReceived() throws Exception { runApplication(); final CamelContext context = getCamelContext(); context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from(context.resolvePropertyPlaceholders("file://{{dts.rootFolder}}/OUT") + "?sortBy=${file:name}&noop=true") // find control file first .to("mock:output"); } }); final MockEndpoint output = MockEndpoint.resolve(context, "mock:output"); final String trackingId = UUID.randomUUID().toString(); final DistributionEnvelope busAck = new DistributionEnvelope(); busAck.setTrackingId(trackingId); busAck.setService("service"); busAck.getHandlingSpec().setBusinessAck(true); busAck.getHandlingSpec().setInfrastructureAckRequested(true); final ManifestItem manifestItem = new ManifestItem(); manifestItem.setMimeType("application/xml"); busAck.addPayload(manifestItem, "<root></root>"); busAck.applyDefaults(); final ControlFile controlFile = new ControlFile(); controlFile.setAddressType(AddressType.DTS); controlFile.setMessageType(MessageType.Data); controlFile.setLocalId(trackingId); controlFile.setToDTS("sender"); controlFile.setWorkflowId("TOC_DISCH_DMS_ACK"); final StatusRecord statusRecord = new StatusRecord(); statusRecord.setEvent(Event.TRANSFER); statusRecord.setStatus(Status.SUCCESS); statusRecord.setStatusCode("00"); controlFile.setStatusRecord(statusRecord); controlFile.applyDefaults(); final String dtsId = UUID.randomUUID().toString(); final Exchange dataExchange = new DefaultExchange(context); dataExchange.getIn().setBody(busAck, String.class); dataExchange.getIn().setHeader(Exchange.FILE_NAME, dtsId + ".dat"); final Exchange controlExchange = new DefaultExchange(context); controlExchange.getIn().setBody(controlFile, String.class); controlExchange.getIn().setHeader(Exchange.FILE_NAME, dtsId + ".ctl"); // expectations output.expectedMessageCount(2); // control + data for INF ack // publish the files for (final Exchange exchange: Arrays.asList(dataExchange, controlExchange)) { exchange.setPattern(ExchangePattern.InOut); getProducerTemplate().send(context.resolvePropertyPlaceholders("file://{{dts.rootFolder}}/IN?tempPrefix=../in-temp"), exchange); } // assertions MockEndpoint.assertIsSatisfied(10, TimeUnit.SECONDS, output); final ControlFile responseControlFile = output.getExchanges().get(0).getIn().getMandatoryBody(ControlFile.class); Assert.assertEquals(controlFile.getWorkflowId(), responseControlFile.getWorkflowId()); final DistributionEnvelope infAck = output.getExchanges().get(1).getIn().getMandatoryBody(DistributionEnvelope.class); Assert.assertTrue(infAck.containsInfrastructureAck()); final byte[] body = infAck.getDecodedPayloadBody(infAck.getManifestItems().get(0).getId()); final InfrastructureResponse infrastructureResponse = context.getTypeConverter().mandatoryConvertTo( InfrastructureResponse.class, body); Assert.assertEquals(trackingId, infrastructureResponse.getTrackingIdRef()); } public static class SuccessResponseBuilder { public ControlFile createResponse(final ControlFile controlFile) { final ControlFile response = new ControlFile(); response.copyFrom(controlFile, true); final StatusRecord statusRecord = new StatusRecord(); statusRecord.setEvent(Event.TRANSFER); statusRecord.setStatus(Status.SUCCESS); statusRecord.setStatusCode("00"); response.setStatusRecord(statusRecord); response.applyDefaults(); return response; } } private Exchange sendMessage(final String uri, final Message message) throws Exception { final Exchange exchange = getCamelContext().getEndpoint(uri).createExchange(); exchange.getIn().copyFrom(message); return getProducerTemplate().send(uri, exchange); } private Message getExampleJson() throws IOException { final Map<String, Object> properties = Maps.newLinkedHashMap(); properties.put("somekey", "somevalue"); properties.put("itkCorrelationId", "12345"); properties.put("ebxmlCorrelationId", "89EEFD54-7C9E-4B6F-93A8-835CFE6EFC95"); properties.put("receiverPartyId", "BBB-654321"); properties.put("receiverAsid", "000000000000"); properties.put("receiverODSCode", "BBB"); properties.put("receiverCPAId", "S3024519A3110234"); properties.put("itkProfileId", "urn:nhs-en:profile:eDischargeInpatientDischargeSummary-v1-0"); properties.put("itkHandlingSpec", "urn:nhs-itk:interaction:copyRecipientAmbulanceServicePatientReport-v1-0"); final Document originalDocument = new Document("myfile.xml", "<root>content</root>".getBytes(), "text/xml"); final ParsedDocument parsedDocument = new ParsedDocument(originalDocument, properties); final Message message = new DefaultMessage(); message.setBody(objectMapper.writeValueAsString(parsedDocument)); message.setHeader(Exchange.CORRELATION_ID, "12345"); return message; } }
/* * Copyright (C) 2014 iWedia S.A. 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.iwedia.five; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.SharedPreferences; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; import android.widget.Toast; import com.iwedia.five.dtv.DVBManager; import com.iwedia.five.dtv.IPService; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; /** * Parent class off all activities. This class contains connection to dtv * service through dtv manager object. */ public abstract class DTVActivity extends Activity { public static final String TAG = "DTV_EXAMPLE_IP"; private static final String LAST_WATCHED_CHANNEL_INDEX = "last_watched"; public static final String EXTERNAL_MEDIA_PATH = "/mnt/media/"; public static final String IP_CHANNELS = "ip_service_list.txt"; private static DTVActivity instance; /** DTV manager instance. */ protected DVBManager mDVBManager = null; /** List of IP channels */ public static ArrayList<IPService> sIpChannels = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); instance = this; /** Set Full Screen Application. */ requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().clearFlags( WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); /** Creates dtv manager object and connects it to service. */ mDVBManager = DVBManager.getInstance(); mDVBManager.registerCallbacks(); initializeIpChannels(); } /** * Returns object for storing application preferences. */ public static SharedPreferences getSharedPreferences() { return instance.getSharedPreferences(TAG, MODE_PRIVATE); } /** * Save last watched channel index to application preferences. * * @param index * Index to save. */ public static void setLastWatchedChannelIndex(int index) { getSharedPreferences().edit().putInt(LAST_WATCHED_CHANNEL_INDEX, index) .commit(); } /** * Returns last watched channel index. */ public static int getLastWatchedChannelIndex() { return getSharedPreferences().getInt(LAST_WATCHED_CHANNEL_INDEX, 0); } public void finishActivity() { Toast.makeText(this, "Error with DTV service connection, closing application...", Toast.LENGTH_LONG).show(); super.finish(); } /** * Initialize IP channels from assets. */ private void initializeIpChannels() { copyFile(IP_CHANNELS); } /** * Copy configuration file. */ private void copyFile(String filename) { ContextWrapper contextWrapper = new ContextWrapper(this); String file = contextWrapper.getFilesDir().getPath() + "/" + filename; File fl = new File(file); if (!fl.exists()) copyAssetToData(fl); } /** * Copy configuration file from assets to data folder. * * @param strFilename */ private void copyAssetToData(File file) { /** Open your local db as the input stream */ try { InputStream myInput = getAssets().open(file.getName()); String outFileName = file.getPath(); /** Open the empty db as the output stream */ OutputStream myOutput = new FileOutputStream(outFileName); /** transfer bytes from the inputfile to the outputfile */ byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } /** Close the streams */ myOutput.flush(); myOutput.close(); myInput.close(); } catch (Exception e) { e.printStackTrace(); } } /** * Read the configuration file with built-in application which will be * displayed in Content list. */ public static void readFile(Context ctx, String filePath, ArrayList<IPService> arrayList) { File file = new File(filePath); BufferedReader br; try { br = new BufferedReader(new FileReader(file)); String line; String[] separated = new String[2]; while ((line = br.readLine()) != null) { separated = line.split("#"); arrayList.add(new IPService(separated[0], separated[1])); } br.close(); } catch (IOException e) { e.printStackTrace(); } br = null; } /** * Load list of IP channels from external storage. * * @param ipChannels * List to populate with IP channels. */ public void loadIPChannelsFromExternalStorage( ArrayList<IPService> ipChannels) { ArrayList<File> ipServiceListFiles = new ArrayList<File>(); File[] storages = new File(EXTERNAL_MEDIA_PATH).listFiles(); if (storages != null) { /** * Loop through storages */ for (File storage : storages) { File[] foundIpFiles = storage.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { if (pathname.getName().equalsIgnoreCase(IP_CHANNELS)) { return true; } return false; } }); /** * Files with given name are found in this array */ if (foundIpFiles != null) { for (File ip : foundIpFiles) { ipServiceListFiles.add(ip); } } } /** * Loop through found files and add it to IP service list */ for (File ipFile : ipServiceListFiles) { readFile(this, ipFile.getPath(), ipChannels); } /** * No files found */ if (ipServiceListFiles.size() == 0) { Toast.makeText(this, "No files found with name: " + IP_CHANNELS, Toast.LENGTH_LONG).show(); } } } }
/* * Copyright 2015 Daniel Schoonwinkel 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 meesters.wifip2p.connect; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import meesters.wifip2p.deps.IP2PMessage; import meesters.wifip2p.deps.Router; import meesters.wifip2p.deps.Router.MsgType; import android.util.Log; public class ClientThread extends Thread implements IP2PMessageSender, IP2PMessageReceiver { private IClientConnectListener mListener = null; private Socket mSocket = null; private InetAddress mAddress = null; private int mPort = -1; private static final String TAG = "ClientThread"; private IP2PMessageReceiver mP2PMessageReceiver = null; private SocketSendDelegate mSendDelegate = null; private SocketReceiveDelegate mReceiveDelegate = null; private static final int MSG_TIMEOUT = 60; private static final int SOCKET_TIMEOUT = 60; private int mTimeOutCounter = 0; private boolean isConnected = false; private boolean isWaiting = false; public ClientThread(IClientConnectListener listener, InetAddress address, int port) { Log.v(TAG, "ClientThread constructor"); mListener = listener; mAddress = address; mPort = port; } @Override public void run() { Log.v(TAG, "run"); try { mSocket = new Socket(mAddress, mPort); } catch (IOException e) { Log.e(TAG, "Could not open Socket"); e.printStackTrace(); // TODO: Send broadcast here that something went wrong.... mSocket = null; return; } catch (IllegalArgumentException iae) { // Port number was incorrect mSocket = null; Log.e(TAG, "Could not open Socket on specified port"); // TODO: Send broadcast here that port number was wrong... return; } catch (NullPointerException npe) { mSocket = null; Log.e(TAG, "mAddress was null, could not open port"); // TODO: Send broadcast here that port number was wrong... return; } Log.i(TAG, "Client connected"); mListener.onClientConnected(); if (mSocket == null) { Log.e(TAG, "Socket was null, bailing out"); return; } try { mSendDelegate = new SocketSendDelegate(mSocket.getOutputStream(), TAG); // Changed receiver to this, so that we can intercept the messages mReceiveDelegate = new SocketReceiveDelegate( mSocket.getInputStream(), this, TAG); } catch (IOException e) { Log.e(TAG, ": " + "Could not open Output or Input Streams"); e.printStackTrace(); } sendPongP2PMessage(); isConnected = true; mTimeOutThread = new TimeOutThread(); mTimeOutThread.start(); mReceiveDelegate.receiveLoop(); } public Socket getSocket() { Log.v(TAG, "getSocket"); return mSocket; } public void setP2PMessageReceiver(IP2PMessageReceiver receiver) { Log.v(TAG, "setP2PMessageReceiver"); mP2PMessageReceiver = receiver; } public IP2PMessageSender getP2PMessageSender() { Log.v(TAG, "getP2PMessageSender"); return this; } // @Override // public void sendBytes(byte[] data) { // Log.v(TAG, "sendBytes" + new String(data)); // mSendDelegate.sendBytes(data); // } public void sendPongP2PMessage() { // Send a test string String testString = new String("Hello world! :)"); PongP2PMessage msg = new PongP2PMessage("TestMessage", "0", MsgType.PONG_MESSAGE, null, null, testString.getBytes().length, testString.getBytes()); mSendDelegate.sendP2PMessage(msg); } private TimeOutThread mTimeOutThread = null; private class TimeOutThread extends Thread { public void run() { while (true && !isInterrupted() && isConnected) { mTimeOutCounter++; if (mTimeOutCounter > MSG_TIMEOUT) { // Log.e(TAG, "It's been a while since I was refreshed"); if (!isWaiting) { Log.e(TAG, "It's been a while since I was refreshed"); Log.e(TAG, "Sending a Pong message"); sendPongP2PMessage(); isWaiting = true; } else { if (mTimeOutCounter > MSG_TIMEOUT + SOCKET_TIMEOUT) { Log.e(TAG, "Something terrible happened, should I retry the connection?"); if (isConnected) { Log.e(TAG, "Let's retry:"); new Thread() { public void run() { ClientThread.this.run(); } }.start(); } } } } try { sleep(1000); if (mTimeOutCounter % 10 == 0) Log.e(TAG, "mTimeOutThread sleeping " + mTimeOutCounter); } catch (InterruptedException e) { Log.e(TAG, "I was interrupted"); } } } }; public void refresh(PongP2PMessage msg) { Log.e(TAG, "I have been refreshed"); mTimeOutCounter = 0; isWaiting = false; } @Override public void interrupt() { // Only close Socket and ReceiveDelegate if Socket was successfully // opened try { if (mSocket != null) { mSocket.close(); } } catch (IOException e) { Log.e(TAG, "Closing sockets in interrupt failed"); e.printStackTrace(); } if (mReceiveDelegate != null) { mReceiveDelegate.setInterrupted(true); } if (mTimeOutThread != null) { mTimeOutThread.interrupt(); mTimeOutThread = null; } isConnected = false; // super.interrupt(); } @Override public void sendP2PMessage(IP2PMessage msg) { Log.v(TAG, "sendP2PMessage" + msg.toString()); if (mSendDelegate != null) { mSendDelegate.sendP2PMessage(msg); } else { Log.e(TAG, "mSendDelegate was null"); } } @Override public void receiveP2PMessage(IP2PMessage msg) { if (mP2PMessageReceiver != null) { mP2PMessageReceiver.receiveP2PMessage(msg); } if (msg instanceof PongP2PMessage && msg.getMsgType() == Router.MsgType.PONG_ANSW_MESSAGE) { PongP2PMessage pong_msg = (PongP2PMessage) msg; refresh(pong_msg); } } }
/** * 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.waveprotocol.box.server.util; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.annotation.Nullable; import org.waveprotocol.box.common.Receiver; import org.waveprotocol.box.server.waveserver.DeltaStore; import org.waveprotocol.box.server.waveserver.WaveletDeltaRecord; import org.waveprotocol.wave.model.document.util.EmptyDocument; import org.waveprotocol.wave.model.id.IdUtil; import org.waveprotocol.wave.model.id.WaveletId; import org.waveprotocol.wave.model.id.WaveletName; import org.waveprotocol.wave.model.operation.OperationException; import org.waveprotocol.wave.model.operation.wave.TransformedWaveletDelta; import org.waveprotocol.wave.model.operation.wave.WaveletOperation; import org.waveprotocol.wave.model.schema.SchemaCollection; import org.waveprotocol.wave.model.version.HashedVersion; import org.waveprotocol.wave.model.wave.ParticipantId; import org.waveprotocol.wave.model.wave.data.BlipData; import org.waveprotocol.wave.model.wave.data.ObservableWaveletData; import org.waveprotocol.wave.model.wave.data.ReadableWaveletData; import org.waveprotocol.wave.model.wave.data.WaveViewData; import org.waveprotocol.wave.model.wave.data.WaveletData; import org.waveprotocol.wave.model.wave.data.impl.EmptyWaveletSnapshot; import org.waveprotocol.wave.model.wave.data.impl.ObservablePluggableMutableDocument; import org.waveprotocol.wave.model.wave.data.impl.WaveletDataImpl; import com.google.common.base.Preconditions; /** * Utility methods for {@link WaveletData}. * * @author ljvderijk@google.com (Lennard de Rijk) */ public final class WaveletDataUtil { // TODO(ljvderijk): Schemas should be enforced, see issue 109. private static final ObservableWaveletData.Factory<?> WAVELET_FACTORY = WaveletDataImpl.Factory.create( ObservablePluggableMutableDocument.createFactory(SchemaCollection.empty())); private WaveletDataUtil() { } /** * Returns the {@link WaveletName} for the given wavelet. * * @param wavelet the wavelet to get the name for */ public static WaveletName waveletNameOf(ReadableWaveletData wavelet) { return WaveletName.of(wavelet.getWaveId(), wavelet.getWaveletId()); } /** * Apply a delta to the given wavelet. Rolls back the operation if it fails. * * @param delta delta to apply. * @param wavelet the wavelet to apply the operations to. * * @throws OperationException if the operations fail to apply (and are * successfully rolled back). * @throws IllegalStateException if the operations have failed and can not be * rolled back. */ public static void applyWaveletDelta(TransformedWaveletDelta delta, WaveletData wavelet) throws OperationException { Preconditions.checkState(wavelet != null, "wavelet may not be null"); Preconditions.checkState(delta.getAppliedAtVersion() == wavelet.getVersion(), "Delta's version %s doesn't apply to wavelet at %s", delta.getAppliedAtVersion(), wavelet.getVersion()); List<WaveletOperation> reverseOps = new ArrayList<WaveletOperation>(); WaveletOperation lastOp = null; int opsApplied = 0; try { for (WaveletOperation op : delta) { lastOp = op; List<? extends WaveletOperation> reverseOp = op.applyAndReturnReverse(wavelet); reverseOps.addAll(reverseOp); opsApplied++; } } catch (OperationException e) { // Deltas are atomic, so roll back all operations that were successful rollbackWaveletOperations(wavelet, reverseOps); throw new OperationException("Only applied " + opsApplied + " of " + delta.size() + " operations at version " + wavelet.getVersion() + ", rolling back, failed op was " + lastOp, e); } } /** * Like applyWaveletOperations, but throws an {@link IllegalStateException} * when ops fail to apply. Is used for rolling back operations. * * @param ops to apply for rollback */ private static void rollbackWaveletOperations(WaveletData wavelet, List<WaveletOperation> ops) { for (int i = ops.size() - 1; i >= 0; i--) { try { ops.get(i).apply(wavelet); } catch (OperationException e) { throw new IllegalStateException( "Failed to roll back operation with inverse " + ops.get(i), e); } } } /** * Creates an empty wavelet. * * @param waveletName the name of the wavelet. * @param author the author of the wavelet. * @param creationTimestamp the time at which the wavelet is created. */ public static ObservableWaveletData createEmptyWavelet(WaveletName waveletName, ParticipantId author, HashedVersion version, long creationTimestamp) { return copyWavelet(new EmptyWaveletSnapshot(waveletName.waveId, waveletName.waveletId, author, version, creationTimestamp)); } /** * Constructs the wavelet state after the application of the first delta. * * @param waveletName the name of the wavelet. * @param delta first delta to apply at version zero. */ public static ObservableWaveletData buildWaveletFromFirstDelta(WaveletName waveletName, TransformedWaveletDelta delta) throws OperationException { Preconditions.checkArgument(delta.getAppliedAtVersion() == 0, "first delta has non-zero version: %s", delta.getAppliedAtVersion()); ObservableWaveletData wavelet = createEmptyWavelet( waveletName, delta.getAuthor(), // creator HashedVersion.unsigned(0), // garbage hash, is overwritten by first delta below delta.getApplicationTimestamp()); // creation time applyWaveletDelta(delta, wavelet); return wavelet; } /** * Reads all deltas from the given iterator and constructs the end * wavelet state by successive application of all deltas beginning * from the empty wavelet. * * @param waveletName the name of the wavelet. * @param deltas non-empty, contiguous sequence of non-empty deltas beginning * from version zero. */ public static ObservableWaveletData buildWaveletFromDeltas(WaveletName waveletName, Iterator<TransformedWaveletDelta> deltas) throws OperationException { Preconditions.checkArgument(deltas.hasNext(), "empty deltas"); ObservableWaveletData wavelet = buildWaveletFromFirstDelta(waveletName, deltas.next()); while (deltas.hasNext()) { TransformedWaveletDelta delta = deltas.next(); applyWaveletDelta(delta, wavelet); } return wavelet; } public static ObservableWaveletData buildWaveletFromDeltaAccess( DeltaStore.DeltasAccess deltaAccess) throws OperationException, IOException { Preconditions.checkArgument(!deltaAccess.isEmpty(), "empty deltas"); WaveletDeltaRecord initDelta = deltaAccess.getDelta(0); final ObservableWaveletData wavelet = createEmptyWavelet( deltaAccess.getWaveletName(), initDelta.getAuthor(), // creator HashedVersion.unsigned(0), // garbage hash, is overwritten by first delta below initDelta.getApplicationTimestamp()); // creation time try { deltaAccess.getAllDeltas(new Receiver<WaveletDeltaRecord>() { @Override public boolean put(WaveletDeltaRecord deltaRecord) { try { applyWaveletDelta(deltaRecord.getTransformedDelta(), wavelet); } catch (OperationException e) { return false; } catch (IllegalStateException e) { return false; } return true; } }); } catch (Exception e) { throw new OperationException(e); } return wavelet; } /** * Copies a wavelet. * * @param wavelet the wavelet to copy. * @return A mutable copy. */ public static ObservableWaveletData copyWavelet(ReadableWaveletData wavelet) { return WAVELET_FACTORY.create(wavelet); } /** * Adds an empty blip to the given wavelet. * * @param wavelet the wavelet to add the blip to. * @param blipId the id of the blip to add. * @param author the author of this blip (will also be the only participant). * @param time the time to set in the blip as creation/lastmodified time. */ public static BlipData addEmptyBlip( WaveletData wavelet, String blipId, ParticipantId author, long time) { return wavelet.createDocument(blipId, author, Collections.<ParticipantId>singleton(author), EmptyDocument.EMPTY_DOCUMENT, time, time); } /** * @return true if the wave has conversational root wavelet. */ public static boolean hasConversationalRootWavelet(@Nullable WaveViewData wave) { if (wave == null) { return false; } for (ObservableWaveletData waveletData : wave.getWavelets()) { WaveletId waveletId = waveletData.getWaveletId(); if (IdUtil.isConversationRootWaveletId(waveletId)) { return true; } } return false; } /** * Checks if the user has access to the wavelet. * * @deprecated replaced by {@link WaveletAccessCheccker} * * @param snapshot * the wavelet data. * @param user * the user that wants to access the wavelet. * @param sharedDomainParticipantId * the shared domain participant id. * @return true if the user has access to the wavelet. */ @Deprecated public static boolean checkAccessPermission(ReadableWaveletData snapshot, ParticipantId user, ParticipantId sharedDomainParticipantId) { return user != null && (snapshot == null || snapshot.getParticipants().contains(user) || (sharedDomainParticipantId != null && snapshot.getParticipants().contains(sharedDomainParticipantId))); } }
/* Generated by camel build tools - do NOT edit this file! */ package org.apache.camel.component.debezium; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.spi.GeneratedPropertyConfigurer; import org.apache.camel.spi.PropertyConfigurerGetter; import org.apache.camel.util.CaseInsensitiveMap; import org.apache.camel.support.component.PropertyConfigurerSupport; /** * Generated by camel build tools - do NOT edit this file! */ @SuppressWarnings("unchecked") public class DebeziumPostgresEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("name", java.lang.String.class); map.put("additionalProperties", java.util.Map.class); map.put("bridgeErrorHandler", boolean.class); map.put("internalKeyConverter", java.lang.String.class); map.put("internalValueConverter", java.lang.String.class); map.put("offsetCommitPolicy", java.lang.String.class); map.put("offsetCommitTimeoutMs", long.class); map.put("offsetFlushIntervalMs", long.class); map.put("offsetStorage", java.lang.String.class); map.put("offsetStorageFileName", java.lang.String.class); map.put("offsetStoragePartitions", int.class); map.put("offsetStorageReplicationFactor", int.class); map.put("offsetStorageTopic", java.lang.String.class); map.put("exceptionHandler", org.apache.camel.spi.ExceptionHandler.class); map.put("exchangePattern", org.apache.camel.ExchangePattern.class); map.put("basicPropertyBinding", boolean.class); map.put("synchronous", boolean.class); map.put("binaryHandlingMode", java.lang.String.class); map.put("columnBlacklist", java.lang.String.class); map.put("columnWhitelist", java.lang.String.class); map.put("converters", java.lang.String.class); map.put("databaseDbname", java.lang.String.class); map.put("databaseHistoryFileFilename", java.lang.String.class); map.put("databaseHostname", java.lang.String.class); map.put("databaseInitialStatements", java.lang.String.class); map.put("databasePassword", java.lang.String.class); map.put("databasePort", int.class); map.put("databaseServerName", java.lang.String.class); map.put("databaseSslcert", java.lang.String.class); map.put("databaseSslfactory", java.lang.String.class); map.put("databaseSslkey", java.lang.String.class); map.put("databaseSslmode", java.lang.String.class); map.put("databaseSslpassword", java.lang.String.class); map.put("databaseSslrootcert", java.lang.String.class); map.put("databaseTcpkeepalive", boolean.class); map.put("databaseUser", java.lang.String.class); map.put("decimalHandlingMode", java.lang.String.class); map.put("eventProcessingFailureHandlingMode", java.lang.String.class); map.put("heartbeatActionQuery", java.lang.String.class); map.put("heartbeatIntervalMs", int.class); map.put("heartbeatTopicsPrefix", java.lang.String.class); map.put("hstoreHandlingMode", java.lang.String.class); map.put("includeUnknownDatatypes", boolean.class); map.put("intervalHandlingMode", java.lang.String.class); map.put("maxBatchSize", int.class); map.put("maxQueueSize", int.class); map.put("messageKeyColumns", java.lang.String.class); map.put("pluginName", java.lang.String.class); map.put("pollIntervalMs", long.class); map.put("provideTransactionMetadata", boolean.class); map.put("publicationAutocreateMode", java.lang.String.class); map.put("publicationName", java.lang.String.class); map.put("sanitizeFieldNames", boolean.class); map.put("schemaBlacklist", java.lang.String.class); map.put("schemaRefreshMode", java.lang.String.class); map.put("schemaWhitelist", java.lang.String.class); map.put("skippedOperations", java.lang.String.class); map.put("slotDropOnStop", boolean.class); map.put("slotMaxRetries", int.class); map.put("slotName", java.lang.String.class); map.put("slotRetryDelayMs", long.class); map.put("slotStreamParams", java.lang.String.class); map.put("snapshotCustomClass", java.lang.String.class); map.put("snapshotDelayMs", long.class); map.put("snapshotFetchSize", int.class); map.put("snapshotLockTimeoutMs", long.class); map.put("snapshotMode", java.lang.String.class); map.put("snapshotSelectStatementOverrides", java.lang.String.class); map.put("sourceStructVersion", java.lang.String.class); map.put("statusUpdateIntervalMs", int.class); map.put("tableBlacklist", java.lang.String.class); map.put("tableIgnoreBuiltin", boolean.class); map.put("tableWhitelist", java.lang.String.class); map.put("timePrecisionMode", java.lang.String.class); map.put("toastedValuePlaceholder", java.lang.String.class); map.put("tombstonesOnDelete", boolean.class); map.put("xminFetchIntervalMs", long.class); ALL_OPTIONS = map; } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { DebeziumPostgresEndpoint target = (DebeziumPostgresEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "additionalproperties": case "additionalProperties": target.getConfiguration().setAdditionalProperties(property(camelContext, java.util.Map.class, value)); return true; case "basicpropertybinding": case "basicPropertyBinding": target.setBasicPropertyBinding(property(camelContext, boolean.class, value)); return true; case "binaryhandlingmode": case "binaryHandlingMode": target.getConfiguration().setBinaryHandlingMode(property(camelContext, java.lang.String.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "columnblacklist": case "columnBlacklist": target.getConfiguration().setColumnBlacklist(property(camelContext, java.lang.String.class, value)); return true; case "columnwhitelist": case "columnWhitelist": target.getConfiguration().setColumnWhitelist(property(camelContext, java.lang.String.class, value)); return true; case "converters": target.getConfiguration().setConverters(property(camelContext, java.lang.String.class, value)); return true; case "databasedbname": case "databaseDbname": target.getConfiguration().setDatabaseDbname(property(camelContext, java.lang.String.class, value)); return true; case "databasehistoryfilefilename": case "databaseHistoryFileFilename": target.getConfiguration().setDatabaseHistoryFileFilename(property(camelContext, java.lang.String.class, value)); return true; case "databasehostname": case "databaseHostname": target.getConfiguration().setDatabaseHostname(property(camelContext, java.lang.String.class, value)); return true; case "databaseinitialstatements": case "databaseInitialStatements": target.getConfiguration().setDatabaseInitialStatements(property(camelContext, java.lang.String.class, value)); return true; case "databasepassword": case "databasePassword": target.getConfiguration().setDatabasePassword(property(camelContext, java.lang.String.class, value)); return true; case "databaseport": case "databasePort": target.getConfiguration().setDatabasePort(property(camelContext, int.class, value)); return true; case "databaseservername": case "databaseServerName": target.getConfiguration().setDatabaseServerName(property(camelContext, java.lang.String.class, value)); return true; case "databasesslcert": case "databaseSslcert": target.getConfiguration().setDatabaseSslcert(property(camelContext, java.lang.String.class, value)); return true; case "databasesslfactory": case "databaseSslfactory": target.getConfiguration().setDatabaseSslfactory(property(camelContext, java.lang.String.class, value)); return true; case "databasesslkey": case "databaseSslkey": target.getConfiguration().setDatabaseSslkey(property(camelContext, java.lang.String.class, value)); return true; case "databasesslmode": case "databaseSslmode": target.getConfiguration().setDatabaseSslmode(property(camelContext, java.lang.String.class, value)); return true; case "databasesslpassword": case "databaseSslpassword": target.getConfiguration().setDatabaseSslpassword(property(camelContext, java.lang.String.class, value)); return true; case "databasesslrootcert": case "databaseSslrootcert": target.getConfiguration().setDatabaseSslrootcert(property(camelContext, java.lang.String.class, value)); return true; case "databasetcpkeepalive": case "databaseTcpkeepalive": target.getConfiguration().setDatabaseTcpkeepalive(property(camelContext, boolean.class, value)); return true; case "databaseuser": case "databaseUser": target.getConfiguration().setDatabaseUser(property(camelContext, java.lang.String.class, value)); return true; case "decimalhandlingmode": case "decimalHandlingMode": target.getConfiguration().setDecimalHandlingMode(property(camelContext, java.lang.String.class, value)); return true; case "eventprocessingfailurehandlingmode": case "eventProcessingFailureHandlingMode": target.getConfiguration().setEventProcessingFailureHandlingMode(property(camelContext, java.lang.String.class, value)); return true; case "exceptionhandler": case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true; case "exchangepattern": case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true; case "heartbeatactionquery": case "heartbeatActionQuery": target.getConfiguration().setHeartbeatActionQuery(property(camelContext, java.lang.String.class, value)); return true; case "heartbeatintervalms": case "heartbeatIntervalMs": target.getConfiguration().setHeartbeatIntervalMs(property(camelContext, int.class, value)); return true; case "heartbeattopicsprefix": case "heartbeatTopicsPrefix": target.getConfiguration().setHeartbeatTopicsPrefix(property(camelContext, java.lang.String.class, value)); return true; case "hstorehandlingmode": case "hstoreHandlingMode": target.getConfiguration().setHstoreHandlingMode(property(camelContext, java.lang.String.class, value)); return true; case "includeunknowndatatypes": case "includeUnknownDatatypes": target.getConfiguration().setIncludeUnknownDatatypes(property(camelContext, boolean.class, value)); return true; case "internalkeyconverter": case "internalKeyConverter": target.getConfiguration().setInternalKeyConverter(property(camelContext, java.lang.String.class, value)); return true; case "internalvalueconverter": case "internalValueConverter": target.getConfiguration().setInternalValueConverter(property(camelContext, java.lang.String.class, value)); return true; case "intervalhandlingmode": case "intervalHandlingMode": target.getConfiguration().setIntervalHandlingMode(property(camelContext, java.lang.String.class, value)); return true; case "maxbatchsize": case "maxBatchSize": target.getConfiguration().setMaxBatchSize(property(camelContext, int.class, value)); return true; case "maxqueuesize": case "maxQueueSize": target.getConfiguration().setMaxQueueSize(property(camelContext, int.class, value)); return true; case "messagekeycolumns": case "messageKeyColumns": target.getConfiguration().setMessageKeyColumns(property(camelContext, java.lang.String.class, value)); return true; case "offsetcommitpolicy": case "offsetCommitPolicy": target.getConfiguration().setOffsetCommitPolicy(property(camelContext, java.lang.String.class, value)); return true; case "offsetcommittimeoutms": case "offsetCommitTimeoutMs": target.getConfiguration().setOffsetCommitTimeoutMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "offsetflushintervalms": case "offsetFlushIntervalMs": target.getConfiguration().setOffsetFlushIntervalMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "offsetstorage": case "offsetStorage": target.getConfiguration().setOffsetStorage(property(camelContext, java.lang.String.class, value)); return true; case "offsetstoragefilename": case "offsetStorageFileName": target.getConfiguration().setOffsetStorageFileName(property(camelContext, java.lang.String.class, value)); return true; case "offsetstoragepartitions": case "offsetStoragePartitions": target.getConfiguration().setOffsetStoragePartitions(property(camelContext, int.class, value)); return true; case "offsetstoragereplicationfactor": case "offsetStorageReplicationFactor": target.getConfiguration().setOffsetStorageReplicationFactor(property(camelContext, int.class, value)); return true; case "offsetstoragetopic": case "offsetStorageTopic": target.getConfiguration().setOffsetStorageTopic(property(camelContext, java.lang.String.class, value)); return true; case "pluginname": case "pluginName": target.getConfiguration().setPluginName(property(camelContext, java.lang.String.class, value)); return true; case "pollintervalms": case "pollIntervalMs": target.getConfiguration().setPollIntervalMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "providetransactionmetadata": case "provideTransactionMetadata": target.getConfiguration().setProvideTransactionMetadata(property(camelContext, boolean.class, value)); return true; case "publicationautocreatemode": case "publicationAutocreateMode": target.getConfiguration().setPublicationAutocreateMode(property(camelContext, java.lang.String.class, value)); return true; case "publicationname": case "publicationName": target.getConfiguration().setPublicationName(property(camelContext, java.lang.String.class, value)); return true; case "sanitizefieldnames": case "sanitizeFieldNames": target.getConfiguration().setSanitizeFieldNames(property(camelContext, boolean.class, value)); return true; case "schemablacklist": case "schemaBlacklist": target.getConfiguration().setSchemaBlacklist(property(camelContext, java.lang.String.class, value)); return true; case "schemarefreshmode": case "schemaRefreshMode": target.getConfiguration().setSchemaRefreshMode(property(camelContext, java.lang.String.class, value)); return true; case "schemawhitelist": case "schemaWhitelist": target.getConfiguration().setSchemaWhitelist(property(camelContext, java.lang.String.class, value)); return true; case "skippedoperations": case "skippedOperations": target.getConfiguration().setSkippedOperations(property(camelContext, java.lang.String.class, value)); return true; case "slotdroponstop": case "slotDropOnStop": target.getConfiguration().setSlotDropOnStop(property(camelContext, boolean.class, value)); return true; case "slotmaxretries": case "slotMaxRetries": target.getConfiguration().setSlotMaxRetries(property(camelContext, int.class, value)); return true; case "slotname": case "slotName": target.getConfiguration().setSlotName(property(camelContext, java.lang.String.class, value)); return true; case "slotretrydelayms": case "slotRetryDelayMs": target.getConfiguration().setSlotRetryDelayMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "slotstreamparams": case "slotStreamParams": target.getConfiguration().setSlotStreamParams(property(camelContext, java.lang.String.class, value)); return true; case "snapshotcustomclass": case "snapshotCustomClass": target.getConfiguration().setSnapshotCustomClass(property(camelContext, java.lang.String.class, value)); return true; case "snapshotdelayms": case "snapshotDelayMs": target.getConfiguration().setSnapshotDelayMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "snapshotfetchsize": case "snapshotFetchSize": target.getConfiguration().setSnapshotFetchSize(property(camelContext, int.class, value)); return true; case "snapshotlocktimeoutms": case "snapshotLockTimeoutMs": target.getConfiguration().setSnapshotLockTimeoutMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "snapshotmode": case "snapshotMode": target.getConfiguration().setSnapshotMode(property(camelContext, java.lang.String.class, value)); return true; case "snapshotselectstatementoverrides": case "snapshotSelectStatementOverrides": target.getConfiguration().setSnapshotSelectStatementOverrides(property(camelContext, java.lang.String.class, value)); return true; case "sourcestructversion": case "sourceStructVersion": target.getConfiguration().setSourceStructVersion(property(camelContext, java.lang.String.class, value)); return true; case "statusupdateintervalms": case "statusUpdateIntervalMs": target.getConfiguration().setStatusUpdateIntervalMs(property(camelContext, int.class, value)); return true; case "synchronous": target.setSynchronous(property(camelContext, boolean.class, value)); return true; case "tableblacklist": case "tableBlacklist": target.getConfiguration().setTableBlacklist(property(camelContext, java.lang.String.class, value)); return true; case "tableignorebuiltin": case "tableIgnoreBuiltin": target.getConfiguration().setTableIgnoreBuiltin(property(camelContext, boolean.class, value)); return true; case "tablewhitelist": case "tableWhitelist": target.getConfiguration().setTableWhitelist(property(camelContext, java.lang.String.class, value)); return true; case "timeprecisionmode": case "timePrecisionMode": target.getConfiguration().setTimePrecisionMode(property(camelContext, java.lang.String.class, value)); return true; case "toastedvalueplaceholder": case "toastedValuePlaceholder": target.getConfiguration().setToastedValuePlaceholder(property(camelContext, java.lang.String.class, value)); return true; case "tombstonesondelete": case "tombstonesOnDelete": target.getConfiguration().setTombstonesOnDelete(property(camelContext, boolean.class, value)); return true; case "xminfetchintervalms": case "xminFetchIntervalMs": target.getConfiguration().setXminFetchIntervalMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { DebeziumPostgresEndpoint target = (DebeziumPostgresEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "additionalproperties": case "additionalProperties": return target.getConfiguration().getAdditionalProperties(); case "basicpropertybinding": case "basicPropertyBinding": return target.isBasicPropertyBinding(); case "binaryhandlingmode": case "binaryHandlingMode": return target.getConfiguration().getBinaryHandlingMode(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "columnblacklist": case "columnBlacklist": return target.getConfiguration().getColumnBlacklist(); case "columnwhitelist": case "columnWhitelist": return target.getConfiguration().getColumnWhitelist(); case "converters": return target.getConfiguration().getConverters(); case "databasedbname": case "databaseDbname": return target.getConfiguration().getDatabaseDbname(); case "databasehistoryfilefilename": case "databaseHistoryFileFilename": return target.getConfiguration().getDatabaseHistoryFileFilename(); case "databasehostname": case "databaseHostname": return target.getConfiguration().getDatabaseHostname(); case "databaseinitialstatements": case "databaseInitialStatements": return target.getConfiguration().getDatabaseInitialStatements(); case "databasepassword": case "databasePassword": return target.getConfiguration().getDatabasePassword(); case "databaseport": case "databasePort": return target.getConfiguration().getDatabasePort(); case "databaseservername": case "databaseServerName": return target.getConfiguration().getDatabaseServerName(); case "databasesslcert": case "databaseSslcert": return target.getConfiguration().getDatabaseSslcert(); case "databasesslfactory": case "databaseSslfactory": return target.getConfiguration().getDatabaseSslfactory(); case "databasesslkey": case "databaseSslkey": return target.getConfiguration().getDatabaseSslkey(); case "databasesslmode": case "databaseSslmode": return target.getConfiguration().getDatabaseSslmode(); case "databasesslpassword": case "databaseSslpassword": return target.getConfiguration().getDatabaseSslpassword(); case "databasesslrootcert": case "databaseSslrootcert": return target.getConfiguration().getDatabaseSslrootcert(); case "databasetcpkeepalive": case "databaseTcpkeepalive": return target.getConfiguration().isDatabaseTcpkeepalive(); case "databaseuser": case "databaseUser": return target.getConfiguration().getDatabaseUser(); case "decimalhandlingmode": case "decimalHandlingMode": return target.getConfiguration().getDecimalHandlingMode(); case "eventprocessingfailurehandlingmode": case "eventProcessingFailureHandlingMode": return target.getConfiguration().getEventProcessingFailureHandlingMode(); case "exceptionhandler": case "exceptionHandler": return target.getExceptionHandler(); case "exchangepattern": case "exchangePattern": return target.getExchangePattern(); case "heartbeatactionquery": case "heartbeatActionQuery": return target.getConfiguration().getHeartbeatActionQuery(); case "heartbeatintervalms": case "heartbeatIntervalMs": return target.getConfiguration().getHeartbeatIntervalMs(); case "heartbeattopicsprefix": case "heartbeatTopicsPrefix": return target.getConfiguration().getHeartbeatTopicsPrefix(); case "hstorehandlingmode": case "hstoreHandlingMode": return target.getConfiguration().getHstoreHandlingMode(); case "includeunknowndatatypes": case "includeUnknownDatatypes": return target.getConfiguration().isIncludeUnknownDatatypes(); case "internalkeyconverter": case "internalKeyConverter": return target.getConfiguration().getInternalKeyConverter(); case "internalvalueconverter": case "internalValueConverter": return target.getConfiguration().getInternalValueConverter(); case "intervalhandlingmode": case "intervalHandlingMode": return target.getConfiguration().getIntervalHandlingMode(); case "maxbatchsize": case "maxBatchSize": return target.getConfiguration().getMaxBatchSize(); case "maxqueuesize": case "maxQueueSize": return target.getConfiguration().getMaxQueueSize(); case "messagekeycolumns": case "messageKeyColumns": return target.getConfiguration().getMessageKeyColumns(); case "offsetcommitpolicy": case "offsetCommitPolicy": return target.getConfiguration().getOffsetCommitPolicy(); case "offsetcommittimeoutms": case "offsetCommitTimeoutMs": return target.getConfiguration().getOffsetCommitTimeoutMs(); case "offsetflushintervalms": case "offsetFlushIntervalMs": return target.getConfiguration().getOffsetFlushIntervalMs(); case "offsetstorage": case "offsetStorage": return target.getConfiguration().getOffsetStorage(); case "offsetstoragefilename": case "offsetStorageFileName": return target.getConfiguration().getOffsetStorageFileName(); case "offsetstoragepartitions": case "offsetStoragePartitions": return target.getConfiguration().getOffsetStoragePartitions(); case "offsetstoragereplicationfactor": case "offsetStorageReplicationFactor": return target.getConfiguration().getOffsetStorageReplicationFactor(); case "offsetstoragetopic": case "offsetStorageTopic": return target.getConfiguration().getOffsetStorageTopic(); case "pluginname": case "pluginName": return target.getConfiguration().getPluginName(); case "pollintervalms": case "pollIntervalMs": return target.getConfiguration().getPollIntervalMs(); case "providetransactionmetadata": case "provideTransactionMetadata": return target.getConfiguration().isProvideTransactionMetadata(); case "publicationautocreatemode": case "publicationAutocreateMode": return target.getConfiguration().getPublicationAutocreateMode(); case "publicationname": case "publicationName": return target.getConfiguration().getPublicationName(); case "sanitizefieldnames": case "sanitizeFieldNames": return target.getConfiguration().isSanitizeFieldNames(); case "schemablacklist": case "schemaBlacklist": return target.getConfiguration().getSchemaBlacklist(); case "schemarefreshmode": case "schemaRefreshMode": return target.getConfiguration().getSchemaRefreshMode(); case "schemawhitelist": case "schemaWhitelist": return target.getConfiguration().getSchemaWhitelist(); case "skippedoperations": case "skippedOperations": return target.getConfiguration().getSkippedOperations(); case "slotdroponstop": case "slotDropOnStop": return target.getConfiguration().isSlotDropOnStop(); case "slotmaxretries": case "slotMaxRetries": return target.getConfiguration().getSlotMaxRetries(); case "slotname": case "slotName": return target.getConfiguration().getSlotName(); case "slotretrydelayms": case "slotRetryDelayMs": return target.getConfiguration().getSlotRetryDelayMs(); case "slotstreamparams": case "slotStreamParams": return target.getConfiguration().getSlotStreamParams(); case "snapshotcustomclass": case "snapshotCustomClass": return target.getConfiguration().getSnapshotCustomClass(); case "snapshotdelayms": case "snapshotDelayMs": return target.getConfiguration().getSnapshotDelayMs(); case "snapshotfetchsize": case "snapshotFetchSize": return target.getConfiguration().getSnapshotFetchSize(); case "snapshotlocktimeoutms": case "snapshotLockTimeoutMs": return target.getConfiguration().getSnapshotLockTimeoutMs(); case "snapshotmode": case "snapshotMode": return target.getConfiguration().getSnapshotMode(); case "snapshotselectstatementoverrides": case "snapshotSelectStatementOverrides": return target.getConfiguration().getSnapshotSelectStatementOverrides(); case "sourcestructversion": case "sourceStructVersion": return target.getConfiguration().getSourceStructVersion(); case "statusupdateintervalms": case "statusUpdateIntervalMs": return target.getConfiguration().getStatusUpdateIntervalMs(); case "synchronous": return target.isSynchronous(); case "tableblacklist": case "tableBlacklist": return target.getConfiguration().getTableBlacklist(); case "tableignorebuiltin": case "tableIgnoreBuiltin": return target.getConfiguration().isTableIgnoreBuiltin(); case "tablewhitelist": case "tableWhitelist": return target.getConfiguration().getTableWhitelist(); case "timeprecisionmode": case "timePrecisionMode": return target.getConfiguration().getTimePrecisionMode(); case "toastedvalueplaceholder": case "toastedValuePlaceholder": return target.getConfiguration().getToastedValuePlaceholder(); case "tombstonesondelete": case "tombstonesOnDelete": return target.getConfiguration().isTombstonesOnDelete(); case "xminfetchintervalms": case "xminFetchIntervalMs": return target.getConfiguration().getXminFetchIntervalMs(); default: return null; } } }
/* * The MIT License (MIT) * * Copyright (c) 2014 Marcel Mika, marcelmika.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.marcelmika.lims.persistence.service; import com.marcelmika.lims.api.entity.BuddyDetails; import com.marcelmika.lims.api.environment.Environment; import com.marcelmika.lims.api.events.buddy.*; import com.marcelmika.lims.persistence.domain.Buddy; import com.marcelmika.lims.persistence.domain.Presence; import com.marcelmika.lims.persistence.generated.model.Settings; import com.marcelmika.lims.persistence.generated.service.SettingsLocalServiceUtil; import com.marcelmika.lims.persistence.manager.SearchManager; import java.util.LinkedList; import java.util.List; /** * @author Ing. Marcel Mika * @link http://marcelmika.com * Date: 2/4/14 * Time: 11:56 PM */ public class BuddyPersistenceServiceImpl implements BuddyPersistenceService { // Dependencies SearchManager searchManager; /** * Constructor * * @param searchManager SearchManager */ public BuddyPersistenceServiceImpl(final SearchManager searchManager) { this.searchManager = searchManager; } /** * Login buddy to System * * @param event Request event for login method * @return Response event for login method */ @Override public LoginBuddyResponseEvent loginBuddy(LoginBuddyRequestEvent event) { // Get buddy from buddy details Buddy buddy = Buddy.fromBuddyDetails(event.getDetails()); try { // Take presence from user settings Settings settings = SettingsLocalServiceUtil.getSettingsByUser(buddy.getBuddyId()); // If the user disabled the chat keep it offline if (settings.isChatEnabled()) { // When the user logs in, change the presence to active SettingsLocalServiceUtil.changePresence(buddy.getBuddyId(), Presence.ACTIVE.getDescription()); } // Call success return LoginBuddyResponseEvent.loginSuccess(buddy.toBuddyDetails()); } catch (Exception exception) { // Call failure return LoginBuddyResponseEvent.loginFailure( LoginBuddyResponseEvent.Status.ERROR_PERSISTENCE, exception ); } } /** * Logout buddy from System * * @param event Request event for logout method * @return Response event for logout method */ @Override public LogoutBuddyResponseEvent logoutBuddy(LogoutBuddyRequestEvent event) { // Get buddy from buddy details Buddy buddy = Buddy.fromBuddyDetails(event.getDetails()); try { // Change presence to offline SettingsLocalServiceUtil.changePresence(buddy.getBuddyId(), Presence.OFFLINE.getDescription()); // Call success return LogoutBuddyResponseEvent.logoutSuccess("User successfully logged out", buddy.toBuddyDetails()); } catch (Exception e) { // Call failure return LogoutBuddyResponseEvent.logoutFailure(e.getLocalizedMessage(), buddy.toBuddyDetails()); } } /** * Completely removes buddy from Persistence * * @param event Request event for logout method * @return Response event for logout method */ @Override public DeleteBuddyResponseEvent removeBuddy(DeleteBuddyRequestEvent event) { // Get buddy from buddy details Buddy buddy = Buddy.fromBuddyDetails(event.getDetails()); try { // Remove settings from database Settings settings = SettingsLocalServiceUtil.getSettingsByUser(buddy.getBuddyId()); if (settings != null) { // Delete only if the user is in the system otherwise do nothing SettingsLocalServiceUtil.deleteSettings(settings); } // Success return DeleteBuddyResponseEvent.removeSuccess("Buddy " + buddy.getBuddyId() + " has been successfully " + "removed from the persistence layer", buddy.toBuddyDetails()); } catch (Exception e) { // Failure return DeleteBuddyResponseEvent.removeFailure( "Cannot remove buddy from persistence layer.", buddy.toBuddyDetails() ); } } /** * Reads buddy's presence * * @param event Request event * @return Response event */ @Override public ReadPresenceBuddyResponseEvent readPresence(ReadPresenceBuddyRequestEvent event) { // Get buddy from buddy details Buddy buddy = Buddy.fromBuddyDetails(event.getBuddyDetails()); try { // Take presence from user settings Settings settings = SettingsLocalServiceUtil.getSettingsByUser(buddy.getBuddyId()); if (settings != null) { // Create Presence from string Presence presence = Presence.fromDescription(settings.getPresence()); // Success return ReadPresenceBuddyResponseEvent.readPresenceSuccess( "Presence successfully read", presence.toPresenceDetails() ); } else { // Failure return ReadPresenceBuddyResponseEvent.readPresenceFailure( new Exception(String.format("Cannot find settings for buddy with ID: %s", buddy.getBuddyId())) ); } } catch (Exception e) { // Failure return ReadPresenceBuddyResponseEvent.readPresenceFailure(e); } } /** * Change buddy's presence * * @param event Request event for logout method * @return Response event for logout method */ @Override public UpdatePresenceBuddyResponseEvent updatePresence(UpdatePresenceBuddyRequestEvent event) { // Get presence Presence presence = Presence.fromPresenceDetails(event.getPresenceDetails()); try { // Save to settings SettingsLocalServiceUtil.changePresence(event.getBuddyId(), presence.getDescription()); // Success return UpdatePresenceBuddyResponseEvent.updatePresenceSuccess(); } catch (Exception exception) { // Failure return UpdatePresenceBuddyResponseEvent.updatePresenceFailure( UpdatePresenceBuddyResponseEvent.Status.ERROR_PERSISTENCE, exception ); } } /** * Search buddies in the system * * @param event Request event * @return Response event */ @Override public SearchBuddiesResponseEvent searchBuddies(SearchBuddiesRequestEvent event) { // Map buddy from details Buddy buddy = Buddy.fromBuddyDetails(event.getBuddyDetails()); // Check params if (buddy.getBuddyId() == null) { return SearchBuddiesResponseEvent.searchFailure(SearchBuddiesResponseEvent.Status.ERROR_WRONG_PARAMETERS); } try { // Define boundaries int start = 0; int end = Environment.getBuddyListMaxSearch(); // Get buddies from manager List<Buddy> buddies = searchManager.searchBuddies(buddy.getBuddyId(), event.getSearchQuery(), start, end); // Create buddy details list from the buddy list List<BuddyDetails> buddyDetails = new LinkedList<BuddyDetails>(); for (Buddy searchedBuddy : buddies) { buddyDetails.add(searchedBuddy.toBuddyDetails()); } // Call success return SearchBuddiesResponseEvent.searchSuccess(buddyDetails); } // Failure catch (Exception exception) { return SearchBuddiesResponseEvent.searchFailure( SearchBuddiesResponseEvent.Status.ERROR_PERSISTENCE, exception ); } } }
package com.tacticalnuclearstrike.tttumblr; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import com.google.inject.Inject; import roboguice.service.RoboIntentService; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * TumblrService - a Service subclass to interact with tumblr's api * * contains all the relevant bits for making calls to the backend web service. * * Intents received by this service (prefixed with package name): * POST_TEXT - * String title, String body, boolean isPrivate * POST_PHOTO - Uri photo, String * caption */ public class TumblrService extends RoboIntentService { @Inject TumblrApi api; public TumblrService() { super("Tumblr Upload service"); Log.d(TAG, "TumblrService()"); } private static final String TAG = "TumblrService"; // notification integers. public static final int N_POSTING = 1; // we're currently posting something // Actions: public static final String ACTION_POST_TEXT = "com.tacticalnuclearstrike.tttumblr.POST_TEXT"; public static final String ACTION_POST_PHOTO = "com.tacticalnuclearstrike.tttumblr.POST_PHOTO"; public static final String ACTION_POST_VIDEO = "com.tacticalnuclearstrike.tttumblr.POST_VIDEO"; public static final String ACTION_POST_CONVERSATION = "com.tacticalnuclearstrike.tttumblr.POST_CONVERSATION"; public static final String ACTION_POST_QUOTE = "com.tacticalnuclearstrike.tttumblr.POST_QUOTE"; public static final String ACTION_POST_LINK = "com.tacticalnuclearstrike.tttumblr.POST_LINK"; @Override public void onCreate() { super.onCreate(); Log.d(TAG, "oncreate!"); mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); try { mStartForeground = getClass().getMethod("startForeground", mStartForegroundSignature); mStopForeground = getClass().getMethod("stopForeground", mStopForegroundSignature); } catch (NoSuchMethodException e) { // Running on an older platform. mStartForeground = mStopForeground = null; } } private static final Class[] mStartForegroundSignature = new Class[] { int.class, Notification.class }; private static final Class[] mStopForegroundSignature = new Class[] { boolean.class }; private NotificationManager mNM; private Method mStartForeground; private Method mStopForeground; private Object[] mStartForegroundArgs = new Object[2]; private Object[] mStopForegroundArgs = new Object[1]; /** * This is a wrapper around the new startForeground method, using the older * APIs if it is not available. */ void startForegroundCompat(int id, Notification notification) { // If we have the new startForeground API, then use it. if (mStartForeground != null) { mStartForegroundArgs[0] = Integer.valueOf(id); mStartForegroundArgs[1] = notification; try { mStartForeground.invoke(this, mStartForegroundArgs); } catch (InvocationTargetException e) { // Should not happen. Log.w("ttTumblr", "Unable to invoke startForeground", e); } catch (IllegalAccessException e) { // Should not happen. Log.w("ttTumblr", "Unable to invoke startForeground", e); } return; } // Fall back on the old API. setForeground(true); mNM.notify(id, notification); } /** * This is a wrapper around the new stopForeground method, using the older * APIs if it is not available. */ void stopForegroundCompat(Boolean value) { // If we have the new stopForeground API, then use it. if (mStopForeground != null) { mStopForegroundArgs[0] = Boolean.TRUE; try { mStopForeground.invoke(this, mStopForegroundArgs); } catch (InvocationTargetException e) { // Should not happen. Log.w("ttTumblr", "Unable to invoke stopForeground", e); } catch (IllegalAccessException e) { // Should not happen. Log.w("ttTumblr", "Unable to invoke stopForeground", e); } return; } // Fall back on the old API. Note to cancel BEFORE changing the // foreground state, since we could be killed at that point. // mNM.cancel(id); setForeground(false); } @Override public IBinder onBind(Intent i) { return null; } // dont use onBind. /* @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); Log.d(TAG, "onStartCommand"); return START_REDELIVER_INTENT; }*/ private void handleCommand(Intent intent) { Log.d(TAG, "start intent received: " + intent.getAction()); if (ACTION_POST_TEXT.equals(intent.getAction())) { doTextPost(intent); } else if (ACTION_POST_PHOTO.equals(intent.getAction())) { doPhotoPost(intent); } else if (ACTION_POST_CONVERSATION.equals(intent.getAction())) { doConversationPost(intent); } else if (ACTION_POST_QUOTE.equals(intent.getAction())) { doQuotePost(intent); } else if (ACTION_POST_LINK.equals(intent.getAction())) { doUrlPost(intent); } else if (ACTION_POST_VIDEO.equals(intent.getAction())) { doVideoPost(intent); } else { Log.d(TAG, "UNKNOWN ACTION!"); } } // TODO: should these posts be cached somewhere so we can retry? private void doTextPost(Intent i) { final String titleText = i.getStringExtra("title"); final String postText = i.getStringExtra("body"); final Bundle options = i.getBundleExtra("options"); //final TumblrApi api = new TumblrApi(this); Log.d(TAG, "attempting text post.."); startForegroundCompat(N_POSTING, getNotification("text")); Log.d(TAG, "calling api."); api.postText(titleText, postText, options); stopForegroundCompat(true); } /** * doPhotoPost - posts a photo (given extras). Extras: 'photo' - Uri, * 'caption' - String. */ private void doPhotoPost(Intent i) { String p = i.getStringExtra("photo"); if(p.compareTo("")==0) return; final Uri photo = Uri.parse(p); final String text = i.getStringExtra("caption"); final Bundle options = i.getBundleExtra("options"); //final TumblrApi api = new TumblrApi(this); startForegroundCompat(N_POSTING, getNotification("photo")); api.postImage(photo, text, options); stopForegroundCompat(true); } private void doVideoPost(Intent i) { Bundle options = i.getBundleExtra("options"); String text = i.getStringExtra("caption"); Uri video = null; if (i.hasExtra("video")) video = Uri.parse(i.getStringExtra("video")); String youtube_url = null; if (i.hasExtra("url")) youtube_url = i.getStringExtra("url"); //TumblrApi api = new TumblrApi(this); startForegroundCompat(N_POSTING, getNotification("video")); if (video != null) { api.PostVideo(video, text, options); Log.d(TAG, "video"); } else if (youtube_url != null) { api.PostYoutubeUrl(youtube_url, text, options); Log.d(TAG, "youtube"); } else { Log.d(TAG, "no data to post"); } stopForegroundCompat(true); } /** * doConversationPost - posts a conversation. Extras: 'title' - String, * 'conversation' - String. */ private void doConversationPost(Intent i) { final String title = i.getStringExtra("title"); final String convo = i.getStringExtra("conversation"); final Bundle options = i.getBundleExtra("options"); //final TumblrApi api = new TumblrApi(this); startForegroundCompat(N_POSTING, getNotification("conversation")); api.postConversation(title, convo, options); stopForegroundCompat(true); } /** * doQuotePost - posts a quote Extras: 'quote' - String, 'source' - String * (optional). */ private void doQuotePost(Intent i) { final String quote = i.getStringExtra("quote"); final String source = i.getStringExtra("source"); final Bundle options = i.getBundleExtra("options"); //final TumblrApi api = new TumblrApi(this); startForegroundCompat(N_POSTING, getNotification("quote")); api.postQuote(quote, source, options); stopForegroundCompat(true); } /** * doUrlPost - posts a link; Extras: 'link' - String, 'name' - String, * 'description' - String */ private void doUrlPost(Intent i) { final String link = i.getStringExtra("link"); final String name = i.getStringExtra("name"); final String description = i.getStringExtra("description"); final Bundle options = i.getBundleExtra("options"); //final TumblrApi api = new TumblrApi(this); startForegroundCompat(N_POSTING, getNotification("url")); api.postUrl(link, name, description, options); stopForegroundCompat(true); } private Notification getNotification(String type) { Notification n = new Notification(android.R.drawable.stat_notify_sync, "Uploading to Tumblr...", 0); Intent i = new Intent("android.intent.action.MAIN"); i.setClassName("com.tacticalnuclearstrike.tttumblr", "MainActivity"); PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0); n.setLatestEventInfo(this, "posting", "posting " + type, pi); return n; } @Override public void onDestroy() { Log.d(TAG, "tumblr service stopped!"); stopForegroundCompat(true); } @Override protected void onHandleIntent(Intent intent) { Log.d(TAG, "onHandleIntent"); handleCommand(intent); } }
/* Derby - Class org.apache.derby.impl.store.access.sort.ExternalSortFactory Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.derby.impl.store.access.sort; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Properties; import org.apache.derby.iapi.services.monitor.ModuleControl; import org.apache.derby.iapi.services.monitor.ModuleFactory; import org.apache.derby.iapi.services.monitor.ModuleSupportable; import org.apache.derby.iapi.services.monitor.Monitor; import org.apache.derby.iapi.services.property.PropertyUtil; import org.apache.derby.shared.common.sanity.SanityManager; import org.apache.derby.shared.common.error.StandardException; import org.apache.derby.iapi.store.access.conglomerate.Sort; import org.apache.derby.iapi.store.access.conglomerate.SortFactory; import org.apache.derby.iapi.store.access.SortObserver; import org.apache.derby.iapi.store.access.SortCostController; import org.apache.derby.iapi.store.access.ColumnOrdering; import org.apache.derby.iapi.store.access.TransactionController; import org.apache.derby.iapi.types.DataValueDescriptor; import org.apache.derby.iapi.services.uuid.UUIDFactory; import org.apache.derby.catalog.UUID; // For JavaDoc references (i.e. @see) import org.apache.derby.iapi.store.access.conglomerate.MethodFactory; /** **/ public class ExternalSortFactory implements SortFactory, ModuleControl, ModuleSupportable, SortCostController { private boolean userSpecified; // did the user specify sortBufferMax private int defaultSortBufferMax; private int sortBufferMax; private static final String IMPLEMENTATIONID = "sort external"; private static final String FORMATUUIDSTRING = "D2976090-D9F5-11d0-B54D-00A024BF8879"; private UUID formatUUID = null; private static final int DEFAULT_SORTBUFFERMAX = 1024; private static final int MINIMUM_SORTBUFFERMAX = 4; protected static final int DEFAULT_MEM_USE = 1024*1024; // aim for about 1Meg // how many sort runs to combined into a larger sort run // (DERBY-1661) protected static final int DEFAULT_MAX_MERGE_RUN = 512; // sizeof Node + reference to Node + 12 bytes tax private static final int SORT_ROW_OVERHEAD = 8*4+12; /* ** Methods of MethodFactory */ /** There are no default properties for the external sort.. @see MethodFactory#defaultProperties **/ public Properties defaultProperties() { return new Properties(); } /** @see MethodFactory#supportsImplementation **/ public boolean supportsImplementation(String implementationId) { return implementationId.equals(IMPLEMENTATIONID); } /** @see MethodFactory#primaryImplementationType **/ public String primaryImplementationType() { return IMPLEMENTATIONID; } /** @see MethodFactory#supportsFormat **/ public boolean supportsFormat(UUID formatid) { return formatid.equals(formatUUID); } /** @see MethodFactory#primaryFormat **/ public UUID primaryFormat() { return formatUUID; } /** * Returns merge sort implementation. Extending classes can overide this * method to customize sorting. * * @return MergeSort implementation */ protected MergeSort getMergeSort() { return new MergeSort(); } /* ** Methods of SortFactory */ /** Create a sort. This method could choose among different sort options, depending on the properties etc., but currently it always returns a merge sort. @see SortFactory#createSort **/ public Sort createSort( TransactionController tran, int segment, Properties implParameters, DataValueDescriptor[] template, ColumnOrdering columnOrdering[], SortObserver sortObserver, boolean alreadyInOrder, long estimatedRows, int estimatedRowSize) throws StandardException { MergeSort sort = getMergeSort(); // RESOLVE - mikem change this to use estimatedRows and // estimatedRowSize to come up with a smarter number for sortBufferMax // than a fixed number of rows. At least 2 possibilities: // 1) add sortBufferMaxMem which would be the amount of memory // the sorter could use, and then just pick the number of // rows as (sortBufferMaxMem / (estimatedRows * estimatedRowSize) // 2) add sortBufferUsePercentFree. This would be how much of // the current free memory can the current sort use. // if (!userSpecified) { // derby.storage.sortBufferMax is not specified by the // user, use default or try to figure out a reasonable sort // size. // if we have some idea on row size, set sort approx 1 meg of // memory sort. if (estimatedRowSize > 0) { // // for each column, there is a reference from the key array and // the 4 bytes reference to the column object plus 12 bytes // tax on the column object // for each row, SORT_ROW_OVERHEAD is the Node and 4 bytes to // point to the column array and 4 for alignment // estimatedRowSize += SORT_ROW_OVERHEAD + (template.length*(4+12)) + 8; sortBufferMax = DEFAULT_MEM_USE/estimatedRowSize; } else { sortBufferMax = defaultSortBufferMax; } // if there are barely more rows than sortBufferMax, use 2 // smaller runs of similar size instead of one larger run // // 10% slush is added to estimated Rows to catch the case where // estimated rows underestimate the actual number of rows by 10%. // if (estimatedRows > sortBufferMax && (estimatedRows*1.1) < sortBufferMax*2) sortBufferMax = (int)(estimatedRows/2 + estimatedRows/10); // Make sure it is at least the minimum sort buffer size if (sortBufferMax < MINIMUM_SORTBUFFERMAX) sortBufferMax = MINIMUM_SORTBUFFERMAX; } else { // if user specified derby.storage.sortBufferMax, use it. sortBufferMax = defaultSortBufferMax; } if (SanityManager.DEBUG) { if (SanityManager.DEBUG_ON("SortTuning")) { SanityManager.DEBUG("SortTuning", "sortBufferMax = " + sortBufferMax + " estimatedRows = " + estimatedRows + " estimatedRowSize = " + estimatedRowSize + " defaultSortBufferMax = " + defaultSortBufferMax); } } sort.initialize( template, columnOrdering, sortObserver, alreadyInOrder, estimatedRows, sortBufferMax); return sort; } /** * Return an open SortCostController. * <p> * Return an open SortCostController which can be used to ask about * the estimated costs of SortController() operations. * <p> * * @return The open SortCostController. * * @exception StandardException Standard exception policy. * * @see SortCostController **/ public SortCostController openSortCostController() throws StandardException { return(this); } /* ** Methods of SortCostController */ public void close() { // nothing to do. } /** * Short one line description of routine. * <p> * The sort algorithm is a N * log(N) algorithm. The following numbers * on a PII, 400 MHZ machine, jdk117 with jit, insane.zip. This test * is a simple "select * from table order by first_int_column. I then * subtracted the time it takes to do "select * from table" from the * result. * * number of rows elaspsed time in seconds * -------------- ----------------------------- * 1000 0.20 * 10000 10.5 * 100000 80.0 * * We assume that the formula for sort performance is of the form: * performance = K * N * log(N). Solving the equation for the 1000 * and 100000 case we come up with: * * performance = 1 + 0.08 N ln(n) * * NOTE: Apparently, these measurements were done on a faster machine * than was used for other performance measurements used by the optimizer. * Experiments show that the 0.8 multiplier is off by a factor of 4 * with respect to other measurements (such as the time it takes to * scan a conglomerate). I am correcting the formula to use 0.32 * rather than 0.08. * * - Jeff * * <p> * RESOLVE (mikem) - this formula is very crude at the moment and will be * refined later. known problems: * 1) internal vs. external sort - we know that the performance of sort * is discontinuous when we go from an internal to an external sort. * A better model is probably a different set of contants for internal * vs. external sort and some way to guess when this is going to happen. * 2) current row size is never considered but is critical to performance. * 3) estimatedExportRows is not used. This is a critical number to know * if an internal vs. an external sort will happen. * * <p> * * @return The identifier to be used to open the conglomerate later. * * * @exception StandardException Standard exception policy. **/ public double getSortCost( DataValueDescriptor[] template, ColumnOrdering columnOrdering[], boolean alreadyInOrder, long estimatedInputRows, long estimatedExportRows, int estimatedRowSize) throws StandardException { /* Avoid taking the log of 0 */ if (estimatedInputRows == 0) return 0.0; // RESOLVE - come up with some real benchmark. For now the cost // of sort is 3 times the cost of scanning the data. if (SanityManager.DEBUG) { SanityManager.ASSERT(estimatedInputRows >= 0); SanityManager.ASSERT(estimatedExportRows >= 0); } double ret_val = 1 + ((0.32) * (estimatedInputRows) * Math.log(estimatedInputRows)); return(ret_val); } /* ** Methods of ModuleControl. */ public boolean canSupport(Properties startParams) { if (startParams == null) return false; String impl = startParams.getProperty("derby.access.Conglomerate.type"); if (impl == null) return false; return supportsImplementation(impl); } public void boot(boolean create, Properties startParams) throws StandardException { // Find the UUID factory. UUIDFactory uuidFactory = getMonitor().getUUIDFactory(); // Make a UUID that identifies this sort's format. formatUUID = uuidFactory.recreateUUID(FORMATUUIDSTRING); // See if there's a new maximum sort buffer size. defaultSortBufferMax = PropertyUtil.getSystemInt("derby.storage.sortBufferMax", 0, Integer.MAX_VALUE, 0); // if defaultSortBufferMax is 0, the user did not specify // sortBufferMax, then just set it to DEFAULT_SORTBUFFERMAX. // if defaultSortBufferMax is not 0, the user specified sortBufferMax, // do not override it. if (defaultSortBufferMax == 0) { userSpecified = false; defaultSortBufferMax = DEFAULT_SORTBUFFERMAX; } else { userSpecified = true; if (defaultSortBufferMax < MINIMUM_SORTBUFFERMAX) defaultSortBufferMax = MINIMUM_SORTBUFFERMAX; } } public void stop() { } /** * Privileged Monitor lookup. Must be private so that user code * can't call this entry point. */ private static ModuleFactory getMonitor() { return AccessController.doPrivileged ( new PrivilegedAction<ModuleFactory>() { public ModuleFactory run() { return Monitor.getMonitor(); } } ); } }
/* * The MIT License * * Copyright 2016 Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.cli; import hudson.model.Computer; import hudson.slaves.DumbSlave; import hudson.slaves.OfflineCause; import jenkins.model.Jenkins; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import static hudson.cli.CLICommandInvoker.Matcher.failedWith; import static hudson.cli.CLICommandInvoker.Matcher.hasNoStandardOutput; import static hudson.cli.CLICommandInvoker.Matcher.succeededSilently; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.not; /** * @author pjanouse */ public class DisconnectNodeCommandTest { private CLICommandInvoker command; @Rule public final JenkinsRule j = new JenkinsRule(); @Before public void setUp() { command = new CLICommandInvoker(j, "disconnect-node"); } @Test public void disconnectNodeShouldFailWithoutComputerDisconnectPermission() throws Exception { j.createSlave("aNode", "", null); final CLICommandInvoker.Result result = command .authorizedTo(Jenkins.READ) .invokeWithArgs("aNode"); assertThat(result, failedWith(6)); assertThat(result, hasNoStandardOutput()); assertThat(result.stderr(), containsString("ERROR: user is missing the Agent/Disconnect permission")); assertThat(result.stderr(), not(containsString("ERROR: " + CLICommand.CLI_LISTPARAM_SUMMARY_ERROR_TEXT))); } @Test public void disconnectNodeShouldFailIfNodeDoesNotExist() throws Exception { final CLICommandInvoker.Result result = command .authorizedTo(Computer.DISCONNECT, Jenkins.READ) .invokeWithArgs("never_created"); assertThat(result, failedWith(3)); assertThat(result, hasNoStandardOutput()); assertThat(result.stderr(), containsString("ERROR: No such agent \"never_created\" exists.")); assertThat(result.stderr(), not(containsString("ERROR: " + CLICommand.CLI_LISTPARAM_SUMMARY_ERROR_TEXT))); } @Test public void disconnectNodeShouldSucceed() throws Exception { DumbSlave slave = j.createSlave("aNode", "", null); slave.toComputer().waitUntilOnline(); assertThat(slave.toComputer().isOnline(), equalTo(true)); assertThat(slave.toComputer().getOfflineCause(), equalTo(null)); CLICommandInvoker.Result result = command .authorizedTo(Computer.DISCONNECT, Jenkins.READ) .invokeWithArgs("aNode"); assertThat(result, succeededSilently()); assertThat(slave.toComputer().isOffline(), equalTo(true)); assertThat(slave.toComputer().getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) slave.toComputer().getOfflineCause()).message, equalTo(null)); slave.toComputer().connect(true); slave.toComputer().waitUntilOnline(); assertThat(slave.toComputer().isOnline(), equalTo(true)); assertThat(slave.toComputer().getOfflineCause(), equalTo(null)); result = command .authorizedTo(Computer.DISCONNECT, Jenkins.READ) .invokeWithArgs("aNode"); assertThat(result, succeededSilently()); assertThat(slave.toComputer().isOffline(), equalTo(true)); assertThat(slave.toComputer().getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) slave.toComputer().getOfflineCause()).message, equalTo(null)); result = command .authorizedTo(Computer.DISCONNECT, Jenkins.READ) .invokeWithArgs("aNode"); assertThat(result, succeededSilently()); assertThat(slave.toComputer().isOffline(), equalTo(true)); assertThat(slave.toComputer().getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) slave.toComputer().getOfflineCause()).message, equalTo(null)); } @Test public void disconnectNodeShouldSucceedWithCause() throws Exception { DumbSlave slave = j.createSlave("aNode", "", null); slave.toComputer().waitUntilOnline(); assertThat(slave.toComputer().isOnline(), equalTo(true)); assertThat(slave.toComputer().getOfflineCause(), equalTo(null)); CLICommandInvoker.Result result = command .authorizedTo(Computer.DISCONNECT, Jenkins.READ) .invokeWithArgs("aNode", "-m", "aCause"); assertThat(result, succeededSilently()); assertThat(slave.toComputer().isOffline(), equalTo(true)); assertThat(slave.toComputer().getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) slave.toComputer().getOfflineCause()).message, equalTo("aCause")); slave.toComputer().connect(true); slave.toComputer().waitUntilOnline(); assertThat(slave.toComputer().isOnline(), equalTo(true)); assertThat(slave.toComputer().getOfflineCause(), equalTo(null)); result = command .authorizedTo(Computer.DISCONNECT, Jenkins.READ) .invokeWithArgs("aNode", "-m", "anotherCause"); assertThat(result, succeededSilently()); assertThat(slave.toComputer().isOffline(), equalTo(true)); assertThat(slave.toComputer().getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) slave.toComputer().getOfflineCause()).message, equalTo("anotherCause")); result = command .authorizedTo(Computer.DISCONNECT, Jenkins.READ) .invokeWithArgs("aNode", "-m", "yetAnotherCause"); assertThat(result, succeededSilently()); assertThat(slave.toComputer().isOffline(), equalTo(true)); assertThat(slave.toComputer().getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) slave.toComputer().getOfflineCause()).message, equalTo("yetAnotherCause")); } @Test public void disconnectNodeManyShouldSucceed() throws Exception { DumbSlave slave1 = j.createSlave("aNode1", "", null); DumbSlave slave2 = j.createSlave("aNode2", "", null); DumbSlave slave3 = j.createSlave("aNode3", "", null); slave1.toComputer().waitUntilOnline(); assertThat(slave1.toComputer().isOnline(), equalTo(true)); assertThat(slave1.toComputer().getOfflineCause(), equalTo(null)); slave2.toComputer().waitUntilOnline(); assertThat(slave2.toComputer().isOnline(), equalTo(true)); assertThat(slave2.toComputer().getOfflineCause(), equalTo(null)); slave3.toComputer().waitUntilOnline(); assertThat(slave3.toComputer().isOnline(), equalTo(true)); assertThat(slave3.toComputer().getOfflineCause(), equalTo(null)); final CLICommandInvoker.Result result = command .authorizedTo(Computer.DISCONNECT, Jenkins.READ) .invokeWithArgs("aNode1", "aNode2", "aNode3"); assertThat(result, succeededSilently()); assertThat(slave1.toComputer().isOffline(), equalTo(true)); assertThat(slave1.toComputer().getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) slave1.toComputer().getOfflineCause()).message, equalTo(null)); assertThat(slave2.toComputer().isOffline(), equalTo(true)); assertThat(slave2.toComputer().getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) slave2.toComputer().getOfflineCause()).message, equalTo(null)); assertThat(slave3.toComputer().isOffline(), equalTo(true)); assertThat(slave3.toComputer().getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) slave3.toComputer().getOfflineCause()).message, equalTo(null)); } @Test public void disconnectNodeManyShouldSucceedWithCause() throws Exception { DumbSlave slave1 = j.createSlave("aNode1", "", null); DumbSlave slave2 = j.createSlave("aNode2", "", null); DumbSlave slave3 = j.createSlave("aNode3", "", null); slave1.toComputer().waitUntilOnline(); assertThat(slave1.toComputer().isOnline(), equalTo(true)); assertThat(slave1.toComputer().getOfflineCause(), equalTo(null)); slave2.toComputer().waitUntilOnline(); assertThat(slave2.toComputer().isOnline(), equalTo(true)); assertThat(slave2.toComputer().getOfflineCause(), equalTo(null)); slave3.toComputer().waitUntilOnline(); assertThat(slave3.toComputer().isOnline(), equalTo(true)); assertThat(slave3.toComputer().getOfflineCause(), equalTo(null)); final CLICommandInvoker.Result result = command .authorizedTo(Computer.DISCONNECT, Jenkins.READ) .invokeWithArgs("aNode1", "aNode2", "aNode3", "-m", "aCause"); assertThat(result, succeededSilently()); assertThat(slave1.toComputer().isOffline(), equalTo(true)); assertThat(slave1.toComputer().getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) slave1.toComputer().getOfflineCause()).message, equalTo("aCause")); assertThat(slave2.toComputer().isOffline(), equalTo(true)); assertThat(slave2.toComputer().getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) slave2.toComputer().getOfflineCause()).message, equalTo("aCause")); assertThat(slave3.toComputer().isOffline(), equalTo(true)); assertThat(slave3.toComputer().getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) slave3.toComputer().getOfflineCause()).message, equalTo("aCause")); } @Test public void disconnectNodeManyShouldFailIfANodeDoesNotExist() throws Exception { DumbSlave slave1 = j.createSlave("aNode1", "", null); DumbSlave slave2 = j.createSlave("aNode2", "", null); slave1.toComputer().waitUntilOnline(); assertThat(slave1.toComputer().isOnline(), equalTo(true)); assertThat(slave1.toComputer().getOfflineCause(), equalTo(null)); slave2.toComputer().waitUntilOnline(); assertThat(slave2.toComputer().isOnline(), equalTo(true)); assertThat(slave2.toComputer().getOfflineCause(), equalTo(null)); final CLICommandInvoker.Result result = command .authorizedTo(Computer.DISCONNECT, Jenkins.READ) .invokeWithArgs("aNode1", "aNode2", "never_created", "-m", "aCause"); assertThat(result, failedWith(5)); assertThat(result, hasNoStandardOutput()); assertThat(result.stderr(), containsString("never_created: No such agent \"never_created\" exists. Did you mean \"aNode1\"?")); assertThat(result.stderr(), containsString("ERROR: " + CLICommand.CLI_LISTPARAM_SUMMARY_ERROR_TEXT)); assertThat(slave1.toComputer().isOffline(), equalTo(true)); assertThat(slave1.toComputer().getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) slave1.toComputer().getOfflineCause()).message, equalTo("aCause")); assertThat(slave2.toComputer().isOffline(), equalTo(true)); assertThat(slave2.toComputer().getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) slave2.toComputer().getOfflineCause()).message, equalTo("aCause")); } @Test public void disconnectNodeManyShouldSucceedEvenANodeIsSpecifiedTwice() throws Exception { DumbSlave slave1 = j.createSlave("aNode1", "", null); DumbSlave slave2 = j.createSlave("aNode2", "", null); slave1.toComputer().waitUntilOnline(); assertThat(slave1.toComputer().isOnline(), equalTo(true)); assertThat(slave1.toComputer().getOfflineCause(), equalTo(null)); slave2.toComputer().waitUntilOnline(); assertThat(slave2.toComputer().isOnline(), equalTo(true)); assertThat(slave2.toComputer().getOfflineCause(), equalTo(null)); final CLICommandInvoker.Result result = command .authorizedTo(Computer.DISCONNECT, Jenkins.READ) .invokeWithArgs("aNode1", "aNode2", "aNode1", "-m", "aCause"); assertThat(result, succeededSilently()); assertThat(slave1.toComputer().isOffline(), equalTo(true)); assertThat(slave1.toComputer().getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) slave1.toComputer().getOfflineCause()).message, equalTo("aCause")); assertThat(slave2.toComputer().isOffline(), equalTo(true)); assertThat(slave2.toComputer().getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) slave2.toComputer().getOfflineCause()).message, equalTo("aCause")); } public void disconnectNodeShouldSucceedOnMaster() throws Exception { final Computer masterComputer = j.jenkins.getActiveInstance().getComputer(""); assertThat(masterComputer.isOnline(), equalTo(true)); assertThat(masterComputer.getOfflineCause(), equalTo(null)); CLICommandInvoker.Result result = command .authorizedTo(Computer.DISCONNECT, Jenkins.READ) .invokeWithArgs(""); assertThat(result, succeededSilently()); assertThat(masterComputer.isOffline(), equalTo(true)); assertThat(masterComputer.getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) masterComputer.getOfflineCause()).message, equalTo(null)); masterComputer.connect(true); masterComputer.waitUntilOnline(); assertThat(masterComputer.isOnline(), equalTo(true)); assertThat(masterComputer.getOfflineCause(), equalTo(null)); result = command .authorizedTo(Computer.DISCONNECT, Jenkins.READ) .invokeWithArgs(""); assertThat(result, succeededSilently()); assertThat(masterComputer.isOffline(), equalTo(true)); assertThat(masterComputer.getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) masterComputer.getOfflineCause()).message, equalTo(null)); result = command .authorizedTo(Computer.DISCONNECT, Jenkins.READ) .invokeWithArgs(""); assertThat(result, succeededSilently()); assertThat(masterComputer.isOffline(), equalTo(true)); assertThat(masterComputer.getOfflineCause(), instanceOf(OfflineCause.ByCLI.class)); assertThat(((OfflineCause.ByCLI) masterComputer.getOfflineCause()).message, equalTo(null)); } }
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import java.io.Serializable; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.RandomAccess; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import javax.annotation.Nullable; /** * Basic implementation of the {@link Multimap} interface. This class represents * a multimap as a map that associates each key with a collection of values. All * methods of {@link Multimap} are supported, including those specified as * optional in the interface. * * <p>To implement a multimap, a subclass must define the method {@link * #createCollection()}, which creates an empty collection of values for a key. * * <p>The multimap constructor takes a map that has a single entry for each * distinct key. When you insert a key-value pair with a key that isn't already * in the multimap, {@code AbstractMultimap} calls {@link #createCollection()} * to create the collection of values for that key. The subclass should not call * {@link #createCollection()} directly, and a new instance should be created * every time the method is called. * * <p>For example, the subclass could pass a {@link java.util.TreeMap} during * construction, and {@link #createCollection()} could return a {@link * java.util.TreeSet}, in which case the multimap's iterators would propagate * through the keys and values in sorted order. * * <p>Keys and values may be null, as long as the underlying collection classes * support null elements. * * <p>The collections created by {@link #createCollection()} may or may not * allow duplicates. If the collection, such as a {@link Set}, does not support * duplicates, an added key-value pair will replace an existing pair with the * same key and value, if such a pair is present. With collections like {@link * List} that allow duplicates, the collection will keep the existing key-value * pairs while adding a new pair. * * <p>This class is not threadsafe when any concurrent operations update the * multimap, even if the underlying map and {@link #createCollection()} method * return threadsafe classes. Concurrent read operations will work correctly. To * allow concurrent update operations, wrap your multimap with a call to {@link * Multimaps#synchronizedMultimap}. * * <p>For serialization to work, the subclass must specify explicit * {@code readObject} and {@code writeObject} methods. * * @author Jared Levy */ @GwtCompatible abstract class AbstractMultimap<K, V> implements Multimap<K, V>, Serializable { /* * Here's an outline of the overall design. * * The map variable contains the collection of values associated with each * key. When a key-value pair is added to a multimap that didn't previously * contain any values for that key, a new collection generated by * createCollection is added to the map. That same collection instance * remains in the map as long as the multimap has any values for the key. If * all values for the key are removed, the key and collection are removed * from the map. * * The get method returns a WrappedCollection, which decorates the collection * in the map (if the key is present) or an empty collection (if the key is * not present). When the collection delegate in the WrappedCollection is * empty, the multimap may contain subsequently added values for that key. To * handle that situation, the WrappedCollection checks whether map contains * an entry for the provided key, and if so replaces the delegate. */ private transient Map<K, Collection<V>> map; private transient int totalSize; /** * Creates a new multimap that uses the provided map. * * @param map place to store the mapping from each key to its corresponding * values * @throws IllegalArgumentException if {@code map} is not empty */ protected AbstractMultimap(Map<K, Collection<V>> map) { checkArgument(map.isEmpty()); this.map = map; } /** Used during deserialization only. */ final void setMap(Map<K, Collection<V>> map) { this.map = map; totalSize = 0; for (Collection<V> values : map.values()) { checkArgument(!values.isEmpty()); totalSize += values.size(); } } /** * Creates the collection of values for a single key. * * <p>Collections with weak, soft, or phantom references are not supported. * Each call to {@code createCollection} should create a new instance. * * <p>The returned collection class determines whether duplicate key-value * pairs are allowed. * * @return an empty collection of values */ abstract Collection<V> createCollection(); /** * Creates the collection of values for an explicitly provided key. By * default, it simply calls {@link #createCollection()}, which is the correct * behavior for most implementations. The {@link LinkedHashMultimap} class * overrides it. * * @param key key to associate with values in the collection * @return an empty collection of values */ Collection<V> createCollection(@Nullable K key) { return createCollection(); } Map<K, Collection<V>> backingMap() { return map; } // Query Operations public int size() { return totalSize; } public boolean isEmpty() { return totalSize == 0; } public boolean containsKey(@Nullable Object key) { return map.containsKey(key); } public boolean containsValue(@Nullable Object value) { for (Collection<V> collection : map.values()) { if (collection.contains(value)) { return true; } } return false; } public boolean containsEntry(@Nullable Object key, @Nullable Object value) { Collection<V> collection = map.get(key); return collection != null && collection.contains(value); } // Modification Operations public boolean put(@Nullable K key, @Nullable V value) { Collection<V> collection = getOrCreateCollection(key); if (collection.add(value)) { totalSize++; return true; } else { return false; } } private Collection<V> getOrCreateCollection(@Nullable K key) { Collection<V> collection = map.get(key); if (collection == null) { collection = createCollection(key); map.put(key, collection); } return collection; } public boolean remove(@Nullable Object key, @Nullable Object value) { Collection<V> collection = map.get(key); if (collection == null) { return false; } boolean changed = collection.remove(value); if (changed) { totalSize--; if (collection.isEmpty()) { map.remove(key); } } return changed; } // Bulk Operations public boolean putAll(@Nullable K key, Iterable<? extends V> values) { if (!values.iterator().hasNext()) { return false; } Collection<V> collection = getOrCreateCollection(key); int oldSize = collection.size(); boolean changed = false; if (values instanceof Collection) { @SuppressWarnings("unchecked") Collection<? extends V> c = (Collection<? extends V>) values; changed = collection.addAll(c); } else { for (V value : values) { changed |= collection.add(value); } } totalSize += (collection.size() - oldSize); return changed; } public boolean putAll(Multimap<? extends K, ? extends V> multimap) { boolean changed = false; for (Map.Entry<? extends K, ? extends V> entry : multimap.entries()) { changed |= put(entry.getKey(), entry.getValue()); } return changed; } /** * {@inheritDoc} * * <p>The returned collection is immutable. */ public Collection<V> replaceValues( @Nullable K key, Iterable<? extends V> values) { Iterator<? extends V> iterator = values.iterator(); if (!iterator.hasNext()) { return removeAll(key); } Collection<V> collection = getOrCreateCollection(key); Collection<V> oldValues = createCollection(); oldValues.addAll(collection); totalSize -= collection.size(); collection.clear(); while (iterator.hasNext()) { if (collection.add(iterator.next())) { totalSize++; } } return unmodifiableCollectionSubclass(oldValues); } /** * {@inheritDoc} * * <p>The returned collection is immutable. */ public Collection<V> removeAll(@Nullable Object key) { Collection<V> collection = map.remove(key); Collection<V> output = createCollection(); if (collection != null) { output.addAll(collection); totalSize -= collection.size(); collection.clear(); } return unmodifiableCollectionSubclass(output); } private Collection<V> unmodifiableCollectionSubclass( Collection<V> collection) { if (collection instanceof SortedSet) { return Collections.unmodifiableSortedSet((SortedSet<V>) collection); } else if (collection instanceof Set) { return Collections.unmodifiableSet((Set<V>) collection); } else if (collection instanceof List) { return Collections.unmodifiableList((List<V>) collection); } else { return Collections.unmodifiableCollection(collection); } } public void clear() { // Clear each collection, to make previously returned collections empty. for (Collection<V> collection : map.values()) { collection.clear(); } map.clear(); totalSize = 0; } // Views /** * {@inheritDoc} * * <p>The returned collection is not serializable. */ public Collection<V> get(@Nullable K key) { Collection<V> collection = map.get(key); if (collection == null) { collection = createCollection(key); } return wrapCollection(key, collection); } /** * Generates a decorated collection that remains consistent with the values in * the multimap for the provided key. Changes to the multimap may alter the * returned collection, and vice versa. */ private Collection<V> wrapCollection( @Nullable K key, Collection<V> collection) { if (collection instanceof SortedSet) { return new WrappedSortedSet(key, (SortedSet<V>) collection, null); } else if (collection instanceof Set) { return new WrappedSet(key, (Set<V>) collection); } else if (collection instanceof List) { return wrapList(key, (List<V>) collection, null); } else { return new WrappedCollection(key, collection, null); } } private List<V> wrapList( K key, List<V> list, @Nullable WrappedCollection ancestor) { return (list instanceof RandomAccess) ? new RandomAccessWrappedList(key, list, ancestor) : new WrappedList(key, list, ancestor); } /** * Collection decorator that stays in sync with the multimap values for a key. * There are two kinds of wrapped collections: full and subcollections. Both * have a delegate pointing to the underlying collection class. * * <p>Full collections, identified by a null ancestor field, contain all * multimap values for a given key. Its delegate is a value in {@link * AbstractMultimap#map} whenever the delegate is non-empty. The {@code * refreshIfEmpty}, {@code removeIfEmpty}, and {@code addToMap} methods ensure * that the {@code WrappedCollection} and map remain consistent. * * <p>A subcollection, such as a sublist, contains some of the values for a * given key. Its ancestor field points to the full wrapped collection with * all values for the key. The subcollection {@code refreshIfEmpty}, {@code * removeIfEmpty}, and {@code addToMap} methods call the corresponding methods * of the full wrapped collection. */ private class WrappedCollection extends AbstractCollection<V> { final K key; Collection<V> delegate; final WrappedCollection ancestor; final Collection<V> ancestorDelegate; WrappedCollection(@Nullable K key, Collection<V> delegate, @Nullable WrappedCollection ancestor) { this.key = key; this.delegate = delegate; this.ancestor = ancestor; this.ancestorDelegate = (ancestor == null) ? null : ancestor.getDelegate(); } /** * If the delegate collection is empty, but the multimap has values for the * key, replace the delegate with the new collection for the key. * * <p>For a subcollection, refresh its ancestor and validate that the * ancestor delegate hasn't changed. */ void refreshIfEmpty() { if (ancestor != null) { ancestor.refreshIfEmpty(); if (ancestor.getDelegate() != ancestorDelegate) { throw new ConcurrentModificationException(); } } else if (delegate.isEmpty()) { Collection<V> newDelegate = map.get(key); if (newDelegate != null) { delegate = newDelegate; } } } /** * If collection is empty, remove it from {@code map}. For subcollections, * check whether the ancestor collection is empty. */ void removeIfEmpty() { if (ancestor != null) { ancestor.removeIfEmpty(); } else if (delegate.isEmpty()) { map.remove(key); } } K getKey() { return key; } /** * Add the delegate to the map. Other {@code WrappedCollection} methods * should call this method after adding elements to a previously empty * collection. * * <p>Subcollection add the ancestor's delegate instead. */ void addToMap() { if (ancestor != null) { ancestor.addToMap(); } else { map.put(key, delegate); } } @Override public int size() { refreshIfEmpty(); return delegate.size(); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } refreshIfEmpty(); return delegate.equals(object); } @Override public int hashCode() { refreshIfEmpty(); return delegate.hashCode(); } @Override public String toString() { refreshIfEmpty(); return delegate.toString(); } Collection<V> getDelegate() { return delegate; } @Override public Iterator<V> iterator() { refreshIfEmpty(); return new WrappedIterator(); } /** Collection iterator for {@code WrappedCollection}. */ class WrappedIterator implements Iterator<V> { final Iterator<V> delegateIterator; final Collection<V> originalDelegate = delegate; WrappedIterator() { delegateIterator = iteratorOrListIterator(delegate); } WrappedIterator(Iterator<V> delegateIterator) { this.delegateIterator = delegateIterator; } /** * If the delegate changed since the iterator was created, the iterator is * no longer valid. */ void validateIterator() { refreshIfEmpty(); if (delegate != originalDelegate) { throw new ConcurrentModificationException(); } } public boolean hasNext() { validateIterator(); return delegateIterator.hasNext(); } public V next() { validateIterator(); return delegateIterator.next(); } public void remove() { delegateIterator.remove(); totalSize--; removeIfEmpty(); } Iterator<V> getDelegateIterator() { validateIterator(); return delegateIterator; } } @Override public boolean add(V value) { refreshIfEmpty(); boolean wasEmpty = delegate.isEmpty(); boolean changed = delegate.add(value); if (changed) { totalSize++; if (wasEmpty) { addToMap(); } } return changed; } WrappedCollection getAncestor() { return ancestor; } // The following methods are provided for better performance. @Override public boolean addAll(Collection<? extends V> collection) { if (collection.isEmpty()) { return false; } int oldSize = size(); // calls refreshIfEmpty boolean changed = delegate.addAll(collection); if (changed) { int newSize = delegate.size(); totalSize += (newSize - oldSize); if (oldSize == 0) { addToMap(); } } return changed; } @Override public boolean contains(Object o) { refreshIfEmpty(); return delegate.contains(o); } @Override public boolean containsAll(Collection<?> c) { refreshIfEmpty(); return delegate.containsAll(c); } @Override public void clear() { int oldSize = size(); // calls refreshIfEmpty if (oldSize == 0) { return; } delegate.clear(); totalSize -= oldSize; removeIfEmpty(); // maybe shouldn't be removed if this is a sublist } @Override public boolean remove(Object o) { refreshIfEmpty(); boolean changed = delegate.remove(o); if (changed) { totalSize--; removeIfEmpty(); } return changed; } @Override public boolean removeAll(Collection<?> c) { if (c.isEmpty()) { return false; } int oldSize = size(); // calls refreshIfEmpty boolean changed = delegate.removeAll(c); if (changed) { int newSize = delegate.size(); totalSize += (newSize - oldSize); removeIfEmpty(); } return changed; } @Override public boolean retainAll(Collection<?> c) { checkNotNull(c); int oldSize = size(); // calls refreshIfEmpty boolean changed = delegate.retainAll(c); if (changed) { int newSize = delegate.size(); totalSize += (newSize - oldSize); removeIfEmpty(); } return changed; } } private Iterator<V> iteratorOrListIterator(Collection<V> collection) { return (collection instanceof List) ? ((List<V>) collection).listIterator() : collection.iterator(); } /** Set decorator that stays in sync with the multimap values for a key. */ private class WrappedSet extends WrappedCollection implements Set<V> { WrappedSet(K key, Set<V> delegate) { super(key, delegate, null); } } /** * SortedSet decorator that stays in sync with the multimap values for a key. */ private class WrappedSortedSet extends WrappedCollection implements SortedSet<V> { WrappedSortedSet(@Nullable K key, SortedSet<V> delegate, @Nullable WrappedCollection ancestor) { super(key, delegate, ancestor); } SortedSet<V> getSortedSetDelegate() { return (SortedSet<V>) getDelegate(); } public Comparator<? super V> comparator() { return getSortedSetDelegate().comparator(); } public V first() { refreshIfEmpty(); return getSortedSetDelegate().first(); } public V last() { refreshIfEmpty(); return getSortedSetDelegate().last(); } public SortedSet<V> headSet(V toElement) { refreshIfEmpty(); return new WrappedSortedSet( getKey(), getSortedSetDelegate().headSet(toElement), (getAncestor() == null) ? this : getAncestor()); } public SortedSet<V> subSet(V fromElement, V toElement) { refreshIfEmpty(); return new WrappedSortedSet( getKey(), getSortedSetDelegate().subSet(fromElement, toElement), (getAncestor() == null) ? this : getAncestor()); } public SortedSet<V> tailSet(V fromElement) { refreshIfEmpty(); return new WrappedSortedSet( getKey(), getSortedSetDelegate().tailSet(fromElement), (getAncestor() == null) ? this : getAncestor()); } } /** List decorator that stays in sync with the multimap values for a key. */ private class WrappedList extends WrappedCollection implements List<V> { WrappedList(K key, List<V> delegate, @Nullable WrappedCollection ancestor) { super(key, delegate, ancestor); } List<V> getListDelegate() { return (List<V>) getDelegate(); } public boolean addAll(int index, Collection<? extends V> c) { if (c.isEmpty()) { return false; } int oldSize = size(); // calls refreshIfEmpty boolean changed = getListDelegate().addAll(index, c); if (changed) { int newSize = getDelegate().size(); totalSize += (newSize - oldSize); if (oldSize == 0) { addToMap(); } } return changed; } public V get(int index) { refreshIfEmpty(); return getListDelegate().get(index); } public V set(int index, V element) { refreshIfEmpty(); return getListDelegate().set(index, element); } public void add(int index, V element) { refreshIfEmpty(); boolean wasEmpty = getDelegate().isEmpty(); getListDelegate().add(index, element); totalSize++; if (wasEmpty) { addToMap(); } } public V remove(int index) { refreshIfEmpty(); V value = getListDelegate().remove(index); totalSize--; removeIfEmpty(); return value; } public int indexOf(Object o) { refreshIfEmpty(); return getListDelegate().indexOf(o); } public int lastIndexOf(Object o) { refreshIfEmpty(); return getListDelegate().lastIndexOf(o); } public ListIterator<V> listIterator() { refreshIfEmpty(); return new WrappedListIterator(); } public ListIterator<V> listIterator(int index) { refreshIfEmpty(); return new WrappedListIterator(index); } @GwtIncompatible("List.subList") public List<V> subList(int fromIndex, int toIndex) { refreshIfEmpty(); return wrapList(getKey(), Platform.subList(getListDelegate(), fromIndex, toIndex), (getAncestor() == null) ? this : getAncestor()); } /** ListIterator decorator. */ private class WrappedListIterator extends WrappedIterator implements ListIterator<V> { WrappedListIterator() {} public WrappedListIterator(int index) { super(getListDelegate().listIterator(index)); } private ListIterator<V> getDelegateListIterator() { return (ListIterator<V>) getDelegateIterator(); } public boolean hasPrevious() { return getDelegateListIterator().hasPrevious(); } public V previous() { return getDelegateListIterator().previous(); } public int nextIndex() { return getDelegateListIterator().nextIndex(); } public int previousIndex() { return getDelegateListIterator().previousIndex(); } public void set(V value) { getDelegateListIterator().set(value); } public void add(V value) { boolean wasEmpty = isEmpty(); getDelegateListIterator().add(value); totalSize++; if (wasEmpty) { addToMap(); } } } } /** * List decorator that stays in sync with the multimap values for a key and * supports rapid random access. */ private class RandomAccessWrappedList extends WrappedList implements RandomAccess { RandomAccessWrappedList(K key, List<V> delegate, @Nullable WrappedCollection ancestor) { super(key, delegate, ancestor); } } private transient Set<K> keySet; public Set<K> keySet() { Set<K> result = keySet; return (result == null) ? keySet = createKeySet() : result; } private Set<K> createKeySet() { return (map instanceof SortedMap) ? new SortedKeySet((SortedMap<K, Collection<V>>) map) : new KeySet(map); } private class KeySet extends AbstractSet<K> { /** * This is usually the same as map, except when someone requests a * subcollection of a {@link SortedKeySet}. */ final Map<K, Collection<V>> subMap; KeySet(final Map<K, Collection<V>> subMap) { this.subMap = subMap; } @Override public int size() { return subMap.size(); } @Override public Iterator<K> iterator() { return new Iterator<K>() { final Iterator<Map.Entry<K, Collection<V>>> entryIterator = subMap.entrySet().iterator(); Map.Entry<K, Collection<V>> entry; public boolean hasNext() { return entryIterator.hasNext(); } public K next() { entry = entryIterator.next(); return entry.getKey(); } public void remove() { checkState(entry != null); Collection<V> collection = entry.getValue(); entryIterator.remove(); totalSize -= collection.size(); collection.clear(); } }; } // The following methods are included for better performance. @Override public boolean contains(Object key) { return subMap.containsKey(key); } @Override public boolean remove(Object key) { int count = 0; Collection<V> collection = subMap.remove(key); if (collection != null) { count = collection.size(); collection.clear(); totalSize -= count; } return count > 0; } @Override public boolean containsAll(Collection<?> c) { return subMap.keySet().containsAll(c); } @Override public boolean equals(@Nullable Object object) { return this == object || this.subMap.keySet().equals(object); } @Override public int hashCode() { return subMap.keySet().hashCode(); } } private class SortedKeySet extends KeySet implements SortedSet<K> { SortedKeySet(SortedMap<K, Collection<V>> subMap) { super(subMap); } SortedMap<K, Collection<V>> sortedMap() { return (SortedMap<K, Collection<V>>) subMap; } public Comparator<? super K> comparator() { return sortedMap().comparator(); } public K first() { return sortedMap().firstKey(); } public SortedSet<K> headSet(K toElement) { return new SortedKeySet(sortedMap().headMap(toElement)); } public K last() { return sortedMap().lastKey(); } public SortedSet<K> subSet(K fromElement, K toElement) { return new SortedKeySet(sortedMap().subMap(fromElement, toElement)); } public SortedSet<K> tailSet(K fromElement) { return new SortedKeySet(sortedMap().tailMap(fromElement)); } } private transient Multiset<K> multiset; public Multiset<K> keys() { Multiset<K> result = multiset; return (result == null) ? multiset = new MultisetView() : result; } /** Multiset view that stays in sync with the multimap keys. */ private class MultisetView extends AbstractMultiset<K> { @Override public int remove(Object key, int occurrences) { if (occurrences == 0) { return count(key); } checkArgument(occurrences > 0); Collection<V> collection; try { collection = map.get(key); } catch (NullPointerException e) { return 0; } catch (ClassCastException e) { return 0; } if (collection == null) { return 0; } int count = collection.size(); if (occurrences >= count) { return removeValuesForKey(key); } Iterator<V> iterator = collection.iterator(); for (int i = 0; i < occurrences; i++) { iterator.next(); iterator.remove(); } totalSize -= occurrences; return count; } @Override public Set<K> elementSet() { return AbstractMultimap.this.keySet(); } transient Set<Multiset.Entry<K>> entrySet; @Override public Set<Multiset.Entry<K>> entrySet() { Set<Multiset.Entry<K>> result = entrySet; return (result == null) ? entrySet = new EntrySet() : result; } private class EntrySet extends AbstractSet<Multiset.Entry<K>> { @Override public Iterator<Multiset.Entry<K>> iterator() { return new MultisetEntryIterator(); } @Override public int size() { return map.size(); } // The following methods are included for better performance. @Override public boolean contains(Object o) { if (!(o instanceof Multiset.Entry)) { return false; } Multiset.Entry<?> entry = (Multiset.Entry<?>) o; Collection<V> collection = map.get(entry.getElement()); return (collection != null) && (collection.size() == entry.getCount()); } @Override public void clear() { AbstractMultimap.this.clear(); } @Override public boolean remove(Object o) { return contains(o) && (removeValuesForKey(((Multiset.Entry<?>) o).getElement()) > 0); } } @Override public Iterator<K> iterator() { return new MultisetKeyIterator(); } // The following methods are included for better performance. @Override public int count(Object key) { try { Collection<V> collection = map.get(key); return (collection == null) ? 0 : collection.size(); } catch (NullPointerException e) { return 0; } catch (ClassCastException e) { return 0; } } @Override public int size() { return totalSize; } @Override public void clear() { AbstractMultimap.this.clear(); } } /** * Removes all values for the provided key. Unlike {@link #removeAll}, it * returns the number of removed mappings. */ private int removeValuesForKey(Object key) { Collection<V> collection; try { collection = map.remove(key); } catch (NullPointerException e) { return 0; } catch (ClassCastException e) { return 0; } int count = 0; if (collection != null) { count = collection.size(); collection.clear(); totalSize -= count; } return count; } /** Iterator across each key, repeating once per value. */ private class MultisetEntryIterator implements Iterator<Multiset.Entry<K>> { final Iterator<Map.Entry<K, Collection<V>>> asMapIterator = asMap().entrySet().iterator(); public boolean hasNext() { return asMapIterator.hasNext(); } public Multiset.Entry<K> next() { return new MultisetEntry(asMapIterator.next()); } public void remove() { asMapIterator.remove(); } } private class MultisetEntry extends Multisets.AbstractEntry<K> { final Map.Entry<K, Collection<V>> entry; public MultisetEntry(Map.Entry<K, Collection<V>> entry) { this.entry = entry; } public K getElement() { return entry.getKey(); } public int getCount() { return entry.getValue().size(); } } /** Iterator across each key, repeating once per value. */ private class MultisetKeyIterator implements Iterator<K> { final Iterator<Map.Entry<K, V>> entryIterator = entries().iterator(); public boolean hasNext() { return entryIterator.hasNext(); } public K next() { return entryIterator.next().getKey(); } public void remove() { entryIterator.remove(); } } private transient Collection<V> valuesCollection; /** * {@inheritDoc} * * <p>The iterator generated by the returned collection traverses the values * for one key, followed by the values of a second key, and so on. */ public Collection<V> values() { Collection<V> result = valuesCollection; return (result == null) ? valuesCollection = new Values() : result; } private class Values extends AbstractCollection<V> { @Override public Iterator<V> iterator() { return new ValueIterator(); } @Override public int size() { return totalSize; } // The following methods are included to improve performance. @Override public void clear() { AbstractMultimap.this.clear(); } @Override public boolean contains(Object value) { return containsValue(value); } } /** Iterator across all values. */ private class ValueIterator implements Iterator<V> { final Iterator<Map.Entry<K, V>> entryIterator = createEntryIterator(); public boolean hasNext() { return entryIterator.hasNext(); } public V next() { return entryIterator.next().getValue(); } public void remove() { entryIterator.remove(); } } private transient Collection<Map.Entry<K, V>> entries; // TODO: should we copy this javadoc to each concrete class, so that classes // like LinkedHashMultimap that need to say something different are still // able to {@inheritDoc} all the way from Multimap? /** * {@inheritDoc} * * <p>The iterator generated by the returned collection traverses the values * for one key, followed by the values of a second key, and so on. * * <p>Each entry is an immutable snapshot of a key-value mapping in the * multimap, taken at the time the entry is returned by a method call to the * collection or its iterator. */ public Collection<Map.Entry<K, V>> entries() { Collection<Map.Entry<K, V>> result = entries; return (entries == null) ? entries = createEntries() : result; } private Collection<Map.Entry<K, V>> createEntries() { // TODO: can we refactor so we're not doing "this instanceof"? return (this instanceof SetMultimap) ? new EntrySet() : new Entries(); } /** Entries for multimap. */ private class Entries extends AbstractCollection<Map.Entry<K, V>> { @Override public Iterator<Map.Entry<K, V>> iterator() { return createEntryIterator(); } @Override public int size() { return totalSize; } // The following methods are included to improve performance. @Override public boolean contains(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; return containsEntry(entry.getKey(), entry.getValue()); } @Override public void clear() { AbstractMultimap.this.clear(); } @Override public boolean remove(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; return AbstractMultimap.this.remove(entry.getKey(), entry.getValue()); } } /** * Returns an iterator across all key-value map entries, used by {@code * entries().iterator()} and {@code values().iterator()}. The default * behavior, which traverses the values for one key, the values for a second * key, and so on, suffices for most {@code AbstractMultimap} implementations. * * @return an iterator across map entries */ Iterator<Map.Entry<K, V>> createEntryIterator() { return new EntryIterator(); } /** Iterator across all key-value pairs. */ private class EntryIterator implements Iterator<Map.Entry<K, V>> { final Iterator<Map.Entry<K, Collection<V>>> keyIterator; K key; Collection<V> collection; Iterator<V> valueIterator; EntryIterator() { keyIterator = map.entrySet().iterator(); if (keyIterator.hasNext()) { findValueIteratorAndKey(); } else { valueIterator = Iterators.emptyModifiableIterator(); } } void findValueIteratorAndKey() { Map.Entry<K, Collection<V>> entry = keyIterator.next(); key = entry.getKey(); collection = entry.getValue(); valueIterator = collection.iterator(); } public boolean hasNext() { return keyIterator.hasNext() || valueIterator.hasNext(); } public Map.Entry<K, V> next() { if (!valueIterator.hasNext()) { findValueIteratorAndKey(); } return Maps.immutableEntry(key, valueIterator.next()); } public void remove() { valueIterator.remove(); if (collection.isEmpty()) { keyIterator.remove(); } totalSize--; } } /** Entry set for a {@link SetMultimap}. */ private class EntrySet extends Entries implements Set<Map.Entry<K, V>> { @Override public boolean equals(@Nullable Object object) { return Collections2.setEquals(this, object); } @Override public int hashCode() { return Sets.hashCodeImpl(this); } } private transient Map<K, Collection<V>> asMap; public Map<K, Collection<V>> asMap() { Map<K, Collection<V>> result = asMap; return (result == null) ? asMap = createAsMap() : result; } private Map<K, Collection<V>> createAsMap() { return (map instanceof SortedMap) ? new SortedAsMap((SortedMap<K, Collection<V>>) map) : new AsMap(map); } private class AsMap extends AbstractMap<K, Collection<V>> { /** * Usually the same as map, but smaller for the headMap(), tailMap(), or * subMap() of a SortedAsMap. */ final transient Map<K, Collection<V>> submap; AsMap(Map<K, Collection<V>> submap) { this.submap = submap; } transient Set<Map.Entry<K, Collection<V>>> entrySet; @Override public Set<Map.Entry<K, Collection<V>>> entrySet() { Set<Map.Entry<K, Collection<V>>> result = entrySet; return (entrySet == null) ? entrySet = new AsMapEntries() : result; } // The following methods are included for performance. @Override public boolean containsKey(Object key) { return submap.containsKey(key); } @Override public Collection<V> get(Object key) { Collection<V> collection = submap.get(key); if (collection == null) { return null; } @SuppressWarnings("unchecked") K k = (K) key; return wrapCollection(k, collection); } @Override public Set<K> keySet() { return AbstractMultimap.this.keySet(); } @Override public Collection<V> remove(Object key) { Collection<V> collection = submap.remove(key); if (collection == null) { return null; } Collection<V> output = createCollection(); output.addAll(collection); totalSize -= collection.size(); collection.clear(); return output; } @Override public boolean equals(@Nullable Object object) { return this == object || submap.equals(object); } @Override public int hashCode() { return submap.hashCode(); } @Override public String toString() { return submap.toString(); } class AsMapEntries extends AbstractSet<Map.Entry<K, Collection<V>>> { @Override public Iterator<Map.Entry<K, Collection<V>>> iterator() { return new AsMapIterator(); } @Override public int size() { return submap.size(); } // The following methods are included for performance. @Override public boolean contains(Object o) { return submap.entrySet().contains(o); } @Override public boolean remove(Object o) { if (!contains(o)) { return false; } Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; removeValuesForKey(entry.getKey()); return true; } } /** Iterator across all keys and value collections. */ class AsMapIterator implements Iterator<Map.Entry<K, Collection<V>>> { final Iterator<Map.Entry<K, Collection<V>>> delegateIterator = submap.entrySet().iterator(); Collection<V> collection; public boolean hasNext() { return delegateIterator.hasNext(); } public Map.Entry<K, Collection<V>> next() { Map.Entry<K, Collection<V>> entry = delegateIterator.next(); K key = entry.getKey(); collection = entry.getValue(); return Maps.immutableEntry(key, wrapCollection(key, collection)); } public void remove() { delegateIterator.remove(); totalSize -= collection.size(); collection.clear(); } } } private class SortedAsMap extends AsMap implements SortedMap<K, Collection<V>> { SortedAsMap(SortedMap<K, Collection<V>> submap) { super(submap); } SortedMap<K, Collection<V>> sortedMap() { return (SortedMap<K, Collection<V>>) submap; } public Comparator<? super K> comparator() { return sortedMap().comparator(); } public K firstKey() { return sortedMap().firstKey(); } public K lastKey() { return sortedMap().lastKey(); } public SortedMap<K, Collection<V>> headMap(K toKey) { return new SortedAsMap(sortedMap().headMap(toKey)); } public SortedMap<K, Collection<V>> subMap(K fromKey, K toKey) { return new SortedAsMap(sortedMap().subMap(fromKey, toKey)); } public SortedMap<K, Collection<V>> tailMap(K fromKey) { return new SortedAsMap(sortedMap().tailMap(fromKey)); } SortedSet<K> sortedKeySet; // returns a SortedSet, even though returning a Set would be sufficient to // satisfy the SortedMap.keySet() interface @Override public SortedSet<K> keySet() { SortedSet<K> result = sortedKeySet; return (result == null) ? sortedKeySet = new SortedKeySet(sortedMap()) : result; } } // Comparison and hashing @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof Multimap) { Multimap<?, ?> that = (Multimap<?, ?>) object; return this.map.equals(that.asMap()); } return false; } /** * Returns the hash code for this multimap. * * <p>The hash code of a multimap is defined as the hash code of the map view, * as returned by {@link Multimap#asMap}. * * @see Map#hashCode */ @Override public int hashCode() { return map.hashCode(); } /** * Returns a string representation of the multimap, generated by calling * {@code toString} on the map returned by {@link Multimap#asMap}. * * @return a string representation of the multimap */ @Override public String toString() { return map.toString(); } private static final long serialVersionUID = 2447537837011683357L; }
package com.github.shynixn.astraledit.bukkit.logic.lib; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.inventory.meta.SkullMeta; import java.util.ArrayList; import java.util.List; /** * Copyright 2017 Shynixn * <p> * Do not remove this header! * <p> * Version 1.0 * <p> * MIT License * <p> * Copyright (c) 2017 * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ public class ItemStackBuilder extends ItemStack { /** * Initializes a new itemStackBuilder */ public ItemStackBuilder() { super(); } /** * Initializes a new itemStackBuilder * * @param type type */ public ItemStackBuilder(Material type) { super(type); } /** * Initializes a new itemStackBuilder * * @param type type * @param amount amount */ public ItemStackBuilder(Material type, int amount) { super(type, amount); } /** * Initializes a new itemStackBuilder * * @param type type * @param amount amount * @param damage damage */ public ItemStackBuilder(Material type, int amount, short damage) { super(type, amount, damage); } /** * Initializes a new itemstackBuilder from an existing itemStack * * @param itemStack itemStack */ public ItemStackBuilder(ItemStack itemStack) { super(); this.setType(itemStack.getType()); this.setAmount(itemStack.getAmount()); this.setData(itemStack.getData()); this.setDurability(itemStack.getDurability()); this.setItemMeta(itemStack.getItemMeta()); } /** * Sets the displayName of the itemStack * * @param name name * @return builder */ public ItemStackBuilder setDisplayName(String name) { final ItemMeta itemMeta = this.getItemMeta(); itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', name)); this.setItemMeta(itemMeta); return this; } /** * Sets the skin of the itemStack. Only works on playerHeads * * @param skin skin * @return builder */ public ItemStackBuilder setSkin(String skin) { if (this.getItemMeta() instanceof SkullMeta) { final SkullMeta skullMeta = (SkullMeta) this.getItemMeta(); skullMeta.setOwner(skin); this.setItemMeta(skullMeta); } return this; } /** * Sets the color of the itemStack. Only works on leatherItems * * @param color color * @return builder */ public ItemStackBuilder setColor(Color color) { if (this.getItemMeta() instanceof LeatherArmorMeta) { final LeatherArmorMeta meta = (LeatherArmorMeta) this.getItemMeta(); meta.setColor(color); this.setItemMeta(meta); } return this; } /** * Sets the lore of the itemStack * * @param lore lore * @return builder */ public ItemStackBuilder setLore(String... lore) { final List<String> data = new ArrayList<>(); for (final String s : lore) { data.add(ChatColor.translateAlternateColorCodes('&', s)); } final ItemMeta itemMeta = this.getItemMeta(); itemMeta.setLore(data); this.setItemMeta(itemMeta); return this; } /** * Adds lore to the end of the itemstack lore * * @param lore lore * @return builder */ public ItemStackBuilder addLore(String... lore) { final ItemMeta itemMeta = this.getItemMeta(); final List<String> data = new ArrayList<>(itemMeta.getLore()); for (final String s : lore) { data.add(ChatColor.translateAlternateColorCodes('&', s)); } itemMeta.setLore(data); this.setItemMeta(itemMeta); return this; } /** * Adds lore after the index of a lore line * * @param index index * @param lore lore * @return builder */ public ItemStackBuilder addLore(int index, String... lore) { final ItemMeta itemMeta = this.getItemMeta(); final List<String> data = new ArrayList<>(); for (int i = 0; i < itemMeta.getLore().size(); i++) { data.add(itemMeta.getLore().get(0)); if (i == index) { for (final String s : lore) { data.add(ChatColor.translateAlternateColorCodes('&', s)); } } } itemMeta.setLore(data); this.setItemMeta(itemMeta); return this; } /** * Clears all lore from the itemStack * @return builder * */ public ItemStackBuilder clearLore() { final ItemMeta itemMeta = this.getItemMeta(); itemMeta.setLore(new ArrayList<>()); this.setItemMeta(itemMeta); return this; } /** * Removes the lore matching the lines * * @param lore lore * @return builder */ public ItemStackBuilder removeLore(String... lore) { final ItemMeta itemMeta = this.getItemMeta(); final List<String> data = new ArrayList<>(); for (final String s : itemMeta.getLore()) { boolean add = true; for (final String k : lore) { if (s.equals(k)) { add = false; } } if (add) { data.add(s); } } itemMeta.setLore(data); this.setItemMeta(itemMeta); return this; } /** * Removes the lore from the specific index * * @param index index * @return builder */ public ItemStackBuilder removeLore(int index) { final List<String> data = new ArrayList<>(); final ItemMeta itemMeta = this.getItemMeta(); for (int i = 0; i < itemMeta.getLore().size(); i++) { if (i != index) { data.add(itemMeta.getLore().get(i)); } } itemMeta.setLore(data); this.setItemMeta(itemMeta); return this; } /** * Creates a new itemStack from this * * @return itemStack */ public ItemStack build() { final ItemStack itemStack = new ItemStack(this.getType()); itemStack.setAmount(this.getAmount()); itemStack.setData(this.getData()); itemStack.setDurability(this.getDurability()); itemStack.setItemMeta(this.getItemMeta()); return itemStack; } }
package com.capitalone.dashboard.datafactory.versionone.test; import com.capitalone.dashboard.datafactory.versionone.VersionOneDataFactoryImpl; import com.capitalone.dashboard.misc.HygieiaException; import org.apache.commons.lang3.StringUtils; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests all facets of the VerisonOneDataFactoryImpl class, which is responsible * for handling all transactions to the source system, VersionOne. * * @author KFK884 * */ public class VersionOneDataFactoryImplTest { private static Logger logger = LoggerFactory.getLogger("VersionOneDataFactoryImplTest"); protected static String queryName; protected static String query; protected static String yesterday; protected static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); protected static Map<String, String> auth; protected static VersionOneDataFactoryImpl v1DataFactory; /** * Default constructor. */ public VersionOneDataFactoryImplTest() { } /** * Runs actions before test is initialized. * * @throws java.lang.Exception */ @BeforeClass public static void setUpBeforeClass() throws Exception { logger.info( "Beginning tests for com.capitalone.dashboard.datafactory.versionone.VersionOneDataFactoryImpl"); auth = new HashMap<>(); // TODO: Include your own company proxy auth.put("v1ProxyUrl", ""); // TODO: Include your own base uri for VersionOne auth.put("v1BaseUri", ""); // TODO: Include your own v1 auth token auth.put("v1AccessToken", ""); Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -3); yesterday = dateFormat.format(cal.getTime()); yesterday = yesterday.replace(" ", "T"); query = "from: Story\n" + "select:\n" + " - Number\n" + "filter:\n" + " - ChangeDate>'" + yesterday + "'\n" + " - (IsDeleted='False'|IsDeleted='True')\n"; if (StringUtils.isNotEmpty(auth.get("v1BaseUri"))) { v1DataFactory = new VersionOneDataFactoryImpl(auth); } else { logger.warn( "Switching to generic V1 data factory connnection (with no auth). This should eventually be resolved by mocking a V1 response model in testing"); v1DataFactory = new VersionOneDataFactoryImpl(); } } /** * Runs actions after test is complete. * * @throws java.lang.Exception */ @AfterClass public static void tearDownAfterClass() throws Exception { v1DataFactory = null; auth = null; yesterday = null; query = null; } /** * Performs these actions before each test. * * @throws java.lang.Exception */ @Before public void setUp() throws Exception { } /** * Performs these actions after each test completes. * * @throws java.lang.Exception */ @After public void tearDown() throws Exception { } /** * Test method for * {@link com.capitalone.dashboard.datafactory.versionone.VersionOneDataFactoryImpl#buildPagingQuery(int)} * . */ @Test public void testBuildPagingQuery() { v1DataFactory.setPageSize(1); v1DataFactory.setBasicQuery(query); v1DataFactory.buildPagingQuery(30); assertNotNull("The basic query was created", v1DataFactory.getPagingQuery()); assertEquals("The page size was accurate", 1, v1DataFactory.getPageSize()); assertEquals("The page index was accurate", 30, v1DataFactory.getPageIndex()); } /** * Test method for * {@link com.capitalone.dashboard.datafactory.versionone.VersionOneDataFactoryImpl#getPagingQueryResponse()} * . */ @Ignore @Test public void testGetPagingQueryResponse() { v1DataFactory.setPageSize(1); v1DataFactory.setBasicQuery(query); v1DataFactory.buildPagingQuery(0); try { JSONArray rs = v1DataFactory.getPagingQueryResponse(); /* * Testing actual JSON for values */ JSONArray dataMainArry = (JSONArray) rs.get(0); JSONObject dataMainObj = (JSONObject) dataMainArry.get(0); // number assertTrue("No valid Number was found", dataMainObj.get("Number").toString().length() >= 7); } catch (NullPointerException npe) { fail("There was a problem with an object used to connect to VersionOne during the test"); } catch (ArrayIndexOutOfBoundsException aioobe) { fail("The object returned from VersionOne had no JSONObjects in it during the test; try increasing the scope of your test case query and try again."); } catch (IndexOutOfBoundsException ioobe) { logger.info("JSON artifact may be empty - re-running test to prove this out..."); JSONArray rs = new JSONArray(); try { rs = v1DataFactory.getPagingQueryResponse(); } catch (HygieiaException e) { fail("There was an unexpected problem while connecting to VersionOne during the test"); } /* * Testing actual JSON for values */ String strRs = rs.toString(); assertEquals( "There was nothing returned from VersionOne that is consistent with a valid response.", "[[]]", strRs); } catch (Exception e) { fail("There was an unexpected problem while connecting to VersionOne during the test"); } } @Test public void testVersionOneDataFactoryImpl() { assertEquals("The compared contructed page size values did not match", 2000, v1DataFactory.getPageSize()); } @Test public void testVersionOneDataFactoryImplInt() { v1DataFactory.setPageSize(1000); assertEquals("The compared contructed page size values did not match", 1000, v1DataFactory.getPageSize()); } @Test public void testBuildBasicQuery() { v1DataFactory.setPageSize(1); v1DataFactory.setBasicQuery(query); assertNotNull("The basic query was created", v1DataFactory.getBasicQuery()); assertEquals("The page size was accurate", 1, v1DataFactory.getPageSize()); assertEquals("The page index was accurate", 0, v1DataFactory.getPageIndex()); } @Ignore @Test public void testGetQueryResponse() { v1DataFactory.setPageSize(1); v1DataFactory.setBasicQuery(query); try { JSONArray rs = v1DataFactory.getQueryResponse(); /* * Testing actual JSON for values */ JSONArray dataMainArry = (JSONArray) rs.get(0); JSONObject dataMainObj = (JSONObject) dataMainArry.get(0); // number assertTrue("No valid Number was found", dataMainObj.get("Number").toString().length() >= 7); } catch (NullPointerException npe) { fail("There was a problem with an object used to connect to VersionOne during the test"); } catch (ArrayIndexOutOfBoundsException aioobe) { fail("The object returned from VersionOne had no JSONObjects in it during the test; try increasing the scope of your test case query and try again."); } catch (IndexOutOfBoundsException ioobe) { logger.info("JSON artifact may be empty - re-running test to prove this out..."); JSONArray rs = new JSONArray(); try { rs = v1DataFactory.getQueryResponse(); } catch (HygieiaException e) { fail("There was an unexpected problem while connecting to VersionOne during the test"); } /* * Testing actual JSON for values */ String strRs = rs.toString(); assertEquals( "There was nothing returned from VersionOne that is consistent with a valid response.", "[[]]", strRs); } catch (Exception e) { fail("There was an unexpected problem while connecting to VersionOne during the test"); } } }
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.reducisaurus.servlets; import com.google.appengine.api.memcache.Expiration; import com.google.appengine.api.memcache.MemcacheService; import com.google.appengine.api.memcache.MemcacheServiceFactory; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.FileItemStream; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.IOUtils; import javax.annotation.Nullable; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collection; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.logging.Logger; public abstract class BaseServlet extends HttpServlet { private static final String EXPIRE_URLS_PARAM = "expire_urls"; private static final String CONTENT_TYPE_ERROR = "text/plain"; private static final int STATUS_CODE_ERROR = 400; private static final int DISABLE_URL_CACHE_VALUE = 0; private static final int DEFAULT_URL_CACHE_TIME_SECS = 300; private static final String MAX_AGE_PARAM = "max-age"; private static final int DISABLE_MAX_AGE = 0; private static final int DEFAULT_MAX_AGE_PARAM = 600; private final MemcacheService memcache = MemcacheServiceFactory.getMemcacheService(); private static final Logger logger = Logger.getLogger(BaseServlet.class.getName()); @Override protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { String filecontents; boolean useMemcache = isMemcacheAllowed(req); if (ServletFileUpload.isMultipartContent(req)) { filecontents = collectFromFileUpload(req); } else { filecontents = collectFromFormArgs(req); } filecontents = filecontents.trim(); if (filecontents.length() == 0) { resp.setStatus(STATUS_CODE_ERROR); resp.setContentType(CONTENT_TYPE_ERROR); resp.getWriter().println("No data to parse!"); return; } final String key = getKeyForContents(filecontents); Object cachedCopy; if (useMemcache && (cachedCopy = memcache.get(key)) != null) { maybeSetHttpCacheHeaders(req, resp); render(resp, (String) cachedCopy); } else { StringReader reader = new StringReader(filecontents); Response results = process(resp, reader); if (results.isCacheable()) { maybeSetHttpCacheHeaders(req, resp); if (useMemcache) { memcache.put(key, results.getBody()); } } render(resp, results.getBody()); } } private boolean isMemcacheAllowed(HttpServletRequest hreq) { // If there are any caching related headers, don't use any server side // caches. This isn't built to HTTP spec, but it covers the // shift-reload case. String cacheControl = hreq.getHeader("Cache-Control"); if (cacheControl != null && (cacheControl.contains("max-age") || cacheControl.contains("no-cache"))) { return false; } String pragma = hreq.getHeader("Pragma"); if (pragma != null && pragma.contains("no-cache")) { return false; } try { long ims = hreq.getDateHeader("If-Modified-Since"); if (ims != -1) { return false; } } catch (IllegalArgumentException e) { return false; } return true; } private void maybeSetHttpCacheHeaders(HttpServletRequest req, HttpServletResponse resp) { long cachePolicy = getCachingPolicy(req, MAX_AGE_PARAM, DISABLE_MAX_AGE, DEFAULT_MAX_AGE_PARAM); if (cachePolicy != DISABLE_MAX_AGE) { resp.setDateHeader("Expires", new Date().getTime() + cachePolicy * 1000); resp.setHeader("Cache-Control", "max-age=" + cachePolicy); } } private String collectFromFileUpload(final HttpServletRequest req) throws IOException, ServletException { StringBuilder collector = new StringBuilder(); try { ServletFileUpload sfu = new ServletFileUpload(); FileItemIterator it = sfu.getItemIterator(req); while (it.hasNext()) { FileItemStream item = it.next(); if (!item.isFormField()) { InputStream stream = item.openStream(); collector.append(IOUtils.toString(stream, "UTF-8")); collector.append("\n"); IOUtils.closeQuietly(stream); } } } catch (FileUploadException e) { throw new ServletException(e); } return collector.toString(); } private String collectFromFormArgs(final HttpServletRequest req) throws IOException, ServletException { StringBuilder collector = new StringBuilder(); for (String urlParameterName : getSortedParameterNames(req)) { final String[] values = req.getParameterValues(urlParameterName); for (String value : values) { if (value.matches("^https?://.*")) { acquireFromRemoteUrl(req, collector, value); } else { acquireFromParameterValue(collector, value); } } } return collector.toString(); } private void acquireFromRemoteUrl(final HttpServletRequest req, StringBuilder concatenatedContents, final String url) throws IOException, ServletException { logger.severe("fetching url " + url); try { final String cached = maybeFetchUrlFromCache(req, url); if (cached != null) { concatenatedContents.append(cached); } else { final String urlContents = fetchUrl(url); acquireFromParameterValue(concatenatedContents, urlContents); maybePutUrlInCache(req, url, urlContents); } } catch (MalformedURLException ex) { throw new ServletException(ex); } } private void acquireFromParameterValue(StringBuilder concatenatedContents, String value) { concatenatedContents.append(value); concatenatedContents.append("\n"); } private Collection<String> getSortedParameterNames(HttpServletRequest req) { // We want a deterministic order so that dependencies can span input files. // We don't trust the servlet container to return query parameters in any // order, so we impose our own ordering. In this case, we use natural String // ordering. List<String> list = Lists.newArrayList(Iterators.forEnumeration( (Enumeration<String>) req.getParameterNames())); // Some parameter names should be ignored. Iterable<String> filtered = Collections2.filter(list, new Predicate<String>() { @Override public boolean apply(@Nullable String s) { return !(s.contains("_") || s.contains("-")); } }); return Ordering.natural().sortedCopy(filtered); } private String getKeyForContents(final String filecontents) throws ServletException { MessageDigest sha1; try { sha1 = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new ServletException(e); } byte[] hashValue = sha1.digest(filecontents.getBytes()); sha1.reset(); return new String(hashValue); } private int getCachingPolicy(final HttpServletRequest req, String paramName, int disabledValue, int defaultValue) { int returnValue = defaultValue; final String asString = req.getParameter(paramName); if (asString != null) { try { int seconds = Integer.parseInt(asString); if (seconds >= 0) { returnValue = seconds; } } catch (NumberFormatException e) { returnValue = disabledValue; } } return returnValue; } private String fetchUrl(final String url) throws IOException { final URL u = new URL(url); return IOUtils.toString(u.openStream(), "UTF-8"); } private void maybePutUrlInCache(final HttpServletRequest req, final String url, final String contents) { int cacheForSecs = getUrlCachePolicyFromParams(req); if (cacheForSecs == DISABLE_URL_CACHE_VALUE) { return; } memcache.put(url, contents, Expiration.byDeltaSeconds(cacheForSecs)); } private int getUrlCachePolicyFromParams(HttpServletRequest req) { return getCachingPolicy(req, EXPIRE_URLS_PARAM, DISABLE_URL_CACHE_VALUE, DEFAULT_URL_CACHE_TIME_SECS); } private String maybeFetchUrlFromCache(final HttpServletRequest req, final String url) { // If the client asks us to not cache, we also delete any cached values for // this key. if (getUrlCachePolicyFromParams(req) == DISABLE_URL_CACHE_VALUE || !isMemcacheAllowed(req)) { memcache.delete(url); return null; } Object cached = memcache.get(url); if (cached != null) { return (String) cached; } else { return null; } } protected abstract void render(HttpServletResponse resp, String response) throws IOException; protected abstract Response process(HttpServletResponse resp, StringReader reader) throws IOException; }
package org.hisp.dhis.calendar; /* * Copyright (c) 2004-2017, 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.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.chrono.ISOChronology; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import java.util.List; /** * @author Morten Olav Hansen <mortenoh@gmail.com> */ public abstract class AbstractCalendar implements Calendar { protected static final String[] DEFAULT_I18N_MONTH_NAMES = new String[]{ "month.january", "month.february", "month.march", "month.april", "month.may", "month.june", "month.july", "month.august", "month.september", "month.october", "month.november", "month.december" }; protected static final String[] DEFAULT_I18N_MONTH_SHORT_NAMES = new String[]{ "month.short.january", "month.short.february", "month.short.march", "month.short.april", "month.short.may", "month.short.june", "month.short.july", "month.short.august", "month.short.september", "month.short.october", "month.short.november", "month.short.december" }; protected static final String[] DEFAULT_I18N_DAY_NAMES = new String[]{ "weekday.monday", "weekday.tuesday", "weekday.wednesday", "weekday.thursday", "weekday.friday", "weekday.saturday", "weekday.sunday" }; protected static final String[] DEFAULT_I18N_DAY_SHORT_NAMES = new String[]{ "weekday.short.monday", "weekday.short.tuesday", "weekday.short.wednesday", "weekday.short.thursday", "weekday.short.friday", "weekday.short.saturday", "weekday.short.sunday" }; protected static final String DEFAULT_ISO8601_DATE_FORMAT = "yyyy-MM-dd"; protected String dateFormat = DEFAULT_ISO8601_DATE_FORMAT; @Override public String getDateFormat() { return dateFormat; } @Override public void setDateFormat( String dateFormat ) { this.dateFormat = dateFormat; } @Override public String formattedDate( DateTimeUnit dateTimeUnit ) { return getDateFormat() .replace( "yyyy", String.format( "%04d", dateTimeUnit.getYear() ) ) .replace( "MM", String.format( "%02d", dateTimeUnit.getMonth() ) ) .replace( "dd", String.format( "%02d", dateTimeUnit.getDay() ) ); } @Override public String formattedDate( String dateFormat, DateTimeUnit dateTimeUnit ) { return dateFormat .replace( "yyyy", String.format( "%04d", dateTimeUnit.getYear() ) ) .replace( "MM", String.format( "%02d", dateTimeUnit.getMonth() ) ) .replace( "dd", String.format( "%02d", dateTimeUnit.getDay() ) ); } @Override public String formattedIsoDate( DateTimeUnit dateTimeUnit ) { dateTimeUnit = toIso( dateTimeUnit ); DateTime dateTime = dateTimeUnit.toJodaDateTime(); DateTimeFormatter format = DateTimeFormat.forPattern( getDateFormat() ); return format.print( dateTime ); } @Override public DateTimeUnit toIso( int year, int month, int day ) { return toIso( new DateTimeUnit( year, month, day ) ); } @Override public DateTimeUnit toIso( String date ) { DateTimeFormatter format = DateTimeFormat.forPattern( getDateFormat() ); DateTime dateTime = format.parseDateTime( date ); return toIso( DateTimeUnit.fromJodaDateTime( dateTime ) ); } @Override public DateTimeUnit fromIso( int year, int month, int day ) { return fromIso( new DateTimeUnit( year, month, day, true ) ); } @Override public DateInterval toInterval( DateIntervalType type ) { return toInterval( today(), type ); } @Override public DateInterval toInterval( DateTimeUnit dateTimeUnit, DateIntervalType type ) { return toInterval( dateTimeUnit, type, 0, 1 ); } @Override public DateInterval toInterval( DateIntervalType type, int offset, int length ) { return toInterval( today(), type, offset, length ); } @Override public List<DateInterval> toIntervals( DateTimeUnit dateTimeUnit, DateIntervalType type, int offset, int length, int periods ) { List<DateInterval> dateIntervals = Lists.newArrayList(); for ( int i = offset; i <= (offset + periods - 1); i++ ) { dateIntervals.add( toInterval( dateTimeUnit, type, i, length ) ); } return dateIntervals; } @Override public DateTimeUnit today() { DateTime dateTime = DateTime.now( ISOChronology.getInstance( DateTimeZone.getDefault() ) ); DateTimeUnit dateTimeUnit = new DateTimeUnit( dateTime.getYear(), dateTime.getMonthOfYear(), dateTime.getDayOfMonth(), true ); return fromIso( dateTimeUnit ); } @Override public int monthsInYear() { return 12; } @Override public int daysInWeek() { return 7; } @Override public String nameOfMonth( int month ) { if ( month > DEFAULT_I18N_MONTH_NAMES.length || month <= 0 ) { return null; } return DEFAULT_I18N_MONTH_NAMES[month - 1]; } @Override public String shortNameOfMonth( int month ) { if ( month > DEFAULT_I18N_MONTH_SHORT_NAMES.length || month <= 0 ) { return null; } return DEFAULT_I18N_MONTH_SHORT_NAMES[month - 1]; } @Override public String nameOfDay( int day ) { if ( day > DEFAULT_I18N_DAY_NAMES.length || day <= 0 ) { return null; } return DEFAULT_I18N_DAY_NAMES[day - 1]; } @Override public String shortNameOfDay( int day ) { if ( day > DEFAULT_I18N_DAY_SHORT_NAMES.length || day <= 0 ) { return null; } return DEFAULT_I18N_DAY_SHORT_NAMES[day - 1]; } @Override public boolean isIso8601() { return false; } @Override public DateTimeUnit isoStartOfYear( int year ) { return new DateTimeUnit( year, 1, 1 ); } @Override public boolean isValid( DateTimeUnit dateTime ) { if ( dateTime.getMonth() < 1 || dateTime.getMonth() > monthsInYear() ) { return false; } if ( dateTime.getDay() < 1 || dateTime.getDay() > daysInMonth( dateTime.getYear(), dateTime.getMonth() ) ) { return false; } return true; } }
package co.cask.coopr.provisioner; import co.cask.coopr.account.Account; import co.cask.coopr.cluster.Cluster; import co.cask.coopr.common.conf.Configuration; import co.cask.coopr.common.conf.Constants; import co.cask.coopr.common.queue.Element; import co.cask.coopr.common.queue.QueueGroup; import co.cask.coopr.common.queue.QueueService; import co.cask.coopr.common.queue.TrackingQueue; import co.cask.coopr.common.zookeeper.LockService; import co.cask.coopr.common.zookeeper.lib.ZKInterProcessReentrantLock; import co.cask.coopr.provisioner.plugin.ResourceCollection; import co.cask.coopr.provisioner.plugin.ResourceService; import co.cask.coopr.scheduler.task.MissingEntityException; import co.cask.coopr.spec.Tenant; import co.cask.coopr.spec.TenantSpecification; import co.cask.coopr.store.cluster.ClusterStoreService; import co.cask.coopr.store.cluster.ClusterStoreView; import co.cask.coopr.store.entity.EntityStoreService; import co.cask.coopr.store.provisioner.ProvisionerStore; import co.cask.coopr.store.tenant.TenantStore; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.name.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; /** * Service for managing provisioners. */ public class TenantProvisionerService { private static final Logger LOG = LoggerFactory.getLogger(TenantProvisionerService.class); private final ProvisionerStore provisionerStore; private final TenantStore tenantStore; private final ZKInterProcessReentrantLock tenantLock; private final long provisionerTimeoutSecs; private final TrackingQueue balanceQueue; private final ProvisionerRequestService provisionerRequestService; private final ClusterStoreService clusterStoreService; private final ResourceService resourceService; private final EntityStoreService entityStoreService; private final QueueService queueService; @Inject private TenantProvisionerService(ProvisionerStore provisionerStore, final TenantStore tenantStore, LockService lockService, @Named(Constants.Queue.WORKER_BALANCE) TrackingQueue balanceQueue, ClusterStoreService clusterStoreService, ProvisionerRequestService provisionerRequestService, ResourceService resourceService, EntityStoreService entityStoreService, QueueService queueService, Configuration conf) { this.provisionerStore = provisionerStore; this.tenantStore = tenantStore; this.provisionerRequestService = provisionerRequestService; this.clusterStoreService = clusterStoreService; this.resourceService = resourceService; this.entityStoreService = entityStoreService; // a single lock is used across all tenants and provisioners. This is so that a request modifies worker assignments // across multiple provisioners does not conflict with requests that modify worker capacity. For example, if a // tenant is added the same time a tenant is deleted, we don't want to be modifying the same provisioner at the // same time and cause conflicts. Similarly, if we're moving workers from one provisioner to another at the same // time as we're adding a tenant, we don't want to both add workers to the same provisioner at the same time. this.tenantLock = lockService.getTenantProvisionerLock(); this.provisionerTimeoutSecs = conf.getLong(Constants.PROVISIONER_TIMEOUT_SECS); this.balanceQueue = balanceQueue; this.queueService = queueService; } /** * Get an unmodifiable collection of all tenant specifications. * * @return Unmodifiable collection of all tenant specifications * @throws IOException */ public Collection<TenantSpecification> getAllTenantSpecifications() throws IOException { return tenantStore.getAllTenantSpecifications(); } /** * Get a tenant specification by tenant name. * * @param name Name of the tenant to get * @return Tenant for the given name, or null if none exists * @throws IOException */ public TenantSpecification getTenantSpecification(String name) throws IOException { Tenant tenant = tenantStore.getTenantByName(name); return tenant == null ? null : tenant.getSpecification(); } /** * Get an immutable collection of all provisioners for external display, with tenant ids mapped to tenant names. * * @return Immutable collection of all provisioners for external display, with tenant ids mapped to tenant names * @throws IOException */ public Collection<Provisioner> getAllProvisioners() throws IOException { Collection<Provisioner> provisioners = provisionerStore.getAllProvisioners(); List<Provisioner> externalProvisioners = Lists.newArrayListWithCapacity(provisioners.size()); for (Provisioner provisioner : provisioners) { externalProvisioners.add(createExternalProvisioner(provisioner)); } return externalProvisioners; } /** * Get the provisioner for the given id for external display, with tenant ids mapped to tenant names, * or null if none exists. * * @param provisionerId Id of the provisioner to get * @return Provisioner for the given id with tenant ids mapped to tenant names, or null if none exists * @throws IOException */ public Provisioner getProvisioner(String provisionerId) throws IOException { return createExternalProvisioner(provisionerStore.getProvisioner(provisionerId)); } /** * Write the tenant to the store and balance the tenant workers across provisioners. Returns the id of the tenant * that was written. * * @param tenantSpecification Tenant to write * @throws IOException if there was an exception persisting the tenant * @throws CapacityException if there is not enough capacity to support all tenant workers * @throws QuotaException if a tenant quota would be violated by the change * @return Id of the written tenant */ public String writeTenantSpecification(TenantSpecification tenantSpecification) throws IOException, CapacityException, QuotaException { tenantLock.acquire(); try { Tenant prevTenant = tenantStore.getTenantByName(tenantSpecification.getName()); String id; if (prevTenant == null) { // if we're adding a new tenant id = UUID.randomUUID().toString(); checkCapacity(tenantSpecification.getWorkers()); } else { // we're updating an existing tenant id = prevTenant.getId(); checkCapacity(tenantSpecification.getWorkers() - prevTenant.getSpecification().getWorkers()); } Tenant updatedTenant = new Tenant(id, tenantSpecification); // check if changing the tenant would cause the cluster or node quotas to be exceeded. if (!satisfiesTenantQuotas(updatedTenant, 0, 0)) { throw new QuotaException("Writing tenant would cause cluster or node quotas to be violated."); } balanceQueue.add(new Element(id)); tenantStore.writeTenant(updatedTenant); return id; } finally { tenantLock.release(); } } /** * Verify that tenant cluster and node quotas would not be exceeded if the given number of additional clusters and * nodes would be added. * * @param tenantId Id of the tenant to verify quotas for * @param additionalClusters Number of clusters that would be added * @param additionalNodes Number of nodes that would be added * @return true if the tenant quotas would be satisfied, false if they would be exceeded. */ public boolean satisfiesTenantQuotas(String tenantId, int additionalClusters, int additionalNodes) throws IOException { Tenant tenant = tenantStore.getTenantByID(tenantId); // if there is no tenant there are no quotas to voilate if (tenant == null) { return true; } return satisfiesTenantQuotas(tenant, additionalClusters, additionalNodes); } /** * Verify that tenant cluster and node quotas would not be exceeded if the given number of additional clusters and * nodes would be added. * * @param tenant Tenant to verify quotas for * @param additionalClusters Number of clusters that would be added * @param additionalNodes Number of nodes that would be added * @return true if the tenant quotas would be satisfied, false if they would be exceeded. */ public boolean satisfiesTenantQuotas(Tenant tenant, int additionalClusters, int additionalNodes) throws IOException { ClusterStoreView view = clusterStoreService.getView(new Account(Constants.ADMIN_USER, tenant.getId())); List<Cluster> nonTerminatedClusters = view.getNonTerminatedClusters(); int numClusters = additionalClusters + nonTerminatedClusters.size(); if (numClusters > tenant.getSpecification().getMaxClusters()) { return false; } int numNodes = additionalNodes; for (Cluster cluster : nonTerminatedClusters) { numNodes += cluster.getNodeIDs().size(); } if (numNodes > tenant.getSpecification().getMaxNodes()) { return false; } return true; } /** * Delete the given tenant. A tenant must not have any assigned workers in order for deletion to be allowed. * * @param name Name of the tenant to delete * @throws IllegalStateException if the tenant has one or more assigned workers * @throws IOException if there was an exception persisting the deletion */ public void deleteTenantByName(String name) throws IllegalStateException, IOException { tenantLock.acquire(); try { Tenant tenant = tenantStore.getTenantByName(name); if (tenant == null) { return; } int numAssignedWorkers = provisionerStore.getNumAssignedWorkers(tenant.getId()); if (numAssignedWorkers > 0) { throw new IllegalStateException("Tenant " + name + " still has " + numAssignedWorkers + " workers. " + "Cannot delete it until workers are set to 0."); } tenantStore.deleteTenantByName(name); for (QueueGroup queueGroup : queueService.getAllQueueGroups().values()) { queueGroup.removeAll(tenant.getId()); } } finally { tenantLock.release(); } } /** * Delete the given provisioner, queueing a job to reassign its workers to different provisioners. * * @param provisionerId Id of the provisioner to delete * @throws IOException */ public void deleteProvisioner(String provisionerId) throws IOException { tenantLock.acquire(); try { Provisioner provisioner = provisionerStore.getProvisioner(provisionerId); if (provisioner == null) { return; } deleteProvisioner(provisioner); } finally { tenantLock.release(); } } /** * Handle the heartbeat of a provisioner, updating the last heartbeat time of the provisioner and updating the number * of live workers running on the provisioner for each tenant it is responsible for. * * @param provisionerId Id of the provisioner that sent the heartbeat * @param heartbeat The heartbeat containing live worker information * @throws IOException if there was an exception persisting the data * @throws MissingEntityException if there is no provisioner for the given id */ public void handleHeartbeat(String provisionerId, ProvisionerHeartbeat heartbeat) throws IOException, MissingEntityException { // no lock required here. Simply getting a provisioner and writing worker usage. Would only expect one provisioner // to be calling this at a time, and even if it is calling it concurrently for some reason, only the usage can // change and for that its ok for one of them to win. Provisioner provisioner = provisionerStore.getProvisioner(provisionerId); if (provisioner == null) { throw new MissingEntityException("Provisioner " + provisionerId + " not found."); } if (!provisioner.getUsage().equals(heartbeat.getUsage())) { provisioner.setUsage(heartbeat.getUsage()); provisionerStore.writeProvisioner(provisioner); } provisionerStore.setHeartbeat(provisionerId, System.currentTimeMillis()); } /** * Write a provisioner, and queue jobs to rebalance workers for all tenants in the system. * * @param provisioner Provisioner to write * @throws IOException */ public void writeProvisioner(Provisioner provisioner) throws IOException { tenantLock.acquire(); try { provisionerStore.writeProvisioner(provisioner); // rebalance tenants every time a provisioner registers itself for (Tenant tenant : tenantStore.getAllTenants()) { balanceQueue.add(new Element(tenant.getId())); } } finally { tenantLock.release(); } } /** * Rebalance workers for the tenant across the provisioners. * * @param tenantId Id of the tenant whose workers need to be rebalanced * @throws CapacityException if there is not enough capacity to rebalance tenant workers * @throws IOException if there was an exception persisting the worker rebalance */ public void rebalanceTenantWorkers(String tenantId) throws IOException, CapacityException { // lock across all tenants to protect against conflicts in setting worker counts for different tenants across // different provisioners tenantLock.acquire(); try { Tenant tenant = tenantStore.getTenantByID(tenantId); if (tenant == null) { return; } int diff = tenant.getSpecification().getWorkers() - provisionerStore.getNumAssignedWorkers(tenantId); if (diff < 0) { Account tenantAdmin = new Account(Constants.ADMIN_USER, tenantId); ResourceCollection liveResources = resourceService.getLiveResources(tenantAdmin); // too many workers assigned, remove some. int toRemove = 0 - diff; LOG.debug("Removing {} workers from tenant {}", toRemove, tenantId); removeWorkers(tenantId, toRemove, liveResources); } else if (diff > 0) { Account tenantAdmin = new Account(Constants.ADMIN_USER, tenantId); ResourceCollection liveResources = resourceService.getLiveResources(tenantAdmin); // not enough workers assigned, assign some more. LOG.debug("Adding {} workers to tenant {}", diff, tenantId); addWorkers(tenantId, diff, liveResources); } } finally { tenantLock.release(); } } /** * Get a snapshot of what plugin resources are slated to be active on the provisioners that are running workers * for the given account, and push those resources to the provisioners. * * @param account Account to sync * @throws IOException */ public void syncResources(Account account) throws IOException { // this will mean that a sync from one tenant will block a sync from another, but we need this because when // workers are being re-balanced, the live resource collection is sent to the provisioners. We don't want a // scenario where the live collection is read for rebalancing, a sync is called, and the sync and rebalance // fight over what resource versions should be live on the provisioners, resulting in inconsistent state. // Since syncs are uncommon, this should be ok... tenantLock.acquire(); try { ResourceCollection resources = resourceService.getResourcesToSync(account); // TODO: failures will cause inconsistencies between metadata state and provisioner state. // We can add an ability to block tasks for a given tenant from going out here, then make the calls to the // provisioners and update the metadata store, then unblock tasks for the tenant. That way if the sync fails, // tasks are not being taken so there is no ambiguity on what code is running. Maybe add a blockTakes call // to the queue group interface. // update tenant provisioners syncProvisionerResources(account.getTenantId(), resources); // update metadata store resourceService.syncResourceMeta(account, resources); } finally { tenantLock.release(); } } private void syncProvisionerResources(String tenantId, ResourceCollection resourceCollection) throws IOException { for (Provisioner provisioner : provisionerStore.getTenantProvisioners(tenantId)) { if (!provisionerRequestService.putTenant(provisioner, tenantId, resourceCollection)) { LOG.error("Could not write resource metadata for tenant {} to provisioner {}. " + "The provisioner appears broken, deleting it and rebalancing its tenant workers", tenantId, provisioner.getId()); deleteProvisioner(provisioner); } } } /** * Delete and reassign workers for provisioners that have not sent a heartbeat since the given timestamp in * milliseconds. * * @param timeoutTs Timestamp in milliseconds to use as a cut off for deleting provisioners. * @throws IOException */ public void timeoutProvisioners(long timeoutTs) throws IOException { tenantLock.acquire(); try { Set<String> affectedTenants = Sets.newHashSet(); for (Provisioner provisioner : provisionerStore.getTimedOutProvisioners(timeoutTs)) { String provisionerId = provisioner.getId(); LOG.error("provisioner {} has not sent a heartbeat in over {} seconds, deleting it...", provisionerId, provisionerTimeoutSecs); provisionerStore.deleteProvisioner(provisioner.getId()); affectedTenants.addAll(provisioner.getAssignedTenants()); } for (String affectedTenant : affectedTenants) { balanceQueue.add(new Element(affectedTenant)); } } finally { tenantLock.release(); } } public void bootstrapTenant(String tenantId) throws IOException, IllegalAccessException { Account account = new Account(Constants.ADMIN_USER, tenantId); LOG.debug("Bootstrapping entities"); entityStoreService.copyEntities(Account.SUPERADMIN, account); // bootstrap plugin resources LOG.debug("Bootstrapping plugin resources"); resourceService.bootstrapResources(account); LOG.debug("Syncing plugin resources"); syncResources(account); } // TODO: abstract out to support different types of balancing policies // Currently a greedy approach, just remove from first available. private void removeWorkers(String tenantId, int numToRemove, ResourceCollection resources) throws IOException { // go through each provisioner, removing workers for the tenant until we've removed enough. for (Provisioner provisioner : provisionerStore.getTenantProvisioners(tenantId)) { int numRemoved = provisioner.tryRemoveTenantAssignments(tenantId, numToRemove); if (numRemoved > 0) { provisionerStore.writeProvisioner(provisioner); LOG.debug("Requesting provisioner {} to set workers to {} for tenant {} (removing {})", provisioner.getId(), provisioner.getAssignedWorkers(tenantId), tenantId, numRemoved); if (provisionerRequestService.putTenant(provisioner, tenantId, resources)) { numToRemove -= numRemoved; } else { // request failed with retries. something is wrong with the provisioner, delete it and rebalance its workers // TODO: what if this fails? LOG.error("Could not set workers for tenant {} to provisioner {}. " + "The provisioner appears broken, deleting it and rebalancing its tenant workers", tenantId, provisioner.getId()); deleteProvisioner(provisioner); } } } } // TODO: abstract out to support different types of balancing policies // Currently a greedy approach, just add to first available. private void addWorkers(String tenantId, int numToAdd, ResourceCollection resources) throws CapacityException, IOException { for (Provisioner provisioner : provisionerStore.getProvisionersWithFreeCapacity()) { if (numToAdd <= 0) { break; } int numAdded = provisioner.tryAddTenantAssignments(tenantId, numToAdd); if (numAdded > 0) { provisionerStore.writeProvisioner(provisioner); LOG.debug("Requesting provisioner {} to set workers to {} for tenant {} (adding {})", provisioner.getId(), provisioner.getAssignedWorkers(tenantId), tenantId, numAdded); if (provisionerRequestService.putTenant(provisioner, tenantId, resources)) { numToAdd -= numAdded; } else { // request failed with retries. something is wrong with the provisioner, delete it and rebalance its workers. // Rebalancing will be queued, but will not be triggered until after this method finishes due to the // lock that is held. // TODO: what if this fails due to db failure or something of that sort? // should be ok as long as the tenant balance task is in the queue and retried. LOG.error("Could not set workers for tenant {} to provisioner {}. " + "The provisioner appears broken, deleting it and rebalancing its tenant workers", tenantId, provisioner.getId()); deleteProvisioner(provisioner); } } } if (numToAdd > 0) { throw new CapacityException("Unable to add all " + numToAdd + " workers to tenant " + tenantId + " without exceeding worker capacity."); } } /** * Create a new Provisioner object where the tenant ids have been replaced with tenant names for external * consumption. * * @param provisioner Internal provisioner that uses tenant ids * @return New Provisioner where the tenant ids have been replaced with tenant names * @throws IOException */ private Provisioner createExternalProvisioner(Provisioner provisioner) throws IOException { if (provisioner == null) { return null; } Map<String, Integer> nameUsage = Maps.newHashMap(); for (Map.Entry<String, Integer> entry : provisioner.getUsage().entrySet()) { nameUsage.put(tenantIdToName(entry.getKey()), entry.getValue()); } Map<String, Integer> nameAssignments = Maps.newHashMap(); for (String tenantId : provisioner.getAssignedTenants()) { nameAssignments.put(tenantIdToName(tenantId), provisioner.getAssignedWorkers(tenantId)); } return new Provisioner(provisioner.getId(), provisioner.getHost(), provisioner.getPort(), provisioner.getCapacityTotal(), nameUsage, nameAssignments); } // id to name mapping is cached, so this mapping should not be expensive private String tenantIdToName(String id) throws IOException { String tenantName = tenantStore.getNameForId(id); if (tenantName == null) { LOG.warn("Could not map tenant id {} to a name, will use the id."); tenantName = id; } return tenantName; } private void deleteProvisioner(Provisioner provisioner) throws IOException { for (String tenant : provisioner.getAssignedTenants()) { balanceQueue.add(new Element(tenant)); } provisionerStore.deleteProvisioner(provisioner.getId()); } private void checkCapacity(int diff) throws IOException, CapacityException { if (diff > provisionerStore.getFreeCapacity()) { throw new CapacityException("Not enough capacity."); } } }
/* * 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.cloudwatch.model; import java.io.Serializable; /** * <p> * The <code>StatisticSet</code> data type describes the * <code>StatisticValues</code> component of MetricDatum, and represents * a set of statistics that describes a specific metric. * </p> */ public class StatisticSet implements Serializable, Cloneable { /** * The number of samples used for the statistic set. */ private Double sampleCount; /** * The sum of values for the sample set. */ private Double sum; /** * The minimum value of the sample set. */ private Double minimum; /** * The maximum value of the sample set. */ private Double maximum; /** * The number of samples used for the statistic set. * * @return The number of samples used for the statistic set. */ public Double getSampleCount() { return sampleCount; } /** * The number of samples used for the statistic set. * * @param sampleCount The number of samples used for the statistic set. */ public void setSampleCount(Double sampleCount) { this.sampleCount = sampleCount; } /** * The number of samples used for the statistic set. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param sampleCount The number of samples used for the statistic set. * * @return A reference to this updated object so that method calls can be chained * together. */ public StatisticSet withSampleCount(Double sampleCount) { this.sampleCount = sampleCount; return this; } /** * The sum of values for the sample set. * * @return The sum of values for the sample set. */ public Double getSum() { return sum; } /** * The sum of values for the sample set. * * @param sum The sum of values for the sample set. */ public void setSum(Double sum) { this.sum = sum; } /** * The sum of values for the sample set. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param sum The sum of values for the sample set. * * @return A reference to this updated object so that method calls can be chained * together. */ public StatisticSet withSum(Double sum) { this.sum = sum; return this; } /** * The minimum value of the sample set. * * @return The minimum value of the sample set. */ public Double getMinimum() { return minimum; } /** * The minimum value of the sample set. * * @param minimum The minimum value of the sample set. */ public void setMinimum(Double minimum) { this.minimum = minimum; } /** * The minimum value of the sample set. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param minimum The minimum value of the sample set. * * @return A reference to this updated object so that method calls can be chained * together. */ public StatisticSet withMinimum(Double minimum) { this.minimum = minimum; return this; } /** * The maximum value of the sample set. * * @return The maximum value of the sample set. */ public Double getMaximum() { return maximum; } /** * The maximum value of the sample set. * * @param maximum The maximum value of the sample set. */ public void setMaximum(Double maximum) { this.maximum = maximum; } /** * The maximum value of the sample set. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param maximum The maximum value of the sample set. * * @return A reference to this updated object so that method calls can be chained * together. */ public StatisticSet withMaximum(Double maximum) { this.maximum = maximum; 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 (getSampleCount() != null) sb.append("SampleCount: " + getSampleCount() + ","); if (getSum() != null) sb.append("Sum: " + getSum() + ","); if (getMinimum() != null) sb.append("Minimum: " + getMinimum() + ","); if (getMaximum() != null) sb.append("Maximum: " + getMaximum() ); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getSampleCount() == null) ? 0 : getSampleCount().hashCode()); hashCode = prime * hashCode + ((getSum() == null) ? 0 : getSum().hashCode()); hashCode = prime * hashCode + ((getMinimum() == null) ? 0 : getMinimum().hashCode()); hashCode = prime * hashCode + ((getMaximum() == null) ? 0 : getMaximum().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof StatisticSet == false) return false; StatisticSet other = (StatisticSet)obj; if (other.getSampleCount() == null ^ this.getSampleCount() == null) return false; if (other.getSampleCount() != null && other.getSampleCount().equals(this.getSampleCount()) == false) return false; if (other.getSum() == null ^ this.getSum() == null) return false; if (other.getSum() != null && other.getSum().equals(this.getSum()) == false) return false; if (other.getMinimum() == null ^ this.getMinimum() == null) return false; if (other.getMinimum() != null && other.getMinimum().equals(this.getMinimum()) == false) return false; if (other.getMaximum() == null ^ this.getMaximum() == null) return false; if (other.getMaximum() != null && other.getMaximum().equals(this.getMaximum()) == false) return false; return true; } @Override public StatisticSet clone() { try { return (StatisticSet) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.jps.model.serialization.library; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.JDOMUtil; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.model.JpsDummyElement; import org.jetbrains.jps.model.JpsElement; import org.jetbrains.jps.model.JpsElementFactory; import org.jetbrains.jps.model.java.JpsJavaExtensionService; import org.jetbrains.jps.model.java.JpsJavaSdkType; import org.jetbrains.jps.model.java.JpsJavaSdkTypeWrapper; import org.jetbrains.jps.model.library.JpsLibrary; import org.jetbrains.jps.model.library.JpsLibraryCollection; import org.jetbrains.jps.model.library.JpsLibraryRoot; import org.jetbrains.jps.model.library.JpsOrderRootType; import org.jetbrains.jps.model.library.sdk.JpsSdk; import org.jetbrains.jps.model.library.sdk.JpsSdkReference; import org.jetbrains.jps.model.library.sdk.JpsSdkType; import org.jetbrains.jps.model.module.JpsSdkReferencesTable; import org.jetbrains.jps.model.serialization.JpsModelSerializerExtension; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * @author nik */ public class JpsSdkTableSerializer { private static final Logger LOG = Logger.getInstance(JpsSdkTableSerializer.class); private static final JpsLibraryRootTypeSerializer[] PREDEFINED_ROOT_TYPE_SERIALIZERS = { new JpsLibraryRootTypeSerializer("classPath", JpsOrderRootType.COMPILED, true), new JpsLibraryRootTypeSerializer("sourcePath", JpsOrderRootType.SOURCES, true) }; private static final JpsSdkPropertiesSerializer<JpsDummyElement> JPS_JAVA_SDK_PROPERTIES_LOADER = new JpsSdkPropertiesSerializer<JpsDummyElement>("JavaSDK", JpsJavaSdkType.INSTANCE) { @NotNull @Override public JpsDummyElement loadProperties(Element propertiesElement) { return JpsElementFactory.getInstance().createDummyElement(); } @Override public void saveProperties(@NotNull JpsDummyElement properties, @NotNull Element element) { } }; private static final String JDK_TAG = "jdk"; private static final String NAME_TAG = "name"; private static final String TYPE_TAG = "type"; private static final String TYPE_ATTRIBUTE = "type"; private static final String ROOTS_TAG = "roots"; private static final String ROOT_TAG = "root"; private static final String VERSION_TAG = "version"; private static final String HOME_PATH_TAG = "homePath"; private static final String VALUE_ATTRIBUTE = "value"; private static final String COMPOSITE_TYPE = "composite"; private static final String SIMPLE_TYPE = "simple"; private static final String URL_ATTRIBUTE = "url"; private static final String ADDITIONAL_TAG = "additional"; public static void loadSdks(@Nullable Element sdkListElement, JpsLibraryCollection result) { for (Element sdkElement : JDOMUtil.getChildren(sdkListElement, JDK_TAG)) { result.addLibrary(loadSdk(sdkElement)); } } public static void saveSdks(JpsLibraryCollection libraryCollection, Element sdkListElement) { for (JpsLibrary library : libraryCollection.getLibraries()) { JpsElement properties = library.getProperties(); if (properties instanceof JpsSdk<?>) { Element sdkTag = new Element(JDK_TAG); saveSdk((JpsSdk<?>)properties, sdkTag); sdkListElement.addContent(sdkTag); } } } private static JpsLibrary loadSdk(Element sdkElement) { String name = getAttributeValue(sdkElement, NAME_TAG); String typeId = getAttributeValue(sdkElement, TYPE_TAG); LOG.debug("Loading " + typeId + " SDK '" + name + "'"); JpsSdkPropertiesSerializer<?> serializer = getSdkPropertiesSerializer(typeId); final JpsLibrary library = createSdk(name, serializer, sdkElement); final Element roots = sdkElement.getChild(ROOTS_TAG); for (Element rootTypeElement : JDOMUtil.getChildren(roots)) { JpsLibraryRootTypeSerializer rootTypeSerializer = getRootTypeSerializer(rootTypeElement.getName()); if (rootTypeSerializer != null) { for (Element rootElement : rootTypeElement.getChildren()) { loadRoots(rootElement, library, rootTypeSerializer.getType()); } } else { LOG.info("root type serializer not found for " + rootTypeElement.getName()); } } if (LOG.isDebugEnabled()) { List<File> files = library.getFiles(JpsOrderRootType.COMPILED); LOG.debug(name + " SDK classpath (" + files.size() + " roots):"); for (File file : files) { LOG.debug(" " + file.getAbsolutePath()); } } return library; } private static <P extends JpsElement> void saveSdk(final JpsSdk<P> sdk, Element sdkTag) { JpsLibrary library = sdk.getParent(); sdkTag.setAttribute("version", "2"); setAttributeValue(sdkTag, NAME_TAG, library.getName()); JpsSdkPropertiesSerializer<P> serializer = getSdkPropertiesSerializer(sdk.getSdkType()); setAttributeValue(sdkTag, TYPE_TAG, serializer.getTypeId()); String versionString = sdk.getVersionString(); if (versionString != null) { setAttributeValue(sdkTag, VERSION_TAG, versionString); } setAttributeValue(sdkTag, HOME_PATH_TAG, sdk.getHomePath()); Element rootsTag = new Element(ROOTS_TAG); for (JpsLibraryRootTypeSerializer rootTypeSerializer : getRootTypeSerializers()) { Element rootTypeTag = new Element(rootTypeSerializer.getTypeId()); Element compositeTag = new Element(ROOT_TAG); compositeTag.setAttribute(TYPE_ATTRIBUTE, COMPOSITE_TYPE); List<JpsLibraryRoot> roots = library.getRoots(rootTypeSerializer.getType()); for (JpsLibraryRoot root : roots) { compositeTag.addContent(new Element(ROOT_TAG).setAttribute(TYPE_ATTRIBUTE, SIMPLE_TYPE).setAttribute(URL_ATTRIBUTE, root.getUrl())); } rootTypeTag.addContent(compositeTag); rootsTag.addContent(rootTypeTag); } sdkTag.addContent(rootsTag); Element additionalTag = new Element(ADDITIONAL_TAG); serializer.saveProperties(sdk.getSdkProperties(), additionalTag); sdkTag.addContent(additionalTag); } private static void setAttributeValue(Element tag, final String tagName, final String value) { tag.addContent(new Element(tagName).setAttribute(VALUE_ATTRIBUTE, value)); } private static void loadRoots(Element rootElement, JpsLibrary library, JpsOrderRootType rootType) { final String type = rootElement.getAttributeValue(TYPE_ATTRIBUTE); if (type.equals(COMPOSITE_TYPE)) { for (Element element : rootElement.getChildren()) { loadRoots(element, library, rootType); } } else if (type.equals(SIMPLE_TYPE)) { library.addRoot(rootElement.getAttributeValue(URL_ATTRIBUTE), rootType); } } @Nullable private static JpsLibraryRootTypeSerializer getRootTypeSerializer(String typeId) { for (JpsLibraryRootTypeSerializer serializer : PREDEFINED_ROOT_TYPE_SERIALIZERS) { if (serializer.getTypeId().equals(typeId)) { return serializer; } } for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) { for (JpsLibraryRootTypeSerializer serializer : extension.getSdkRootTypeSerializers()) { if (serializer.getTypeId().equals(typeId)) { return serializer; } } } return null; } private static List<JpsLibraryRootTypeSerializer> getRootTypeSerializers() { List<JpsLibraryRootTypeSerializer> serializers = new ArrayList<JpsLibraryRootTypeSerializer>(Arrays.asList(PREDEFINED_ROOT_TYPE_SERIALIZERS)); for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) { serializers.addAll(extension.getSdkRootTypeSerializers()); } Collections.sort(serializers); return serializers; } private static <P extends JpsElement> JpsLibrary createSdk(String name, JpsSdkPropertiesSerializer<P> loader, Element sdkElement) { String versionString = getAttributeValue(sdkElement, VERSION_TAG); String homePath = getAttributeValue(sdkElement, HOME_PATH_TAG); Element propertiesTag = sdkElement.getChild(ADDITIONAL_TAG); P properties = loader.loadProperties(propertiesTag); return JpsElementFactory.getInstance().createSdk(name, homePath, versionString, loader.getType(), properties); } public static JpsSdkPropertiesSerializer<?> getSdkPropertiesSerializer(@Nullable String typeId) { for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) { for (JpsSdkPropertiesSerializer<?> loader : extension.getSdkPropertiesSerializers()) { if (loader.getTypeId().equals(typeId)) { return loader; } } } return JPS_JAVA_SDK_PROPERTIES_LOADER; } public static <P extends JpsElement> JpsSdkPropertiesSerializer<P> getSdkPropertiesSerializer(JpsSdkType<P> type) { for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) { for (JpsSdkPropertiesSerializer<?> loader : extension.getSdkPropertiesSerializers()) { if (loader.getType().equals(type)) { //noinspection unchecked return (JpsSdkPropertiesSerializer<P>)loader; } } } //noinspection unchecked return (JpsSdkPropertiesSerializer<P>)JPS_JAVA_SDK_PROPERTIES_LOADER; } @Nullable private static String getAttributeValue(Element element, String childName) { final Element child = element.getChild(childName); return child != null ? child.getAttributeValue(VALUE_ATTRIBUTE) : null; } public static JpsSdkType<?> getSdkType(@Nullable String typeId) { return getSdkPropertiesSerializer(typeId).getType(); } public static JpsSdkPropertiesSerializer<?> getLoader(JpsSdkType<?> type) { for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) { for (JpsSdkPropertiesSerializer<?> loader : extension.getSdkPropertiesSerializers()) { if (loader.getType().equals(type)) { return loader; } } } return JPS_JAVA_SDK_PROPERTIES_LOADER; } public static <P extends JpsElement> void setSdkReference(final JpsSdkReferencesTable table, String sdkName, JpsSdkType<P> sdkType) { JpsSdkReference<P> reference = JpsElementFactory.getInstance().createSdkReference(sdkName, sdkType); table.setSdkReference(sdkType, reference); if (sdkType instanceof JpsJavaSdkTypeWrapper) { JpsSdkReference<P> wrapperRef = JpsElementFactory.getInstance().createSdkReference(sdkName, sdkType); table.setSdkReference(JpsJavaSdkType.INSTANCE, JpsJavaExtensionService.getInstance().createWrappedJavaSdkReference((JpsJavaSdkTypeWrapper)sdkType, wrapperRef)); } } }
/** * Copyright 2010 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.ipc; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hbase.ipc.VersionedProtocol; import org.apache.hadoop.metrics.MetricsContext; import org.apache.hadoop.metrics.MetricsRecord; import org.apache.hadoop.metrics.MetricsUtil; import org.apache.hadoop.metrics.Updater; import org.apache.hadoop.metrics.util.*; import java.lang.reflect.Method; /** * * This class is for maintaining the various RPC statistics * and publishing them through the metrics interfaces. * This also registers the JMX MBean for RPC. * <p> * This class has a number of metrics variables that are publicly accessible; * these variables (objects) have methods to update their values; * for example: * <p> {@link #rpcQueueTime}.inc(time) * */ public class HBaseRpcMetrics implements Updater { public static final String NAME_DELIM = "$"; private final MetricsRegistry registry = new MetricsRegistry(); private final MetricsRecord metricsRecord; private static Log LOG = LogFactory.getLog(HBaseRpcMetrics.class); private final HBaseRPCStatistics rpcStatistics; public HBaseRpcMetrics(String hostName, String port) { MetricsContext context = MetricsUtil.getContext("rpc"); metricsRecord = MetricsUtil.createRecord(context, "metrics"); metricsRecord.setTag("port", port); LOG.info("Initializing RPC Metrics with hostName=" + hostName + ", port=" + port); context.registerUpdater(this); initMethods(HMasterInterface.class); initMethods(HMasterRegionInterface.class); initMethods(HRegionInterface.class); rpcStatistics = new HBaseRPCStatistics(this.registry, hostName, port); } /** * The metrics variables are public: * - they can be set directly by calling their set/inc methods * -they can also be read directly - e.g. JMX does this. */ public final MetricsTimeVaryingLong receivedBytes = new MetricsTimeVaryingLong("ReceivedBytes", registry); public final MetricsTimeVaryingLong sentBytes = new MetricsTimeVaryingLong("SentBytes", registry); public final MetricsTimeVaryingRate rpcQueueTime = new MetricsTimeVaryingRate("RpcQueueTime", registry); public MetricsTimeVaryingRate rpcProcessingTime = new MetricsTimeVaryingRate("RpcProcessingTime", registry); public final MetricsIntValue numOpenConnections = new MetricsIntValue("NumOpenConnections", registry); public final MetricsIntValue callQueueLen = new MetricsIntValue("callQueueLen", registry); public final MetricsIntValue priorityCallQueueLen = new MetricsIntValue("priorityCallQueueLen", registry); public final MetricsTimeVaryingInt authenticationFailures = new MetricsTimeVaryingInt("rpcAuthenticationFailures", registry); public final MetricsTimeVaryingInt authenticationSuccesses = new MetricsTimeVaryingInt("rpcAuthenticationSuccesses", registry); public final MetricsTimeVaryingInt authorizationFailures = new MetricsTimeVaryingInt("rpcAuthorizationFailures", registry); public final MetricsTimeVaryingInt authorizationSuccesses = new MetricsTimeVaryingInt("rpcAuthorizationSuccesses", registry); public MetricsTimeVaryingRate rpcSlowResponseTime = new MetricsTimeVaryingRate("RpcSlowResponse", registry); private void initMethods(Class<? extends VersionedProtocol> protocol) { for (Method m : protocol.getDeclaredMethods()) { if (get(m.getName()) == null) create(m.getName()); } } private MetricsTimeVaryingRate get(String key) { return (MetricsTimeVaryingRate) registry.get(key); } private MetricsTimeVaryingRate create(String key) { return new MetricsTimeVaryingRate(key, this.registry); } public void inc(String name, int amt) { MetricsTimeVaryingRate m = get(name); if (m == null) { LOG.warn("Got inc() request for method that doesnt exist: " + name); return; // ignore methods that dont exist. } m.inc(amt); } /** * Generate metrics entries for all the methods defined in the list of * interfaces. A {@link MetricsTimeVaryingRate} counter will be created for * each {@code Class.getMethods().getName()} entry. * @param ifaces Define metrics for all methods in the given classes */ public void createMetrics(Class<?>[] ifaces) { createMetrics(ifaces, false); } /** * Generate metrics entries for all the methods defined in the list of * interfaces. A {@link MetricsTimeVaryingRate} counter will be created for * each {@code Class.getMethods().getName()} entry. * * <p> * If {@code prefixWithClass} is {@code true}, each metric will be named as * {@code [Class.getSimpleName()].[Method.getName()]}. Otherwise each metric * will just be named according to the method -- {@code Method.getName()}. * </p> * @param ifaces Define metrics for all methods in the given classes * @param prefixWithClass If {@code true}, each metric will be named as * "classname.method" */ public void createMetrics(Class<?>[] ifaces, boolean prefixWithClass) { createMetrics(ifaces, prefixWithClass, null); } /** * Generate metrics entries for all the methods defined in the list of * interfaces. A {@link MetricsTimeVaryingRate} counter will be created for * each {@code Class.getMethods().getName()} entry. * * <p> * If {@code prefixWithClass} is {@code true}, each metric will be named as * {@code [Class.getSimpleName()].[Method.getName()]}. Otherwise each metric * will just be named according to the method -- {@code Method.getName()}. * </p> * * <p> * Additionally, if {@code suffixes} is defined, additional metrics will be * created for each method named as the original metric concatenated with * the suffix. * </p> * @param ifaces Define metrics for all methods in the given classes * @param prefixWithClass If {@code true}, each metric will be named as * "classname.method" * @param suffixes If not null, each method will get additional metrics ending * in each of the suffixes. */ public void createMetrics(Class<?>[] ifaces, boolean prefixWithClass, String [] suffixes) { for (Class<?> iface : ifaces) { Method[] methods = iface.getMethods(); for (Method method : methods) { String attrName = prefixWithClass ? getMetricName(iface, method.getName()) : method.getName(); if (get(attrName) == null) create(attrName); if (suffixes != null) { // create metrics for each requested suffix for (String s : suffixes) { String metricName = attrName + s; if (get(metricName) == null) create(metricName); } } } } } public static String getMetricName(Class<?> c, String method) { return c.getSimpleName() + NAME_DELIM + method; } /** * Push the metrics to the monitoring subsystem on doUpdate() call. */ public void doUpdates(final MetricsContext context) { // Both getMetricsList() and pushMetric() are thread-safe for (MetricsBase m : registry.getMetricsList()) { m.pushMetric(metricsRecord); } metricsRecord.update(); } public void shutdown() { if (rpcStatistics != null) rpcStatistics.shutdown(); } }
/* * The MIT License (MIT) * * Copyright (c) 2007-2015 Broad Institute * * 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. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.ui.panel; //~--- non-JDK imports -------------------------------------------------------- import org.apache.log4j.Logger; import org.broad.igv.feature.FeatureUtils; import org.broad.igv.feature.exome.ExomeBlock; import org.broad.igv.feature.exome.ExomeReferenceFrame; import org.broad.igv.track.RenderContext; import org.broad.igv.track.RenderContextImpl; import org.broad.igv.track.Track; import org.broad.igv.track.TrackGroup; import org.broad.igv.ui.IGV; import org.broad.igv.ui.UIConstants; import java.awt.*; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; public class DataPanelPainter { private static Logger log = Logger.getLogger(DataPanelPainter.class); private static Color exomeBorderColor = new Color(190, 190, 255); public synchronized void paint(Collection<TrackGroup> groups, RenderContext context, int width, Color background, Rectangle visibleRect) { Graphics2D graphics2D = null; try { graphics2D = (Graphics2D) context.getGraphics().create(); graphics2D.setBackground(background); graphics2D.clearRect(visibleRect.x, visibleRect.y, visibleRect.width, visibleRect.height); graphics2D.setColor(Color.BLACK); ReferenceFrame frame = context.getReferenceFrame(); resetLastY(groups); if (frame.isExomeMode()) { ExomeReferenceFrame exomeFrame = (ExomeReferenceFrame) frame; int blockGap = exomeFrame.getBlockGap(); Rectangle panelClip = visibleRect; List<ExomeBlock> blocks = exomeFrame.getBlocks(); int idx = exomeFrame.getFirstBlockIdx(); RenderContext exomeContext = new RenderContextImpl(null, null, frame, visibleRect); preloadTracks(groups, exomeContext, visibleRect); ExomeBlock b; int lastPStart = 0; int pStart; int pEnd; int exomeOrigin = ((ExomeReferenceFrame) frame).getExomeOrigin(); int visibleBlockCount = 0; do { b = blocks.get(idx); pStart = (int) ((b.getExomeStart() - exomeOrigin) / frame.getScale()) + visibleBlockCount * blockGap; pEnd = (int) ((b.getExomeEnd() - exomeOrigin) / frame.getScale()) + visibleBlockCount * blockGap; if (pEnd > lastPStart) { lastPStart = pStart; // Don't draw over previously drawn region -- can happen when zoomed out. if (pEnd == pStart) pEnd++; b.setScreenBounds(pStart, pEnd); Rectangle rect = new Rectangle(pStart, visibleRect.y, pEnd - pStart, visibleRect.height); Graphics2D exomeGraphics = (Graphics2D) context.getGraphics().create(); //Shape clip = exomeGraphics.getClip(); // Color c = ColorUtilities.randomColor(idx); // exomeGraphics.setColor(c); // exomeGraphics.fill(rect); // exomeGraphics.setColor(Color.black); // GraphicUtils.drawCenteredText(String.valueOf(idx), rect, exomeGraphics); exomeGraphics.setClip(rect.intersection(panelClip)); exomeGraphics.translate(pStart, 0); ReferenceFrame tmpFrame = new ReferenceFrame(frame); tmpFrame.setOrigin(b.getGenomeStart()); RenderContext tmpContext = new RenderContextImpl(null, exomeGraphics, tmpFrame, rect); paintFrame(groups, tmpContext, rect.width, rect); tmpContext.dispose(); exomeGraphics.dispose(); visibleBlockCount++; } idx++; } while ((pStart < visibleRect.x + visibleRect.width) && idx < blocks.size()); // Draw lines @ gene boundaries String chr = frame.getChrName(); List<ExomeReferenceFrame.Gene> genes = exomeFrame.getGenes(chr); idx = FeatureUtils.getIndexBefore(frame.getOrigin(), genes); exomeOrigin = ((ExomeReferenceFrame) frame).getExomeOrigin(); int top = visibleRect.y; int lastXDrawn = -1; Graphics2D lineGraphics = context.getGraphic2DForColor(exomeBorderColor); do { ExomeReferenceFrame.Gene gene = genes.get(idx); double exomeStart = exomeFrame.genomeToExomePosition(gene.getStart()); double exomeEnd = exomeFrame.genomeToExomePosition(gene.getEnd()); pStart = (int) ((exomeStart - exomeOrigin) / frame.getScale()) + visibleBlockCount * blockGap; pEnd = (int) ((exomeEnd - exomeOrigin) / frame.getScale()) + visibleBlockCount * blockGap; if (pStart != lastXDrawn) { lineGraphics.drawLine(pStart, top, pStart, top + visibleRect.height); } lineGraphics.drawLine(pEnd, top, pEnd, top + visibleRect.height); lastXDrawn = pEnd; idx++; } while ((pStart < visibleRect.x + visibleRect.width) && idx < genes.size()); } else { paintFrame(groups, context, width, visibleRect); } } finally { graphics2D.dispose(); } } private void paintFrame(Collection<TrackGroup> groups, RenderContext context, int width, Rectangle visibleRect) { int trackX = 0; int trackY = 0; for (Iterator<TrackGroup> groupIter = groups.iterator(); groupIter.hasNext(); ) { TrackGroup group = groupIter.next(); if (visibleRect != null && (trackY > visibleRect.y + visibleRect.height)) { break; } if (group.isVisible()) { if (groups.size() > 1) { final Graphics2D greyGraphics = context.getGraphic2DForColor(UIConstants.LIGHT_GREY); greyGraphics.fillRect(0, trackY + 1, width, UIConstants.groupGap - 1); trackY += UIConstants.groupGap; } // Draw a line just above group. if (group.isDrawBorder()) { Graphics2D graphics2D = context.getGraphic2DForColor(Color.black); graphics2D.drawLine(0, trackY - 1, width, trackY - 1); } List<Track> trackList = group.getTracks(); synchronized (trackList) { for (Track track : trackList) { if (track == null) continue; int trackHeight = track.getHeight(); if (visibleRect != null) { if (trackY > visibleRect.y + visibleRect.height) { break; } else if (trackY + trackHeight < visibleRect.y) { if (track.isVisible()) { trackY += trackHeight; } continue; } } if (track.isVisible()) { Rectangle rect = new Rectangle(trackX, trackY, width, trackHeight); draw(track, rect, context); trackY += trackHeight; } } } // Draw a line just below group. if (group.isDrawBorder()) { Graphics2D graphics2D = context.getGraphic2DForColor(Color.black); graphics2D.drawLine(0, trackY, width, trackY); } } } } private void resetLastY(Collection<TrackGroup> groups) { for(TrackGroup group: groups){ for(Track track: group.getTracks()){ track.resetLastY(); } } } final private void draw(Track track, Rectangle rect, RenderContext context) { track.render(context, rect); // Get overlays List<Track> overlayTracks = IGV.getInstance().getOverlayTracks(track); if (overlayTracks != null) { for (Track overlayTrack : overlayTracks) { // Don't overlay on self if (overlayTrack != track) { overlayTrack.overlay(context, rect); } } } } private List<Track> getVisibleTracks(final Collection<TrackGroup> groups) { // Find the tracks that need loaded, we go to this bother to avoid loading tracks scrolled out of view final List<Track> visibleTracks = new ArrayList<Track>(); for (Iterator<TrackGroup> groupIter = groups.iterator(); groupIter.hasNext(); ) { TrackGroup group = groupIter.next(); List<Track> trackList = new ArrayList(group.getTracks()); for (Track track : trackList) { if (track != null && track.isVisible()) { visibleTracks.add(track); } } } return visibleTracks; } private void preloadTracks(final Collection<TrackGroup> groups, final RenderContext context, final Rectangle visibleRect) { final List<Track> visibleTracks = getVisibleTracks(groups); for (Track track : visibleTracks) { RenderContextImpl newContext = new RenderContextImpl(null, null, context.getReferenceFrame(), visibleRect); track.load(newContext); } } }
package prefuse.data.query; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import javax.swing.JComponent; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import prefuse.data.expression.ColumnExpression; import prefuse.data.expression.Literal; import prefuse.data.expression.RangePredicate; import prefuse.data.tuple.TupleSet; import prefuse.util.DataLib; import prefuse.util.TypeLib; import prefuse.util.ui.JRangeSlider; import prefuse.util.ui.ValuedRangeModel; /** * DynamicQueryBinding supporting queries based on a range of included * data values. * @author <a href="http://jheer.org">jeffrey heer</a> */ public class RangeQueryBinding extends DynamicQueryBinding { private Class m_type; private Listener m_lstnr; private ValuedRangeModel m_model; private boolean m_ordinal; private static FocusListener s_sliderAdj; /** * Create a new RangeQueryBinding over the given set and data field. * @param ts the TupleSet to query * @param field the data field (Table column) to query */ public RangeQueryBinding(TupleSet ts, String field) { this(ts, field, false); } /** * Create a new RangeQueryBinding over the given set and data field, * optionally forcing an ordinal treatment of data. * @param ts the TupleSet to query * @param field the data field (Table column) to query * @param forceOrdinal if true, forces all items in the range to be * treated in strictly ordinal fashion. That means that if the data * is numerical, the quantitative nature of the data will be ignored * and only the relative ordering of the numbers will matter. In terms * of mechanism, this entails that a {@link ObjectRangeModel} and not * a {@link NumberRangeModel} will be used to represent the data. If * the argument is false, default inference mechanisms will be used. */ public RangeQueryBinding(TupleSet ts, String field, boolean forceOrdinal) { super(ts, field); m_type = DataLib.inferType(ts, field); m_ordinal = forceOrdinal; m_lstnr = new Listener(); initPredicate(); initModel(); } private void initPredicate() { // determine minimum and maximum values Object min = DataLib.min(m_tuples, m_field).get(m_field); Object max = DataLib.max(m_tuples, m_field).get(m_field); // set up predicate Literal left = Literal.getLiteral(min, m_type); Literal right = Literal.getLiteral(max, m_type); ColumnExpression ce = new ColumnExpression(m_field); RangePredicate rp = new RangePredicate(ce, left, right); setPredicate(rp); } public void initModel() { if ( m_model != null ) m_model.removeChangeListener(m_lstnr); // set up data / selection model ValuedRangeModel model = null; if ( TypeLib.isNumericType(m_type) && !m_ordinal ) { Number min = (Number)DataLib.min(m_tuples, m_field).get(m_field); Number max = (Number)DataLib.max(m_tuples, m_field).get(m_field); model = new NumberRangeModel(min, max, min, max); } else { model = new ObjectRangeModel( DataLib.ordinalArray(m_tuples, m_field)); } m_model = model; m_model.addChangeListener(m_lstnr); } /** * Return the ValuedRangeModel constructed by this dynamic query binding. * This model backs any user interface components generated by this * instance. * @return the ValuedRangeModel for this range query binding. */ public ValuedRangeModel getModel() { return m_model; } /** * Attempts to return the ValuedRangeModel for this binding as a * NumberRangeModel. If the range model is not an instance of * {@link NumberRangeModel}, a null value is returned. * @return the ValuedRangeModel for this binding as a * {@link NumberRangeModel}, or null if the range is not numerical. */ public NumberRangeModel getNumberModel() { return (m_model instanceof NumberRangeModel ? (NumberRangeModel)m_model : null); } /** * Attempts to return the ValuedRangeModel for this binding as an * ObjectRangeModel. If the range model is not an instance of * {@link ObjectRangeModel}, a null value is returned. * @return the ValuedRangeModel for this binding as an * {@link ObjectRangeModel}, or null if the range is numerical. */ public ObjectRangeModel getObjectModel() { return (m_model instanceof ObjectRangeModel ? (ObjectRangeModel)m_model : null); } // ------------------------------------------------------------------------ /** * Create a new horizontal range slider for interacting with the query. * @return a {@link prefuse.util.ui.JRangeSlider} bound to this dynamic * query. * @see prefuse.data.query.DynamicQueryBinding#createComponent() */ public JComponent createComponent() { return createHorizontalRangeSlider(); } /** * Create a new horizontal range slider for interacting with the query. * @return a {@link prefuse.util.ui.JRangeSlider} bound to this dynamic * query. */ public JRangeSlider createHorizontalRangeSlider() { return createRangeSlider(JRangeSlider.HORIZONTAL, JRangeSlider.LEFTRIGHT_TOPBOTTOM); } /** * Create a new vertical range slider for interacting with the query. * @return a {@link prefuse.util.ui.JRangeSlider} bound to this dynamic * query. */ public JRangeSlider createVerticalRangeSlider() { return createRangeSlider(JRangeSlider.VERTICAL, JRangeSlider.RIGHTLEFT_BOTTOMTOP); } /** * Create a new range slider for interacting with the query, using the * given orientation and direction. * @param orientation the orientation (horizontal or vertical) of the * slider (see {@link prefuse.util.ui.JRangeSlider}) * @param direction the direction (direction of data values) of the slider * (see {@link prefuse.util.ui.JRangeSlider}) * @return a {@link prefuse.util.ui.JRangeSlider} bound to this dynamic * query. */ public JRangeSlider createRangeSlider(int orientation, int direction) { return new JRangeSlider(m_model, orientation, direction); } /** * Create a new regular (non-range) slider for interacting with the query. * This allows you to select a single value at a time. * @return a {@link javax.swing.JSlider} bound to this dynamic query. */ public JSlider createSlider() { JSlider slider = new JSlider(m_model); slider.addFocusListener(getSliderAdjuster()); return slider; } private synchronized static FocusListener getSliderAdjuster() { if ( s_sliderAdj == null ) s_sliderAdj = new SliderAdjuster(); return s_sliderAdj; } // ------------------------------------------------------------------------ private static class SliderAdjuster implements FocusListener { public void focusGained(FocusEvent e) { ((JSlider)e.getSource()).setExtent(0); } public void focusLost(FocusEvent e) { // do nothing } } // end of inner class SliderAdjuster private class Listener implements ChangeListener { public void stateChanged(ChangeEvent e) { ValuedRangeModel model = (ValuedRangeModel)e.getSource(); Object lo = model.getLowValue(); Object hi = model.getHighValue(); RangePredicate rp = (RangePredicate)m_query; rp.setLeftExpression(Literal.getLiteral(lo, m_type)); rp.setRightExpression(Literal.getLiteral(hi, m_type)); } } // end of inner class Listener } // end of class RangeQueryBinding
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class Client { public static String RegisterUser(String username,String password,String mail,String phone)throws Exception { String url = "https://clouddeduplication.000webhostapp.com/register.php"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "username="+username+"&password="+password+"&mail="+mail+"&phone="+phone; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); if(response.toString().contains("Success")) { return "Successfully Registered"; } else if(response.toString().contains("User")) { return "username already exists. Please try different username"; } else { return "Error in registering. Please try after some time"; } } public static String Login(String username,String password)throws Exception { String url = "https://clouddeduplication.000webhostapp.com/login.php"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "username="+username+"&password="+password; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result if(!(response.toString().contains("Error"))) { return response.toString(); } else { return "Invalid Credentials"; } } public static String LogActivity(String username,String log)throws Exception { String url = "https://clouddeduplication.000webhostapp.com/logdetails.php"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "username="+username+"&log="+log; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); if(!(response.toString().contains("Error"))) { return response.toString(); } else { return "Error in logging data. This activity will not be logged."; } } public static String ShowLog(String username)throws Exception { String url = "https://clouddeduplication.000webhostapp.com/showlog.php"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "username="+username; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); if(!(response.toString().contains("Error"))) { return response.toString(); } else { return "unable to fetch log"; } } public static void ChangePassword(String username,String password)throws Exception { String url = "https://clouddeduplication.000webhostapp.com/changepassword.php"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); System.out.println(username); String urlParameters = "username="+username+"&password="+password; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); if(response.toString().contains("Success")) { System.out.println("Successfully Password Changed"); } else { System.out.println("Error in Changing Password"); } } public static String GetServerDetails()throws Exception { String url = "https://clouddeduplication.000webhostapp.com/getdetails.php"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); con.setDoOutput(true); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } public static String ForgotPassword(String username,String secquest)throws Exception { secquest=secquest.toLowerCase(); String url = "https://clouddeduplication.000webhostapp.com/forgotpassword.php"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "username="+username+"&secquest="+secquest; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); if(!((response.toString()).contains("Error"))) { return response.toString(); } else { return "Invalid Credentials"; } } public static void main(String args[])throws Exception { if(args[0].equals("login")) { String response=Login(args[1],args[2]); String responses=LogActivity(args[1],"Login Attempt"); if(!response.contains("Invalid Credentials")) { System.out.print(response); } else System.out.print("0"); } else if(args[0].equals("signup")) { String response=RegisterUser(args[1],args[2],args[3],args[4]); if(response.contains("Successfully Registered")) { String responses=LogActivity(args[1],"Created Account"); System.out.print(response); } else if(response.contains("username already exists")) { System.out.print(response); } else System.out.print("0"); } else if(args[0].equals("forgot")) { String responses=LogActivity(args[1],"Attempting Forgot Password"); String response=ForgotPassword(args[1],args[2]); System.out.print(response); } else if(args[0].equals("logactivity")) { String response=LogActivity(args[1],args[2]); System.out.print(response); } else if(args[0].equals("showlog")) { String response=ShowLog(args[1]); System.out.print(response); } } }
/* * Copyright 2000-2013 JetBrains s.r.o. * Copyright 2014-2015 AS3Boyan * Copyright 2014-2014 Elias Ku * * 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.plugins.haxe.model.type; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class SpecificTypeReference { final protected PsiElement context; public SpecificTypeReference(@NotNull PsiElement context) { this.context = context; } static public SpecificTypeReference createArray(@NotNull ResultHolder elementType) { return SpecificHaxeClassReference .withGenerics(new HaxeClassReference("Array", elementType.getElementContext()), new ResultHolder[]{elementType}, null); } public SpecificTypeReference withRangeConstraint(HaxeRange range) { return this; } static public SpecificHaxeClassReference getVoid(@NotNull PsiElement context) { return primitive("Void", context); } static public SpecificHaxeClassReference getBool(@NotNull PsiElement context) { return primitive("Bool", context); } static public SpecificHaxeClassReference getInt(@NotNull PsiElement context) { return primitive("Int", context); } static public SpecificHaxeClassReference getClass(@NotNull PsiElement context) { return primitive("Class", context); } static public SpecificHaxeClassReference getInt(@NotNull PsiElement context, int value) { return primitive("Int", context, value); } static public SpecificHaxeClassReference getDynamic(@NotNull PsiElement context) { return primitive("Dynamic", context); } static public SpecificHaxeClassReference getUnknown(@NotNull PsiElement context) { return primitive("Unknown", context); } static public SpecificHaxeClassReference getInvalid(@NotNull PsiElement context) { return primitive("@@Invalid", context); } static public SpecificHaxeClassReference getIterator(SpecificHaxeClassReference type) { return SpecificHaxeClassReference.withGenerics(new HaxeClassReference("Iterator", type.getElementContext()), new ResultHolder[]{type.createHolder()}); } static public SpecificHaxeClassReference primitive(String name, @NotNull PsiElement context) { return SpecificHaxeClassReference.withoutGenerics(new HaxeClassReference(name, context)); } static public SpecificHaxeClassReference primitive(String name, @NotNull PsiElement context, Object constant) { return SpecificHaxeClassReference.withoutGenerics(new HaxeClassReference(name, context), constant); } final public boolean isUnknown() { return this.toStringWithoutConstant().equals("Unknown"); } final public boolean isDynamic() { return this.toStringWithoutConstant().equals("Dynamic"); } final public boolean isInvalid() { return this.toStringWithoutConstant().equals("@@Invalid"); } final public boolean isVoid() { return this.toStringWithoutConstant().equals("Void"); } final public boolean isInt() { return this.toStringWithoutConstant().equals("Int"); } final public boolean isNumeric() { return isInt() || isFloat(); } final public boolean isBool() { return this.toStringWithoutConstant().equals("Bool"); } final public boolean isFloat() { return this.toStringWithoutConstant().equals("Float"); } final public boolean isString() { return this.toStringWithoutConstant().equals("String"); } final public boolean isArray() { if (this instanceof SpecificHaxeClassReference) { final SpecificHaxeClassReference reference = (SpecificHaxeClassReference)this; return reference.clazz.getName().equals("Array"); } return false; } final public boolean isClass() { if (this instanceof SpecificHaxeClassReference) { final SpecificHaxeClassReference reference = (SpecificHaxeClassReference)this; return reference.clazz.getName().equals("Class"); } return false; } final public ResultHolder getArrayElementType() { if (isArray()) { final ResultHolder[] specifics = ((SpecificHaxeClassReference)this).specifics; if (specifics.length >= 1) return specifics[0]; } return getUnknown(context).createHolder(); } abstract public SpecificTypeReference withConstantValue(Object constantValue); //public void mutateConstantValue(Object constantValue) { // //} final public SpecificTypeReference withoutConstantValue() { return withConstantValue(null); } public boolean isConstant() { return this.getConstant() != null; } public HaxeRange getRangeConstraint() { return null; } public Object getConstant() { return null; } final public boolean getConstantAsBool() { return HaxeTypeUtils.getBoolValue(getConstant()); } final public double getConstantAsDouble() { return HaxeTypeUtils.getDoubleValue(getConstant()); } final public int getConstantAsInt() { return HaxeTypeUtils.getIntValue(getConstant()); } @NotNull final public PsiElement getElementContext() { return context; } abstract public String toString(); abstract public String toStringWithoutConstant(); public String toStringWithConstant() { return toString(); } @Nullable final public ResultHolder access(String name, HaxeExpressionEvaluatorContext context) { return access(name, context, false); } @Nullable public ResultHolder access(String name, HaxeExpressionEvaluatorContext context, boolean isStatic) { return null; } final public boolean canAssign(SpecificTypeReference type2) { return HaxeTypeCompatible.canAssignToFrom(this, type2); } final public boolean canAssign(ResultHolder type2) { return HaxeTypeCompatible.canAssignToFrom(this, type2); } public ResultHolder createHolder() { return new ResultHolder(this); } @NotNull final public ResultHolder getIterableElementType(@NotNull HaxeExpressionEvaluatorContext context) { final ResultHolder iterator = this.access("iterator", context); if (iterator != null) { final SpecificFunctionReference iteratorFunc = iterator.getFunctionType(); if (iteratorFunc != null) { final ResultHolder iteratorReturnType = iteratorFunc.getReturnType(); return iteratorReturnType.getType().getIterableElementType(context); } } final ResultHolder iteratorNextType = access("next", context); if (iteratorNextType != null) { final SpecificFunctionReference type = iteratorNextType.getFunctionType(); if (type != null) { final ResultHolder returnType = type.getReturnType(); return returnType; } } return getDynamic(context.root).createHolder(); } @NotNull final public boolean isIterable(@NotNull HaxeExpressionEvaluatorContext context) { if (this.access("iterator", context) != null) return true; if ((this.access("next", context) != null) && (this.access("hasNext", context) != null)) return true; return false; } public void applyGenerics(HaxeGenericResolver generic) { } public abstract SpecificTypeReference duplicate(); }
/** * 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.wss4j.stax.test; import java.util.HashMap; import java.util.Map; import org.apache.wss4j.common.ConfigurationConstants; import org.apache.wss4j.stax.ext.WSSConstants; import org.apache.wss4j.stax.ext.WSSConstants.UsernameTokenPasswordType; import org.apache.wss4j.stax.ext.WSSSecurityProperties; import org.apache.wss4j.stax.securityToken.WSSecurityTokenConstants; import org.apache.wss4j.stax.setup.ConfigurationConverter; import org.apache.wss4j.stax.setup.WSSec; import org.apache.wss4j.stax.test.saml.SAMLCallbackHandlerImpl; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Some tests for the ConfigurationConverter utility */ public class ConfigurationConverterTest extends AbstractTestBase { @Test public void testUsernameTokenConfiguration() throws Exception { Map<String, Object> config = new HashMap<>(); config.put(ConfigurationConstants.ACTION, ConfigurationConstants.USERNAME_TOKEN); config.put(ConfigurationConstants.USER, "testuser"); config.put(ConfigurationConstants.PW_CALLBACK_CLASS, "org.apache.wss4j.stax.test.CallbackHandlerImpl"); config.put(ConfigurationConstants.PASSWORD_TYPE, "PasswordText"); config.put(ConfigurationConstants.ADD_USERNAMETOKEN_NONCE, "true"); config.put(ConfigurationConstants.ADD_USERNAMETOKEN_CREATED, "false"); WSSSecurityProperties properties = ConfigurationConverter.convert(config); assertEquals(properties.getTokenUser(), "testuser"); assertEquals(properties.getActions().size(), 1); assertEquals(properties.getActions().get(0), WSSConstants.USERNAMETOKEN); assertTrue(properties.getCallbackHandler() instanceof CallbackHandlerImpl); assertEquals(properties.getUsernameTokenPasswordType(), UsernameTokenPasswordType.PASSWORD_TEXT); assertTrue(properties.isAddUsernameTokenNonce()); assertFalse(properties.isAddUsernameTokenCreated()); WSSec.validateAndApplyDefaultsToOutboundSecurityProperties(properties); } @Test public void testOutboundSignatureConfiguration() throws Exception { Map<String, Object> config = new HashMap<>(); config.put(ConfigurationConstants.ACTION, ConfigurationConstants.SIGNATURE); config.put(ConfigurationConstants.USER, "transmitter"); config.put(ConfigurationConstants.PW_CALLBACK_REF, new CallbackHandlerImpl()); String sigAlgo = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; config.put(ConfigurationConstants.SIG_ALGO, sigAlgo); config.put(ConfigurationConstants.SIG_KEY_ID, "Thumbprint"); config.put(ConfigurationConstants.ADD_INCLUSIVE_PREFIXES, "false"); config.put(ConfigurationConstants.SIG_PROP_FILE, "transmitter-crypto.properties"); config.put(ConfigurationConstants.SIGNATURE_PARTS, "{}{http://schemas.xmlsoap.org/soap/envelope/}Body;"); WSSSecurityProperties properties = ConfigurationConverter.convert(config); assertEquals(properties.getSignatureUser(), "transmitter"); assertEquals(properties.getActions().size(), 1); assertEquals(properties.getActions().get(0), WSSConstants.SIGNATURE); assertTrue(properties.getCallbackHandler() instanceof CallbackHandlerImpl); assertEquals(properties.getSignatureAlgorithm(), sigAlgo); assertEquals(properties.getSignatureKeyIdentifiers().size(), 1); assertEquals(properties.getSignatureKeyIdentifiers().get(0), WSSecurityTokenConstants.KEYIDENTIFIER_THUMBPRINT_IDENTIFIER); assertFalse(properties.isAddExcC14NInclusivePrefixes()); assertNotNull(properties.getSignatureCrypto()); assertNotNull(properties.getSignatureSecureParts()); assertEquals(properties.getSignatureSecureParts().size(), 1); assertEquals(properties.getSignatureSecureParts().get(0).getName().getLocalPart(), "Body"); assertEquals(properties.getSignatureSecureParts().get(0).getName().getNamespaceURI(), "http://schemas.xmlsoap.org/soap/envelope/"); WSSec.validateAndApplyDefaultsToOutboundSecurityProperties(properties); } @Test public void testInboundSignatureConfiguration() throws Exception { Map<String, Object> config = new HashMap<>(); config.put(ConfigurationConstants.ACTION, ConfigurationConstants.SIGNATURE); config.put(ConfigurationConstants.PW_CALLBACK_REF, new CallbackHandlerImpl()); config.put(ConfigurationConstants.ADD_INCLUSIVE_PREFIXES, "false"); config.put(ConfigurationConstants.SIG_VER_PROP_FILE, "transmitter-crypto.properties"); config.put(ConfigurationConstants.IS_BSP_COMPLIANT, "false"); config.put(ConfigurationConstants.ENABLE_REVOCATION, "true"); WSSSecurityProperties properties = ConfigurationConverter.convert(config); assertEquals(properties.getActions().size(), 1); assertEquals(properties.getActions().get(0), WSSConstants.SIGNATURE); assertTrue(properties.getCallbackHandler() instanceof CallbackHandlerImpl); assertTrue(properties.isDisableBSPEnforcement()); assertTrue(properties.isEnableRevocation()); assertNotNull(properties.getSignatureVerificationCrypto()); WSSec.validateAndApplyDefaultsToInboundSecurityProperties(properties); } @Test public void testOutboundEncryptionConfiguration() throws Exception { Map<String, Object> config = new HashMap<>(); config.put(ConfigurationConstants.ACTION, ConfigurationConstants.ENCRYPT); config.put(ConfigurationConstants.USER, "transmitter"); config.put(ConfigurationConstants.PW_CALLBACK_REF, new CallbackHandlerImpl()); config.put(ConfigurationConstants.ENC_KEY_TRANSPORT, WSSConstants.NS_XENC_RSA15); config.put(ConfigurationConstants.ENC_KEY_ID, "EncryptedKeySHA1"); config.put(ConfigurationConstants.ENC_PROP_FILE, "receiver-crypto.properties"); config.put(ConfigurationConstants.ENCRYPTION_PARTS, "{}{http://schemas.xmlsoap.org/soap/envelope/}Body;"); WSSSecurityProperties properties = ConfigurationConverter.convert(config); assertEquals(properties.getEncryptionUser(), "transmitter"); assertEquals(properties.getActions().size(), 1); assertEquals(properties.getActions().get(0), WSSConstants.ENCRYPT); assertTrue(properties.getCallbackHandler() instanceof CallbackHandlerImpl); assertEquals(properties.getEncryptionKeyTransportAlgorithm(), WSSConstants.NS_XENC_RSA15); assertEquals(properties.getEncryptionKeyIdentifier(), WSSecurityTokenConstants.KEYIDENTIFIER_ENCRYPTED_KEY_SHA1_IDENTIFIER); assertNotNull(properties.getEncryptionCrypto()); assertNotNull(properties.getEncryptionSecureParts()); assertEquals(properties.getEncryptionSecureParts().size(), 1); assertEquals(properties.getEncryptionSecureParts().get(0).getName().getLocalPart(), "Body"); assertEquals(properties.getEncryptionSecureParts().get(0).getName().getNamespaceURI(), "http://schemas.xmlsoap.org/soap/envelope/"); WSSec.validateAndApplyDefaultsToOutboundSecurityProperties(properties); } @Test public void testInboundEncryptionConfiguration() throws Exception { Map<String, Object> config = new HashMap<>(); config.put(ConfigurationConstants.ACTION, ConfigurationConstants.ENCRYPT); config.put(ConfigurationConstants.PW_CALLBACK_REF, new CallbackHandlerImpl()); config.put(ConfigurationConstants.DEC_PROP_FILE, "receiver-crypto.properties"); config.put(ConfigurationConstants.ALLOW_RSA15_KEY_TRANSPORT_ALGORITHM, "true"); WSSSecurityProperties properties = ConfigurationConverter.convert(config); assertEquals(properties.getActions().size(), 1); assertEquals(properties.getActions().get(0), WSSConstants.ENCRYPT); assertTrue(properties.getCallbackHandler() instanceof CallbackHandlerImpl); assertNotNull(properties.getDecryptionCrypto()); WSSec.validateAndApplyDefaultsToInboundSecurityProperties(properties); } @Test public void testSAMLConfiguration() throws Exception { Map<String, Object> config = new HashMap<>(); config.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_UNSIGNED); config.put(ConfigurationConstants.SAML_CALLBACK_REF, new SAMLCallbackHandlerImpl()); WSSSecurityProperties properties = ConfigurationConverter.convert(config); assertEquals(properties.getActions().size(), 1); assertEquals(properties.getActions().get(0), WSSConstants.SAML_TOKEN_UNSIGNED); assertTrue(properties.getSamlCallbackHandler() instanceof SAMLCallbackHandlerImpl); WSSec.validateAndApplyDefaultsToOutboundSecurityProperties(properties); } @Test public void testTimestampConfiguration() throws Exception { // Outbound Map<String, Object> config = new HashMap<>(); config.put(ConfigurationConstants.ACTION, ConfigurationConstants.TIMESTAMP); config.put(ConfigurationConstants.TTL_TIMESTAMP, "180"); WSSSecurityProperties properties = ConfigurationConverter.convert(config); assertEquals(properties.getActions().size(), 1); assertEquals(properties.getActions().get(0), WSSConstants.TIMESTAMP); assertEquals(properties.getTimestampTTL(), Integer.valueOf(180)); WSSec.validateAndApplyDefaultsToOutboundSecurityProperties(properties); // Inbound config.put(ConfigurationConstants.TTL_FUTURE_TIMESTAMP, "120"); config.put(ConfigurationConstants.TIMESTAMP_STRICT, "false"); properties = ConfigurationConverter.convert(config); assertEquals(properties.getTimeStampFutureTTL(), Integer.valueOf(120)); assertFalse(properties.isStrictTimestampCheck()); WSSec.validateAndApplyDefaultsToInboundSecurityProperties(properties); } }
/* * Copyright 2014 The Netty Project * * The Netty Project licenses this file to you under the Apache License, version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at: * * 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.netty.handler.codec.http2; import static io.netty.handler.codec.http2.Http2CodecUtil.CONNECTION_STREAM_ID; import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_PRIORITY_WEIGHT; import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_WINDOW_SIZE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelConfig; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http2.Http2FrameWriter.Configuration; import io.netty.util.concurrent.EventExecutor; import junit.framework.AssertionFailedError; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.util.concurrent.atomic.AtomicInteger; /** * Tests for {@link DefaultHttp2RemoteFlowController}. */ public class DefaultHttp2RemoteFlowControllerTest { private static final int STREAM_A = 1; private static final int STREAM_B = 3; private static final int STREAM_C = 5; private static final int STREAM_D = 7; private DefaultHttp2RemoteFlowController controller; @Mock private ByteBuf buffer; @Mock private Http2FrameSizePolicy frameWriterSizePolicy; @Mock private Configuration frameWriterConfiguration; @Mock private ChannelHandlerContext ctx; @Mock private Channel channel; @Mock private ChannelConfig config; @Mock private EventExecutor executor; @Mock private ChannelPromise promise; @Mock private Http2RemoteFlowController.Listener listener; private DefaultHttp2Connection connection; @Before public void setup() throws Http2Exception { MockitoAnnotations.initMocks(this); when(ctx.newPromise()).thenReturn(promise); when(ctx.flush()).thenThrow(new AssertionFailedError("forbidden")); setChannelWritability(true); when(channel.config()).thenReturn(config); when(executor.inEventLoop()).thenReturn(true); initConnectionAndController(); resetCtx(); // This is intentionally left out of initConnectionAndController so it can be tested below. controller.channelHandlerContext(ctx); assertWritabilityChanged(1, true); reset(listener); } private void initConnectionAndController() throws Http2Exception { connection = new DefaultHttp2Connection(false); controller = new DefaultHttp2RemoteFlowController(connection, listener); connection.remote().flowController(controller); connection.local().createStream(STREAM_A, false); connection.local().createStream(STREAM_B, false); Http2Stream streamC = connection.local().createStream(STREAM_C, false); Http2Stream streamD = connection.local().createStream(STREAM_D, false); streamC.setPriority(STREAM_A, DEFAULT_PRIORITY_WEIGHT, false); streamD.setPriority(STREAM_A, DEFAULT_PRIORITY_WEIGHT, false); } @Test public void initialWindowSizeShouldOnlyChangeStreams() throws Http2Exception { controller.initialWindowSize(0); assertEquals(DEFAULT_WINDOW_SIZE, window(CONNECTION_STREAM_ID)); assertEquals(0, window(STREAM_A)); assertEquals(0, window(STREAM_B)); assertEquals(0, window(STREAM_C)); assertEquals(0, window(STREAM_D)); assertWritabilityChanged(1, false); } @Test public void windowUpdateShouldChangeConnectionWindow() throws Http2Exception { incrementWindowSize(CONNECTION_STREAM_ID, 100); assertEquals(DEFAULT_WINDOW_SIZE + 100, window(CONNECTION_STREAM_ID)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_A)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_B)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_C)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_D)); verifyZeroInteractions(listener); } @Test public void windowUpdateShouldChangeStreamWindow() throws Http2Exception { incrementWindowSize(STREAM_A, 100); assertEquals(DEFAULT_WINDOW_SIZE, window(CONNECTION_STREAM_ID)); assertEquals(DEFAULT_WINDOW_SIZE + 100, window(STREAM_A)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_B)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_C)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_D)); verifyZeroInteractions(listener); } @Test public void payloadSmallerThanWindowShouldBeWrittenImmediately() throws Http2Exception { FakeFlowControlled data = new FakeFlowControlled(5); sendData(STREAM_A, data); data.assertNotWritten(); verifyZeroInteractions(listener); controller.writePendingBytes(); data.assertFullyWritten(); verify(listener, times(1)).streamWritten(stream(STREAM_A), 5); verifyZeroInteractions(listener); } @Test public void emptyPayloadShouldBeWrittenImmediately() throws Http2Exception { FakeFlowControlled data = new FakeFlowControlled(0); sendData(STREAM_A, data); data.assertNotWritten(); controller.writePendingBytes(); data.assertFullyWritten(); verify(listener, times(1)).streamWritten(stream(STREAM_A), 0); verifyZeroInteractions(listener); } @Test public void unflushedPayloadsShouldBeDroppedOnCancel() throws Http2Exception { FakeFlowControlled data = new FakeFlowControlled(5); sendData(STREAM_A, data); connection.stream(STREAM_A).close(); controller.writePendingBytes(); data.assertNotWritten(); controller.writePendingBytes(); data.assertNotWritten(); verify(listener, times(1)).writabilityChanged(stream(STREAM_A)); } @Test public void payloadsShouldMerge() throws Http2Exception { controller.initialWindowSize(15); FakeFlowControlled data1 = new FakeFlowControlled(5, true); FakeFlowControlled data2 = new FakeFlowControlled(10, true); sendData(STREAM_A, data1); sendData(STREAM_A, data2); data1.assertNotWritten(); data1.assertNotWritten(); data2.assertMerged(); controller.writePendingBytes(); data1.assertFullyWritten(); data2.assertNotWritten(); verify(listener, times(1)).streamWritten(stream(STREAM_A), 15); verify(listener, times(1)).writabilityChanged(stream(STREAM_A)); assertFalse(controller.isWritable(stream(STREAM_A))); } @Test public void stalledStreamShouldQueuePayloads() throws Http2Exception { controller.initialWindowSize(0); verify(listener, times(1)).writabilityChanged(stream(STREAM_A)); assertFalse(controller.isWritable(stream(STREAM_A))); reset(listener); FakeFlowControlled data = new FakeFlowControlled(15); FakeFlowControlled moreData = new FakeFlowControlled(0); sendData(STREAM_A, data); controller.writePendingBytes(); data.assertNotWritten(); sendData(STREAM_A, moreData); controller.writePendingBytes(); moreData.assertNotWritten(); verifyZeroInteractions(listener); } @Test public void queuedPayloadsReceiveErrorOnStreamClose() throws Http2Exception { controller.initialWindowSize(0); verify(listener, times(1)).writabilityChanged(stream(STREAM_A)); assertFalse(controller.isWritable(stream(STREAM_A))); reset(listener); FakeFlowControlled data = new FakeFlowControlled(15); FakeFlowControlled moreData = new FakeFlowControlled(0); sendData(STREAM_A, data); controller.writePendingBytes(); data.assertNotWritten(); sendData(STREAM_A, moreData); controller.writePendingBytes(); moreData.assertNotWritten(); connection.stream(STREAM_A).close(); data.assertError(); moreData.assertError(); verifyZeroInteractions(listener); } @Test public void payloadLargerThanWindowShouldWritePartial() throws Http2Exception { controller.initialWindowSize(5); verify(listener, never()).writabilityChanged(stream(STREAM_A)); assertTrue(controller.isWritable(stream(STREAM_A))); reset(listener); final FakeFlowControlled data = new FakeFlowControlled(10); sendData(STREAM_A, data); controller.writePendingBytes(); // Verify that a partial frame of 5 remains to be sent data.assertPartiallyWritten(5); verify(listener, times(1)).streamWritten(stream(STREAM_A), 5); verify(listener, times(1)).writabilityChanged(stream(STREAM_A)); assertFalse(controller.isWritable(stream(STREAM_A))); verifyNoMoreInteractions(listener); } @Test public void windowUpdateAndFlushShouldTriggerWrite() throws Http2Exception { controller.initialWindowSize(10); verify(listener, never()).writabilityChanged(stream(STREAM_A)); assertTrue(controller.isWritable(stream(STREAM_A))); FakeFlowControlled data = new FakeFlowControlled(20); FakeFlowControlled moreData = new FakeFlowControlled(10); sendData(STREAM_A, data); sendData(STREAM_A, moreData); controller.writePendingBytes(); data.assertPartiallyWritten(10); moreData.assertNotWritten(); verify(listener, times(1)).streamWritten(stream(STREAM_A), 10); verify(listener, times(1)).writabilityChanged(stream(STREAM_A)); assertFalse(controller.isWritable(stream(STREAM_A))); reset(listener); resetCtx(); // Update the window and verify that the rest of data and some of moreData are written incrementWindowSize(STREAM_A, 15); verify(listener, never()).writabilityChanged(stream(STREAM_A)); assertFalse(controller.isWritable(stream(STREAM_A))); reset(listener); controller.writePendingBytes(); data.assertFullyWritten(); moreData.assertPartiallyWritten(5); verify(listener, times(1)).streamWritten(stream(STREAM_A), 15); verify(listener, never()).writabilityChanged(stream(STREAM_A)); assertFalse(controller.isWritable(stream(STREAM_A))); assertEquals(DEFAULT_WINDOW_SIZE - 25, window(CONNECTION_STREAM_ID)); assertEquals(0, window(STREAM_A)); assertEquals(10, window(STREAM_B)); assertEquals(10, window(STREAM_C)); assertEquals(10, window(STREAM_D)); } @Test public void initialWindowUpdateShouldSendPayload() throws Http2Exception { incrementWindowSize(CONNECTION_STREAM_ID, -window(CONNECTION_STREAM_ID) + 10); assertWritabilityChanged(0, true); reset(listener); controller.initialWindowSize(0); assertWritabilityChanged(1, false); reset(listener); FakeFlowControlled data = new FakeFlowControlled(10); sendData(STREAM_A, data); controller.writePendingBytes(); data.assertNotWritten(); // Verify that the entire frame was sent. controller.initialWindowSize(10); data.assertFullyWritten(); verify(listener, times(1)).streamWritten(stream(STREAM_A), 10); assertWritabilityChanged(0, false); } @Test public void successiveSendsShouldNotInteract() throws Http2Exception { // Collapse the connection window to force queueing. incrementWindowSize(CONNECTION_STREAM_ID, -window(CONNECTION_STREAM_ID)); assertEquals(0, window(CONNECTION_STREAM_ID)); assertWritabilityChanged(1, false); reset(listener); FakeFlowControlled dataA = new FakeFlowControlled(10); // Queue data for stream A and allow most of it to be written. sendData(STREAM_A, dataA); controller.writePendingBytes(); dataA.assertNotWritten(); incrementWindowSize(CONNECTION_STREAM_ID, 8); assertWritabilityChanged(0, false); reset(listener); controller.writePendingBytes(); dataA.assertPartiallyWritten(8); assertEquals(65527, window(STREAM_A)); assertEquals(0, window(CONNECTION_STREAM_ID)); verify(listener, times(1)).streamWritten(stream(STREAM_A), 8); assertWritabilityChanged(0, false); reset(listener); // Queue data for stream B and allow the rest of A and all of B to be written. FakeFlowControlled dataB = new FakeFlowControlled(10); sendData(STREAM_B, dataB); controller.writePendingBytes(); dataB.assertNotWritten(); incrementWindowSize(CONNECTION_STREAM_ID, 12); assertWritabilityChanged(0, false); reset(listener); controller.writePendingBytes(); assertEquals(0, window(CONNECTION_STREAM_ID)); assertWritabilityChanged(0, false); // Verify the rest of A is written. dataA.assertFullyWritten(); assertEquals(65525, window(STREAM_A)); verify(listener, times(1)).streamWritten(stream(STREAM_A), 2); dataB.assertFullyWritten(); assertEquals(65525, window(STREAM_B)); verify(listener, times(1)).streamWritten(stream(STREAM_B), 10); verifyNoMoreInteractions(listener); } @Test public void negativeWindowShouldNotThrowException() throws Http2Exception { final int initWindow = 20; final int secondWindowSize = 10; controller.initialWindowSize(initWindow); assertWritabilityChanged(0, true); reset(listener); FakeFlowControlled data1 = new FakeFlowControlled(initWindow); FakeFlowControlled data2 = new FakeFlowControlled(5); // Deplete the stream A window to 0 sendData(STREAM_A, data1); controller.writePendingBytes(); data1.assertFullyWritten(); verify(listener, times(1)).streamWritten(stream(STREAM_A), 20); assertTrue(window(CONNECTION_STREAM_ID) > 0); verify(listener, times(1)).writabilityChanged(stream(STREAM_A)); verify(listener, never()).writabilityChanged(stream(STREAM_B)); verify(listener, never()).writabilityChanged(stream(STREAM_C)); verify(listener, never()).writabilityChanged(stream(STREAM_D)); assertFalse(controller.isWritable(stream(STREAM_A))); assertTrue(controller.isWritable(stream(STREAM_B))); assertTrue(controller.isWritable(stream(STREAM_C))); assertTrue(controller.isWritable(stream(STREAM_D))); reset(listener); // Make the window size for stream A negative controller.initialWindowSize(initWindow - secondWindowSize); assertEquals(-secondWindowSize, window(STREAM_A)); verify(listener, never()).writabilityChanged(stream(STREAM_A)); verify(listener, never()).writabilityChanged(stream(STREAM_B)); verify(listener, never()).writabilityChanged(stream(STREAM_C)); verify(listener, never()).writabilityChanged(stream(STREAM_D)); assertFalse(controller.isWritable(stream(STREAM_A))); assertTrue(controller.isWritable(stream(STREAM_B))); assertTrue(controller.isWritable(stream(STREAM_C))); assertTrue(controller.isWritable(stream(STREAM_D))); reset(listener); // Queue up a write. It should not be written now because the window is negative sendData(STREAM_A, data2); controller.writePendingBytes(); data2.assertNotWritten(); verify(listener, never()).writabilityChanged(stream(STREAM_A)); verify(listener, never()).writabilityChanged(stream(STREAM_B)); verify(listener, never()).writabilityChanged(stream(STREAM_C)); verify(listener, never()).writabilityChanged(stream(STREAM_D)); assertFalse(controller.isWritable(stream(STREAM_A))); assertTrue(controller.isWritable(stream(STREAM_B))); assertTrue(controller.isWritable(stream(STREAM_C))); assertTrue(controller.isWritable(stream(STREAM_D))); reset(listener); // Open the window size back up a bit (no send should happen) incrementWindowSize(STREAM_A, 5); controller.writePendingBytes(); assertEquals(-5, window(STREAM_A)); data2.assertNotWritten(); verify(listener, never()).writabilityChanged(stream(STREAM_A)); verify(listener, never()).writabilityChanged(stream(STREAM_B)); verify(listener, never()).writabilityChanged(stream(STREAM_C)); verify(listener, never()).writabilityChanged(stream(STREAM_D)); assertFalse(controller.isWritable(stream(STREAM_A))); assertTrue(controller.isWritable(stream(STREAM_B))); assertTrue(controller.isWritable(stream(STREAM_C))); assertTrue(controller.isWritable(stream(STREAM_D))); reset(listener); // Open the window size back up a bit (no send should happen) incrementWindowSize(STREAM_A, 5); controller.writePendingBytes(); assertEquals(0, window(STREAM_A)); data2.assertNotWritten(); verify(listener, never()).writabilityChanged(stream(STREAM_A)); verify(listener, never()).writabilityChanged(stream(STREAM_B)); verify(listener, never()).writabilityChanged(stream(STREAM_C)); verify(listener, never()).writabilityChanged(stream(STREAM_D)); assertFalse(controller.isWritable(stream(STREAM_A))); assertTrue(controller.isWritable(stream(STREAM_B))); assertTrue(controller.isWritable(stream(STREAM_C))); assertTrue(controller.isWritable(stream(STREAM_D))); reset(listener); // Open the window size back up and allow the write to happen incrementWindowSize(STREAM_A, 5); controller.writePendingBytes(); data2.assertFullyWritten(); verify(listener, never()).writabilityChanged(stream(STREAM_A)); verify(listener, never()).writabilityChanged(stream(STREAM_B)); verify(listener, never()).writabilityChanged(stream(STREAM_C)); verify(listener, never()).writabilityChanged(stream(STREAM_D)); assertFalse(controller.isWritable(stream(STREAM_A))); assertTrue(controller.isWritable(stream(STREAM_B))); assertTrue(controller.isWritable(stream(STREAM_C))); assertTrue(controller.isWritable(stream(STREAM_D))); } @Test public void initialWindowUpdateShouldSendEmptyFrame() throws Http2Exception { controller.initialWindowSize(0); assertWritabilityChanged(1, false); reset(listener); // First send a frame that will get buffered. FakeFlowControlled data = new FakeFlowControlled(10, false); sendData(STREAM_A, data); controller.writePendingBytes(); data.assertNotWritten(); // Now send an empty frame on the same stream and verify that it's also buffered. FakeFlowControlled data2 = new FakeFlowControlled(0, false); sendData(STREAM_A, data2); controller.writePendingBytes(); data2.assertNotWritten(); // Re-expand the window and verify that both frames were sent. controller.initialWindowSize(10); verify(listener, never()).writabilityChanged(stream(STREAM_A)); verify(listener, times(1)).writabilityChanged(stream(STREAM_B)); verify(listener, times(1)).writabilityChanged(stream(STREAM_C)); verify(listener, times(1)).writabilityChanged(stream(STREAM_D)); assertFalse(controller.isWritable(stream(STREAM_A))); assertTrue(controller.isWritable(stream(STREAM_B))); assertTrue(controller.isWritable(stream(STREAM_C))); assertTrue(controller.isWritable(stream(STREAM_D))); data.assertFullyWritten(); data2.assertFullyWritten(); verify(listener, times(1)).streamWritten(stream(STREAM_A), 10); } @Test public void initialWindowUpdateShouldSendPartialFrame() throws Http2Exception { controller.initialWindowSize(0); assertWritabilityChanged(1, false); reset(listener); FakeFlowControlled data = new FakeFlowControlled(10); sendData(STREAM_A, data); controller.writePendingBytes(); data.assertNotWritten(); // Verify that a partial frame of 5 was sent. controller.initialWindowSize(5); verify(listener, never()).writabilityChanged(stream(STREAM_A)); verify(listener, times(1)).writabilityChanged(stream(STREAM_B)); verify(listener, times(1)).writabilityChanged(stream(STREAM_C)); verify(listener, times(1)).writabilityChanged(stream(STREAM_D)); assertFalse(controller.isWritable(stream(STREAM_A))); assertTrue(controller.isWritable(stream(STREAM_B))); assertTrue(controller.isWritable(stream(STREAM_C))); assertTrue(controller.isWritable(stream(STREAM_D))); data.assertPartiallyWritten(5); verify(listener, times(1)).streamWritten(stream(STREAM_A), 5); } @Test public void connectionWindowUpdateShouldSendFrame() throws Http2Exception { // Set the connection window size to zero. exhaustStreamWindow(CONNECTION_STREAM_ID); assertWritabilityChanged(1, false); reset(listener); FakeFlowControlled data = new FakeFlowControlled(10); sendData(STREAM_A, data); controller.writePendingBytes(); data.assertNotWritten(); assertWritabilityChanged(0, false); reset(listener); // Verify that the entire frame was sent. incrementWindowSize(CONNECTION_STREAM_ID, 10); assertWritabilityChanged(0, false); reset(listener); data.assertNotWritten(); controller.writePendingBytes(); data.assertFullyWritten(); verify(listener, times(1)).streamWritten(stream(STREAM_A), 10); assertWritabilityChanged(0, false); assertEquals(0, window(CONNECTION_STREAM_ID)); assertEquals(DEFAULT_WINDOW_SIZE - 10, window(STREAM_A)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_B)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_C)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_D)); } @Test public void connectionWindowUpdateShouldSendPartialFrame() throws Http2Exception { // Set the connection window size to zero. exhaustStreamWindow(CONNECTION_STREAM_ID); assertWritabilityChanged(1, false); reset(listener); FakeFlowControlled data = new FakeFlowControlled(10); sendData(STREAM_A, data); controller.writePendingBytes(); data.assertNotWritten(); // Verify that a partial frame of 5 was sent. incrementWindowSize(CONNECTION_STREAM_ID, 5); data.assertNotWritten(); assertWritabilityChanged(0, false); reset(listener); controller.writePendingBytes(); data.assertPartiallyWritten(5); verify(listener, times(1)).streamWritten(stream(STREAM_A), 5); assertWritabilityChanged(0, false); assertEquals(0, window(CONNECTION_STREAM_ID)); assertEquals(DEFAULT_WINDOW_SIZE - 5, window(STREAM_A)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_B)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_C)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_D)); } @Test public void streamWindowUpdateShouldSendFrame() throws Http2Exception { // Set the stream window size to zero. exhaustStreamWindow(STREAM_A); verify(listener, times(1)).writabilityChanged(stream(STREAM_A)); verify(listener, never()).writabilityChanged(stream(STREAM_B)); verify(listener, never()).writabilityChanged(stream(STREAM_C)); verify(listener, never()).writabilityChanged(stream(STREAM_D)); assertFalse(controller.isWritable(stream(STREAM_A))); assertTrue(controller.isWritable(stream(STREAM_B))); assertTrue(controller.isWritable(stream(STREAM_C))); assertTrue(controller.isWritable(stream(STREAM_D))); reset(listener); FakeFlowControlled data = new FakeFlowControlled(10); sendData(STREAM_A, data); controller.writePendingBytes(); data.assertNotWritten(); // Verify that the entire frame was sent. incrementWindowSize(STREAM_A, 10); verify(listener, never()).writabilityChanged(stream(STREAM_A)); verify(listener, never()).writabilityChanged(stream(STREAM_B)); verify(listener, never()).writabilityChanged(stream(STREAM_C)); verify(listener, never()).writabilityChanged(stream(STREAM_D)); assertFalse(controller.isWritable(stream(STREAM_A))); assertTrue(controller.isWritable(stream(STREAM_B))); assertTrue(controller.isWritable(stream(STREAM_C))); assertTrue(controller.isWritable(stream(STREAM_D))); reset(listener); data.assertNotWritten(); controller.writePendingBytes(); data.assertFullyWritten(); verify(listener, times(1)).streamWritten(stream(STREAM_A), 10); verify(listener, never()).writabilityChanged(stream(STREAM_A)); verify(listener, never()).writabilityChanged(stream(STREAM_B)); verify(listener, never()).writabilityChanged(stream(STREAM_C)); verify(listener, never()).writabilityChanged(stream(STREAM_D)); assertFalse(controller.isWritable(stream(STREAM_A))); assertTrue(controller.isWritable(stream(STREAM_B))); assertTrue(controller.isWritable(stream(STREAM_C))); assertTrue(controller.isWritable(stream(STREAM_D))); assertEquals(DEFAULT_WINDOW_SIZE - 10, window(CONNECTION_STREAM_ID)); assertEquals(0, window(STREAM_A)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_B)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_C)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_D)); } @Test public void streamWindowUpdateShouldSendPartialFrame() throws Http2Exception { // Set the stream window size to zero. exhaustStreamWindow(STREAM_A); verify(listener, times(1)).writabilityChanged(stream(STREAM_A)); verify(listener, never()).writabilityChanged(stream(STREAM_B)); verify(listener, never()).writabilityChanged(stream(STREAM_C)); verify(listener, never()).writabilityChanged(stream(STREAM_D)); assertFalse(controller.isWritable(stream(STREAM_A))); assertTrue(controller.isWritable(stream(STREAM_B))); assertTrue(controller.isWritable(stream(STREAM_C))); assertTrue(controller.isWritable(stream(STREAM_D))); reset(listener); FakeFlowControlled data = new FakeFlowControlled(10); sendData(STREAM_A, data); controller.writePendingBytes(); data.assertNotWritten(); // Verify that a partial frame of 5 was sent. incrementWindowSize(STREAM_A, 5); verify(listener, never()).writabilityChanged(stream(STREAM_A)); verify(listener, never()).writabilityChanged(stream(STREAM_B)); verify(listener, never()).writabilityChanged(stream(STREAM_C)); verify(listener, never()).writabilityChanged(stream(STREAM_D)); assertFalse(controller.isWritable(stream(STREAM_A))); assertTrue(controller.isWritable(stream(STREAM_B))); assertTrue(controller.isWritable(stream(STREAM_C))); assertTrue(controller.isWritable(stream(STREAM_D))); reset(listener); data.assertNotWritten(); controller.writePendingBytes(); data.assertPartiallyWritten(5); verify(listener, times(1)).streamWritten(stream(STREAM_A), 5); assertEquals(DEFAULT_WINDOW_SIZE - 5, window(CONNECTION_STREAM_ID)); assertEquals(0, window(STREAM_A)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_B)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_C)); assertEquals(DEFAULT_WINDOW_SIZE, window(STREAM_D)); } @Test public void flowControlledWriteThrowsAnException() throws Exception { final Http2RemoteFlowController.FlowControlled flowControlled = mockedFlowControlledThatThrowsOnWrite(); final Http2Stream stream = stream(STREAM_A); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocationOnMock) { stream.closeLocalSide(); return null; } }).when(flowControlled).error(any(ChannelHandlerContext.class), any(Throwable.class)); int windowBefore = window(STREAM_A); controller.addFlowControlled(stream, flowControlled); controller.writePendingBytes(); verify(flowControlled, times(3)).write(any(ChannelHandlerContext.class), anyInt()); verify(flowControlled).error(any(ChannelHandlerContext.class), any(Throwable.class)); verify(flowControlled, never()).writeComplete(); assertEquals(90, windowBefore - window(STREAM_A)); verify(listener, times(1)).streamWritten(stream(STREAM_A), 90); assertWritabilityChanged(0, true); } @Test public void flowControlledWriteAndErrorThrowAnException() throws Exception { final Http2RemoteFlowController.FlowControlled flowControlled = mockedFlowControlledThatThrowsOnWrite(); final Http2Stream stream = stream(STREAM_A); final RuntimeException fakeException = new RuntimeException("error failed"); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocationOnMock) { throw fakeException; } }).when(flowControlled).error(any(ChannelHandlerContext.class), any(Throwable.class)); int windowBefore = window(STREAM_A); try { controller.addFlowControlled(stream, flowControlled); controller.writePendingBytes(); fail(); } catch (Http2Exception e) { assertSame(fakeException, e.getCause()); } catch (Throwable t) { fail(); } verify(flowControlled, times(3)).write(any(ChannelHandlerContext.class), anyInt()); verify(flowControlled).error(any(ChannelHandlerContext.class), any(Throwable.class)); verify(flowControlled, never()).writeComplete(); assertEquals(90, windowBefore - window(STREAM_A)); verifyZeroInteractions(listener); } @Test public void flowControlledWriteCompleteThrowsAnException() throws Exception { final Http2RemoteFlowController.FlowControlled flowControlled = Mockito.mock(Http2RemoteFlowController.FlowControlled.class); final AtomicInteger size = new AtomicInteger(150); doAnswer(new Answer<Integer>() { @Override public Integer answer(InvocationOnMock invocationOnMock) throws Throwable { return size.get(); } }).when(flowControlled).size(); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocationOnMock) throws Throwable { size.addAndGet(-50); return null; } }).when(flowControlled).write(any(ChannelHandlerContext.class), anyInt()); final Http2Stream stream = stream(STREAM_A); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocationOnMock) { throw new RuntimeException("writeComplete failed"); } }).when(flowControlled).writeComplete(); int windowBefore = window(STREAM_A); try { controller.addFlowControlled(stream, flowControlled); controller.writePendingBytes(); } catch (Exception e) { fail(); } verify(flowControlled, times(3)).write(any(ChannelHandlerContext.class), anyInt()); verify(flowControlled, never()).error(any(ChannelHandlerContext.class), any(Throwable.class)); verify(flowControlled).writeComplete(); assertEquals(150, windowBefore - window(STREAM_A)); verify(listener, times(1)).streamWritten(stream(STREAM_A), 150); assertWritabilityChanged(0, true); } @Test public void closeStreamInFlowControlledError() throws Exception { final Http2RemoteFlowController.FlowControlled flowControlled = Mockito.mock(Http2RemoteFlowController.FlowControlled.class); final Http2Stream stream = stream(STREAM_A); when(flowControlled.size()).thenReturn(100); doThrow(new RuntimeException("write failed")) .when(flowControlled).write(any(ChannelHandlerContext.class), anyInt()); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocationOnMock) { stream.close(); return null; } }).when(flowControlled).error(any(ChannelHandlerContext.class), any(Throwable.class)); controller.addFlowControlled(stream, flowControlled); controller.writePendingBytes(); verify(flowControlled).write(any(ChannelHandlerContext.class), anyInt()); verify(flowControlled).error(any(ChannelHandlerContext.class), any(Throwable.class)); verify(flowControlled, never()).writeComplete(); verify(listener, times(1)).streamWritten(stream(STREAM_A), 0); verify(listener, times(1)).writabilityChanged(stream(STREAM_A)); verify(listener, never()).writabilityChanged(stream(STREAM_B)); verify(listener, never()).writabilityChanged(stream(STREAM_C)); verify(listener, never()).writabilityChanged(stream(STREAM_D)); assertFalse(controller.isWritable(stream(STREAM_A))); assertTrue(controller.isWritable(stream(STREAM_B))); assertTrue(controller.isWritable(stream(STREAM_C))); assertTrue(controller.isWritable(stream(STREAM_D))); } @Test public void nonWritableChannelDoesNotAttemptToWrite() throws Exception { // Start the channel as not writable and exercise the public methods of the flow controller // making sure no frames are written. setChannelWritability(false); assertWritabilityChanged(1, false); reset(listener); FakeFlowControlled dataA = new FakeFlowControlled(1); FakeFlowControlled dataB = new FakeFlowControlled(1); final Http2Stream stream = stream(STREAM_A); controller.addFlowControlled(stream, dataA); controller.writePendingBytes(); dataA.assertNotWritten(); controller.incrementWindowSize(stream, 100); controller.writePendingBytes(); dataA.assertNotWritten(); controller.addFlowControlled(stream, dataB); controller.writePendingBytes(); dataA.assertNotWritten(); dataB.assertNotWritten(); assertWritabilityChanged(0, false); // Now change the channel to writable and make sure frames are written. setChannelWritability(true); assertWritabilityChanged(1, true); controller.writePendingBytes(); dataA.assertFullyWritten(); dataB.assertFullyWritten(); } @Test public void contextShouldSendQueuedFramesWhenSet() throws Exception { // Re-initialize the controller so we can ensure the context hasn't been set yet. initConnectionAndController(); FakeFlowControlled dataA = new FakeFlowControlled(1); final Http2Stream stream = stream(STREAM_A); // Queue some frames controller.addFlowControlled(stream, dataA); dataA.assertNotWritten(); controller.incrementWindowSize(stream, 100); dataA.assertNotWritten(); assertWritabilityChanged(0, false); // Set the controller controller.channelHandlerContext(ctx); dataA.assertFullyWritten(); assertWritabilityChanged(1, true); } @Test public void initialWindowSizeWithNoContextShouldNotThrow() throws Exception { // Re-initialize the controller so we can ensure the context hasn't been set yet. initConnectionAndController(); FakeFlowControlled dataA = new FakeFlowControlled(1); final Http2Stream stream = stream(STREAM_A); // Queue some frames controller.addFlowControlled(stream, dataA); dataA.assertNotWritten(); // Set the controller controller.channelHandlerContext(ctx); dataA.assertFullyWritten(); } private void assertWritabilityChanged(int amt, boolean writable) { verify(listener, times(amt)).writabilityChanged(stream(STREAM_A)); verify(listener, times(amt)).writabilityChanged(stream(STREAM_B)); verify(listener, times(amt)).writabilityChanged(stream(STREAM_C)); verify(listener, times(amt)).writabilityChanged(stream(STREAM_D)); if (writable) { assertTrue(controller.isWritable(stream(STREAM_A))); assertTrue(controller.isWritable(stream(STREAM_B))); assertTrue(controller.isWritable(stream(STREAM_C))); assertTrue(controller.isWritable(stream(STREAM_D))); } else { assertFalse(controller.isWritable(stream(STREAM_A))); assertFalse(controller.isWritable(stream(STREAM_B))); assertFalse(controller.isWritable(stream(STREAM_C))); assertFalse(controller.isWritable(stream(STREAM_D))); } } private static Http2RemoteFlowController.FlowControlled mockedFlowControlledThatThrowsOnWrite() throws Exception { final Http2RemoteFlowController.FlowControlled flowControlled = Mockito.mock(Http2RemoteFlowController.FlowControlled.class); when(flowControlled.size()).thenReturn(100); doAnswer(new Answer<Void>() { private int invocationCount; @Override public Void answer(InvocationOnMock invocationOnMock) throws Throwable { switch(invocationCount) { case 0: when(flowControlled.size()).thenReturn(50); invocationCount = 1; return null; case 1: when(flowControlled.size()).thenReturn(20); invocationCount = 2; return null; default: when(flowControlled.size()).thenReturn(10); throw new RuntimeException("Write failed"); } } }).when(flowControlled).write(any(ChannelHandlerContext.class), anyInt()); return flowControlled; } private void sendData(int streamId, FakeFlowControlled data) throws Http2Exception { Http2Stream stream = stream(streamId); controller.addFlowControlled(stream, data); } private void exhaustStreamWindow(int streamId) throws Http2Exception { incrementWindowSize(streamId, -window(streamId)); } private int window(int streamId) throws Http2Exception { return controller.windowSize(stream(streamId)); } private void incrementWindowSize(int streamId, int delta) throws Http2Exception { controller.incrementWindowSize(stream(streamId), delta); } private Http2Stream stream(int streamId) { return connection.stream(streamId); } private void resetCtx() { reset(ctx); when(ctx.channel()).thenReturn(channel); when(ctx.executor()).thenReturn(executor); } private void setChannelWritability(boolean isWritable) throws Http2Exception { when(channel.bytesBeforeUnwritable()).thenReturn(isWritable ? Long.MAX_VALUE : 0); when(channel.isWritable()).thenReturn(isWritable); if (controller != null) { controller.channelWritabilityChanged(); } } private static final class FakeFlowControlled implements Http2RemoteFlowController.FlowControlled { private int currentSize; private int originalSize; private boolean writeCalled; private final boolean mergeable; private boolean merged; private Throwable t; private FakeFlowControlled(int size) { this.currentSize = size; this.originalSize = size; this.mergeable = false; } private FakeFlowControlled(int size, boolean mergeable) { this.currentSize = size; this.originalSize = size; this.mergeable = mergeable; } @Override public int size() { return currentSize; } @Override public void error(ChannelHandlerContext ctx, Throwable t) { this.t = t; } @Override public void writeComplete() { } @Override public void write(ChannelHandlerContext ctx, int allowedBytes) { if (allowedBytes <= 0 && currentSize != 0) { // Write has been called but no data can be written return; } writeCalled = true; int written = Math.min(currentSize, allowedBytes); currentSize -= written; } @Override public boolean merge(ChannelHandlerContext ctx, Http2RemoteFlowController.FlowControlled next) { if (mergeable && next instanceof FakeFlowControlled) { this.originalSize += ((FakeFlowControlled) next).originalSize; this.currentSize += ((FakeFlowControlled) next).originalSize; ((FakeFlowControlled) next).merged = true; return true; } return false; } public int written() { return originalSize - currentSize; } public void assertNotWritten() { assertFalse(writeCalled); } public void assertPartiallyWritten(int expectedWritten) { assertPartiallyWritten(expectedWritten, 0); } public void assertPartiallyWritten(int expectedWritten, int delta) { assertTrue(writeCalled); assertEquals(expectedWritten, written(), delta); } public void assertFullyWritten() { assertTrue(writeCalled); assertEquals(0, currentSize); } public boolean assertMerged() { return merged; } public void assertError() { assertNotNull(t); } } }
package aQute.bnd.component; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.ServiceScope; import aQute.bnd.osgi.Analyzer; import aQute.bnd.osgi.Descriptors.TypeRef; import aQute.bnd.version.Version; import aQute.bnd.xmlattribute.ExtensionDef; import aQute.bnd.xmlattribute.Namespaces; import aQute.bnd.xmlattribute.XMLAttributeFinder; import aQute.lib.collections.MultiMap; import aQute.lib.tag.Tag; /** * This class just holds the information for the component, implementation, and * service/provide elements. The {@link #prepare(Analyzer)} method will check if * things are ok and the {@link #getTag()} method returns a tag if the prepare * method returns without any errors. The class uses {@link ReferenceDef} to * hold the references. */ class ComponentDef extends ExtensionDef { final static String NAMESPACE_STEM = "http://www.osgi.org/xmlns/scr"; final static String MARKER = new String("|marker"); final List<String> properties = new ArrayList<>(); final MultiMap<String,String> property = new MultiMap<>(); // key // is // property // name final Map<String,String> propertyType = new HashMap<>(); final Map<String,ReferenceDef> references = new LinkedHashMap<>(); Version version; String name; String factory; Boolean immediate; ServiceScope scope; ConfigurationPolicy configurationPolicy; TypeRef implementation; TypeRef service[]; String activate; String deactivate; String modified; Boolean enabled; String xmlns; String[] configurationPid; List<Tag> propertyTags = new ArrayList<>(); public ComponentDef(XMLAttributeFinder finder, Version minVersion) { super(finder); version = minVersion; } String effectiveName() { if (name != null) return name; if (implementation != null) return implementation.getFQN(); return "<name not yet determined>"; } /** * Called to prepare. If will look for any errors or inconsistencies in the * setup. * * @param analyzer the analyzer to report errors and create references * @throws Exception */ void prepare(Analyzer analyzer) throws Exception { prepareVersion(analyzer); if (implementation == null) { analyzer.error("No Implementation defined for component %s", name); return; } analyzer.referTo(implementation); if (name == null) name = implementation.getFQN(); if (service != null && service.length > 0) { for (TypeRef interfaceName : service) analyzer.referTo(interfaceName); } else if (scope != null && scope != ServiceScope.BUNDLE) analyzer.warning("The servicefactory:=true directive is set but no service is provided, ignoring it"); for (Map.Entry<String,List<String>> kvs : property.entrySet()) { Tag property = new Tag("property"); String name = kvs.getKey(); String type = propertyType.get(name); property.addAttribute("name", name); if (type != null) { property.addAttribute("type", type); } if (kvs.getValue().size() == 1) { String value = kvs.getValue().get(0); value = check(type, value, analyzer); property.addAttribute("value", value); } else { StringBuilder sb = new StringBuilder(); String del = ""; for (String v : kvs.getValue()) { if (v == MARKER) { continue; } sb.append(del); v = check(type, v, analyzer); sb.append(v); del = "\n"; } property.addContent(sb.toString()); } propertyTags.add(property); } } private void prepareVersion(Analyzer analyzer) throws Exception { for (ReferenceDef ref : references.values()) { ref.prepare(analyzer); updateVersion(ref.version); } if (configurationPolicy != null) updateVersion(AnnotationReader.V1_1); if (configurationPid != null) updateVersion(AnnotationReader.V1_2); if (modified != null) updateVersion(AnnotationReader.V1_1); } void sortReferences() { Map<String,ReferenceDef> temp = new TreeMap<>(references); references.clear(); references.putAll(temp); } /** * Returns a tag describing the component element. * * @return a component element */ Tag getTag() { String xmlns = this.xmlns; if (xmlns == null && !version.equals(AnnotationReader.V1_0)) xmlns = NAMESPACE_STEM + "/v" + version; Tag component = new Tag(xmlns == null ? "component" : "scr:component"); Namespaces namespaces = null; if (xmlns != null) { namespaces = new Namespaces(); namespaces.registerNamespace("scr", xmlns); addNamespaces(namespaces, xmlns); for (ReferenceDef ref : references.values()) ref.addNamespaces(namespaces, xmlns); namespaces.addNamespaces(component); } component.addAttribute("name", name); if (configurationPolicy != null) component.addAttribute("configuration-policy", configurationPolicy.toString().toLowerCase()); if (enabled != null) component.addAttribute("enabled", enabled); if (immediate != null) component.addAttribute("immediate", immediate); if (factory != null) component.addAttribute("factory", factory); if (activate != null && !version.equals(AnnotationReader.V1_0)) component.addAttribute("activate", activate); if (deactivate != null && !version.equals(AnnotationReader.V1_0)) component.addAttribute("deactivate", deactivate); if (modified != null) component.addAttribute("modified", modified); if (configurationPid != null) { StringBuilder b = new StringBuilder(); String space = ""; for (String pid : configurationPid) { if ("$".equals(pid)) pid = name; b.append(space).append(pid); space = " "; } component.addAttribute("configuration-pid", b.toString()); } addAttributes(component, namespaces); Tag impl = new Tag(component, "implementation"); impl.addAttribute("class", implementation.getFQN()); if (service != null && service.length != 0) { Tag s = new Tag(component, "service"); if (scope != null) {// TODO check for DEFAULT??? if (AnnotationReader.V1_3.compareTo(version) > 0) { if (scope == ServiceScope.PROTOTYPE) { throw new IllegalStateException("verification failed, pre 1.3 component with scope PROTOTYPE"); } s.addAttribute("servicefactory", scope == ServiceScope.BUNDLE); } else { s.addAttribute("scope", scope.toString().toLowerCase()); } } for (TypeRef ss : service) { Tag provide = new Tag(s, "provide"); provide.addAttribute("interface", ss.getFQN()); } } for (ReferenceDef ref : references.values()) { Tag refTag = ref.getTag(namespaces); component.addContent(refTag); } for (Tag tag : propertyTags) component.addContent(tag); for (String entry : properties) { Tag properties = new Tag(component, "properties"); properties.addAttribute("entry", entry); } return component; } private String check(String type, String v, Analyzer analyzer) { if (type == null) return v; try { if (type.equals("Char")) type = "Character"; Class< ? > c = Class.forName("java.lang." + type); if (c == String.class) return v; v = v.trim(); if (c == Character.class) c = Integer.class; Method m = c.getMethod("valueOf", String.class); m.invoke(null, v); } catch (ClassNotFoundException e) { analyzer.error("Invalid data type %s", type); } catch (NoSuchMethodException e) { analyzer.error("Cannot convert data %s to type %s", v, type); } catch (NumberFormatException e) { analyzer.error("Not a valid number %s for %s, %s", v, type, e.getMessage()); } catch (Exception e) { analyzer.error("Cannot convert data %s to type %s", v, type); } return v; } void updateVersion(Version version) { this.version = max(this.version, version); } static <T extends Comparable<T>> T max(T a, T b) { int n = a.compareTo(b); if (n >= 0) return a; return b; } }
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2021 Equinix, Inc * Copyright 2014-2021 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * 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.killbill.billing.invoice.tree; import java.io.IOException; import java.io.OutputStream; import java.math.BigDecimal; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import org.joda.time.LocalDate; import org.killbill.billing.invoice.api.InvoiceItem; import org.killbill.billing.invoice.tree.Item.ItemAction; import org.killbill.billing.util.jackson.ObjectMapper; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.JsonGenerator; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; /** * Node in the SubscriptionItemTree */ public class ItemsNodeInterval extends NodeInterval { private final ItemsInterval items; public ItemsNodeInterval() { this.items = new ItemsInterval(this); } private ItemsNodeInterval(final ItemsInterval items) { this.items = items; } public ItemsNodeInterval(final NodeInterval parent, final Item item) { super(parent, item.getStartDate(), item.getEndDate()); this.items = new ItemsInterval(this, item); } public ItemsNodeInterval(final NodeInterval parent, final LocalDate startDate, final LocalDate endDate) { super(parent, startDate, endDate); this.items = new ItemsInterval(this); } public ItemsNodeInterval[] split(final LocalDate splitDate) { Preconditions.checkState(splitDate.compareTo(start) > 0 && splitDate.compareTo(end) < 0, String.format("Unexpected item split with startDate='%s' and endDate='%s', splitDate='%s'", start, end, splitDate)); Preconditions.checkState(leftChild == null); Preconditions.checkState(rightSibling == null); final List<Item> rawItems = items.getItems(); Preconditions.checkState(rawItems.size() == 1, "Interval should have a single item: " + rawItems); final Item[] splitItems = rawItems.get(0).split(splitDate); final ItemsNodeInterval split1 = new ItemsNodeInterval(this.parent, splitItems[0]); final ItemsNodeInterval split2 = new ItemsNodeInterval(this.parent, splitItems[1]); final ItemsNodeInterval[] result = new ItemsNodeInterval[2]; result[0] = split1; result[1] = split2; return result; } @JsonIgnore public ItemsInterval getItemsInterval() { return items; } public List<Item> getItems() { return items.getItems(); } /** * Add existing item into the tree * * @param newNode an existing item */ public void addExistingItem(final ItemsNodeInterval newNode) { Preconditions.checkState(newNode.getItems().size() == 1, "Invalid node=%s", newNode); addNode(newNode, new AddNodeCallback() { @Override public boolean onExistingNode(final NodeInterval existingNode, final ItemsNodeInterval updatedNewNode) { final Item item = updatedNewNode.getItems().get(0); final ItemsInterval existingOrNewNodeItems = ((ItemsNodeInterval) existingNode).getItemsInterval(); existingOrNewNodeItems.add(item); // There is no new node added but instead we just populated the list of items for the already existing node return false; } @Override public boolean shouldInsertNode(final NodeInterval insertionNode, final ItemsNodeInterval updatedNewNode) { // Always want to insert node in the tree when we find the right place. return true; } }); } /** * <p/> * There is no limit in the depth of the tree, * and the build strategy is to first consider the lowest child for a given period * and go up the tree adding missing interval if needed. For e.g, one of the possible scenario: * <pre> * D1 D2 * |---------------------------------------------------| Plan P1 * D1' D2' * |---------------|/////////////////////////////| Plan P2, REPAIR * * In that case we will generate: * [D1,D1') on Plan P1; [D1', D2') on Plan P2, and [D2', D2) repair item * * <pre/> * * In the merge mode, the strategy is different, the tree is fairly shallow * and the goal is to generate the repair items; @see addProposedItem * * @param output result list of built items * @param targetInvoiceId */ public void buildForExistingItems(final Collection<Item> output, final UUID targetInvoiceId) { // Sanity on the tree validateTree(); build(output, targetInvoiceId, false); } /** * Add proposed item into the (flattened and reversed) tree * * @param newNode a new proposed item * @return true if the item was merged and will trigger a repair or false if the proposed item should be kept as such and no repair generated */ public List<ItemsNodeInterval> addProposedItem(final ItemsNodeInterval newNode) { Preconditions.checkState(newNode.getItems().size() == 1, "Invalid node=%s", newNode); final List<ItemsNodeInterval> newNodes = new LinkedList<>(); addNode(newNode, new AddNodeCallback() { @Override public boolean onExistingNode(final NodeInterval existingNode, final ItemsNodeInterval updatedNewNode) { final Item item = updatedNewNode.getItems().get(0); // If we receive a new proposed that is the same kind as the reversed existing (current node), // we match existing and proposed. If not, we keep the proposed item as-is outside of the tree. if (isSameKind((ItemsNodeInterval) existingNode, item)) { final ItemsInterval existingOrNewNodeItems = ((ItemsNodeInterval) existingNode).getItemsInterval(); existingOrNewNodeItems.cancelItems(item); return true; } else { newNodes.add(updatedNewNode); return false; } } @Override public boolean shouldInsertNode(final NodeInterval insertionNode, final ItemsNodeInterval updatedNewNode) { final Item item = updatedNewNode.getItems().get(0); // At this stage, we're currently merging a proposed item that does not fit any of the existing intervals. // If this new node is about to be inserted at the root level, this means the proposed item overlaps any // existing item. We keep these as-is, outside of the tree: they will become part of the resulting list. if (insertionNode.isRoot()) { // If updatedNewNode was rebalanced and it is fully repaired by its children it just gets canceled out. LocalDate curDate = updatedNewNode.start; NodeInterval curChild = updatedNewNode.leftChild; while (curChild != null && curChild.start.equals(curDate) && isSameKind((ItemsNodeInterval) curChild, item)) { curDate = curChild.end; curChild = curChild.rightSibling; } if (curDate.equals(updatedNewNode.end)) { updatedNewNode.getItems().clear(); curChild = updatedNewNode.leftChild; while (curChild != null) { ((ItemsNodeInterval) curChild).getItems().clear(); curChild = curChild.rightSibling; } return false; } newNodes.add(updatedNewNode); return false; } // If we receive a new proposed that is the same kind as the reversed existing (parent node), // we want to insert it to generate a piece of repair (see SubscriptionItemTree#buildForMerge). // If not, we keep the proposed item as-is outside of the tree. final boolean result = isSameKind((ItemsNodeInterval) insertionNode, item); if (!result) { newNodes.add(updatedNewNode); } return result; } private boolean isSameKind(final ItemsNodeInterval insertionNode, final Item item) { final List<Item> insertionNodeItems = insertionNode.getItems(); Preconditions.checkState(insertionNodeItems.size() == 1, "Expected existing node to have only one item"); final Item insertionNodeItem = insertionNodeItems.get(0); return insertionNodeItem.isSameKind(item); } }); return newNodes; } /** * The merge tree is initially constructed by flattening all the existing items and reversing them (CANCEL node). * <p/> * That means that if we were to not merge any new proposed items, we would end up with only those reversed existing * items, and they would all end up repaired-- which is what we want. * <p/> * However, if there are new proposed items, then we look to see if they are children one our existing reverse items * so that we can generate the repair pieces missing. For e.g, below is one scenario among so many: * <p/> * <pre> * D1 D2 * |---------------------------------------------------| (existing reversed (CANCEL) item * D1' D2' * |---------------| (proposed same plan) * </pre> * In that case we want to generated a repair for [D1, D1') and [D2',D2) * <p/> * Note that this tree is never very deep, only 3 levels max, with exiting at the first level * and proposed that are the for the exact same plan but for different dates below. * * @param output result list of built items */ public void mergeExistingAndProposed(final Collection<Item> output, final UUID targetInvoiceId) { build(output, targetInvoiceId, true); } /** * Add the adjustment amount on the item specified by the targetId. * * @return linked item if fully adjusted, null otherwise */ public Item addAdjustment(final InvoiceItem item) { final UUID targetId = item.getLinkedItemId(); final NodeInterval node = findNode(new SearchCallback() { @Override public boolean isMatch(final NodeInterval curNode) { return ((ItemsNodeInterval) curNode).getItemsInterval().findItem(targetId) != null; } }); Preconditions.checkNotNull(node, "Unable to find item interval for id='%s', tree=%s", targetId, this); final ItemsInterval targetItemsInterval = ((ItemsNodeInterval) node).getItemsInterval(); final Item targetItem = targetItemsInterval.findItem(targetId); Preconditions.checkNotNull(targetItem, "Unable to find item with id='%s', itemsInterval=%s", targetId, targetItemsInterval); final BigDecimal adjustmentAmount = item.getAmount().negate(); targetItem.incrementAdjustedAmount(adjustmentAmount); return null; } private void build(final Collection<Item> output, final UUID targetInvoiceId, final boolean mergeMode) { final List<Item> tmpOutput = new LinkedList<Item>(output); output.clear(); build(new BuildNodeCallback() { @Override public void onMissingInterval(final NodeInterval curNode, final LocalDate startDate, final LocalDate endDate) { final ItemsInterval items = ((ItemsNodeInterval) curNode).getItemsInterval(); items.buildForMissingInterval(startDate, endDate, targetInvoiceId, tmpOutput, mergeMode); } @Override public void onLastNode(final NodeInterval curNode) { final ItemsInterval items = ((ItemsNodeInterval) curNode).getItemsInterval(); items.buildFromItems(tmpOutput, mergeMode); } }); // // Join items that were previously split to fit in the tree as necessary. // // 1. Build a map for each item pointing to a heap of (potential) split items final Map<UUID, PriorityQueue<Item>> joinMap = new HashMap<>(); for (final Item i : tmpOutput) { PriorityQueue<Item> l = joinMap.get(i.getId()); if (l == null) { l = new PriorityQueue<>(new Comparator<Item>() { @Override public int compare(final Item o1, final Item o2) { return o1.getStartDate().compareTo(o2.getEndDate()); } }); joinMap.put(i.getId(), l); } l.add(i); } // 2. For each entry in the map, check which items can be re-joined based on their contiguous periods for (final PriorityQueue<Item> v : joinMap.values()) { Item prev = v.poll(); Item cur = null; while ((cur = v.poll()) != null) { if (prev.getEndDate().compareTo(cur.getStartDate()) == 0) { prev = Item.join(prev, cur); } else { output.add(prev); prev = cur; } } if (prev != null) { output.add(prev); } } } // // This is not strictly necessary -- just there to add a layer of sanity on what our tree contains // private void validateTree() { final NodeInterval root = this; walkTree(new WalkCallback() { @Override public void onCurrentNode(final int depth, final NodeInterval curNode, final NodeInterval parent) { if (curNode.isRoot()) { return; } final ItemsInterval curNodeItems = ((ItemsNodeInterval) curNode).getItemsInterval(); for (final Item curCancelItem : curNodeItems.get_CANCEL_items()) { // Sanity: cancelled items should only be in the same node or parents if (curNode.getLeftChild() != null) { curNode.getLeftChild() .walkTree(new WalkCallback() { @Override public void onCurrentNode(final int depth, final NodeInterval curNode, final NodeInterval parent) { final ItemsInterval curChildItems = ((ItemsNodeInterval) curNode).getItemsInterval(); final Item cancelledItem = curChildItems.getCancelledItemIfExists(curCancelItem.getLinkedId()); Preconditions.checkState(cancelledItem == null, "Invalid cancelledItem=%s for cancelItem=%s", cancelledItem, curCancelItem); } }); } // Sanity: make sure the CANCEL item points to an ADD item final NodeInterval nodeIntervalForCancelledItem = root.findNode(new SearchCallback() { @Override public boolean isMatch(final NodeInterval curNode) { final ItemsInterval curChildItems = ((ItemsNodeInterval) curNode).getItemsInterval(); final Item cancelledItem = curChildItems.getCancelledItemIfExists(curCancelItem.getLinkedId()); return cancelledItem != null; } }); Preconditions.checkState(nodeIntervalForCancelledItem != null, "Missing cancelledItem for cancelItem=%s", curCancelItem); } for (final Item curAddItem : curNodeItems.get_ADD_items()) { // Sanity: verify the item hasn't been repaired too much if (curNode.getLeftChild() != null) { final AtomicReference<BigDecimal> totalRepaired = new AtomicReference<BigDecimal>(BigDecimal.ZERO); curNode.getLeftChild() .walkTree(new WalkCallback() { @Override public void onCurrentNode(final int depth, final NodeInterval curNode, final NodeInterval parent) { final ItemsInterval curChildItems = ((ItemsNodeInterval) curNode).getItemsInterval(); final Item cancelledItem = curChildItems.getCancellingItemIfExists(curAddItem.getId()); if (cancelledItem != null && curAddItem.getId().equals(cancelledItem.getLinkedId())) { totalRepaired.set(totalRepaired.get().add(cancelledItem.getAmount())); } } }); Preconditions.checkState(curAddItem.getNetAmount().compareTo(totalRepaired.get()) >= 0, "Item %s overly repaired", curAddItem); } // Old behavior compatibility for full item adjustment (Temp code should go away as move in time) // If we see a fully adjusted item and an existing child (one ADD item), we discard the fully adjusted item // in such a way that we are left with the child that will look like the proposed and nothing will be generated. if (curAddItem.isFullyAdjusted()) { final NodeInterval leftChild = curNode.getLeftChild(); if (leftChild != null) { final ItemsInterval leftChildItems = ((ItemsNodeInterval) leftChild).getItemsInterval(); if (leftChildItems.getItems().size() == 1 && leftChildItems.getItems().get(0).getAction() == ItemAction.ADD) { curNodeItems.remove(curAddItem); } } } } } }); } @VisibleForTesting public void jsonSerializeTree(final ObjectMapper mapper, final OutputStream output) throws IOException { final JsonGenerator generator = mapper.getFactory().createGenerator(output); generator.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); walkTree(new WalkCallback() { private int curDepth = 0; @Override public void onCurrentNode(final int depth, final NodeInterval curNode, final NodeInterval parent) { final ItemsNodeInterval node = (ItemsNodeInterval) curNode; if (node.isRoot()) { return; } try { if (curDepth < depth) { generator.writeStartArray(); curDepth = depth; } else if (curDepth > depth) { generator.writeEndArray(); curDepth = depth; } generator.writeObject(node); } catch (final IOException e) { throw new RuntimeException("Failed to deserialize tree", e); } } }); generator.close(); } @Override public String toString() { final StringBuilder sb = new StringBuilder("ItemsNodeInterval{"); sb.append("items=").append(items); sb.append('}'); return sb.toString(); } }
package mil.nga.giat.geowave.format.stanag4676; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import java.util.TreeMap; import javax.imageio.ImageIO; import javax.imageio.stream.ImageInputStream; import mil.nga.giat.geowave.core.geotime.GeometryUtils; import mil.nga.giat.geowave.core.ingest.hdfs.mapreduce.KeyValueData; import mil.nga.giat.geowave.format.stanag4676.image.ImageChipInfo; import mil.nga.giat.geowave.format.stanag4676.image.ImageChipUtils; import mil.nga.giat.geowave.format.stanag4676.parser.TrackReader.ProcessMessage; import mil.nga.giat.geowave.format.stanag4676.parser.model.MotionEventPoint; import mil.nga.giat.geowave.format.stanag4676.parser.model.MotionImagery; import mil.nga.giat.geowave.format.stanag4676.parser.model.TrackEvent; import mil.nga.giat.geowave.format.stanag4676.parser.model.TrackMessage; import mil.nga.giat.geowave.format.stanag4676.parser.model.TrackPoint; import mil.nga.giat.geowave.format.stanag4676.parser.model.TrackRun; import org.apache.hadoop.io.Text; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.io.BaseEncoding; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Polygon; import com.vividsolutions.jts.io.WKBWriter; import mil.nga.giat.geowave.format.stanag4676.parser.model.MissionFrame; import mil.nga.giat.geowave.format.stanag4676.parser.model.MissionSummary; import mil.nga.giat.geowave.format.stanag4676.parser.model.MissionSummaryMessage; import mil.nga.giat.geowave.format.stanag4676.parser.model.ModalityType; import mil.nga.giat.geowave.format.stanag4676.parser.model.NATO4676Message; import mil.nga.giat.geowave.format.stanag4676.parser.model.ObjectClassification; import mil.nga.giat.geowave.format.stanag4676.parser.model.TrackClassification; public class IngestMessageHandler implements ProcessMessage { private final static Logger LOGGER = LoggerFactory.getLogger(IngestMessageHandler.class); private final WKBWriter wkbWriter = new WKBWriter( 3); private final static String DEFAULT_IMAGE_FORMAT = "jpg"; private final List<KeyValueData<Text, Stanag4676EventWritable>> intermediateData = new ArrayList<KeyValueData<Text, Stanag4676EventWritable>>(); public IngestMessageHandler() {} public List<KeyValueData<Text, Stanag4676EventWritable>> getIntermediateData() { return intermediateData; } // Parses events sent out by 4676 parser code - each msg is a "Track" entry // - here we extract what we want and emit it as a value to group up in the // reducer @Override public void notify( final NATO4676Message msg ) throws IOException, InterruptedException { if (msg == null) { LOGGER.error("Received null msg"); return; } if (msg instanceof TrackMessage) { TrackMessage trackMessage = (TrackMessage) msg; for (final TrackEvent evt : trackMessage.getTracks()) { if (evt.getPoints().size() > 0) { final String trackUuid = evt.getUuid().toString(); String missionUUID = evt.getMissionId(); final String comment = evt.getComment(); if ((missionUUID == null) && (comment != null)) { missionUUID = comment; } if (missionUUID == null) { /* TODO: parse mission from filename? - can provide here */ missionUUID = ""; } else { missionUUID = missionUUID.replaceAll( "Mission:", "").trim(); } final String trackNumber = evt.getTrackNumber(); String trackStatus = ""; if (evt.getStatus() != null) { trackStatus = evt.getStatus().name(); } String trackClassification = ""; if ((evt.getSecurity() != null) && (evt.getSecurity().getClassification() != null)) { trackClassification = evt.getSecurity().getClassification().name(); } final TreeMap<Long, ImageChipInfo> timesWithImageChips = new TreeMap<Long, ImageChipInfo>(); final List<MotionImagery> images = evt.getMotionImages(); // keep track of the minimum image size and use that to size // the video int width = -1; int height = -1; for (final MotionImagery imagery : images) { try { String imageChip = imagery.getImageChip(); BufferedImage img = null; if (imageChip != null && imageChip.length() > 0) { final byte[] binary = BaseEncoding.base64().decode( imageChip); final ImageInputStream stream = ImageIO .createImageInputStream(new ByteArrayInputStream( binary)); img = ImageIO.read(stream); if ((width < 0) || (img.getWidth() > width)) { width = img.getWidth(); } if ((height < 0) || (img.getHeight() > height)) { height = img.getHeight(); } } timesWithImageChips.put( imagery.getTime(), new ImageChipInfo( img, imagery.getFrameNumber(), imagery.getPixelRow(), imagery.getPixelColumn())); } catch (final Exception e) { LOGGER.warn( "Unable to write image chip to file", e); } } for (final Entry<Long, ImageChipInfo> chipInfo : timesWithImageChips.entrySet()) { final BufferedImage img = chipInfo.getValue().getImage(); if (img != null) { final BufferedImage scaledImage = toBufferedImage( img.getScaledInstance( width, height, Image.SCALE_SMOOTH), BufferedImage.TYPE_3BYTE_BGR); chipInfo.getValue().setImage( scaledImage); try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { ImageIO.write( scaledImage, DEFAULT_IMAGE_FORMAT, baos); baos.flush(); chipInfo.getValue().setImageBytes( baos.toByteArray()); } catch (final Exception e) { LOGGER.warn( "Unable to write image chip to file", e); } } } for (final TrackPoint pt : evt.getPoints().values()) { final byte[] geometry = wkbWriter.write(GeometryUtils.GEOMETRY_FACTORY .createPoint(new Coordinate( pt.getLocation().longitude, pt.getLocation().latitude))); final String trackItemUUID = pt.getUuid(); final long timeStamp = pt.getEventTime(); final long endTimeStamp = -1L; final double speed = pt.getSpeed(); final double course = pt.getCourse(); String trackItemClassification = "UNKNOWN"; if ((pt.getSecurity() != null) && (pt.getSecurity().getClassification() != null)) { trackItemClassification = pt.getSecurity().getClassification().name(); } ModalityType mt = pt.getTrackPointSource(); final String trackPointSource = (mt != null) ? mt.toString() : ""; final double latitude = pt.getLocation().latitude; final double longitude = pt.getLocation().longitude; final double elevation = pt.getLocation().elevation; final ImageChipInfo chipInfo = timesWithImageChips.get(timeStamp); int pixelRow = -1; int pixelColumn = -1; int frameNumber = -1; byte[] imageBytes = new byte[] {}; if (chipInfo != null) { pixelRow = chipInfo.getPixelRow(); pixelColumn = chipInfo.getPixelColumn(); frameNumber = chipInfo.getFrameNumber(); imageBytes = chipInfo.getImageBytes(); } Stanag4676EventWritable sw = new Stanag4676EventWritable(); sw.setTrackPointData( geometry, imageBytes, missionUUID, trackNumber, trackUuid, trackStatus, trackClassification, trackItemUUID, trackPointSource, timeStamp, endTimeStamp, speed, course, trackItemClassification, latitude, longitude, elevation, pixelRow, pixelColumn, frameNumber); intermediateData.add(new KeyValueData<Text, Stanag4676EventWritable>( new Text( trackUuid), sw)); } for (final MotionEventPoint pt : evt.getMotionPoints().values()) { final byte[] geometry = wkbWriter.write(GeometryUtils.GEOMETRY_FACTORY .createPoint(new Coordinate( pt.getLocation().longitude, pt.getLocation().latitude))); final String trackItemUUID = pt.getUuid(); final long timeStamp = pt.getEventTime(); final long endTimeStamp = pt.getEndTime(); final double speed = pt.getSpeed(); final double course = pt.getCourse(); String trackItemClassification = "UNKNOWN"; if ((pt.getSecurity() != null) && (pt.getSecurity().getClassification() != null)) { trackItemClassification = pt.getSecurity().getClassification().name(); } final double latitude = pt.getLocation().latitude; final double longitude = pt.getLocation().longitude; final double elevation = pt.getLocation().elevation; ModalityType mt = pt.getTrackPointSource(); final String trackPointSource = (mt != null) ? mt.toString() : ""; final ImageChipInfo chipInfo = timesWithImageChips.get(timeStamp); int pixelRow = -1; int pixelColumn = -1; int frameNumber = -1; byte[] imageBytes = new byte[] {}; if (chipInfo != null) { pixelRow = chipInfo.getPixelRow(); pixelColumn = chipInfo.getPixelColumn(); frameNumber = chipInfo.getFrameNumber(); imageBytes = chipInfo.getImageBytes(); } final String motionEvent = pt.motionEvent; Stanag4676EventWritable sw = new Stanag4676EventWritable(); sw.setMotionPointData( geometry, imageBytes, missionUUID, trackNumber, trackUuid, trackStatus, trackClassification, trackItemUUID, trackPointSource, timeStamp, endTimeStamp, speed, course, trackItemClassification, latitude, longitude, elevation, pixelRow, pixelColumn, frameNumber, motionEvent); // motion events emitted, grouped by track intermediateData.add(new KeyValueData<Text, Stanag4676EventWritable>( new Text( trackUuid), sw)); } for (TrackClassification tc : evt.getClassifications()) { long objectClassTime = tc.getTime(); String objectClass = tc.classification.toString(); int objectClassConf = tc.credibility.getValueConfidence(); int objectClassRel = tc.credibility.getSourceReliability(); Stanag4676EventWritable sw = new Stanag4676EventWritable(); sw.setTrackObjectClassData( objectClassTime, objectClass, objectClassConf, objectClassRel); intermediateData.add(new KeyValueData<Text, Stanag4676EventWritable>( new Text( trackUuid), sw)); } } } } if (msg instanceof MissionSummaryMessage) { MissionSummaryMessage missionSummaryMessage = (MissionSummaryMessage) msg; MissionSummary missionSummary = missionSummaryMessage.getMissionSummary(); if (missionSummary != null && missionSummary.getCoverageArea() != null) { Polygon missionPolygon = missionSummary.getCoverageArea().getPolygon(); final byte[] missionGeometry = wkbWriter.write(missionPolygon); String missionUUID = missionSummary.getMissionId(); String missionName = missionSummary.getName(); int missionNumFrames = missionSummary.getFrames().size(); long missionStartTime = missionSummary.getStartTime(); long missionEndTime = missionSummary.getEndTime(); String missionClassification = missionSummary.getSecurity(); StringBuilder sb = new StringBuilder(); for (final ObjectClassification oc : missionSummary.getClassifications()) { if (sb.length() > 0) sb.append(","); sb.append(oc.toString()); } String activeObjectClass = sb.toString(); Stanag4676EventWritable msw = new Stanag4676EventWritable(); msw.setMissionSummaryData( missionGeometry, missionUUID, missionName, missionNumFrames, missionStartTime, missionEndTime, missionClassification, activeObjectClass); intermediateData.add(new KeyValueData<Text, Stanag4676EventWritable>( new Text( missionUUID), msw)); for (MissionFrame frame : missionSummary.getFrames()) { if (frame != null && frame.getCoverageArea() != null) { Polygon framePolygon = frame.getCoverageArea().getPolygon(); final byte[] frameGeometry = wkbWriter.write(framePolygon); long frameTimeStamp = frame.getFrameTime(); int frameNumber = frame.getFrameNumber(); Stanag4676EventWritable fsw = new Stanag4676EventWritable(); fsw.setMissionFrameData( frameGeometry, missionUUID, frameNumber, frameTimeStamp); intermediateData.add(new KeyValueData<Text, Stanag4676EventWritable>( new Text( missionUUID), fsw)); } } } } } private static BufferedImage toBufferedImage( final Image image, final int type ) { if (image instanceof BufferedImage) { return (BufferedImage) image; } return ImageChipUtils.toBufferedImage( image, type); } @Override public void notify( final TrackRun run ) { // TODO Auto-generated method stub } @Override public void initialize( final TrackRun run ) { // TODO Auto-generated method stub } }
package com.cebedo.pmsys.domain; import javax.persistence.Transient; import com.cebedo.pmsys.base.IObjectDomain; import com.cebedo.pmsys.constants.ConstantsRedis; import com.cebedo.pmsys.constants.RegistryRedisKeys; import com.cebedo.pmsys.enums.HTMLCSSDetails; import com.cebedo.pmsys.model.Company; import com.cebedo.pmsys.model.Project; import com.cebedo.pmsys.utils.HTMLUtils; import com.cebedo.pmsys.utils.NumberFormatUtils; public class ProjectAux implements IObjectDomain { private static final long serialVersionUID = 4250896962237506975L; private Company company; private Project project; /** * Grand totals of expenses. */ private double grandTotalDelivery; private double grandTotalPayroll; private double grandTotalOtherExpenses; private double grandTotalEquipmentExpenses; // Estimate costs. private double grandTotalCostsDirect; private double grandTotalCostsIndirect; private double grandTotalActualCostsDirect; private double grandTotalActualCostsIndirect; public ProjectAux() { ; } public ProjectAux(Project project2) { Company co = project2.getCompany(); setCompany(co); setProject(project2); } /** * company.fk:%s:project:%s */ @Override public String getKey() { return String.format(RegistryRedisKeys.KEY_AUX_PROJECT, this.company.getId(), this.project.getId()); } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } public Project getProject() { return project; } public void setProject(Project project) { this.project = project; } public static String constructKey(Project project) { Company company = project.getCompany(); return String.format(RegistryRedisKeys.KEY_AUX_PROJECT, company.getId(), project.getId()); } public double getPlannedTotalProject() { return grandTotalCostsDirect + grandTotalCostsIndirect; } public double getDiffEstimatedActualTotal() { return getPlannedTotalProject() - getActualTotalProject(); } public String getDiffEstimatedActualTotalAsString() { double diff = getDiffEstimatedActualTotal(); String diffStr = NumberFormatUtils.getCurrencyFormatter().format(diff); if (diff < 0) { return diffStr.replace("&#8369;", "&#8369;-").replace("(", "").replace(")", ""); } return diffStr; } public String getDiffEstimatedActualTotalAsHTML() { String label = getDiffEstimatedActualTotalAsString(); double diff = getDiffEstimatedActualTotal(); if (diff < 0) { return HTMLUtils.getBadgeHTML(HTMLCSSDetails.DANGER, label); } return HTMLUtils.getBadgeHTML(HTMLCSSDetails.SUCCESS, label); } public double getDiffEstimatedActualDirect() { return getGrandTotalCostsDirect() - getGrandTotalActualCostsDirect(); } public String getDiffEstimatedActualDirectAsString() { double diff = getDiffEstimatedActualDirect(); String diffStr = NumberFormatUtils.getCurrencyFormatter().format(diff); if (diff < 0) { return diffStr.replace("&#8369;", "&#8369;-").replace("(", "").replace(")", ""); } return diffStr; } public String getDiffEstimatedActualDirectAsHTML() { String label = getDiffEstimatedActualDirectAsString(); double diff = getDiffEstimatedActualDirect(); if (diff < 0) { return HTMLUtils.getBadgeHTML(HTMLCSSDetails.DANGER, label); } return HTMLUtils.getBadgeHTML(HTMLCSSDetails.SUCCESS, label); } public double getDiffEstimatedActualIndirect() { return getGrandTotalCostsIndirect() - getGrandTotalActualCostsIndirect(); } public String getDiffEstimatedActualIndirectAsString() { double diff = getDiffEstimatedActualIndirect(); String diffStr = NumberFormatUtils.getCurrencyFormatter().format(diff); if (diff < 0) { return diffStr.replace("&#8369;", "&#8369;-").replace("(", "").replace(")", ""); } return diffStr; } public String getDiffEstimatedActualIndirectAsHTML() { String label = getDiffEstimatedActualIndirectAsString(); double diff = getDiffEstimatedActualIndirect(); if (diff < 0) { return HTMLUtils.getBadgeHTML(HTMLCSSDetails.DANGER, label); } return HTMLUtils.getBadgeHTML(HTMLCSSDetails.SUCCESS, label); } public double getActualTotalProject() { return grandTotalActualCostsDirect + grandTotalActualCostsIndirect; } public String getActualTotalProjectAsString() { return NumberFormatUtils.getCurrencyFormatter().format(getActualTotalProject()); } public double getCurrentTotalProject() { return grandTotalDelivery + grandTotalPayroll + grandTotalOtherExpenses + grandTotalEquipmentExpenses; } @Transient public HTMLCSSDetails getCSSofOverspent() { if (getRemainingBudget() < 0) { return HTMLCSSDetails.OVERSPENT; } return HTMLCSSDetails.SPENT; } public double getRemainingBudget() { return getPlannedTotalProject() - getCurrentTotalProject(); } public String getRemainingBudgetAsString() { double budget = getRemainingBudget(); String budgetStr = NumberFormatUtils.getCurrencyFormatter().format(budget); if (budget < 0) { return budgetStr.replace("&#8369;", "&#8369;-").replace("(", "").replace(")", ""); } return budgetStr; } public double getRemainingBudgetAsPercent() { return (getRemainingBudget() / getPlannedTotalProject()) * 100; } public String getRemainingBudgetAsPercentAsString() { return getPlannedTotalProject() == 0 ? "" : "(" + NumberFormatUtils.getQuantityFormatter().format(getRemainingBudgetAsPercent()) + "%)"; } public double getCurrentTotalProjectAsPercent() { double currentTotal = getCurrentTotalProject(); double plannedTotal = getPlannedTotalProject(); return (currentTotal / plannedTotal) * 100; } public String getCurrentTotalProjectAsPercentAsString() { return getPlannedTotalProject() == 0 ? "" : "(" + NumberFormatUtils.getQuantityFormatter() .format(getCurrentTotalProjectAsPercent()) + "%)"; } public String getPlannedTotalProjectAsString() { return NumberFormatUtils.getCurrencyFormatter().format(getPlannedTotalProject()); } public String getCurrentTotalProjectAsString() { return NumberFormatUtils.getCurrencyFormatter().format(getCurrentTotalProject()); } public double getGrandTotalDelivery() { return grandTotalDelivery; } public String getGrandTotalDeliveryAsString() { return NumberFormatUtils.getCurrencyFormatter().format(this.grandTotalDelivery); } public void setGrandTotalDelivery(double grandTotalDelivery) { this.grandTotalDelivery = grandTotalDelivery; } public double getGrandTotalPayroll() { return grandTotalPayroll; } public String getGrandTotalPayrollAsString() { return NumberFormatUtils.getCurrencyFormatter().format(this.grandTotalPayroll); } public void setGrandTotalPayroll(double grandTotalPayroll) { this.grandTotalPayroll = grandTotalPayroll; } @Override public boolean equals(Object obj) { return obj instanceof ProjectAux ? ((ProjectAux) obj).getKey().equals(getKey()) : false; } @Override public int hashCode() { return getKey().hashCode(); } public String getGrandTotalCostsDirectAsString() { return NumberFormatUtils.getCurrencyFormatter().format(getGrandTotalCostsDirect()); } public double getGrandTotalCostsDirect() { return grandTotalCostsDirect; } public void setGrandTotalCostsDirect(double grandTotalCostsDirect) { this.grandTotalCostsDirect = grandTotalCostsDirect; } public double getGrandTotalCostsIndirect() { return grandTotalCostsIndirect; } public String getGrandTotalCostsIndirectAsString() { return NumberFormatUtils.getCurrencyFormatter().format(getGrandTotalCostsIndirect()); } public void setGrandTotalCostsIndirect(double grandTotalCostsIndirect) { this.grandTotalCostsIndirect = grandTotalCostsIndirect; } public double getGrandTotalActualCostsDirect() { return grandTotalActualCostsDirect; } public String getGrandTotalActualCostsDirectAsString() { return NumberFormatUtils.getCurrencyFormatter().format(getGrandTotalActualCostsDirect()); } public void setGrandTotalActualCostsDirect(double grandTotalActualCostsDirect) { this.grandTotalActualCostsDirect = grandTotalActualCostsDirect; } public double getGrandTotalActualCostsIndirect() { return grandTotalActualCostsIndirect; } public String getGrandTotalActualCostsIndirectAsString() { return NumberFormatUtils.getCurrencyFormatter().format(getGrandTotalActualCostsIndirect()); } public void setGrandTotalActualCostsIndirect(double grandTotalActualCostsIndirect) { this.grandTotalActualCostsIndirect = grandTotalActualCostsIndirect; } public double getGrandTotalOtherExpenses() { return grandTotalOtherExpenses; } public String getGrandTotalOtherExpensesAsString() { return NumberFormatUtils.getCurrencyFormatter().format(getGrandTotalOtherExpenses()); } public void setGrandTotalOtherExpenses(double grandTotalOtherExpenses) { this.grandTotalOtherExpenses = grandTotalOtherExpenses; } public double getGrandTotalEquipmentExpenses() { return grandTotalEquipmentExpenses; } public String getGrandTotalEquipmentExpensesAsString() { return NumberFormatUtils.getCurrencyFormatter().format(getGrandTotalEquipmentExpenses()); } public void setGrandTotalEquipmentExpenses(double grandTotalEquipmentExpenses) { this.grandTotalEquipmentExpenses = grandTotalEquipmentExpenses; } @Override public String getName() { return this.project.getName(); } @Override public String getObjectName() { return ConstantsRedis.OBJECT_AUX_PROJECT; } public ProjectAux clone() { try { return (ProjectAux) super.clone(); } catch (Exception e) { return null; } } }
package org.zbq.excel; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.zbq.bean.Equipment; import org.zbq.bean.Hdd; public class ExcelHandle { public static Map<String, String> getWWID(String fileName) throws IOException { Map<String, String> map = new HashMap<String, String>(); File f = new File(fileName); FileReader fr = new FileReader(f); BufferedReader bf = new BufferedReader(fr); while (bf.read() != -1) { String line = bf.readLine(); if (line.startsWith("[")) { String[] sp = line.split("\\|"); String n = sp[0]; String wwid = sp[1]; int s = n.indexOf("["); int e = n.indexOf("]"); String name = n.substring(s + 1, e); map.put(wwid, name); // System.out.printf("[%s]", sp[1]); // System.out.printf("%d, %d, [%s]\n", s, e, name); } } bf.close(); fr.close(); return map; } public static Map<String, String> getWWID(BufferedReader bf) throws IOException { Map<String, String> map = new TreeMap<String, String>(); while (bf.read() != -1) { String line = bf.readLine(); if (line.startsWith("[")) { String[] sp = line.split("\\|"); String n = sp[0]; String wwid = sp[1]; int s = n.indexOf("["); int e = n.indexOf("]"); String name = n.substring(s + 1, e); map.put(wwid, name); } } bf.close(); return map; } public static List<List<String>> read(String fileName) throws EncryptedDocumentException, InvalidFormatException, IOException { File xlsFile = new File(fileName); Workbook workbook = WorkbookFactory.create(xlsFile); List<List<String>> list = new LinkedList<List<String>>(); Sheet sheet_0 = workbook.getSheetAt(0); int rows = sheet_0.getLastRowNum() + 1; Row tmp = sheet_0.getRow(0); int cols = tmp.getPhysicalNumberOfCells(); for (int row = 1; row < rows; row++) { Row r = sheet_0.getRow(row); List<String> items = new LinkedList<String>(); for (int col = 0; col < cols; col++) { items.add(r.getCell(col).getStringCellValue()); } list.add(items); } return list; } public static List<List<String>> getMediaTeamInfo(Map<String, String> map, List<List<String>> list) { List<List<String>> l = new LinkedList<List<String>>(); for (List<String> items : list) { String owner = items.get(2); if (map.containsKey(owner)) { l.add(items); } } return l; } public static List<List<String>> getMachineInfo(Map<String, String> map, List<List<String>> list) { List<List<String>> l = new LinkedList<List<String>>(); for (List<String> items : list) { // String wwid = items.get(2); // String owner = map.get(wwid); // String name = items.get(0); // String sn = items.get(1); String clazz = items.get(3); // String model = items.get(4); // String status = items.get(5); // String comment = items.get(6); System.out.printf("[%s]\n", clazz); if ("Computer".equals(clazz) || "Server".equals(clazz)) { l.add(items); } } return l; } public void writeMachineInfo2excel(String fileName, List<List<String>> list) throws IOException { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("sheet1"); for (int row = 0; row < 10; row++) { HSSFRow rownum = sheet.createRow(row); for (int col = 0; col < 10; col++) { rownum.createCell(col).setCellValue("data" + row + col); } } File xlsFile = new File(fileName); FileOutputStream xlsStream = new FileOutputStream(xlsFile); workbook.write(xlsStream); workbook.close(); } public static void writeHdd2Excel(File file, List<Hdd> hddList) throws IOException { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("HDD"); HSSFRow rownum = sheet.createRow(0); rownum.createCell(0).setCellValue("Nmae"); rownum.createCell(1).setCellValue("Serial numbe"); rownum.createCell(2).setCellValue("Assigned to"); rownum.createCell(3).setCellValue("Class"); rownum.createCell(4).setCellValue("Model"); rownum.createCell(5).setCellValue("Status(hardware_status)"); rownum.createCell(6).setCellValue("Comments"); rownum.createCell(7).setCellValue("Find"); rownum.createCell(8).setCellValue("Bench"); rownum.createCell(9).setCellValue("Machine_S/N"); for (int row = 1; row < hddList.size(); row++) { rownum = sheet.createRow(row); Hdd hdd = hddList.get(row); rownum.createCell(0).setCellValue(hdd.getName()); rownum.createCell(1).setCellValue(hdd.getSn()); rownum.createCell(2).setCellValue(hdd.getUser().getName()); rownum.createCell(3).setCellValue(hdd.getClazz()); rownum.createCell(4).setCellValue(hdd.getModel()); rownum.createCell(5).setCellValue(hdd.getStatus()); rownum.createCell(6).setCellValue(hdd.getComments()); if (1 == hdd.getFind()) { rownum.createCell(7).setCellValue("Yes"); } else { rownum.createCell(7).setCellValue("No"); } rownum.createCell(8).setCellValue(hdd.getBench()); rownum.createCell(9).setCellValue(hdd.getMachine_sn()); } FileOutputStream xlsStream = new FileOutputStream(file); workbook.write(xlsStream); workbook.close(); } public static void writeEquipment2Excel(File file, List<Equipment> eList) throws IOException { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("HDD"); HSSFRow rownum = sheet.createRow(0); rownum.createCell(0).setCellValue("Nmae"); rownum.createCell(1).setCellValue("Serial numbe"); rownum.createCell(2).setCellValue("Assigned to"); rownum.createCell(3).setCellValue("Class"); rownum.createCell(4).setCellValue("Model"); rownum.createCell(5).setCellValue("Status(hardware_status)"); rownum.createCell(6).setCellValue("Comments"); rownum.createCell(7).setCellValue("Find"); rownum.createCell(8).setCellValue("Location"); for (int row = 1; row < eList.size(); row++) { rownum = sheet.createRow(row); Equipment e = eList.get(row); rownum.createCell(0).setCellValue(e.getName()); rownum.createCell(1).setCellValue(e.getSn()); rownum.createCell(2).setCellValue(e.getUser().getName()); rownum.createCell(3).setCellValue(e.getClazz()); rownum.createCell(4).setCellValue(e.getModel()); rownum.createCell(5).setCellValue(e.getStatus()); rownum.createCell(6).setCellValue(e.getComments()); if (1 == e.getFind()) { rownum.createCell(7).setCellValue("Yes"); } else { rownum.createCell(7).setCellValue("No"); } rownum.createCell(8).setCellValue(e.getLocation()); } FileOutputStream xlsStream = new FileOutputStream(file); workbook.write(xlsStream); workbook.close(); } public static void main(String[] args) throws IOException, EncryptedDocumentException, InvalidFormatException { File file = new File("src/main/resources/wwid.md"); InputStream is = new FileInputStream(file); // InputStream is = ExcelHandle.class.getResourceAsStream("wwid.md"); InputStreamReader isr = new InputStreamReader(is); BufferedReader bf = new BufferedReader(isr); Map<String, String> wwid_name = ExcelHandle.getWWID(bf); for (String key : wwid_name.keySet()) { System.out.println(key + ":" + wwid_name.get(key)); } List<List<String>> list = ExcelHandle.read("cmdb_ci_hardware.xlsx"); List<List<String>> l = getMediaTeamInfo(wwid_name, list); for (List<String> ls : l) { System.out.println(ls.get(1)); } } }
/* * Copyright 2015-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.hal.client.configuration.subsystem.elytron; import java.util.List; import java.util.Map; import java.util.function.Consumer; import javax.inject.Inject; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import org.jboss.hal.ballroom.LabelBuilder; import org.jboss.hal.ballroom.form.Form; import org.jboss.hal.core.ComplexAttributeOperations; import org.jboss.hal.core.CrudOperations; import org.jboss.hal.core.finder.Finder; import org.jboss.hal.core.finder.FinderPath; import org.jboss.hal.core.finder.FinderPathFactory; import org.jboss.hal.core.mbui.MbuiPresenter; import org.jboss.hal.core.mbui.MbuiView; import org.jboss.hal.core.mbui.dialog.AddResourceDialog; import org.jboss.hal.core.mbui.dialog.NameItem; import org.jboss.hal.core.mbui.form.ModelNodeForm; import org.jboss.hal.core.mvp.SupportsExpertMode; import org.jboss.hal.dmr.ModelDescriptionConstants; import org.jboss.hal.dmr.ModelNode; import org.jboss.hal.dmr.NamedNode; import org.jboss.hal.dmr.ResourceAddress; import org.jboss.hal.meta.Metadata; import org.jboss.hal.meta.MetadataRegistry; import org.jboss.hal.meta.StatementContext; import org.jboss.hal.meta.token.NameTokens; import org.jboss.hal.resources.Ids; import org.jboss.hal.resources.Names; import org.jboss.hal.resources.Resources; import org.jboss.hal.spi.Requires; import static java.util.Arrays.asList; import static org.jboss.hal.client.configuration.subsystem.elytron.AddressTemplates.*; import static org.jboss.hal.dmr.ModelDescriptionConstants.*; import static org.jboss.hal.dmr.ModelNodeHelper.asNamedNodes; public class MapperDecoderPresenter extends MbuiPresenter<MapperDecoderPresenter.MyView, MapperDecoderPresenter.MyProxy> implements SupportsExpertMode { private final CrudOperations crud; private final FinderPathFactory finderPathFactory; private final StatementContext statementContext; private final Resources resources; private ComplexAttributeOperations ca; private MetadataRegistry metadataRegistry; @Inject public MapperDecoderPresenter(EventBus eventBus, MapperDecoderPresenter.MyView view, MapperDecoderPresenter.MyProxy proxy, Finder finder, CrudOperations crud, ComplexAttributeOperations ca, FinderPathFactory finderPathFactory, StatementContext statementContext, MetadataRegistry metadataRegistry, Resources resources) { super(eventBus, view, proxy, finder); this.crud = crud; this.ca = ca; this.finderPathFactory = finderPathFactory; this.statementContext = statementContext; this.metadataRegistry = metadataRegistry; this.resources = resources; } @Override protected void onBind() { super.onBind(); getView().setPresenter(this); } @Override public ResourceAddress resourceAddress() { return ELYTRON_SUBSYSTEM_TEMPLATE.resolve(statementContext); } @Override public FinderPath finderPath() { return finderPathFactory.configurationSubsystemPath(Ids.ELYTRON) .append(Ids.ELYTRON, Ids.ELYTRON_MAPPERS_DECODERS, resources.constants().settings(), Names.MAPPERS_DECODERS); } @Override protected void reload() { ResourceAddress address = ELYTRON_SUBSYSTEM_TEMPLATE.resolve(statementContext); crud.readChildren(address, asList( ElytronResource.ADD_PREFIX_ROLE_MAPPER.resource, ElytronResource.ADD_SUFFIX_ROLE_MAPPER.resource, ElytronResource.AGGREGATE_PRINCIPAL_DECODER.resource, ElytronResource.AGGREGATE_ROLE_MAPPER.resource, ElytronResource.CONCATENATING_PRINCIPAL_DECODER.resource, ElytronResource.CONSTANT_PERMISSION_MAPPER.resource, ElytronResource.CONSTANT_PRINCIPAL_DECODER.resource, ElytronResource.CONSTANT_ROLE_MAPPER.resource, ElytronResource.CUSTOM_PERMISSION_MAPPER.resource, ElytronResource.CUSTOM_PRINCIPAL_DECODER.resource, ElytronResource.CUSTOM_ROLE_DECODER.resource, ElytronResource.CUSTOM_ROLE_MAPPER.resource, ElytronResource.LOGICAL_PERMISSION_MAPPER.resource, ElytronResource.LOGICAL_ROLE_MAPPER.resource, ElytronResource.MAPPED_ROLE_MAPPER.resource, ElytronResource.SIMPLE_PERMISSION_MAPPER.resource, ElytronResource.SIMPLE_ROLE_DECODER.resource, ElytronResource.X500_ATTRIBUTE_PRINCIPAL_DECODER.resource), result -> { // @formatter:off int i = 0; getView().updateAddPrefixRoleMapper(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); getView().updateAddSuffixRoleMapper(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); getView().updateAggregatePrincipalDecoder(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); getView().updateAggregateRoleMapper(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); getView().updateConcatenatingPrincipalDecoder(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); getView().updateConstantPermissionMapper(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); getView().updateConstantPrincipalDecoder(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); getView().updateConstantRoleMapper(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); getView().updateCustomPermissionMapper(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); getView().updateCustomPrincipalDecoder(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); getView().updateCustomRoleDecoder(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); getView().updateCustomRoleMapper(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); getView().updateLogicalPermissionMapper(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); getView().updateLogicalRoleMapper(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); getView().updateMappedRoleMapper(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); getView().updateSimplePermissionMapper(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); getView().updateSimpleRoleDecoder(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); getView().updateX500AttributePrincipalDecoder(asNamedNodes(result.step(i++).get(RESULT).asPropertyList())); // @formatter:on }); } void reload(String resource, Consumer<List<NamedNode>> callback) { crud.readChildren(AddressTemplates.ELYTRON_SUBSYSTEM_TEMPLATE, resource, children -> callback.accept(asNamedNodes(children))); } // -------------------------------------------- Simple Permission Mapper void reloadSimplePermissionMapper() { crud.readChildren(AddressTemplates.ELYTRON_SUBSYSTEM_TEMPLATE, ModelDescriptionConstants.SIMPLE_PERMISSION_MAPPER, children -> getView().updateSimplePermissionMapper(asNamedNodes(children))); } void saveSimplePermissionMapping(String name, Map<String, Object> changedValues) { crud.save(Names.SIMPLE_PERMISSION_MAPPER, name, AddressTemplates.SIMPLE_PERMISSION_MAPPER_TEMPLATE, changedValues, this::reloadSimplePermissionMapper); } void addPermissionMappings(String resource) { ca.listAdd(Ids.ELYTRON_PERMISSION_MAPPINGS_ADD, resource, PERMISSION_MAPPINGS, Names.PERMISSION_MAPPINGS, SIMPLE_PERMISSION_MAPPER_TEMPLATE, this::reloadSimplePermissionMapper); } void removePermissionMappings(String resource, int index) { ca.remove(resource, PERMISSION_MAPPINGS, Names.PERMISSION_MAPPINGS, index, SIMPLE_PERMISSION_MAPPER_TEMPLATE, this::reloadSimplePermissionMapper); } void savePermissionMappings(String resource, int i, Map<String, Object> changedValues) { ResourceAddress address = SIMPLE_PERMISSION_MAPPER_TEMPLATE.resolve(statementContext, resource); Metadata metadata = metadataRegistry.lookup(SIMPLE_PERMISSION_MAPPER_TEMPLATE) .forComplexAttribute(PERMISSION_MAPPINGS); ca.save(PERMISSION_MAPPINGS, Names.PERMISSION_MAPPINGS, i, address, changedValues, metadata, this::reloadSimplePermissionMapper); } void addPermissions(String resource, int pmIndex) { Metadata metadata = metadataRegistry.lookup(SIMPLE_PERMISSION_MAPPER_TEMPLATE) .forComplexAttribute(PERMISSION_MAPPINGS) .forComplexAttribute(PERMISSIONS); Form<ModelNode> form = new ModelNodeForm.Builder<>(Ids.ELYTRON_PERMISSIONS_ADD, metadata) .addOnly() //.include(TO, INDEX) .build(); AddResourceDialog dialog = new AddResourceDialog(resources.messages().addResourceTitle(Names.PERMISSIONS), form, (name, model) -> ca.listAdd(resource, permissionsAttribute(pmIndex), Names.PERMISSIONS, SIMPLE_PERMISSION_MAPPER_TEMPLATE, model, this::reloadSimplePermissionMapper)); dialog.show(); } void removePermissions(String resource, int pmIndex, int permissionsIndex) { ca.remove(resource, permissionsAttribute(pmIndex), Names.PERMISSIONS, permissionsIndex, SIMPLE_PERMISSION_MAPPER_TEMPLATE, this::reloadSimplePermissionMapper); } void savePermissions(String resource, int pmIndex, int permissionsIndex, Map<String, Object> changedValues) { ResourceAddress address = SIMPLE_PERMISSION_MAPPER_TEMPLATE.resolve(statementContext, resource); Metadata metadata = metadataRegistry.lookup(SIMPLE_PERMISSION_MAPPER_TEMPLATE) .forComplexAttribute(PERMISSION_MAPPINGS) .forComplexAttribute(PERMISSIONS); ca.save(permissionsAttribute(pmIndex), Names.PERMISSIONS, permissionsIndex, address, changedValues, metadata, this::reloadSimplePermissionMapper); } private String permissionsAttribute(int pmIndex) { return PERMISSION_MAPPINGS + "[" + pmIndex + "]." + PERMISSIONS; } // -------------------------------------------- Mapped Role Mapper void addMappedRoleMapper() { Metadata metadata = metadataRegistry.lookup(MAPPED_ROLE_MAPPER_TEMPLATE); String id = Ids.build(Ids.ELYTRON_MAPPED_ROLE_MAPPER, Ids.ADD); Form<ModelNode> form = new ModelNodeForm.Builder<>(id, metadata) .unboundFormItem(new NameItem(), 0) .customFormItem(ROLE_MAP, desc -> new RoleMapListItem(ROLE_MAP, new LabelBuilder().label(ROLE_MAP))) .addOnly() .build(); String title = new LabelBuilder().label(MAPPED_ROLE_MAPPER); new AddResourceDialog(title, form, (name, payload) -> { // :add(role-map=[role1 => [role2,role3],role2 => [mane,m2n3]]) crud.add(title, name, MAPPED_ROLE_MAPPER_TEMPLATE, payload, (name1, address) -> reload()); }).show(); } @ProxyCodeSplit @Requires(value = { ADD_PREFIX_ROLE_MAPPER_ADDRESS, ADD_SUFFIX_ROLE_MAPPER_ADDRESS, AGGREGATE_PRINCIPAL_DECODER_ADDRESS, AGGREGATE_ROLE_MAPPER_ADDRESS, CONCATENATING_PRINCIPAL_DECODER_ADDRESS, CONSTANT_PERMISSION_MAPPER_ADDRESS, CONSTANT_PRINCIPAL_DECODER_ADDRESS, CONSTANT_ROLE_MAPPER_ADDRESS, CUSTOM_PERMISSION_MAPPER_ADDRESS, CUSTOM_PRINCIPAL_DECODER_ADDRESS, CUSTOM_ROLE_DECODER_ADDRESS, CUSTOM_ROLE_MAPPER_ADDRESS, LOGICAL_PERMISSION_MAPPER_ADDRESS, LOGICAL_ROLE_MAPPER_ADDRESS, MAPPED_ROLE_MAPPER_ADDRESS, SIMPLE_PERMISSION_MAPPER_ADDRESS, SIMPLE_ROLE_DECODER_ADDRESS, X500_ATTRIBUTE_PRINCIPAL_DECODER_ADDRESS}) @NameToken(NameTokens.ELYTRON_MAPPERS_DECODERS) public interface MyProxy extends ProxyPlace<MapperDecoderPresenter> { } // @formatter:off public interface MyView extends MbuiView<MapperDecoderPresenter> { void updateAddPrefixRoleMapper(List<NamedNode> model); void updateAddSuffixRoleMapper(List<NamedNode> model); void updateAggregatePrincipalDecoder(List<NamedNode> model); void updateAggregateRoleMapper(List<NamedNode> model); void updateConcatenatingPrincipalDecoder(List<NamedNode> model); void updateConstantPermissionMapper(List<NamedNode> model); void updateConstantPrincipalDecoder(List<NamedNode> model); void updateConstantRoleMapper(List<NamedNode> model); void updateCustomPermissionMapper(List<NamedNode> model); void updateCustomPrincipalDecoder(List<NamedNode> model); void updateCustomRoleDecoder(List<NamedNode> model); void updateCustomRoleMapper(List<NamedNode> model); void updateLogicalPermissionMapper(List<NamedNode> model); void updateLogicalRoleMapper(List<NamedNode> model); void updateMappedRoleMapper(List<NamedNode> model); void updateSimplePermissionMapper(List<NamedNode> model); void updateSimpleRoleDecoder(List<NamedNode> model); void updateX500AttributePrincipalDecoder(List<NamedNode> model); } // @formatter:on }
/** * Copyright 2010-2016 Boxfuse GmbH * * 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.flywaydb.core.internal.info; import org.flywaydb.core.api.MigrationInfo; import org.flywaydb.core.api.MigrationState; import org.flywaydb.core.api.MigrationType; import org.flywaydb.core.api.MigrationVersion; import org.flywaydb.core.internal.metadatatable.AppliedMigration; import org.flywaydb.core.internal.metadatatable.MetaDataTable; import org.flywaydb.core.api.resolver.MigrationResolver; import org.flywaydb.core.api.resolver.ResolvedMigration; import org.flywaydb.core.internal.resolver.ResolvedMigrationImpl; import org.junit.Test; import java.util.Arrays; import java.util.Date; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Test for MigrationInfoServiceImpl. */ public class MigrationInfoServiceImplSmallTest { @Test public void onlyPending() { MigrationInfoServiceImpl migrationInfoService = new MigrationInfoServiceImpl( createMigrationResolver(createResolvedMigration(1), createResolvedMigration(2)), createMetaDataTable(), MigrationVersion.LATEST, false, true, true); migrationInfoService.refresh(); assertNull(migrationInfoService.current()); assertEquals(2, migrationInfoService.all().length); assertEquals(2, migrationInfoService.pending().length); } @Test public void allApplied() { MigrationInfoServiceImpl migrationInfoService = new MigrationInfoServiceImpl( createMigrationResolver(createResolvedMigration(1), createResolvedMigration(2)), createMetaDataTable(createAppliedMigration(1), createAppliedMigration(2)), MigrationVersion.LATEST, false, true, true); migrationInfoService.refresh(); assertEquals("2", migrationInfoService.current().getVersion().toString()); assertEquals(2, migrationInfoService.all().length); assertEquals(0, migrationInfoService.pending().length); } @Test public void appliedOverridesAvailable() { MigrationInfoServiceImpl migrationInfoService = new MigrationInfoServiceImpl( createMigrationResolver(createResolvedMigration(1)), createMetaDataTable(createAppliedMigration(1, "xyz")), MigrationVersion.LATEST, false, true, true); migrationInfoService.refresh(); assertEquals("1", migrationInfoService.current().getVersion().toString()); assertEquals("xyz", migrationInfoService.current().getDescription()); assertEquals(1, migrationInfoService.all().length); assertEquals(0, migrationInfoService.pending().length); } @Test public void onePendingOneApplied() { MigrationInfoServiceImpl migrationInfoService = new MigrationInfoServiceImpl( createMigrationResolver(createResolvedMigration(1), createResolvedMigration(2)), createMetaDataTable(createAppliedMigration(1)), MigrationVersion.LATEST, false, true, true); migrationInfoService.refresh(); assertEquals("1", migrationInfoService.current().getVersion().toString()); assertEquals(2, migrationInfoService.all().length); assertEquals(1, migrationInfoService.pending().length); } @Test public void oneAppliedOneSkipped() { MigrationInfoServiceImpl migrationInfoService = new MigrationInfoServiceImpl( createMigrationResolver(createResolvedMigration(1), createResolvedMigration(2)), createMetaDataTable(createAppliedMigration(2)), MigrationVersion.LATEST, false, true, true); migrationInfoService.refresh(); assertEquals("2", migrationInfoService.current().getVersion().toString()); assertEquals(MigrationState.IGNORED, migrationInfoService.all()[0].getState()); assertEquals(2, migrationInfoService.all().length); assertEquals(0, migrationInfoService.pending().length); } @Test public void twoAppliedOnePending() { MigrationInfoServiceImpl migrationInfoService = new MigrationInfoServiceImpl( createMigrationResolver(createResolvedMigration(1), createResolvedMigration(2), createResolvedMigration(3)), createMetaDataTable(createAppliedMigration(1), createAppliedMigration(3)), MigrationVersion.LATEST, true, true, true); migrationInfoService.refresh(); assertEquals("3", migrationInfoService.current().getVersion().toString()); final MigrationInfo[] all = migrationInfoService.all(); assertEquals(3, all.length); assertEquals(MigrationState.SUCCESS, all[0].getState()); assertEquals(MigrationState.SUCCESS, all[1].getState()); assertEquals(MigrationState.PENDING, all[2].getState()); assertEquals(1, migrationInfoService.pending().length); } @Test public void twoAppliedOneFuture() { MigrationInfoServiceImpl migrationInfoService = new MigrationInfoServiceImpl( createMigrationResolver(createResolvedMigration(1)), createMetaDataTable(createAppliedMigration(1), createAppliedMigration(2)), MigrationVersion.LATEST, false, true, true); migrationInfoService.refresh(); assertEquals("2", migrationInfoService.current().getVersion().toString()); assertEquals(MigrationState.FUTURE_SUCCESS, migrationInfoService.current().getState()); assertEquals(MigrationState.FUTURE_SUCCESS, migrationInfoService.future()[0].getState()); assertEquals(2, migrationInfoService.all().length); assertEquals(0, migrationInfoService.pending().length); } @Test public void belowBaseline() { MigrationInfoServiceImpl migrationInfoService = new MigrationInfoServiceImpl( createMigrationResolver(createResolvedMigration(1)), createMetaDataTable(createAppliedBaselineMigration(2)), MigrationVersion.LATEST, false, true, true); migrationInfoService.refresh(); assertEquals("2", migrationInfoService.current().getVersion().toString()); assertEquals(MigrationState.BELOW_BASELINE, migrationInfoService.all()[0].getState()); assertEquals(2, migrationInfoService.all().length); assertEquals(0, migrationInfoService.pending().length); } @Test public void missing() { MigrationInfoServiceImpl migrationInfoService = new MigrationInfoServiceImpl( createMigrationResolver(createResolvedMigration(2)), createMetaDataTable(createAppliedMigration(1), createAppliedMigration(2)), MigrationVersion.LATEST, false, true, true); migrationInfoService.refresh(); assertEquals("2", migrationInfoService.current().getVersion().toString()); assertEquals(MigrationState.MISSING_SUCCESS, migrationInfoService.all()[0].getState()); assertEquals(2, migrationInfoService.all().length); assertEquals(0, migrationInfoService.pending().length); } @Test public void schemaCreation() { MigrationInfoServiceImpl migrationInfoService = new MigrationInfoServiceImpl( createMigrationResolver(createResolvedMigration(1)), createMetaDataTable(createAppliedSchemaMigration(), createAppliedMigration(1)), MigrationVersion.LATEST, false, true, true); migrationInfoService.refresh(); assertEquals("1", migrationInfoService.current().getVersion().toString()); assertEquals(MigrationState.SUCCESS, migrationInfoService.all()[0].getState()); assertEquals(MigrationState.SUCCESS, migrationInfoService.all()[1].getState()); assertEquals(2, migrationInfoService.all().length); assertEquals(0, migrationInfoService.pending().length); } /** * Creates a new resolved migration with this version. * * @param version The version of the migration. * @return The resolved migration. */ private ResolvedMigration createResolvedMigration(int version) { ResolvedMigrationImpl migration = new ResolvedMigrationImpl(); migration.setVersion(MigrationVersion.fromVersion(Integer.toString(version))); migration.setDescription("abc"); migration.setScript("x"); migration.setType(MigrationType.SQL); return migration; } /** * Creates a new applied migration with this version. * * @param version The version of the migration. * @return The applied migration. */ private AppliedMigration createAppliedMigration(int version) { return createAppliedMigration(version, "x"); } /** * Creates a new applied migration with this version. * * @param version The version of the migration. * @param description The description of the migration. * @return The applied migration. */ private AppliedMigration createAppliedMigration(int version, String description) { return new AppliedMigration(version, MigrationVersion.fromVersion(Integer.toString(version)), description, MigrationType.SQL, "x", null, new Date(), "sa", 123, true); } /** * Creates a new applied baseline migration with this version. * * @param version The version of the migration. * @return The applied baseline migration. */ private AppliedMigration createAppliedBaselineMigration(int version) { return new AppliedMigration(version, MigrationVersion.fromVersion(Integer.toString(version)), "abc", MigrationType.BASELINE, "x", null, new Date(), "sa", 0, true); } /** * Creates a new applied schema migration with this version. * * @return The applied schema migration. */ private AppliedMigration createAppliedSchemaMigration() { return new AppliedMigration(0, MigrationVersion.fromVersion(Integer.toString(0)), "<< Schema Creation >>", MigrationType.SCHEMA, "x", null, new Date(), "sa", 0, true); } /** * Creates a migrationResolver for testing. * * @param resolvedMigrations The resolved migrations. * @return The migration resolver. */ private MigrationResolver createMigrationResolver(final ResolvedMigration... resolvedMigrations) { return new MigrationResolver() { public List<ResolvedMigration> resolveMigrations() { return Arrays.asList(resolvedMigrations); } }; } /** * Creates a metadata table for testing. * * @param appliedMigrations The applied migrations. * @return The metadata table. */ private MetaDataTable createMetaDataTable(final AppliedMigration... appliedMigrations) { MetaDataTable metaDataTable = mock(MetaDataTable.class); when(metaDataTable.allAppliedMigrations()).thenReturn(Arrays.asList(appliedMigrations)); return metaDataTable; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.cloud; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.request.QueryRequest; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.cloud.ClusterState; import org.apache.solr.common.cloud.DocCollection; import org.apache.solr.common.cloud.Replica; import org.apache.solr.common.cloud.Slice; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.common.params.CollectionParams.CollectionAction; import org.apache.solr.common.params.ModifiableSolrParams; import org.junit.Test; /** Test sync phase that occurs when Leader goes down and a new Leader is elected. */ public abstract class AbstractSyncSliceTestBase extends AbstractFullDistribZkTestBase { private boolean success = false; @Override public void distribTearDown() throws Exception { if (!success) { printLayoutOnTearDown = true; } super.distribTearDown(); } public AbstractSyncSliceTestBase() { super(); sliceCount = 1; fixShardCount(TEST_NIGHTLY ? 7 : 4); } @Test public void test() throws Exception { handle.clear(); handle.put("timestamp", SKIPVAL); waitForThingsToLevelOut(30, TimeUnit.SECONDS); del("*:*"); List<CloudJettyRunner> skipServers = new ArrayList<>(); int docId = 0; indexDoc( skipServers, id, docId++, i1, 50, tlong, 50, t1, "to come to the aid of their country."); indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1, "old haven was blue."); skipServers.add(shardToJetty.get("shard1").get(1)); indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1, "but the song was fancy."); skipServers.add(shardToJetty.get("shard1").get(2)); indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1, "under the moon and over the lake"); commit(); waitForRecoveriesToFinish(false); // shard should be inconsistent String shardFailMessage = checkShardConsistency("shard1", true, false); assertNotNull(shardFailMessage); ModifiableSolrParams params = new ModifiableSolrParams(); params.set("action", CollectionAction.SYNCSHARD.toString()); params.set("collection", "collection1"); params.set("shard", "shard1"); QueryRequest request = new QueryRequest(params); request.setPath("/admin/collections"); String baseUrl = ((HttpSolrClient) shardToJetty.get("shard1").get(2).client.solrClient).getBaseURL(); baseUrl = baseUrl.substring(0, baseUrl.length() - "collection1".length()); // we only set the connect timeout, not so timeout try (HttpSolrClient baseClient = getHttpSolrClient(baseUrl, 30000)) { baseClient.request(request); } waitForThingsToLevelOut(15, TimeUnit.SECONDS); checkShardConsistency(false, true); long cloudClientDocs = cloudClient.query(new SolrQuery("*:*")).getResults().getNumFound(); assertEquals(4, cloudClientDocs); // kill the leader - new leader could have all the docs or be missing one CloudJettyRunner leaderJetty = shardToLeaderJetty.get("shard1"); skipServers = getRandomOtherJetty(leaderJetty, null); // but not the leader // this doc won't be on one node indexDoc( skipServers, id, docId++, i1, 50, tlong, 50, t1, "to come to the aid of their country."); commit(); Set<CloudJettyRunner> jetties = new HashSet<>(); jetties.addAll(shardToJetty.get("shard1")); jetties.remove(leaderJetty); assertEquals(getShardCount() - 1, jetties.size()); leaderJetty.jetty.stop(); Thread.sleep(3000); waitForNoShardInconsistency(); Thread.sleep(1000); checkShardConsistency(false, true); cloudClientDocs = cloudClient.query(new SolrQuery("*:*")).getResults().getNumFound(); assertEquals(5, cloudClientDocs); CloudJettyRunner deadJetty = leaderJetty; // let's get the latest leader while (deadJetty == leaderJetty) { updateMappingsFromZk(this.jettys, this.clients); leaderJetty = shardToLeaderJetty.get("shard1"); } // bring back dead node deadJetty.jetty.start(); // he is not the leader anymore waitTillAllNodesActive(); skipServers = getRandomOtherJetty(leaderJetty, deadJetty); skipServers.addAll(getRandomOtherJetty(leaderJetty, deadJetty)); // skip list should be // System.out.println("leader:" + leaderJetty.url); // System.out.println("dead:" + deadJetty.url); // System.out.println("skip list:" + skipServers); // we are skipping 2 nodes assertEquals(2, skipServers.size()); // more docs than can peer sync for (int i = 0; i < 300; i++) { indexDoc( skipServers, id, docId++, i1, 50, tlong, 50, t1, "to come to the aid of their country."); } commit(); Thread.sleep(1000); waitForRecoveriesToFinish(false); // shard should be inconsistent shardFailMessage = waitTillInconsistent(); assertNotNull( "Test Setup Failure: shard1 should have just been set up to be inconsistent - but it's still consistent. Leader:" + leaderJetty.url + " Dead Guy:" + deadJetty.url + "skip list:" + skipServers, shardFailMessage); // good place to test compareResults boolean shouldFail = CloudInspectUtil.compareResults(controlClient, cloudClient); assertTrue("A test that compareResults is working correctly failed", shouldFail); jetties = new HashSet<>(); jetties.addAll(shardToJetty.get("shard1")); jetties.remove(leaderJetty); assertEquals(getShardCount() - 1, jetties.size()); // kill the current leader leaderJetty.jetty.stop(); waitForNoShardInconsistency(); checkShardConsistency(true, true); success = true; } private void waitTillAllNodesActive() throws Exception { for (int i = 0; i < 60; i++) { Thread.sleep(3000); ZkStateReader zkStateReader = cloudClient.getZkStateReader(); ClusterState clusterState = zkStateReader.getClusterState(); DocCollection collection1 = clusterState.getCollection("collection1"); Slice slice = collection1.getSlice("shard1"); Collection<Replica> replicas = slice.getReplicas(); boolean allActive = true; for (Replica replica : replicas) { if (!clusterState.liveNodesContain(replica.getNodeName()) || replica.getState() != Replica.State.ACTIVE) { allActive = false; break; } } if (allActive) { return; } } printLayout(); fail("timeout waiting to see all nodes active"); } private String waitTillInconsistent() throws Exception, InterruptedException { String shardFailMessage = null; shardFailMessage = pollConsistency(shardFailMessage, 0); shardFailMessage = pollConsistency(shardFailMessage, 3000); shardFailMessage = pollConsistency(shardFailMessage, 5000); shardFailMessage = pollConsistency(shardFailMessage, 15000); return shardFailMessage; } private String pollConsistency(String shardFailMessage, int sleep) throws InterruptedException, Exception { try { commit(); } catch (Throwable t) { t.printStackTrace(); } if (shardFailMessage == null) { // try again Thread.sleep(sleep); shardFailMessage = checkShardConsistency("shard1", true, false); } return shardFailMessage; } private List<CloudJettyRunner> getRandomOtherJetty( CloudJettyRunner leader, CloudJettyRunner down) { List<CloudJettyRunner> skipServers = new ArrayList<>(); List<CloudJettyRunner> candidates = new ArrayList<>(); candidates.addAll(shardToJetty.get("shard1")); if (leader != null) { candidates.remove(leader); } if (down != null) { candidates.remove(down); } CloudJettyRunner cjetty = candidates.get(random().nextInt(candidates.size())); skipServers.add(cjetty); return skipServers; } protected void indexDoc(List<CloudJettyRunner> skipServers, Object... fields) throws IOException, SolrServerException { SolrInputDocument doc = new SolrInputDocument(); addFields(doc, fields); addFields(doc, "rnd_b", true); controlClient.add(doc); UpdateRequest ureq = new UpdateRequest(); ureq.add(doc); ModifiableSolrParams params = new ModifiableSolrParams(); for (CloudJettyRunner skip : skipServers) { params.add("test.distrib.skip.servers", skip.url + "/"); } ureq.setParams(params); ureq.process(cloudClient); } // skip the randoms - they can deadlock... @Override protected void indexr(Object... fields) throws Exception { SolrInputDocument doc = new SolrInputDocument(); addFields(doc, fields); addFields(doc, "rnd_b", true); indexDoc(doc); } }
package org.webcurator.domain.model.core; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import org.webcurator.core.harvester.agent.HarvesterStatusUtil; import org.webcurator.core.util.ConverterUtil; import org.webcurator.domain.model.auth.Agency; /** * An <code>Indicator</code> represents a metric used to measure the * quality of a harvest and is associated with a specific <code>TargetInstance</code> * * @author twoods * * @hibernate.class table="INDICATOR" lazy="true" * @hibernate.query name="org.webcurator.domain.model.core.Indicator.getIndicators" query="SELECT i FROM Indicator i ORDER BY i_agc_oid, i.name" * @hibernate.query name="org.webcurator.domain.model.core.Indicator.getIndicatorsByTargetInstance" query="SELECT i FROM Indicator i WHERE i_ti_oid=? ORDER BY i.name" * @hibernate.query name="org.webcurator.domain.model.core.Indicator.getIndicatorByOid" query="SELECT i FROM Indicator i WHERE i_oid=?" */ public class Indicator { /** Query key for retrieving all reason objects */ public static final String QRY_GET_INDICATORS = "org.webcurator.domain.model.core.Indicator.getIndicators"; /** Query key for retrieving reason objects by agency OID */ public static final String QRY_GET_INDICATORS_BY_TI_OID = "org.webcurator.domain.model.core.Indicator.getIndicatorsByTargetInstance"; /** Query key for retrieving a reason objects by oid*/ public static final String QRY_GET_INDICATOR_BY_OID = "org.webcurator.domain.model.core.Indicator.getIndicatorByOid"; /** unique identifier **/ private Long oid; /** The <code>Indicator</code> on which this <code>Indicator</code> is based.**/ private IndicatorCriteria indicatorCriteria; /** The <code>TargetInstance</code> oid associated with this <code>Indicator</code> */ private Long targetInstanceOid; /** The name of the <code>Indicator</code> that will be displayed **/ private String name; /** The floating point value calculated for this <code>Indicator</code> by the rules engine **/ private Float floatValue; /** The upper limit set for this <code>Indicator</code> as a percentage (eg: +10%) **/ private Float upperLimitPercentage; /** The lower limit set for this <code>Indicator</code> as a percentage (eg: -10%) **/ private Float lowerLimitPercentage; /** The upper limit set for this <code>Indicator</code> as a floating point number (some <code>Indicators</code> do not have associated percentage limits) **/ private Float upperLimit; /** The lower limit set for this <code>Indicator</code> as a floating point number (some <code>Indicators</code> do not have associated percentage limits) **/ private Float lowerLimit; /** The advice issued for this <code>Indicator</code> * based on the supporting facts established by the rules engine. **/ private String advice = null; /** * The unit of measurement used for the <code>Indicator</code>. */ private String unit = null; /** * Display the delta between the reference crawl and the <code>TargetInstance</code> in the UI */ private Boolean showDelta = false; /** * The advice justification for this <code>Indicator</code> * based on the supporting facts established by the rules engine. */ private String justification = null; /** The agency the <code>Indicator</code> belongs to */ private Agency agency; /** The date and time on which this <code>Indicator</code> was created or updated **/ private Date dateTime = null; /** The report lines that are generated for this <code>Indicator</code>s report **/ public List<IndicatorReportLine> indicatorReportLines = new LinkedList<IndicatorReportLine>(); /** * Get the database OID of the <code>Indicator</code>. * @return the primary key * @hibernate.id column="I_OID" generator-class="org.hibernate.id.MultipleHiLoPerTableGenerator" * @hibernate.generator-param name="table" value="ID_GENERATOR" * @hibernate.generator-param name="primary_key_column" value="IG_TYPE" * @hibernate.generator-param name="value_column" value="IG_VALUE" * @hibernate.generator-param name="primary_key_value" value="General" */ public Long getOid() { return oid; } /** * Set the database oid of the <code>Indicator</code>. * @param oid The new database oid. */ public void setOid(Long oid) { this.oid = oid; } /** * Get the <code>IndicatorCriteria</code> that this <code>Indicator</code> is associated with. * @return Returns the <code>IndicatorCriteria</code>. * @hibernate.many-to-one not-null="true" column="I_IC_OID" foreign-key="FK_I_IC_OID" */ public IndicatorCriteria getIndicatorCriteria() { return indicatorCriteria; } /** * Set the <code>IndicatorCriteria</code> for the <code>Indicator</code>. * @param indicatorCriteria The <code>IndicatorCriteria</code> to set. */ public void setIndicatorCriteria(IndicatorCriteria indicatorCriteria) { this.indicatorCriteria = indicatorCriteria; } /** * Gets the name of the <code>Indicator</code>. * @return Returns the name. * @hibernate.property column="I_NAME" not-null="true" */ public String getName() { return name; } /** * Get the <code>TargetInstance</code> oid that this <code>Indicator</code> is associated with. * @return Returns the <code>TargetInstance</code>. * @hibernate.property column="I_TI_OID" */ public Long getTargetInstanceOid() { return targetInstanceOid; } /** * Set the <code>TargetInstance</code> oid for the <code>Indicator</code>. * @param targetInstanceOid The <code>TargetInstance</code> oid to set. */ public void setTargetInstanceOid(Long targetInstanceOid) { this.targetInstanceOid = targetInstanceOid; } /** * Sets the name of the <code>Indicator</code>. * @param name The new name for the <code>Indicator</code>. */ public void setName(String name) { this.name = name; } /** * Gets the value of the <code>Indicator</code>. * @return Returns the floating point value. * @hibernate.property column="I_FLOAT_VALUE" not-null="true" */ public Float getFloatValue() { return floatValue; } /** * Sets the value of the <code>Indicator</code>. * @param name The new value for the <code>Indicator</code>. */ public void setFloatValue(Float floatValue) { this.floatValue = floatValue; } /** * Gets the upper limit percentage value of the <code>Indicator</code>. * @return Returns the upper limit percentage value. * @hibernate.property column="I_UPPER_LIMIT_PERCENTAGE" */ public Float getUpperLimitPercentage() { return upperLimitPercentage; } /** * Sets the upper limit percentage value of the <code>Indicator</code>. * @param name The new upper limit percentage value for the <code>Indicator</code>. */ public void setUpperLimitPercentage(Float floatValue) { this.upperLimitPercentage = floatValue; } /** * Gets the lower limit percentage value of the <code>Indicator</code>. * @return Returns the lower limit percentage value. * @hibernate.property column="I_LOWER_LIMIT_PERCENTAGE" */ public Float getLowerLimitPercentage() { return lowerLimitPercentage; } /** * Sets the lower limit percentage value of the <code>Indicator</code>. * @param name The new lower limit percentage value for the <code>Indicator</code>. */ public void setLowerLimitPercentage(Float floatValue) { this.lowerLimitPercentage = floatValue; } /** * Gets the upper limit value of the <code>Indicator</code>. * @return Returns the upper limit value. * @hibernate.property column="I_UPPER_LIMIT" */ public Float getUpperLimit() { return upperLimit; } /** * Sets the upper limit value of the <code>Indicator</code>. * @param name The new upper limit value for the <code>Indicator</code>. */ public void setUpperLimit(Float floatValue) { this.upperLimit = floatValue; } /** * Gets the lower limit value of the <code>Indicator</code>. * @return Returns the lower limit value. * @hibernate.property column="I_LOWER_LIMIT" */ public Float getLowerLimit() { return lowerLimit; } /** * Sets the lower limit value of the <code>Indicator</code>. * @param name The new lower limit value for the <code>Indicator</code>. */ public void setLowerLimit(Float floatValue) { this.lowerLimit = floatValue; } /** * Fetches the advice set by the QA recommendation service * @hibernate.property column="I_ADVICE" * @return the advised action */ public String getAdvice() { return advice; } /** * Used by the QA Recommendation service to set the QA advice * @param advice the advised action */ public void setAdvice(String advice) { this.advice = advice; } /** * Fetches the justification set by the QA recommendation service * @hibernate.property column="I_JUSTIFICATION" * @return the rationale for the advice */ public String getJustification() { return justification; } /** * Used by the QA Recommendation service to set the QA justification * @param the advice justification */ public void setJustification(String justification) { this.justification = justification; } /** * gets the Agency to which this <code>Indicator</code> belongs. * @return the Agency object * @hibernate.many-to-one not-null="true" class="org.webcurator.domain.model.auth.Agency" column="I_AGC_OID" foreign-key="FK_I_AGENCY_OID" */ public Agency getAgency() { return agency; } /** * Set the agency which can use this <code>Indicator</code>. * @param agency The agency that can use this <code>Indicator</code>. */ public void setAgency(Agency agency) { this.agency = agency; } /** * fetches the <code>Indicator</code>s unit of measurement * @hibernate.property column="I_UNIT" not-null="true" * @return the unit of measurement (eg: integer, millisecond, byte) */ public String getUnit() { return unit; } /** * sets the unit of measurement for this <code>Indicator</code> (eg: integer, millisecond, byte) */ public void setUnit(String unit) { this.unit = unit; } /** * fetches the <code>Indicator</code>s delta visibility * @hibernate.property column="I_SHOW_DELTA" not-null="true" * @return true if the delta for the <code>Indicator</code> should be displayed in the UI, false otherwise */ public Boolean getShowDelta() { return showDelta; } /** * sets the delta display visibility for this <code>Indicator</code> */ public void setShowDelta(Boolean showDelta) { this.showDelta = showDelta; } /** * Get time that the <code>Indicator<code> was generated * @return Date created * @hibernate.property type="timestamp" * @hibernate.column name="I_DATE" not-null="true" sql-type="TIMESTAMP(9)" */ public Date getDateTime() { return dateTime; } /** * Set the time that the <code>Indicator<code> was generated * @param dateTime */ public void setDateTime(Date dateTime) { this.dateTime = dateTime; } /** * Fetch the <code>IndicatorReportLine</code>s for this <code>Indicator</code> * @hibernate.list cascade="all-delete-orphan" lazy="true" * @hibernate.collection-key column="IRL_I_OID" * @hibernate.collection-index column="IRL_INDEX" * @hibernate.collection-one-to-many class="org.webcurator.domain.model.core.IndicatorReportLine" * @return A <code>List</code> of <code>IndicatorReportLine</code>s for the specified <code>Indicator</code> */ public List<IndicatorReportLine> getIndicatorReportLines() { return indicatorReportLines; } /** * Sets the <code>IndicatorReportLine</code>s for the <code>Indicator<code> * @param indicatorReportLines */ public void setIndicatorReportLines(List<IndicatorReportLine> indicatorReportLines) { this.indicatorReportLines = indicatorReportLines; } /** * Fetch the value of the <code>Indicator</code> as a formatted string as dictated by the <code>Indicator</code>s unit value * @return the formatted string value of the <code>Indicator</code> (eg: 100GB) */ public final String getValue() { return getValueOf(floatValue); } /** * Fetch the value of the supplied float value as a formatted string as dictated by the <code>Indicator</code>s unit value * @return the formatted string value of the supplied float value (eg: 100GB) */ public final String getValueOf(Float floatVal) { String output = null; Integer integerVal = floatVal.intValue(); if (getUnit().equals("integer")) { output = integerVal.toString(); } else if (unit.equals("millisecond")) { output = HarvesterStatusUtil.formatTime(floatVal.longValue()); } else if (unit.equals("byte")) { Long bytes; // scale the number of bytes as appropriate String[] decimal = floatVal.toString().split("\\."); if (decimal.length > 1) { bytes = Long.parseLong(decimal[0]); } else { bytes = Long.parseLong(floatVal.toString()); } output = ConverterUtil.formatBytes(bytes); } else { output = floatVal.toString(); } return output; } public final String toString() { return "oid=" + getOid() + ":name=" + getName() + ":floatValue==" + getFloatValue() + ":advice=" + getAdvice() + ":agency=" + getAgency() + ":lowerLimit=" + getLowerLimit() + ":upperLimit=" + getUpperLimit() + ":lowerLimitPercentage=" + getLowerLimitPercentage() + ":upperLimitPercentage=" + getUpperLimitPercentage() + ":justification=" + getJustification() + ":unit=" + getUnit() + ":targetInstanceOid=" + getTargetInstanceOid() ; } }
/* * 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.db; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import com.google.common.util.concurrent.Uninterruptibles; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.Util; import org.apache.cassandra.cache.KeyCacheKey; import org.apache.cassandra.config.KSMetaData; import org.apache.cassandra.concurrent.ScheduledExecutors; import org.apache.cassandra.db.composites.*; import org.apache.cassandra.db.compaction.CompactionManager; import org.apache.cassandra.db.filter.QueryFilter; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.locator.SimpleStrategy; import org.apache.cassandra.service.CacheService; import org.apache.cassandra.utils.ByteBufferUtil; import static org.junit.Assert.assertEquals; public class KeyCacheTest { private static final String KEYSPACE1 = "KeyCacheTest1"; private static final String COLUMN_FAMILY1 = "Standard1"; private static final String COLUMN_FAMILY2 = "Standard2"; @BeforeClass public static void defineSchema() throws ConfigurationException { SchemaLoader.prepareServer(); SchemaLoader.createKeyspace(KEYSPACE1, SimpleStrategy.class, KSMetaData.optsWithRF(1), SchemaLoader.standardCFMD(KEYSPACE1, COLUMN_FAMILY1), SchemaLoader.standardCFMD(KEYSPACE1, COLUMN_FAMILY2)); } @AfterClass public static void cleanup() { SchemaLoader.cleanupSavedCaches(); } @Test public void testKeyCacheLoad() throws Exception { CompactionManager.instance.disableAutoCompaction(); ColumnFamilyStore store = Keyspace.open(KEYSPACE1).getColumnFamilyStore(COLUMN_FAMILY2); // empty the cache CacheService.instance.invalidateKeyCache(); assertKeyCacheSize(0, KEYSPACE1, COLUMN_FAMILY2); // insert data and force to disk SchemaLoader.insertData(KEYSPACE1, COLUMN_FAMILY2, 0, 100); store.forceBlockingFlush(); // populate the cache SchemaLoader.readData(KEYSPACE1, COLUMN_FAMILY2, 0, 100); assertKeyCacheSize(100, KEYSPACE1, COLUMN_FAMILY2); // really? our caches don't implement the map interface? (hence no .addAll) Map<KeyCacheKey, RowIndexEntry> savedMap = new HashMap<KeyCacheKey, RowIndexEntry>(); for (Iterator<KeyCacheKey> iter = CacheService.instance.keyCache.keyIterator(); iter.hasNext();) { KeyCacheKey k = iter.next(); if (k.desc.ksname.equals(KEYSPACE1) && k.desc.cfname.equals(COLUMN_FAMILY2)) savedMap.put(k, CacheService.instance.keyCache.get(k)); } // force the cache to disk CacheService.instance.keyCache.submitWrite(Integer.MAX_VALUE).get(); CacheService.instance.invalidateKeyCache(); assertKeyCacheSize(0, KEYSPACE1, COLUMN_FAMILY2); CacheService.instance.keyCache.loadSaved(store); assertKeyCacheSize(savedMap.size(), KEYSPACE1, COLUMN_FAMILY2); // probably it's better to add equals/hashCode to RowIndexEntry... for (Map.Entry<KeyCacheKey, RowIndexEntry> entry : savedMap.entrySet()) { RowIndexEntry expected = entry.getValue(); RowIndexEntry actual = CacheService.instance.keyCache.get(entry.getKey()); assertEquals(expected.position, actual.position); assertEquals(expected.columnsIndex(), actual.columnsIndex()); if (expected.isIndexed()) { assertEquals(expected.deletionTime(), actual.deletionTime()); } } } @Test public void testKeyCache() throws ExecutionException, InterruptedException { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(COLUMN_FAMILY1); // just to make sure that everything is clean CacheService.instance.invalidateKeyCache(); // KeyCache should start at size 0 if we're caching X% of zero data. assertKeyCacheSize(0, KEYSPACE1, COLUMN_FAMILY1); DecoratedKey key1 = Util.dk("key1"); DecoratedKey key2 = Util.dk("key2"); Mutation rm; // inserts rm = new Mutation(KEYSPACE1, key1.getKey()); rm.add(COLUMN_FAMILY1, Util.cellname("1"), ByteBufferUtil.EMPTY_BYTE_BUFFER, 0); rm.applyUnsafe(); rm = new Mutation(KEYSPACE1, key2.getKey()); rm.add(COLUMN_FAMILY1, Util.cellname("2"), ByteBufferUtil.EMPTY_BYTE_BUFFER, 0); rm.applyUnsafe(); // to make sure we have SSTable cfs.forceBlockingFlush(); // reads to cache key position cfs.getColumnFamily(QueryFilter.getSliceFilter(key1, COLUMN_FAMILY1, Composites.EMPTY, Composites.EMPTY, false, 10, System.currentTimeMillis())); cfs.getColumnFamily(QueryFilter.getSliceFilter(key2, COLUMN_FAMILY1, Composites.EMPTY, Composites.EMPTY, false, 10, System.currentTimeMillis())); assertKeyCacheSize(2, KEYSPACE1, COLUMN_FAMILY1); Set<SSTableReader> readers = cfs.getDataTracker().getSSTables(); for (SSTableReader reader : readers) reader.acquireReference(); Util.compactAll(cfs, Integer.MAX_VALUE).get(); // after compaction cache should have entries for new SSTables, // but since we have kept a reference to the old sstables, // if we had 2 keys in cache previously it should become 4 assertKeyCacheSize(4, KEYSPACE1, COLUMN_FAMILY1); for (SSTableReader reader : readers) reader.releaseReference(); Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS);; while (ScheduledExecutors.nonPeriodicTasks.getActiveCount() + ScheduledExecutors.nonPeriodicTasks.getQueue().size() > 0); // after releasing the reference this should drop to 2 assertKeyCacheSize(2, KEYSPACE1, COLUMN_FAMILY1); // re-read same keys to verify that key cache didn't grow further cfs.getColumnFamily(QueryFilter.getSliceFilter(key1, COLUMN_FAMILY1, Composites.EMPTY, Composites.EMPTY, false, 10, System.currentTimeMillis())); cfs.getColumnFamily(QueryFilter.getSliceFilter(key2, COLUMN_FAMILY1, Composites.EMPTY, Composites.EMPTY, false, 10, System.currentTimeMillis())); assertKeyCacheSize(2, KEYSPACE1, COLUMN_FAMILY1); } private void assertKeyCacheSize(int expected, String keyspace, String columnFamily) { int size = 0; for (Iterator<KeyCacheKey> iter = CacheService.instance.keyCache.keyIterator(); iter.hasNext();) { KeyCacheKey k = iter.next(); if (k.desc.ksname.equals(keyspace) && k.desc.cfname.equals(columnFamily)) size++; } assertEquals(expected, size); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.mapper; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.UnicodeUtil; import java.util.Arrays; import java.util.Base64; public final class Uid { public static final char DELIMITER = '#'; public static final byte DELIMITER_BYTE = 0x23; private static final int UTF8 = 0xff; private static final int NUMERIC = 0xfe; private static final int BASE64_ESCAPE = 0xfd; private Uid() {} static boolean isURLBase64WithoutPadding(String id) { // We are not lenient about padding chars ('=') otherwise // 'xxx=' and 'xxx' could be considered the same id final int length = id.length(); switch (length & 0x03) { case 0: break; case 1: return false; case 2: // the last 2 symbols (12 bits) are encoding 1 byte (8 bits) // so the last symbol only actually uses 8-6=2 bits and can only take 4 values char last = id.charAt(length - 1); if (last != 'A' && last != 'Q' && last != 'g' && last != 'w') { return false; } break; case 3: // The last 3 symbols (18 bits) are encoding 2 bytes (16 bits) // so the last symbol only actually uses 16-12=4 bits and can only take 16 values last = id.charAt(length - 1); if (last != 'A' && last != 'E' && last != 'I' && last != 'M' && last != 'Q'&& last != 'U'&& last != 'Y' && last != 'c'&& last != 'g'&& last != 'k' && last != 'o' && last != 's' && last != 'w' && last != '0' && last != '4' && last != '8') { return false; } break; default: // number & 0x03 is always in [0,3] throw new AssertionError("Impossible case"); } for (int i = 0; i < length; ++i) { final char c = id.charAt(i); final boolean allowed = (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '-' || c == '_'; if (allowed == false) { return false; } } return true; } static boolean isPositiveNumeric(String id) { for (int i = 0; i < id.length(); ++i) { final char c = id.charAt(i); if (c < '0' || c > '9') { return false; } } return true; } /** With numeric ids, we just fold two consecutive chars in a single byte * and use 0x0f as an end marker. */ private static BytesRef encodeNumericId(String id) { byte[] b = new byte[1 + (id.length() + 1) / 2]; b[0] = (byte) NUMERIC; for (int i = 0; i < id.length(); i += 2) { int b1 = id.charAt(i) - '0'; int b2; if (i + 1 == id.length()) { b2 = 0x0f; // end marker } else { b2 = id.charAt(i + 1) - '0'; } b[1 + i/2] = (byte) ((b1 << 4) | b2); } return new BytesRef(b); } /** With base64 ids, we decode and prepend an escape char in the cases that * it could be mixed up with numeric or utf8 encoding. In the majority of * cases (253/256) the encoded id is exactly the binary form. */ private static BytesRef encodeBase64Id(String id) { byte[] b = Base64.getUrlDecoder().decode(id); if (Byte.toUnsignedInt(b[0]) >= BASE64_ESCAPE) { byte[] newB = new byte[b.length + 1]; newB[0] = (byte) BASE64_ESCAPE; System.arraycopy(b, 0, newB, 1, b.length); b = newB; } return new BytesRef(b, 0, b.length); } private static BytesRef encodeUtf8Id(String id) { byte[] b = new byte[1 + UnicodeUtil.maxUTF8Length(id.length())]; // Prepend a byte that indicates that the content is an utf8 string b[0] = (byte) UTF8; int length = UnicodeUtil.UTF16toUTF8(id, 0, id.length(), b, 1); return new BytesRef(b, 0, length); } /** Encode an id for storage in the index. This encoding is optimized for * numeric and base64 ids, which are encoded in a much denser way than * what UTF8 would do. * @see #decodeId */ public static BytesRef encodeId(String id) { if (id.isEmpty()) { throw new IllegalArgumentException("Ids can't be empty"); } if (isPositiveNumeric(id)) { // common for ids that come from databases with auto-increments return encodeNumericId(id); } else if (isURLBase64WithoutPadding(id)) { // common since it applies to autogenerated ids return encodeBase64Id(id); } else { return encodeUtf8Id(id); } } private static String decodeNumericId(byte[] idBytes, int offset, int len) { assert Byte.toUnsignedInt(idBytes[offset]) == NUMERIC; int length = (len - 1) * 2; char[] chars = new char[length]; for (int i = 1; i < len; ++i) { final int b = Byte.toUnsignedInt(idBytes[offset + i]); final int b1 = (b >>> 4); final int b2 = b & 0x0f; chars[(i - 1) * 2] = (char) (b1 + '0'); if (i == len - 1 && b2 == 0x0f) { length--; break; } chars[(i - 1) * 2 + 1] = (char) (b2 + '0'); } return new String(chars, 0, length); } private static String decodeUtf8Id(byte[] idBytes, int offset, int length) { assert Byte.toUnsignedInt(idBytes[offset]) == UTF8; return new BytesRef(idBytes, offset + 1, length - 1).utf8ToString(); } private static String decodeBase64Id(byte[] idBytes, int offset, int length) { assert Byte.toUnsignedInt(idBytes[offset]) <= BASE64_ESCAPE; if (Byte.toUnsignedInt(idBytes[offset]) == BASE64_ESCAPE) { idBytes = Arrays.copyOfRange(idBytes, offset + 1, offset + length); } else if ((idBytes.length == length && offset == 0) == false) { // no need to copy if it's not a slice idBytes = Arrays.copyOfRange(idBytes, offset, offset + length); } return Base64.getUrlEncoder().withoutPadding().encodeToString(idBytes); } /** Decode an indexed id back to its original form. * @see #encodeId */ public static String decodeId(byte[] idBytes) { return decodeId(idBytes, 0, idBytes.length); } /** Decode an indexed id back to its original form. * @see #encodeId */ public static String decodeId(byte[] idBytes, int offset, int length) { if (length == 0) { throw new IllegalArgumentException("Ids can't be empty"); } final int magicChar = Byte.toUnsignedInt(idBytes[offset]); switch (magicChar) { case NUMERIC: return decodeNumericId(idBytes, offset, length); case UTF8: return decodeUtf8Id(idBytes, offset, length); default: return decodeBase64Id(idBytes, offset, length); } } }
package com.webuml.projectmanager.infrastructure; import com.webuml.projectmanager.domain.metamodel.Association; import com.webuml.projectmanager.domain.metamodel.helper.AssociationRepository; import com.webuml.projectmanager.domain.metamodel.Class; import com.webuml.projectmanager.domain.metamodel.helper.ClassRepository; import com.webuml.projectmanager.domain.metamodel.Package; import com.webuml.projectmanager.domain.metamodel.helper.PackagesRepository; import com.webuml.projectmanager.domain.metamodel.Property; import com.webuml.projectmanager.domain.metamodel.helper.PropertyRepository; import com.webuml.projectmanager.domain.primitives.ElementId; import com.webuml.projectmanager.domain.primitives.PackageId; import com.webuml.projectmanager.domain.primitives.ProjectId; import com.webuml.projectmanager.domain.primitives.PropertyId; import com.webuml.projectmanager.domain.projectmodel.Project; import com.webuml.projectmanager.domain.projectmodel.ProjectRepository; import com.webuml.projectmanager.domain.viewmodel.AssociationView; import com.webuml.projectmanager.domain.viewmodel.AssociationViewRepository; import com.webuml.projectmanager.domain.viewmodel.ClassView; import com.webuml.projectmanager.domain.viewmodel.ClassViewRepository; import com.webuml.projectmanager.domain.viewmodel.ElementViewId; import com.webuml.projectmanager.domain.viewmodel.LightTableView; import com.webuml.projectmanager.domain.viewmodel.LightTableViewRepository; import com.webuml.projectmanager.domain.viewmodel.PathRoutingStrategy; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.inject.Inject; import java.util.HashSet; import java.util.Set; @Component public class GoldenTestDataSetup { private static final Logger LOG = Logger.getLogger(GoldenTestDataSetup.class); public static final ProjectId PROJECT_ID = new ProjectId("4711"); public static final ElementId CLASS_LOCAL_DATE_ID = new ElementId("0814"); public static final ElementId CLASS_PERSON_ID = new ElementId("0815"); public static final ElementId CLASS_EMPLOYEE_ID = new ElementId("0816"); public static final PropertyId PROP_ID_NAME = new PropertyId("1000"); public static final PropertyId PROP_ID_DATE_OF_BIRTH = new PropertyId("1001"); public static final PropertyId PROP_ID_NUMBER = new PropertyId("1002"); public static final PropertyId PROP_FRIENDS_INITIATOR = new PropertyId("1003"); public static final PropertyId PROP_FRIENDS_INITIATOR2 = new PropertyId("1004"); public static final PropertyId PROP_FRIENDS_CONFIRMER = new PropertyId("1005"); public static final PropertyId PROP_FRIENDS_CONFIRMER2 = new PropertyId("1006"); public static final PropertyId PROP_ID_SALARY = new PropertyId("1005"); public static final ElementViewId LIGHT_TABLE_VIEW_ID = new ElementViewId("884711"); public static final ElementViewId CLASS_LOCAL_DATE_VIEW_ID = new ElementViewId("880814"); public static final ElementViewId CLASS_PERSON_VIEW_ID = new ElementViewId("880815"); public static final ElementViewId CLASS_EMPLOYEE_VIEW_ID = new ElementViewId("880816"); public static final ElementId ASSOCIATION_ID_FRIENDS = new ElementId("2000"); public static final ElementId ASSOCIATION_ID_FRIENDS2 = new ElementId("2001"); public static final ElementViewId ASSOCIATION_VIEW_ID_1 = new ElementViewId("99001"); public static final ElementViewId ASSOCIATION_VIEW_ID_2 = new ElementViewId("99002"); @Inject ProjectRepository projectRepository; @Inject ClassRepository classRepository; @Inject AssociationRepository associationRepository; @Inject PropertyRepository propertyRepository; @Inject PackagesRepository packagesRepository; @Inject LightTableViewRepository lightTableViewRepository; @Inject ClassViewRepository classViewRepository; @Inject AssociationViewRepository associationViewRepository; @PostConstruct public void persistGoldenTestData() { createProject(); createClass_LocalDate(); createClass_Person(); createClass_Employee(); createAssociation_Friends(); createAssociation_Friends_2(); createLightTableView(); createClassView_LocalDate(); createClassView_Employee(); createClassView_Person(); createAssociationViews(); createAssociationViews_2(); LOG.info("Golden Test Project created or updated. projectId : " + PROJECT_ID); } private void createAssociationViews() { AssociationView associationView = new AssociationView(PROJECT_ID); associationView.setId(ASSOCIATION_VIEW_ID_1); associationView.setParent(LIGHT_TABLE_VIEW_ID); associationView.setRouting(PathRoutingStrategy.STRAIGHT); associationView.setAssociation(ASSOCIATION_ID_FRIENDS); associationViewRepository.save(associationView); } private void createAssociationViews_2() { AssociationView associationView = new AssociationView(PROJECT_ID); associationView.setId(ASSOCIATION_VIEW_ID_2); associationView.setParent(LIGHT_TABLE_VIEW_ID); associationView.setRouting(PathRoutingStrategy.STRAIGHT); associationView.setAssociation(ASSOCIATION_ID_FRIENDS2); associationViewRepository.save(associationView); } private void createClassView_LocalDate() { ClassView classView = new ClassView(PROJECT_ID, CLASS_LOCAL_DATE_ID, LIGHT_TABLE_VIEW_ID); classView.setId(CLASS_LOCAL_DATE_VIEW_ID); classView.setX(10); classView.setY(10); classView.setZ(1); classView.setW(80); classView.setH(60); classViewRepository.save(classView); } private void createClassView_Person() { ClassView classView = new ClassView(PROJECT_ID, CLASS_PERSON_ID, LIGHT_TABLE_VIEW_ID); classView.setId(CLASS_PERSON_VIEW_ID); classView.setX(100); classView.setY(10); classView.setZ(1); classView.setW(80); classView.setH(60); classViewRepository.save(classView); } private void createClassView_Employee() { ClassView classView = new ClassView(PROJECT_ID, CLASS_EMPLOYEE_ID, LIGHT_TABLE_VIEW_ID); classView.setId(CLASS_EMPLOYEE_VIEW_ID); classView.setX(100); classView.setY(80); classView.setZ(1); classView.setW(80); classView.setH(60); classViewRepository.save(classView); } private void createLightTableView() { LightTableView lightTableView = new LightTableView(PROJECT_ID); lightTableView.setId(LIGHT_TABLE_VIEW_ID); lightTableView.setName("Simple light view for golden test project"); lightTableView.setX(1); lightTableView.setY(1); lightTableView.setScale(1); lightTableViewRepository.save(lightTableView); } private void createAssociation_Friends() { Property a = new Property(); a.setId(PROP_FRIENDS_INITIATOR); a.setTypeId(CLASS_PERSON_ID); a.setName("friendshipInitiator"); propertyRepository.save(a); Property b = new Property(); b.setId(PROP_FRIENDS_CONFIRMER); b.setTypeId(CLASS_PERSON_ID); b.setName("friendshipConfirmer"); propertyRepository.save(b); Set<PropertyId> ownedEnd = new HashSet<>(); ownedEnd.add(a.getId()); ownedEnd.add(b.getId()); Association association = new Association(); association.setId(ASSOCIATION_ID_FRIENDS); association.setProjectId(PROJECT_ID); association.setName("Friends"); association.setMemberEnd(ownedEnd); association.setOwnedEnd(ownedEnd); associationRepository.save(association); } private void createAssociation_Friends_2() { Property a = new Property(); a.setId(PROP_FRIENDS_INITIATOR2); a.setTypeId(CLASS_PERSON_ID); a.setName("friendshipInitiator"); propertyRepository.save(a); Property b = new Property(); b.setId(PROP_FRIENDS_CONFIRMER2); b.setTypeId(CLASS_EMPLOYEE_ID); b.setName("friendshipConfirmer"); propertyRepository.save(b); Set<PropertyId> ownedEnd = new HashSet<>(); ownedEnd.add(a.getId()); ownedEnd.add(b.getId()); Association association = new Association(); association.setId(ASSOCIATION_ID_FRIENDS2); association.setProjectId(PROJECT_ID); association.setName("Friends"); association.setMemberEnd(ownedEnd); association.setOwnedEnd(ownedEnd); associationRepository.save(association); } private void createClass_LocalDate() { Class clazz = new Class(); clazz.setId(CLASS_LOCAL_DATE_ID); clazz.setProjectId(PROJECT_ID); clazz.setName("LocalDate"); classRepository.save(clazz); } private PackageId createPackage(String name) { com.webuml.projectmanager.domain.metamodel.Package aPackage = new Package(); aPackage.setName(name); aPackage.setProjectId(PROJECT_ID); packagesRepository.save(aPackage); return aPackage.getId(); } private void createProject() { Project project = new Project(); project.setId(PROJECT_ID); project.setName("Golden Test Project"); projectRepository.save(project); } private void createClass_Person() { Class clazz = new Class(); clazz.setId(CLASS_PERSON_ID); clazz.setProjectId(PROJECT_ID); clazz.setName("Person"); clazz.getOwnedAttribute().add(createProperty(PROP_ID_NAME, "name", null).getId()); clazz.getOwnedAttribute().add(createProperty(PROP_ID_DATE_OF_BIRTH, "dateOfBirth", CLASS_LOCAL_DATE_ID).getId()); clazz.setOwningPackage(createPackage("com.webuml.person")); classRepository.save(clazz); } private void createClass_Employee() { Class clazz = new com.webuml.projectmanager.domain.metamodel.Class(); clazz.setId(CLASS_EMPLOYEE_ID); clazz.setName("Employee"); clazz.setProjectId(PROJECT_ID); clazz.getOwnedAttribute().add(createProperty(PROP_ID_NUMBER, "number", null).getId()); clazz.getOwnedAttribute().add(createProperty(PROP_ID_SALARY, "salary", null).getId()); clazz.setOwningPackage(createPackage("com.webuml.employee")); classRepository.save(clazz); } private Property createProperty(PropertyId id, String name, ElementId typeId) { Property property = new Property(); property.setId(id); property.setName(name); property.setTypeId(typeId); propertyRepository.save(property); return property; } }
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.internal.operators; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import rx.*; import rx.Observable.OnSubscribe; import rx.Observer; import rx.Subscriber; import rx.functions.Action1; import rx.internal.util.RxRingBuffer; import rx.observers.TestSubscriber; import rx.plugins.RxJavaHooks; import rx.schedulers.Schedulers; public class OperatorOnBackpressureDropTest { @Test public void testNoBackpressureSupport() { TestSubscriber<Long> ts = new TestSubscriber<Long>(); // this will be ignored ts.requestMore(100); // we take 500 so it unsubscribes infinite.take(500).subscribe(ts); // it completely ignores the `request(100)` and we get 500 assertEquals(500, ts.getOnNextEvents().size()); ts.assertNoErrors(); } @Test(timeout = 500) public void testWithObserveOn() throws InterruptedException { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); Observable.range(0, RxRingBuffer.SIZE * 10).onBackpressureDrop().observeOn(Schedulers.io()).subscribe(ts); ts.awaitTerminalEvent(); } @Test(timeout = 500) public void testFixBackpressureWithBuffer() throws InterruptedException { final CountDownLatch l1 = new CountDownLatch(100); final CountDownLatch l2 = new CountDownLatch(150); TestSubscriber<Long> ts = new TestSubscriber<Long>(new Observer<Long>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Long t) { l1.countDown(); l2.countDown(); } }); // this will be ignored ts.requestMore(100); // we take 500 so it unsubscribes infinite.subscribeOn(Schedulers.computation()).onBackpressureDrop().take(500).subscribe(ts); // it completely ignores the `request(100)` and we get 500 l1.await(); assertEquals(100, ts.getOnNextEvents().size()); ts.requestMore(50); l2.await(); assertEquals(150, ts.getOnNextEvents().size()); ts.requestMore(350); ts.awaitTerminalEvent(); assertEquals(500, ts.getOnNextEvents().size()); ts.assertNoErrors(); assertEquals(0, ts.getOnNextEvents().get(0).intValue()); } @Test public void testRequestOverflow() throws InterruptedException { final AtomicInteger count = new AtomicInteger(); int n = 10; range(n).onBackpressureDrop().subscribe(new Subscriber<Long>() { @Override public void onStart() { request(10); } @Override public void onCompleted() { } @Override public void onError(Throwable e) { throw new RuntimeException(e); } @Override public void onNext(Long t) { count.incrementAndGet(); //cause overflow of requested if not handled properly in onBackpressureDrop operator request(Long.MAX_VALUE-1); }}); assertEquals(n, count.get()); } @Test public void testNonFatalExceptionFromOverflowActionIsNotReportedFromUpstreamOperator() { final AtomicBoolean errorOccurred = new AtomicBoolean(false); //request 0 TestSubscriber<Long> ts = TestSubscriber.create(0); //range method emits regardless of requests so should trigger onBackpressureDrop action range(2) // if haven't caught exception in onBackpressureDrop operator then would incorrectly // be picked up by this call to doOnError .doOnError(new Action1<Throwable>() { @Override public void call(Throwable t) { errorOccurred.set(true); } }) .onBackpressureDrop(THROW_NON_FATAL) .subscribe(ts); assertFalse(errorOccurred.get()); } @Test public void testOnDropMethodIsCalled() { final List<Integer> list = new ArrayList<Integer>(); // request 0 TestSubscriber<Integer> ts = TestSubscriber.create(0); Observable.create(new OnSubscribe<Integer>() { @Override public void call(final Subscriber<? super Integer> sub) { sub.setProducer(new Producer() { @Override public void request(long n) { if (n > 1) { sub.onNext(1); sub.onNext(2); sub.onCompleted(); } } }); } }).onBackpressureDrop(new Action1<Integer>() { @Override public void call(Integer t) { list.add(t); } }).subscribe(ts); assertEquals(Arrays.asList(1, 2), list); } @Test public void testUpstreamEmitsOnCompletedAfterFailureWithoutCheckingSubscription() { TestSubscriber<Integer> ts = TestSubscriber.create(0); final RuntimeException e = new RuntimeException(); Observable.create(new OnSubscribe<Integer>() { @Override public void call(final Subscriber<? super Integer> sub) { sub.setProducer(new Producer() { @Override public void request(long n) { if (n > 1) { sub.onNext(1); sub.onCompleted(); } } }); } }) .onBackpressureDrop(new Action1<Integer>() { @Override public void call(Integer t) { throw e; }}) .unsafeSubscribe(ts); ts.assertNoValues(); ts.assertError(e); ts.assertNotCompleted(); } @Test public void testUpstreamEmitsErrorAfterFailureWithoutCheckingSubscriptionResultsInHooksOnErrorCalled() { try { final List<Throwable> list = new CopyOnWriteArrayList<Throwable>(); RxJavaHooks.setOnError(new Action1<Throwable>() { @Override public void call(Throwable t) { list.add(t); } }); TestSubscriber<Integer> ts = TestSubscriber.create(0); final RuntimeException e1 = new RuntimeException(); final RuntimeException e2 = new RuntimeException(); Observable.create(new OnSubscribe<Integer>() { @Override public void call(final Subscriber<? super Integer> sub) { sub.setProducer(new Producer() { @Override public void request(long n) { if (n > 1) { sub.onNext(1); sub.onError(e2); } } }); } }).onBackpressureDrop(new Action1<Integer>() { @Override public void call(Integer t) { throw e1; } }).unsafeSubscribe(ts); ts.assertNoValues(); assertEquals(Arrays.asList(e1), ts.getOnErrorEvents()); ts.assertNotCompleted(); assertEquals(Arrays.asList(e2), list); } finally { RxJavaHooks.setOnError(null); } } @Test public void testUpstreamEmitsOnNextAfterFailureWithoutCheckingSubscription() { TestSubscriber<Integer> ts = TestSubscriber.create(0); final RuntimeException e = new RuntimeException(); Observable.create(new OnSubscribe<Integer>() { @Override public void call(final Subscriber<? super Integer> sub) { sub.setProducer(new Producer() { @Override public void request(long n) { if (n > 1) { sub.onNext(1); sub.onNext(2); } } }); } }) .onBackpressureDrop(new Action1<Integer>() { @Override public void call(Integer t) { throw e; }}) .unsafeSubscribe(ts); ts.assertNoValues(); ts.assertError(e); ts.assertNotCompleted(); } private static final Action1<Long> THROW_NON_FATAL = new Action1<Long>() { @Override public void call(Long n) { throw new RuntimeException(); } }; static final Observable<Long> infinite = Observable.create(new OnSubscribe<Long>() { @Override public void call(Subscriber<? super Long> s) { long i = 0; while (!s.isUnsubscribed()) { s.onNext(i++); } } }); private static final Observable<Long> range(final long n) { return Observable.create(new OnSubscribe<Long>() { @Override public void call(Subscriber<? super Long> s) { for (long i=0;i < n;i++) { if (s.isUnsubscribed()) { break; } s.onNext(i); } s.onCompleted(); } }); } }
package org.gertje.abacus.translator.java.nodevisitors; import org.gertje.abacus.context.AbacusContext; import org.gertje.abacus.nodes.AbstractComparisonNode; import org.gertje.abacus.nodes.AddNode; import org.gertje.abacus.nodes.AndNode; import org.gertje.abacus.nodes.ArrayNode; import org.gertje.abacus.nodes.AssignmentNode; import org.gertje.abacus.nodes.BinaryOperationNode; import org.gertje.abacus.nodes.BooleanNode; import org.gertje.abacus.nodes.ConcatStringNode; import org.gertje.abacus.nodes.DateNode; import org.gertje.abacus.nodes.DecimalNode; import org.gertje.abacus.nodes.DivideNode; import org.gertje.abacus.nodes.EqNode; import org.gertje.abacus.nodes.ExpressionNode; import org.gertje.abacus.nodes.FactorNode; import org.gertje.abacus.nodes.FunctionNode; import org.gertje.abacus.nodes.GeqNode; import org.gertje.abacus.nodes.GtNode; import org.gertje.abacus.nodes.IfNode; import org.gertje.abacus.nodes.IntegerNode; import org.gertje.abacus.nodes.LeqNode; import org.gertje.abacus.nodes.LtNode; import org.gertje.abacus.nodes.ModuloNode; import org.gertje.abacus.nodes.MultiplyNode; import org.gertje.abacus.nodes.NegativeNode; import org.gertje.abacus.nodes.NeqNode; import org.gertje.abacus.nodes.Node; import org.gertje.abacus.nodes.NodeType; import org.gertje.abacus.nodes.NotNode; import org.gertje.abacus.nodes.NullNode; import org.gertje.abacus.nodes.OrNode; import org.gertje.abacus.nodes.PositiveNode; import org.gertje.abacus.nodes.PowerNode; import org.gertje.abacus.nodes.RootNode; import org.gertje.abacus.nodes.StatementListNode; import org.gertje.abacus.nodes.StringNode; import org.gertje.abacus.nodes.SubtractNode; import org.gertje.abacus.nodes.SumNode; import org.gertje.abacus.nodes.VariableNode; import org.gertje.abacus.nodevisitors.DefaultVisitor; import org.gertje.abacus.nodevisitors.EvaluationException; import org.gertje.abacus.nodevisitors.ExpressionEvaluator; import org.gertje.abacus.nodevisitors.NodeVisitor; import org.gertje.abacus.nodevisitors.VariableVisitor; import org.gertje.abacus.nodevisitors.VisitingException; import org.gertje.abacus.runtime.expression.ArithmeticOperation; import org.gertje.abacus.runtime.expression.BooleanOperation; import org.gertje.abacus.runtime.expression.CastHelper; import org.gertje.abacus.runtime.expression.StringOperation; import org.gertje.abacus.symboltable.NoSuchVariableException; import org.gertje.abacus.symboltable.SymbolTable; import org.gertje.abacus.symboltable.Variable; import org.gertje.abacus.translator.java.runtime.AbacusRuntimeException; import org.gertje.abacus.types.Type; import org.gertje.abacus.util.JavaTypeHelper; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import java.math.BigDecimal; import java.math.MathContext; import java.sql.Date; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import static org.objectweb.asm.ClassWriter.COMPUTE_FRAMES; import static org.objectweb.asm.Opcodes.AALOAD; import static org.objectweb.asm.Opcodes.AASTORE; import static org.objectweb.asm.Opcodes.ACC_PUBLIC; import static org.objectweb.asm.Opcodes.ACC_SUPER; import static org.objectweb.asm.Opcodes.ACONST_NULL; import static org.objectweb.asm.Opcodes.ALOAD; import static org.objectweb.asm.Opcodes.ARETURN; import static org.objectweb.asm.Opcodes.ARRAYLENGTH; import static org.objectweb.asm.Opcodes.ASTORE; import static org.objectweb.asm.Opcodes.ATHROW; import static org.objectweb.asm.Opcodes.CHECKCAST; import static org.objectweb.asm.Opcodes.DUP; import static org.objectweb.asm.Opcodes.DUP2_X1; import static org.objectweb.asm.Opcodes.DUP_X1; import static org.objectweb.asm.Opcodes.DUP_X2; import static org.objectweb.asm.Opcodes.F_SAME1; import static org.objectweb.asm.Opcodes.GETFIELD; import static org.objectweb.asm.Opcodes.GETSTATIC; import static org.objectweb.asm.Opcodes.GOTO; import static org.objectweb.asm.Opcodes.ICONST_0; import static org.objectweb.asm.Opcodes.ICONST_1; import static org.objectweb.asm.Opcodes.IFEQ; import static org.objectweb.asm.Opcodes.IFLT; import static org.objectweb.asm.Opcodes.IFNE; import static org.objectweb.asm.Opcodes.IFNULL; import static org.objectweb.asm.Opcodes.IF_ICMPGE; import static org.objectweb.asm.Opcodes.INVOKEINTERFACE; import static org.objectweb.asm.Opcodes.INVOKESPECIAL; import static org.objectweb.asm.Opcodes.INVOKESTATIC; import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; import static org.objectweb.asm.Opcodes.NEW; import static org.objectweb.asm.Opcodes.POP; import static org.objectweb.asm.Opcodes.POP2; import static org.objectweb.asm.Opcodes.RETURN; import static org.objectweb.asm.Opcodes.SWAP; import static org.objectweb.asm.Opcodes.V1_7; public class ClassTranslator implements NodeVisitor<Void, TranslationException> { /** * De symboltable met de variabelen en de functies. */ protected SymbolTable symbolTable; /** * The method visitor used to create the method. */ private MethodVisitor mv; /** * The current line number we are processing. */ private int lineNumber = -1; /** * A list containing all the variables that are read at some time. */ private List<Variable> readVariableList; /** * A list containing all the variables to which an assignment is made at some time. */ private List<Variable> storeVariableList; /** * A map identifier --> index of the variable. */ private Map<String, Integer> methodVariableIndexes; /** * The name of the class that is generated. */ private String generatedClassName; /** * Constructor. */ public ClassTranslator(AbacusContext abacusContext) { this.symbolTable = abacusContext.getSymbolTable(); } /** * Translates the node to byte code. * @param node The node to be translated. * @param extendedClass The class that needs to be extended by the generated class. * @param generatedClassName The name of the class that will be generated. * @return A byte array containing the byte code. * @throws TranslationException */ public byte[] translate(Node node, Class extendedClass, String generatedClassName) throws TranslationException { initialize(node); this.generatedClassName = generatedClassName; return buildClass(node, extendedClass); } /** * Initializes the translator for translating the given node. * @param node The node to be translated. * @throws TranslationException */ private void initialize(Node node) throws TranslationException { readMethodVariables(node); } /** * Reads all variables that are read or written in the node and adds them to {@link #readVariableList}, * {@link #storeVariableList} and {@link #methodVariableIndexes}. * @param node The node. * @throws TranslationException */ private void readMethodVariables(Node node) throws TranslationException { VariableVisitor variableVisitor = new VariableVisitor(); try { node.accept(variableVisitor); } catch (VisitingException e) { throw new TranslationException(e.getMessage(), node, e); } readVariableList = new ArrayList<>(variableVisitor.getReadVariables()); storeVariableList = new ArrayList<>(variableVisitor.getStoreVariables()); methodVariableIndexes = new HashMap<>(); // Join both lists to get one set with all Set<Variable> variableSet = new HashSet<>(readVariableList); variableSet.addAll(storeVariableList); // Start counting at 1, because 'this' has index 0. int i = 1; for (Variable variable : variableSet) { methodVariableIndexes.put(variable.getIdentifier(), i++); } } /** * Builds tha class from the node. * @param node The node. * @param extendedClass The class that needs to be extended by the generated class. * @return A byte array containing the byte code. * @throws TranslationException */ private byte[] buildClass(Node node, Class extendedClass) throws TranslationException { ClassWriter cw = new ClassWriter(COMPUTE_FRAMES); cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, determineClassName(generatedClassName), null, determineClassName(extendedClass), null); cw.visitSource(null, null); // Append the constructor. mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); Label l0 = new Label(); mv.visitLabel(l0); mv.visitLineNumber(25, l0); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, determineClassName(extendedClass), "<init>", "()V", false); mv.visitInsn(RETURN); Label l1 = new Label(); mv.visitLabel(l1); mv.visitLocalVariable("this", "L" + determineClassName(generatedClassName) + ";", null, l0, l1, 0); mv.visitMaxs(0, 0); mv.visitEnd(); // Append the function f. mv = cw.visitMethod(ACC_PUBLIC, "f", determineMethodDescriptor(Object.class), null, null); mv.visitCode(); appendReadVariableValues(); node.accept(this); appendStoreVariableValues(); mv.visitInsn(ARETURN); mv.visitMaxs(0, 1); mv.visitEnd(); cw.visitEnd(); return cw.toByteArray(); } @Override public Void visit(AddNode node) throws TranslationException { return null; } @Override public Void visit(AndNode node) throws TranslationException { appendLineNumberLabel(node); appendOrAnd(node, false); return null; } @Override public Void visit(ArrayNode node) throws TranslationException { appendLineNumberLabel(node); unreferenceArray(node, null, null); return null; } @Override public Void visit(AssignmentNode node) throws TranslationException { appendLineNumberLabel(node); ValueAssigner valueAssigner = new ValueAssigner(); valueAssigner.assign(node.getLhs(), node.getRhs(), node.getType()); return null; } @Override public Void visit(BooleanNode node) throws TranslationException { appendLineNumberLabel(node); if (node.getValue() == null) { mv.visitInsn(ACONST_NULL); return null; } mv.visitLdcInsn(node.getValue()); mv.visitMethodInsn(INVOKESTATIC, determineClassName(Boolean.class), "valueOf", "(Z)Ljava/lang/Boolean;", false); return null; } @Override public Void visit(ConcatStringNode node) throws TranslationException { appendLineNumberLabel(node); node.getLhs().accept(this); node.getRhs().accept(this); mv.visitMethodInsn(INVOKESTATIC, determineClassName(StringOperation.class), "concat", determineMethodDescriptor(String.class, String.class, String.class), false); return null; } @Override public Void visit(DateNode node) throws TranslationException { appendLineNumberLabel(node); if (node.getValue() == null) { mv.visitInsn(ACONST_NULL); return null; } mv.visitTypeInsn(NEW, determineClassName(Date.class)); mv.visitInsn(DUP); mv.visitLdcInsn(node.getValue().getTime()); mv.visitMethodInsn(INVOKESPECIAL, determineClassName(Date.class), "<init>", "(J)V", false); return null; } @Override public Void visit(DecimalNode node) throws TranslationException { appendLineNumberLabel(node); if (node.getValue() == null) { mv.visitInsn(ACONST_NULL); return null; } mv.visitTypeInsn(NEW, determineClassName(BigDecimal.class)); mv.visitInsn(DUP); mv.visitLdcInsn(node.getValue().toString()); mv.visitMethodInsn(INVOKESPECIAL, determineClassName(BigDecimal.class), "<init>", determineMethodDescriptor(null, String.class), false); return null; } @Override public Void visit(DivideNode node) throws TranslationException { appendLineNumberLabel(node); appendBinaryArithmeticOperation(node, "divide"); return null; } @Override public Void visit(EqNode node) throws TranslationException { appendLineNumberLabel(node); appendComparisonNode(node, "EQUALS"); return null; } @Override public Void visit(FactorNode node) throws TranslationException { node.getArgument().accept(this); return null; } @Override public Void visit(FunctionNode node) throws TranslationException { mv.visitVarInsn(ALOAD, 0); ArrayList<Class> classes = new ArrayList<>(); for (ExpressionNode parameter : node.getParameters()) { parameter.accept(this); classes.add(determineJavaClass(parameter.getType())); } mv.visitMethodInsn(INVOKEVIRTUAL, determineClassName(generatedClassName), "function_" + node.getIdentifier(), determineMethodDescriptor(determineJavaClass(node.getType()), classes.toArray(new Class[classes.size()])), false); return null; } @Override public Void visit(GeqNode node) throws TranslationException { appendLineNumberLabel(node); appendComparisonNode(node, "GREATER_THAN_EQUALS"); return null; } @Override public Void visit(GtNode node) throws TranslationException { appendLineNumberLabel(node); appendComparisonNode(node, "GREATER_THAN"); return null; } @Override public Void visit(IfNode node) throws TranslationException { appendLineNumberLabel(node); node.getCondition().accept(this); mv.visitInsn(DUP); // place the condition twice on the stack Label l1 = new Label(); mv.visitJumpInsn(IFNULL, l1); // if condition is null --> jump to 1 mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z", false); Label l2 = new Label(); mv.visitJumpInsn(IFEQ, l2); // if condition is false --> jump to 2 node.getIfBody().accept(this); appendCast(node.getIfBody().getType(), node.getType()); Label l3 = new Label(); mv.visitJumpInsn(GOTO, l3); // goto label 3 mv.visitLabel(l2); // define label 2 node.getElseBody().accept(this); appendCast(node.getElseBody().getType(), node.getType()); mv.visitJumpInsn(GOTO, l3); // goto label 3 mv.visitLabel(l1); // define label 1 mv.visitInsn(POP); // pop the last condition from the stack, we don't need it mv.visitInsn(ACONST_NULL); // place null on the stack mv.visitLabel(l3); // define label 3 return null; } @Override public Void visit(IntegerNode node) throws TranslationException { appendLineNumberLabel(node); if (node.getValue() == null) { mv.visitInsn(ACONST_NULL); return null; } mv.visitLdcInsn(node.getValue()); mv.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false); return null; } @Override public Void visit(LeqNode node) throws TranslationException { appendLineNumberLabel(node); appendComparisonNode(node, "LESS_THAN_EQUALS"); return null; } @Override public Void visit(LtNode node) throws TranslationException { appendLineNumberLabel(node); appendComparisonNode(node, "LESS_THAN"); return null; } @Override public Void visit(ModuloNode node) throws TranslationException { appendLineNumberLabel(node); appendBinaryArithmeticOperation(node, "modulo"); return null; } @Override public Void visit(MultiplyNode node) throws TranslationException { appendLineNumberLabel(node); appendBinaryArithmeticOperation(node, "multiply"); return null; } @Override public Void visit(NegativeNode node) throws TranslationException { appendLineNumberLabel(node); node.getArgument().accept(this); mv.visitMethodInsn(INVOKESTATIC, determineClassName(ArithmeticOperation.class), "negate", determineMethodDescriptor( determineJavaClass(node.getType()), determineJavaClass(node.getArgument().getType()) ), false); return null; } @Override public Void visit(NeqNode node) throws TranslationException { appendLineNumberLabel(node); appendComparisonNode(node, "NOT_EQUALS"); return null; } @Override public Void visit(NotNode node) throws TranslationException { appendLineNumberLabel(node); node.getArgument().accept(this); mv.visitMethodInsn(INVOKESTATIC, determineClassName(BooleanOperation.class), "not", determineMethodDescriptor(Boolean.class, Boolean.class), false); return null; } @Override public Void visit(NullNode node) throws TranslationException { mv.visitInsn(ACONST_NULL); return null; } @Override public Void visit(OrNode node) throws TranslationException { appendLineNumberLabel(node); appendOrAnd(node, true); return null; } @Override public Void visit(PositiveNode node) throws TranslationException { return null; } @Override public Void visit(PowerNode node) throws TranslationException { appendLineNumberLabel(node); appendBinaryArithmeticOperation(node, "power"); return null; } @Override public Void visit(RootNode node) throws TranslationException { return null; } @Override public Void visit(StatementListNode node) throws TranslationException { Iterator<Node> it = node.iterator(); while (it.hasNext()) { Node subNode = it.next(); subNode.accept(this); if (it.hasNext() || subNode.getNodeType() != NodeType.EXPRESSION) { mv.visitInsn(POP); } } return null; } @Override public Void visit(StringNode node) throws TranslationException { appendLineNumberLabel(node); if (node.getValue() == null) { mv.visitInsn(ACONST_NULL); return null; } mv.visitLdcInsn(node.getValue()); return null; } @Override public Void visit(SubtractNode node) throws TranslationException { appendLineNumberLabel(node); appendBinaryArithmeticOperation(node, "subtract"); return null; } @Override public Void visit(SumNode node) throws TranslationException { appendLineNumberLabel(node); appendBinaryArithmeticOperation(node, "sum"); return null; } @Override public Void visit(VariableNode node) throws TranslationException { appendLineNumberLabel(node); mv.visitVarInsn(ALOAD, methodVariableIndexes.get(node.getIdentifier())); return null; } /** * Assigns a value to a variable or to an index. */ private class ValueAssigner extends DefaultVisitor<Void, TranslationException> { /** * The value to assign. */ private ExpressionNode value; /** * The type of the assignment. */ private Type type; public ValueAssigner() { // Don't visit the child nodes. visitChildNodes = false; } /** * Assigns the value to the correct variable or array-index. * @param node The node that determines where to assign the value to. * @param value The value to assign. * @throws TranslationException */ public void assign(ExpressionNode node, ExpressionNode value, Type type) throws TranslationException { this.value = value; this.type = type; node.accept(this); } @Override public Void visit(ArrayNode node) throws TranslationException { unreferenceArray(node, value, type); return null; } @Override public Void visit(VariableNode node) throws TranslationException { // Get the value. value.accept(ClassTranslator.this); // Cast the value to the correct type. appendCast(value.getType(), type); // Duplicate the value. mv.visitInsn(DUP); // Store the value in the variable with index. mv.visitVarInsn(ASTORE, methodVariableIndexes.get(node.getIdentifier())); return null; } } /** * Unreferences an array and either returns the value, or assigns a new value. * @param node The array node to unreference. * @param assignValue The value to assign. * @param type The type of the assignment. * @throws TranslationException */ private void unreferenceArray(ArrayNode node, ExpressionNode assignValue, Type type) throws TranslationException { Label labelPop1 = new Label(); Label labelPop2 = new Label(); Label labelPop4 = new Label(); Label labelEnd = new Label(); node.getIndex().accept(this); // Get the index. node.getArray().accept(this); // Get the array. mv.visitInsn(DUP_X1); // Duplicate the index mv.visitJumpInsn(IFNULL, labelPop2); // If null, jump to pop2 mv.visitInsn(DUP); // Duplicate the array mv.visitJumpInsn(IFNULL, labelPop2); // If null, jump to pop1 mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Long", "intValue", "()I", false); mv.visitInsn(DUP_X1); // Duplicate the index mv.visitInsn(DUP2_X1); // Duplicate the index and the array and push to the bottom mv.visitJumpInsn(IFLT, labelPop4); // If the index is less then 0, jump to pop4 mv.visitInsn(ARRAYLENGTH); // Get the length of the array mv.visitJumpInsn(IF_ICMPGE, labelPop2); // If the length is LE to the index jump to pop2 // Assign the value if one was passed to the method. if (assignValue != null) { // Determine the value to assign. assignValue.accept(this); // Cast the value to the correct type. appendCast(assignValue.getType(), type); // Duplicate the value. mv.visitInsn(DUP_X2); // Assign the value. mv.visitInsn(AASTORE); // Otherwise, we need to load the value. } else { mv.visitInsn(AALOAD); } mv.visitJumpInsn(GOTO, labelEnd); // Done! Go to the end! mv.visitLabel(labelPop4); // We need to pop 4 items mv.visitInsn(POP2); // Pop the first 2 items mv.visitLabel(labelPop2); // Now we only need to pop 2 items mv.visitInsn(POP); // Pop the item mv.visitLabel(labelPop1); // Now we only need to pop 1 item mv.visitInsn(POP); // Pop the last item mv.visitInsn(ACONST_NULL); // Set null on the stack mv.visitLabel(labelEnd); // The end! } /** * Appends a cast from one type to another. * @param fromType The type to cast from. * @param toType The type to cast to. */ private void appendCast(Type fromType, Type toType) { if (Type.equals(toType, fromType) || fromType == null) { return; } String operation; if (Type.equals(fromType, Type.DECIMAL) && Type.equals(toType, Type.INTEGER)) { operation = "toInteger"; } else if (Type.equals(fromType, Type.INTEGER) && Type.equals(toType, Type.DECIMAL)) { operation = "toDecimal"; } else { throw new IllegalArgumentException("Unsupported types: " + fromType + ", " + toType); } mv.visitMethodInsn(INVOKESTATIC, determineClassName(CastHelper.class), operation, determineMethodDescriptor( determineJavaClass(toType), determineJavaClass(fromType) ), false); } /** * Appends the or-operation, or appends the and-operation. * @param node The node to append, which is an binary operation node since both the OrNode and the AndNode are. * @param isOr if {@code true} then the operation to append is the or-operation, otherwise it is the and-operation. * @throws TranslationException */ private void appendOrAnd(BinaryOperationNode node, boolean isOr) throws TranslationException { node.getLhs().accept(this); mv.visitInsn(DUP); // place three lhs es on the stack mv.visitInsn(DUP); Label l1 = new Label(); mv.visitJumpInsn(IFNULL, l1); // if lhs is null --> jump to 1 mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z", false); Label l2 = new Label(); mv.visitJumpInsn(isOr ? IFEQ : IFNE, l2); // if lhs is 0 --> jump to 2 mv.visitInsn(POP); // pop the last lhs from the stack (we don't need it). mv.visitInsn(isOr ? ICONST_1 : ICONST_0); // place integer 1 on the stack Label l3 = new Label(); mv.visitJumpInsn(GOTO, l3); // goto label 3 mv.visitLabel(l1); // same as label 2, but performs an extra pop mv.visitInsn(POP); // pop an lhs from the stack, after this one lhs is left mv.visitLabel(l2); node.getRhs().accept(this); mv.visitInsn(DUP); // place three rhs es on the stack mv.visitInsn(DUP); Label l4 = new Label(); mv.visitJumpInsn(IFNULL, l4); // if rhs is null --> jump to 4 mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z", false); Label l5 = new Label(); mv.visitJumpInsn(isOr ? IFEQ : IFNE, l5); // if rhs is 0 --> jump to 5 mv.visitInsn(POP); // pop the last rhs from the stack (we don't need it) mv.visitInsn(POP); // pop the last lhs from the stack (we don't need it) mv.visitInsn(isOr ? ICONST_1 : ICONST_0); // place integer 1 on the stack mv.visitJumpInsn(GOTO, l3); // goto label 3 mv.visitLabel(l4); mv.visitInsn(POP); // pop an rhs from the stack, after this one rhs and one lhs are left mv.visitLabel(l5); Label l6 = new Label(); mv.visitJumpInsn(IFNULL, l6); // if rhs is null --> jump to 6 Label l7 = new Label(); mv.visitJumpInsn(IFNULL, l7); // if lhs is null --> jump to 7 mv.visitInsn(isOr ? ICONST_0 : ICONST_1); // place integer 0 on the stack mv.visitJumpInsn(GOTO, l3); // goto label 3 mv.visitLabel(l6); mv.visitInsn(POP); // pop the last lhs from the stack (we don't need it) mv.visitLabel(l7); mv.visitInsn(ACONST_NULL); // place null on the stack Label l8 = new Label(); mv.visitJumpInsn(GOTO, l8); mv.visitLabel(l3); mv.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false); mv.visitLabel(l8); } /** * Appends a comparison node. * @param node The node to append. * @param comparator The string name of the operation (the name of the static * {@link BooleanOperation.ComparisonEvaluator} in {@link BooleanOperation}. * @throws TranslationException */ private void appendComparisonNode(AbstractComparisonNode node, String comparator) throws TranslationException { node.getLhs().accept(this); node.getRhs().accept(this); mv.visitFieldInsn(GETSTATIC, determineClassName(BooleanOperation.class), comparator, determineFieldDescriptor(BooleanOperation.ComparisonEvaluator.class)); Type lhsType = node.getLhs().getType() != null ? node.getLhs().getType() : node.getRhs().getType(); Type rhsType = node.getRhs().getType() != null ? node.getRhs().getType() : node.getLhs().getType(); mv.visitMethodInsn(INVOKESTATIC, determineClassName(BooleanOperation.class), "compare", determineMethodDescriptor( Boolean.class, determineJavaClass(lhsType), determineJavaClass(rhsType), BooleanOperation.ComparisonEvaluator.class), false); } /** * Appends a binary arithmetic operation. * @param node A binary operation node. * @param operation The name of the operation (the name of the method in {@link ArithmeticOperation}. * @throws TranslationException */ private void appendBinaryArithmeticOperation(BinaryOperationNode node, String operation) throws TranslationException { node.getLhs().accept(this); node.getRhs().accept(this); if (Type.equals(node.getType(), Type.DECIMAL)) { appendGetMathContext(); } mv.visitMethodInsn(INVOKESTATIC, determineClassName(ArithmeticOperation.class), operation, determineMethodDescriptor( determineJavaClass(node.getType()), determineJavaClass(node.getLhs().getType()), determineJavaClass(node.getRhs().getType()), Type.equals(node.getType(), Type.DECIMAL) ? MathContext.class : null ), false); } /** * Appends a call to {@link AbacusContext#getMathContext()}. Effectively pushing the math context on the stack. */ private void appendGetMathContext() { mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, determineClassName(generatedClassName), "abacusContext", determineFieldDescriptor(AbacusContext.class)); mv.visitMethodInsn(INVOKEINTERFACE, determineClassName(AbacusContext.class), "getMathContext", determineMethodDescriptor(MathContext.class), true); } /** * Appends a call to {@link AbacusContext#getSymbolTable()}. Effectively pushing the symbol table on the stack. */ private void appendGetSymbolTable() { mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, determineClassName(generatedClassName), "abacusContext", determineFieldDescriptor(AbacusContext.class)); mv.visitMethodInsn(INVOKEINTERFACE, determineClassName(AbacusContext.class), "getSymbolTable", determineMethodDescriptor(SymbolTable.class), true); } /** * Reads all variables that are read at any time from the symbol table and place them in the method variable array, * using the index that was generated in {@link #readMethodVariables(Node)}. */ private void appendReadVariableValues() { if (readVariableList.isEmpty()) { return; } Label startLabel = new Label(); Label endLabel = new Label(); Label handlerLabel = new Label(); mv.visitTryCatchBlock(startLabel, endLabel, handlerLabel, determineClassName(NoSuchVariableException.class)); mv.visitLabel(startLabel); for (Variable variable : readVariableList) { appendGetSymbolTable(); mv.visitLdcInsn(variable.getIdentifier()); mv.visitMethodInsn(INVOKEINTERFACE, determineClassName(SymbolTable.class), "getVariableValue", determineMethodDescriptor(Object.class, String.class), true); mv.visitTypeInsn(CHECKCAST, determineClassName(variable.getType())); mv.visitVarInsn(ASTORE, methodVariableIndexes.get(variable.getIdentifier())); } mv.visitLabel(endLabel); Label successLabel = new Label(); mv.visitJumpInsn(GOTO, successLabel); mv.visitLabel(handlerLabel); mv.visitFrame(F_SAME1, 0, null, 1, new Object[]{determineClassName(NoSuchVariableException.class)}); mv.visitTypeInsn(NEW, determineClassName(AbacusRuntimeException.class)); mv.visitInsn(DUP_X1); mv.visitInsn(SWAP); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKEVIRTUAL, determineClassName(Throwable.class), "getMessage", determineMethodDescriptor(String.class), false); mv.visitInsn(SWAP); mv.visitInsn(ICONST_0); mv.visitInsn(SWAP); mv.visitInsn(ICONST_0); mv.visitInsn(SWAP); mv.visitMethodInsn(INVOKESPECIAL, determineClassName(AbacusRuntimeException.class), "<init>", "(Ljava/lang/String;IILjava/lang/Exception;)V", false); mv.visitInsn(ATHROW); mv.visitLabel(successLabel); } /** * Stores all variables that are written at any time frin the method variable array to the symbol table. */ private void appendStoreVariableValues() { if (storeVariableList.isEmpty()) { return; } Label startLabel = new Label(); Label endLabel = new Label(); Label handlerLabel = new Label(); mv.visitTryCatchBlock(startLabel, endLabel, handlerLabel, determineClassName(NoSuchVariableException.class)); mv.visitLabel(startLabel); for (Variable variable : storeVariableList) { appendGetSymbolTable(); mv.visitLdcInsn(variable.getIdentifier()); mv.visitVarInsn(ALOAD, methodVariableIndexes.get(variable.getIdentifier())); mv.visitMethodInsn(INVOKEINTERFACE, determineClassName(SymbolTable.class), "setVariableValue", determineMethodDescriptor(null, String.class, Object.class), true); } mv.visitLabel(endLabel); Label successLabel = new Label(); mv.visitJumpInsn(GOTO, successLabel); mv.visitLabel(handlerLabel); mv.visitFrame(F_SAME1, 0, null, 1, new Object[]{determineClassName(Exception.class)}); mv.visitTypeInsn(NEW, determineClassName(AbacusRuntimeException.class)); mv.visitInsn(DUP_X1); mv.visitInsn(SWAP); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKEVIRTUAL, determineClassName(Throwable.class), "getMessage", determineMethodDescriptor(String.class), false); mv.visitInsn(SWAP); mv.visitInsn(ICONST_0); mv.visitInsn(SWAP); mv.visitInsn(ICONST_0); mv.visitInsn(SWAP); mv.visitMethodInsn(INVOKESPECIAL, determineClassName(AbacusRuntimeException.class), "<init>", "(Ljava/lang/String;IILjava/lang/Exception;)V", false); mv.visitInsn(ATHROW); mv.visitLabel(successLabel); } /** * Determines the Java type from the {@link Type}. * @param type The {@link Type} to translate into a Java type. * @return The Java type. */ private static Class determineJavaClass(Type type) { return JavaTypeHelper.determineJavaType(type); } /** * Appends a label with the line number of the token from which the node was created. */ private void appendLineNumberLabel(Node node) { if (lineNumber == node.getToken().getLineNumber()) { return; } lineNumber = node.getToken().getLineNumber(); Label label = new Label(); mv.visitLabel(label); mv.visitLineNumber(lineNumber, label); } /** * Determines the name of the class in the format with slashes. * @param name The class name. * @return The class name, where dots are replaced with slashes. */ private static String determineClassName(String name) { return name.replaceAll("\\.", "/"); } /** * Determines the name of the class from the given class. * @param clazz The class. * @return The name of the class. */ private static String determineClassName(Class clazz) { return determineClassName(clazz.getName()); } /** * Determines the name of the class that represents the given type. * @param type The type. * @return The name of the class. */ private static String determineClassName(Type type) { return determineClassName(determineJavaClass(type)); } /** * Determines the field descriptor representing the given class. * @param clazz The class. * @return The field descriptor. */ private static String determineFieldDescriptor(Class clazz) { return "L" + determineClassName(clazz) + ";"; } /** * Determines the method descriptor represented by the given classes. * @param returnClass The type of the object returned by the method. * @param argumentsClasses The types of the arguments of the method. * @return The method descriptor. */ private static String determineMethodDescriptor(Class returnClass, Class... argumentsClasses) { StringBuilder descriptor = new StringBuilder(); descriptor.append("("); for (Class clazz : argumentsClasses) { if (clazz == null) { continue; } descriptor.append(determineFieldDescriptor(clazz)); } descriptor.append(")"); if (returnClass == null) { return descriptor.append("V").toString(); } return descriptor.append(determineFieldDescriptor(returnClass)).toString(); } }
/* * 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.ui.table; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.ExpirableRunnable; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.ui.*; import com.intellij.ui.speedSearch.SpeedSearchSupply; import com.intellij.util.ui.*; import com.intellij.util.ui.update.Activatable; import com.intellij.util.ui.update.UiNotifyConnector; import org.jetbrains.annotations.NotNull; import javax.accessibility.Accessible; import javax.accessibility.AccessibleContext; import javax.swing.*; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EventObject; public class JBTable extends JTable implements ComponentWithEmptyText, ComponentWithExpandableItems<TableCell> { public static final int PREFERRED_SCROLLABLE_VIEWPORT_HEIGHT_IN_ROWS = 7; public static final int COLUMN_RESIZE_AREA_WIDTH = 3; // same as in BasicTableHeaderUI private static final int DEFAULT_MIN_COLUMN_WIDTH = 15; // see TableColumn constructor javadoc private final StatusText myEmptyText; private final ExpandableItemsHandler<TableCell> myExpandableItemsHandler; private boolean myEnableAntialiasing; private int myRowHeight = -1; private boolean myRowHeightIsExplicitlySet; private boolean myRowHeightIsComputing; private boolean myUiUpdating = true; private Integer myMinRowHeight; private boolean myStriped; protected AsyncProcessIcon myBusyIcon; private boolean myBusy; private int myMaxItemsForSizeCalculation = Integer.MAX_VALUE; private TableCell rollOverCell; public JBTable() { this(new DefaultTableModel()); } public JBTable(TableModel model) { this(model, null); } public JBTable(final TableModel model, final TableColumnModel columnModel) { super(model, columnModel); setSurrendersFocusOnKeystroke(true); myEmptyText = new StatusText(this) { @Override protected boolean isStatusVisible() { return isEmpty(); } }; myExpandableItemsHandler = ExpandableItemsHandlerFactory.install(this); setFillsViewportHeight(true); addMouseListener(new MyMouseListener()); if (UIUtil.isUnderWin10LookAndFeel()) { addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { Point point = e.getPoint(); int column = columnAtPoint(point); int row = rowAtPoint(point); resetRollOverCell(); if (row >= 0 && row < getRowCount() && column >= 0 && column < getColumnCount()) { TableCellRenderer cellRenderer = getCellRenderer(row, column); if (cellRenderer != null) { Component rc = cellRenderer.getTableCellRendererComponent(JBTable.this, getValueAt(row, column), isCellSelected(row, column), hasFocus(), row, column); if (rc instanceof JCheckBox && (rollOverCell == null || !rollOverCell.at(row, column))) { Rectangle cellRect = getCellRect(row, column, false); rollOverCell = new TableCell(row, column); ((JCheckBox)rc).putClientProperty(UIUtil.CHECKBOX_ROLLOVER_PROPERTY, cellRect); if (getModel() instanceof AbstractTableModel) { ((AbstractTableModel)getModel()).fireTableCellUpdated(row, column); } } } } } }); } final TableModelListener modelListener = new TableModelListener() { @Override public void tableChanged(@NotNull final TableModelEvent e) { onTableChanged(e); } }; if (getModel() != null) getModel().addTableModelListener(modelListener); addPropertyChangeListener("model", new PropertyChangeListener() { @Override public void propertyChange(@NotNull PropertyChangeEvent evt) { UIUtil.repaintViewport(JBTable.this); if (evt.getOldValue() instanceof TableModel) { ((TableModel)evt.getOldValue()).removeTableModelListener(modelListener); } if (evt.getNewValue() instanceof TableModel) { ((TableModel)evt.getNewValue()).addTableModelListener(modelListener); } } }); myUiUpdating = false; new MyCellEditorRemover(); } protected void onTableChanged(@NotNull TableModelEvent e) { if (!myRowHeightIsExplicitlySet) { myRowHeight = -1; } if (e.getType() == TableModelEvent.DELETE && isEmpty() || e.getType() == TableModelEvent.INSERT && !isEmpty() || e.getType() == TableModelEvent.UPDATE) { UIUtil.repaintViewport(this); } } @Override public int getRowHeight() { if (myRowHeightIsComputing) { return super.getRowHeight(); } if (myRowHeight < 0) { try { myRowHeightIsComputing = true; myRowHeight = calculateRowHeight(); } finally { myRowHeightIsComputing = false; } } if (myMinRowHeight == null) { myMinRowHeight = getFontMetrics(UIManager.getFont("Label.font")).getHeight(); } return Math.max(myRowHeight, myMinRowHeight); } protected int calculateRowHeight() { int result = -1; for (int row = 0; row < Math.min(getRowCount(), myMaxItemsForSizeCalculation); row++) { for (int column = 0; column < Math.min(getColumnCount(), myMaxItemsForSizeCalculation); column++) { final TableCellRenderer renderer = getCellRenderer(row, column); if (renderer != null) { final Object value = getValueAt(row, column); final Component component = renderer.getTableCellRendererComponent(this, value, true, true, row, column); if (component != null) { final Dimension size = component.getPreferredSize(); result = Math.max(size.height, result); } } } } return result; } public void setShowColumns(boolean value) { JTableHeader tableHeader = getTableHeader(); tableHeader.setVisible(value); tableHeader.setPreferredSize(value ? null : new Dimension()); } @Override public void setRowHeight(int rowHeight) { if (!myUiUpdating || !UIUtil.isUnderGTKLookAndFeel()) { myRowHeight = rowHeight; myRowHeightIsExplicitlySet = true; } // call super to clean rowModel super.setRowHeight(rowHeight); } @Override public void updateUI() { myUiUpdating = true; try { super.updateUI(); myMinRowHeight = null; } finally { myUiUpdating = false; } } @NotNull @Override protected JTableHeader createDefaultTableHeader() { return new JBTableHeader(); } @Override protected void initializeLocalVars() { super.initializeLocalVars(); setPreferredScrollableViewportSize(JBUI.size(getPreferredScrollableViewportSize())); } public boolean isEmpty() { return getRowCount() == 0; } @Override public void setModel(@NotNull TableModel model) { super.setModel(model); if (model instanceof SortableColumnModel) { final SortableColumnModel sortableModel = (SortableColumnModel)model; if (sortableModel.isSortable()) { final TableRowSorter<TableModel> rowSorter = createRowSorter(model); rowSorter.setSortsOnUpdates(isSortOnUpdates()); setRowSorter(rowSorter); final RowSorter.SortKey sortKey = sortableModel.getDefaultSortKey(); if (sortKey != null && sortKey.getColumn() >= 0 && sortKey.getColumn() < model.getColumnCount()) { if (sortableModel.getColumnInfos()[sortKey.getColumn()].isSortable()) { rowSorter.setSortKeys(Collections.singletonList(sortKey)); } } } else { final RowSorter<? extends TableModel> rowSorter = getRowSorter(); if (rowSorter instanceof DefaultColumnInfoBasedRowSorter) { setRowSorter(null); } } } } protected boolean isSortOnUpdates() { return true; } @Override protected void paintComponent(@NotNull Graphics g) { if (myEnableAntialiasing) { GraphicsUtil.setupAntialiasing(g); } super.paintComponent(g); myEmptyText.paint(this, g); } @Override protected void paintChildren(Graphics g) { if (myEnableAntialiasing) { GraphicsUtil.setupAntialiasing(g); } super.paintChildren(g); } public void setEnableAntialiasing(boolean flag) { myEnableAntialiasing = flag; } public static DefaultCellEditor createBooleanEditor() { return new DefaultCellEditor(new JCheckBox()) { { ((JCheckBox)getComponent()).setHorizontalAlignment(SwingConstants.CENTER); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { Component component = super.getTableCellEditorComponent(table, value, isSelected, row, column); component.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); return component; } }; } public void resetDefaultFocusTraversalKeys() { KeyboardFocusManager m = KeyboardFocusManager.getCurrentKeyboardFocusManager(); for (Integer each : Arrays.asList(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS)) { setFocusTraversalKeys(each, m.getDefaultFocusTraversalKeys(each)); } } @NotNull @Override public StatusText getEmptyText() { return myEmptyText; } @Override @NotNull public ExpandableItemsHandler<TableCell> getExpandableItemsHandler() { return myExpandableItemsHandler; } @Override public void setExpandableItemsEnabled(boolean enabled) { myExpandableItemsHandler.setEnabled(enabled); } @Override public void removeNotify() { super.removeNotify(); if (ScreenUtil.isStandardAddRemoveNotify(this)) { if (myBusyIcon != null) { remove(myBusyIcon); Disposer.dispose(myBusyIcon); myBusyIcon = null; } } } @Override public int getScrollableUnitIncrement(@NotNull Rectangle visibleRect, int orientation, int direction) { if (orientation == SwingConstants.VERTICAL) { return super.getScrollableUnitIncrement(visibleRect, orientation, direction); } else { // if orientation == SwingConstants.HORIZONTAL // use smooth editor-like scrolling return SwingUtilities.computeStringWidth(getFontMetrics(getFont()), " "); } } @Override public void doLayout() { super.doLayout(); if (myBusyIcon != null) { myBusyIcon.updateLocation(this); } } @Override protected Graphics getComponentGraphics(Graphics graphics) { return JBSwingUtilities.runGlobalCGTransform(this, super.getComponentGraphics(graphics)); } @Override public void paint(@NotNull Graphics g) { if (!isEnabled()) { g = new Grayer((Graphics2D)g, getBackground()); } super.paint(g); if (myBusyIcon != null) { myBusyIcon.updateLocation(this); } } public void setPaintBusy(boolean paintBusy) { if (myBusy == paintBusy) return; myBusy = paintBusy; updateBusy(); } private void updateBusy() { if (myBusy) { if (myBusyIcon == null) { myBusyIcon = createBusyIcon(); myBusyIcon.setOpaque(false); myBusyIcon.setPaintPassiveIcon(false); add(myBusyIcon); } } if (myBusyIcon != null) { if (myBusy) { myBusyIcon.resume(); } else { myBusyIcon.suspend(); //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> { if (myBusyIcon != null) { repaint(); } }); } if (myBusyIcon != null) { myBusyIcon.updateLocation(this); } } } @NotNull protected AsyncProcessIcon createBusyIcon() { return new AsyncProcessIcon(toString()).setUseMask(false); } public boolean isStriped() { return myStriped; } public void setStriped(boolean striped) { myStriped = striped; if (striped) { getColumnModel().setColumnMargin(0); setIntercellSpacing(new Dimension(getIntercellSpacing().width, 0)); setShowGrid(false); } } @Override public boolean editCellAt(final int row, final int column, final EventObject e) { if (cellEditor != null && !cellEditor.stopCellEditing()) { return false; } if (row < 0 || row >= getRowCount() || column < 0 || column >= getColumnCount()) { return false; } if (!isCellEditable(row, column)) { return false; } if (e instanceof KeyEvent) { // do not start editing in autoStartsEdit mode on Ctrl-Z and other non-typed events if (!UIUtil.isReallyTypedEvent((KeyEvent)e) || ((KeyEvent)e).getKeyChar() == KeyEvent.CHAR_UNDEFINED) return false; SpeedSearchSupply supply = SpeedSearchSupply.getSupply(this); if (supply != null && supply.isPopupActive()) { return false; } } final TableCellEditor editor = getCellEditor(row, column); if (editor != null && editor.isCellEditable(e)) { editorComp = prepareEditor(editor, row, column); //((JComponent)editorComp).setBorder(null); if (editorComp == null) { removeEditor(); return false; } editorComp.setBounds(getCellRect(row, column, false)); add(editorComp); editorComp.validate(); if (surrendersFocusOnKeyStroke()) { // this replaces focus request in JTable.processKeyBinding final IdeFocusManager focusManager = IdeFocusManager.findInstanceByComponent(this); focusManager.setTypeaheadEnabled(false); focusManager.requestFocus(editorComp, true).doWhenProcessed(() -> focusManager.setTypeaheadEnabled(true)); } setCellEditor(editor); setEditingRow(row); setEditingColumn(column); editor.addCellEditorListener(this); return true; } return false; } /** * Always returns false. * If you're interested in value of JTable.surrendersFocusOnKeystroke property, call JBTable.surrendersFocusOnKeyStroke() * @return false * @see #surrendersFocusOnKeyStroke */ @Override public boolean getSurrendersFocusOnKeystroke() { return false; // prevents JTable.processKeyBinding from requesting editor component to be focused } public boolean surrendersFocusOnKeyStroke() { return super.getSurrendersFocusOnKeystroke(); } private static boolean isTableDecorationSupported() { return UIUtil.isUnderAlloyLookAndFeel() || UIUtil.isUnderNativeMacLookAndFeel() || UIUtil.isUnderDarcula() || UIUtil.isUnderIntelliJLaF() || UIUtil.isUnderNimbusLookAndFeel() || UIUtil.isUnderWindowsLookAndFeel(); } @NotNull @Override public Component prepareRenderer(@NotNull TableCellRenderer renderer, int row, int column) { Component result = super.prepareRenderer(renderer, row, column); // Fix GTK background if (UIUtil.isUnderGTKLookAndFeel()) { UIUtil.changeBackGround(this, UIUtil.getTreeTextBackground()); } if (isTableDecorationSupported() && isStriped() && result instanceof JComponent) { final Color bg = row % 2 == 1 ? getBackground() : UIUtil.getDecoratedRowColor(); final JComponent c = (JComponent)result; final boolean cellSelected = isCellSelected(row, column); if (!cellSelected) { c.setOpaque(true); c.setBackground(bg); for (Component child : c.getComponents()) { child.setBackground(bg); } } } if (myExpandableItemsHandler.getExpandedItems().contains(new TableCell(row, column))) { result = ExpandedItemRendererComponentWrapper.wrap(result); } if(renderer instanceof JCheckBox) { ((JCheckBox)renderer).getModel().setRollover(rollOverCell != null && rollOverCell.at(row, column)); } return result; } private final class MyCellEditorRemover extends Activatable.Adapter implements PropertyChangeListener { private boolean myIsActive = false; public MyCellEditorRemover() { addPropertyChangeListener("tableCellEditor", this); new UiNotifyConnector(JBTable.this, this); } public void activate() { if (!myIsActive) { KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("permanentFocusOwner", this); } myIsActive = true; } public void deactivate() { if (myIsActive) { KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener("permanentFocusOwner", this); } myIsActive = false; } @Override public void hideNotify() { removeCellEditor(); } @Override public void propertyChange(@NotNull final PropertyChangeEvent e) { if ("tableCellEditor".equals(e.getPropertyName())) { tableCellEditorChanged(e.getOldValue(), e.getNewValue()); } else if ("permanentFocusOwner".equals(e.getPropertyName())) { permanentFocusOwnerChanged(); } } private void tableCellEditorChanged(Object from, Object to) { boolean editingStarted = from == null && to != null; boolean editingStopped = from != null && to == null; if (editingStarted) { activate(); } else if (editingStopped) { deactivate(); } } private void permanentFocusOwnerChanged() { if (!isEditing()) { return; } final IdeFocusManager focusManager = IdeFocusManager.findInstanceByComponent(JBTable.this); focusManager.doWhenFocusSettlesDown(new ExpirableRunnable() { @Override public boolean isExpired() { return !isEditing(); } @Override public void run() { Component c = focusManager.getFocusOwner(); if (UIUtil.isMeaninglessFocusOwner(c)) { // this allows using popup menus and menu bar without stopping cell editing return; } while (c != null) { if (c instanceof JPopupMenu) { c = ((JPopupMenu)c).getInvoker(); } if (c == JBTable.this) { // focus remains inside the table return; } else if (c instanceof Window) { if (c == SwingUtilities.getWindowAncestor(JBTable.this)) { removeCellEditor(); } break; } c = c.getParent(); } } }, ModalityState.current()); } private void removeCellEditor() { TableCellEditor cellEditor = getCellEditor(); if (cellEditor != null && !cellEditor.stopCellEditing()) { cellEditor.cancelCellEditing(); } } } private final class MyMouseListener extends MouseAdapter { @Override public void mousePressed(@NotNull final MouseEvent e) { if (JBSwingUtilities.isRightMouseButton(e)) { final int[] selectedRows = getSelectedRows(); if (selectedRows.length < 2) { final int row = rowAtPoint(e.getPoint()); if (row != -1) { getSelectionModel().setSelectionInterval(row, row); } } } } @Override public void mouseExited(MouseEvent e) { if (e.getClickCount() == 0) { resetRollOverCell(); } } } @SuppressWarnings({"MethodMayBeStatic", "unchecked"}) protected TableRowSorter<TableModel> createRowSorter(final TableModel model) { return new DefaultColumnInfoBasedRowSorter(model); } protected static class DefaultColumnInfoBasedRowSorter extends TableRowSorter<TableModel> { public DefaultColumnInfoBasedRowSorter(final TableModel model) { super(model); setModelWrapper(new TableRowSorterModelWrapper(model)); setMaxSortKeys(1); } @Override public Comparator<?> getComparator(final int column) { final TableModel model = getModel(); if (model instanceof SortableColumnModel) { final ColumnInfo[] columnInfos = ((SortableColumnModel)model).getColumnInfos(); if (column >= 0 && column < columnInfos.length) { final Comparator comparator = columnInfos[column].getComparator(); if (comparator != null) return comparator; } } return super.getComparator(column); } @Override protected boolean useToString(int column) { return false; } @Override public boolean isSortable(final int column) { final TableModel model = getModel(); if (model instanceof SortableColumnModel) { final ColumnInfo[] columnInfos = ((SortableColumnModel)model).getColumnInfos(); if (column >= 0 && column < columnInfos.length) { return columnInfos[column].isSortable() && columnInfos[column].getComparator() != null; } } return false; } private class TableRowSorterModelWrapper extends ModelWrapper<TableModel, Integer> { private final TableModel myModel; private TableRowSorterModelWrapper(@NotNull TableModel model) { myModel = model; } @Override public TableModel getModel() { return myModel; } @Override public int getColumnCount() { return myModel.getColumnCount(); } @Override public int getRowCount() { return myModel.getRowCount(); } @Override public Object getValueAt(int row, int column) { if (myModel instanceof SortableColumnModel) { return ((SortableColumnModel)myModel).getRowValue(row); } return myModel.getValueAt(row, column); } @NotNull @Override public String getStringValueAt(int row, int column) { TableStringConverter converter = getStringConverter(); if (converter != null) { // Use the converter String value = converter.toString( myModel, row, column); if (value != null) { return value; } return ""; } // No converter, use getValueAt followed by toString Object o = getValueAt(row, column); if (o == null) { return ""; } String string = o.toString(); if (string == null) { return ""; } return string; } @Override public Integer getIdentifier(int index) { return index; } } } protected class JBTableHeader extends JTableHeader { public JBTableHeader() { super(JBTable.this.columnModel); JBTable.this.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(@NotNull PropertyChangeEvent evt) { if ("enabled".equals(evt.getPropertyName())) { JBTableHeader.this.repaint(); } } }); } @Override public void paint(@NotNull Graphics g) { if (myEnableAntialiasing) { GraphicsUtil.setupAntialiasing(g); } if (!JBTable.this.isEnabled()) { g = new Grayer((Graphics2D)g, getBackground()); } super.paint(g); } @Override public String getToolTipText(@NotNull final MouseEvent event) { final TableModel model = getModel(); if (model instanceof SortableColumnModel) { final int i = columnAtPoint(event.getPoint()); final int infoIndex = i >= 0 ? convertColumnIndexToModel(i) : -1; final ColumnInfo[] columnInfos = ((SortableColumnModel)model).getColumnInfos(); final String tooltipText = infoIndex >= 0 && infoIndex < columnInfos.length ? columnInfos[infoIndex].getTooltipText() : null; if (tooltipText != null) { return tooltipText; } } return super.getToolTipText(event); } @Override protected void processMouseEvent(MouseEvent e) { if (e.getID() == MouseEvent.MOUSE_CLICKED && e.getButton() == MouseEvent.BUTTON1) { int columnToPack = getColumnToPack(e.getPoint()); if (columnToPack != -1 && canResize(columnToPack)) { if (e.getClickCount() % 2 == 0) { packColumn(columnToPack); } return; // prevents click events in column resize area } } super.processMouseEvent(e); } protected void packColumn(int columnToPack) { TableColumn column = getColumnModel().getColumn(columnToPack); int currentWidth = column.getWidth(); int expandedWidth = getExpandedColumnWidth(columnToPack); int newWidth = getColumnModel().getColumnMargin() + (currentWidth >= expandedWidth ? getPreferredHeaderWidth(columnToPack) : expandedWidth); setResizingColumn(column); column.setWidth(newWidth); Dimension tableSize = JBTable.this.getSize(); tableSize.width += newWidth - column.getWidth(); JBTable.this.setSize(tableSize); // let the table update it's layout with resizing column set ApplicationManager.getApplication().invokeLater(() -> setResizingColumn(null)); } private int getColumnToPack(Point p) { int viewColumnIdx = JBTable.this.columnAtPoint(p); if (viewColumnIdx == -1) return -1; Rectangle headerRect = getHeaderRect(viewColumnIdx); boolean atLeftBound = p.x - headerRect.x < COLUMN_RESIZE_AREA_WIDTH; if (atLeftBound) { return viewColumnIdx == 0 ? viewColumnIdx : viewColumnIdx - 1; } boolean atRightBound = headerRect.x + headerRect.width - p.x < COLUMN_RESIZE_AREA_WIDTH; return atRightBound ? viewColumnIdx : -1; } private boolean canResize(int columnIdx) { TableColumnModel columnModel = getColumnModel(); return resizingAllowed && columnModel.getColumn(columnIdx).getResizable(); } } public int getExpandedColumnWidth(int columnToExpand) { int expandedWidth = getPreferredHeaderWidth(columnToExpand); for (int row = 0; row < getRowCount(); row++) { TableCellRenderer cellRenderer = getCellRenderer(row, columnToExpand); if (cellRenderer != null) { Component c = prepareRenderer(cellRenderer, row, columnToExpand); expandedWidth = Math.max(expandedWidth, c.getPreferredSize().width); } } return expandedWidth; } private int getPreferredHeaderWidth(int columnIdx) { TableColumn column = getColumnModel().getColumn(columnIdx); TableCellRenderer renderer = column.getHeaderRenderer(); if (renderer == null) { JTableHeader header = getTableHeader(); if (header == null) { return DEFAULT_MIN_COLUMN_WIDTH; } renderer = header.getDefaultRenderer(); } Object headerValue = column.getHeaderValue(); Component headerCellRenderer = renderer.getTableCellRendererComponent(this, headerValue, false, false, -1, columnIdx); return headerCellRenderer.getPreferredSize().width; } /** * JTable gets table data from model lazily - only for a table part to be shown. * JBTable loads <i>all</i> the data on initialization to calculate cell size. * This methods provides possibility to calculate size without loading all the table data. * * @param maxItemsForSizeCalculation maximum number ot items in table to be loaded for size calculation */ public void setMaxItemsForSizeCalculation(int maxItemsForSizeCalculation) { myMaxItemsForSizeCalculation = maxItemsForSizeCalculation; } @Override public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new AccessibleJBTable(); } return accessibleContext; } /** * Specialization of {@link AccessibleJTable} to ensure instances of * {@link AccessibleJBTableCell}, as opposed to {@link AccessibleJTableCell}, * are created in all code paths. */ protected class AccessibleJBTable extends AccessibleJTable { @Override public Accessible getAccessibleChild(int i) { if (i < 0 || i >= getAccessibleChildrenCount()) { return null; } else { int column = getAccessibleColumnAtIndex(i); int row = getAccessibleRowAtIndex(i); return new AccessibleJBTableCell(JBTable.this, row, column, getAccessibleIndexAt(row, column)); } } @Override public Accessible getAccessibleAt(Point p) { int column = columnAtPoint(p); int row = rowAtPoint(p); if ((column != -1) && (row != -1)) { return getAccessibleChild(getAccessibleIndexAt(row, column)); } return null; } /** * Specialization of {@link AccessibleJTableCell} to ensure the underlying cell renderer * is obtained by calling the virtual method {@link JTable#getCellRenderer(int, int)}. * * <p> * NOTE: The reason we need this class is that even though the documentation of the * {@link JTable#getCellRenderer(int, int)} method mentions that * </p> * * <pre> * Throughout the table package, the internal implementations always * use this method to provide renderers so that this default behavior * can be safely overridden by a subclass. * </pre> * * <p> * the {@link AccessibleJTableCell#getCurrentComponent()} and * {@link AccessibleJTableCell#getCurrentAccessibleContext()} methods do not * respect that contract, instead using a <strong>copy</strong> of the default * implementation of {@link JTable#getCellRenderer(int, int)}. * </p> * * <p> * There are a few derived classes of {@link JBTable}, e.g. * {@link com.intellij.ui.dualView.TreeTableView} that depend on the ability to * override {@link JTable#getCellRenderer(int, int)} method to behave correctly, * so we need to ensure we go through the same code path to ensure correct * accessibility behavior. * </p> */ protected class AccessibleJBTableCell extends AccessibleJTableCell { private final int myRow; private final int myColumn; public AccessibleJBTableCell(JTable table, int row, int columns, int index) { super(table, row, columns, index); this.myRow = row; this.myColumn = columns; } @Override protected Component getCurrentComponent() { return JBTable.this .getCellRenderer(myRow, myColumn) .getTableCellRendererComponent(JBTable.this, getValueAt(myRow, myColumn), false, false, myRow, myColumn); } @Override protected AccessibleContext getCurrentAccessibleContext() { Component c = getCurrentComponent(); if (c instanceof Accessible) return c.getAccessibleContext(); // Note: don't call "super" as 1) we know for sure the cell is not accessible // and 2) the super implementation is incorrect anyways return null; } } } private void resetRollOverCell() { if (UIUtil.isUnderWin10LookAndFeel() && getModel() instanceof AbstractTableModel && rollOverCell != null) { TableCellRenderer cellRenderer = getCellRenderer(rollOverCell.row, rollOverCell.column); if (cellRenderer != null) { Object value = getValueAt(rollOverCell.row, rollOverCell.column); boolean selected = isCellSelected(rollOverCell.row, rollOverCell.column); Component rc = cellRenderer.getTableCellRendererComponent(this, value, selected, hasFocus(), rollOverCell.row, rollOverCell.column); if (rc instanceof JCheckBox) { ((JCheckBox)rc).putClientProperty(UIUtil.CHECKBOX_ROLLOVER_PROPERTY, null); } } if (getModel() instanceof AbstractTableModel) { ((AbstractTableModel)getModel()).fireTableCellUpdated(rollOverCell.row, rollOverCell.column); } rollOverCell = null; } } }
/** * University of Campinas - Brazil * Institute of Computing * SED group * * date: February 2009 * */ package br.unicamp.ic.sed.mobilemedia.album.impl; import javax.microedition.lcdui.Alert; import javax.microedition.lcdui.AlertType; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.List; import javax.microedition.midlet.MIDlet; import br.unicamp.ic.sed.mobilemedia.album.spec.dt.Constants; import br.unicamp.ic.sed.mobilemedia.album.spec.prov.IManager; import br.unicamp.ic.sed.mobilemedia.album.spec.req.IFilesystem; import br.unicamp.ic.sed.mobilemedia.album.spec.req.IMobileResources; class AlbumController extends AbstractController { private MIDlet midlet; //private AlbumListScreen albumListScreen; public AlbumController(MIDlet midlet, AlbumListScreen albumListScreen) { super(midlet, albumListScreen); this.midlet = midlet; //this.albumListScreen = albumListScreen; } /*(non-Javadoc) * @see ubc.midp.mobilephoto.core.ui.controller.ControllerInterface#handleCommand(javax.microedition.lcdui.Command, javax.microedition.lcdui.Displayable)*/ public boolean handleCommand(Command command) { String label = command.getLabel(); System.out.println( "<*"+this.getClass().getName()+".handleCommand() *> " + label); IManager manager = ComponentFactory.createInstance(); IFilesystem filesystem = (IFilesystem) manager.getRequiredInterface("IFilesystem"); if (label.equals("Reset")) { System.out.println("<* BaseController.handleCommand() *> Reset Photo Album"); resetImageData(); ScreenSingleton.getInstance().setCurrentScreenName(Constants.ALBUMLIST_SCREEN); this.goToPreviousScreen(); return true; /** Case: Create PhotoAlbum **/ }else if (label.equals("New Photo Album")) { ScreenSingleton.getInstance().setCurrentScreenName(Constants.NEWALBUM_SCREEN); NewLabelScreen newLabelScreen = new NewLabelScreen("Add new Photo Album", NewLabelScreen.NEW_ALBUM); newLabelScreen.setCommandListener(this); this.setCurrentScreen(newLabelScreen); newLabelScreen = null; return true; /** Case: Delete Album Photo**/ }else if (label.equals("Delete Album")) { this.deletePhotoAlbum(); return true; /** * TODO [EF] I think this confirmation questions are complicating the implementation * [EF] How do you know that "Yes - Delete" is to delete Photo Album instead of Photo? * Case: Yes delete Photo Album **/ }else if (label.equals("Yes - Delete")) { //delete photo album //begin - modified in MobileMedia-Cosmos-OO-v4 String albumName = ScreenSingleton.getInstance().getCurrentStoreName(); filesystem.deletePhotoAlbum(albumName); //end - modified in MobileMedia-Cosmos-OO-v4 goToPreviousScreen(); return true; /** * [EF] Same question. How do you know that "No - Delete" is to delete Photo Album instead of Photo? * Case: No delete Photo Album **/ }else if (label.equals("No - Delete")) { goToPreviousScreen(); return true; /** * [EF] Again, see [EF] comments above. * Case: Save new Photo Album **/ } else if (label.equals("Save new label")) { Displayable displayable = getCurrentScreen(); System.out.println("[AlbumController] displayable = "+displayable); if ( displayable instanceof NewLabelScreen) { //begin - modified in MobileMedia-Cosmos-OO-v4 NewLabelScreen currentScreen = (NewLabelScreen)getCurrentScreen(); if (currentScreen.getFormType() == NewLabelScreen.NEW_ALBUM){ String albumName = currentScreen.getLabelName(); System.out.println("[AlbumController] filesystem = "+filesystem); filesystem.createNewPhotoAlbum(albumName); } else{ if (currentScreen.getFormType() == NewLabelScreen.LABEL_PHOTO) { //do nothing? } } //end - modified in MobileMedia-Cosmos-OO-v4 } goToPreviousScreen(); return true; } return false; } /** * This option is mainly for testing purposes. If the record store * on the device or emulator gets into an unstable state, or has too * many images, you can reset it, which clears the record stores and * re-creates them with the default images bundled with the application * @throws PersistenceMechanismException */ private void resetImageData() { //begin - modified in MobileMedia-Cosmos-OO-v4 IManager manager = ComponentFactory.createInstance(); IFilesystem filesystem = (IFilesystem) manager.getRequiredInterface("IFilesystem"); filesystem.resetImageData(); //end - modified in MobileMedia-Cosmos-OO-v4 //Clear the names from the album list for (int i = 0; i < getAlbumListScreen().size(); i++) { getAlbumListScreen().delete(i); } //Get the default ones from the album //begin - modified in MobileMedia-Cosmos-OO-v4 String[] albumNames = filesystem.getAlbumNames(); //end - modified in MobileMedia-Cosmos-OO-v4 for (int i = 0; i < albumNames.length; i++) { if (albumNames[i] != null) { //Add album name to menu list getAlbumListScreen().append(albumNames[i], null); } } setCurrentScreen(getAlbumListScreen()); } private void goToPreviousScreen() { System.out.println("<* AlbumController.goToPreviousScreen() *>"); IManager manager = ComponentFactory.createInstance(); IFilesystem filesystem = (IFilesystem) manager.getRequiredInterface("IFilesystem"); String[] albumNames = filesystem.getAlbumNames(); //debug for(int i=0;i<albumNames.length;i++){ System.out.println("[AlbumController]albumNames["+i+"]="+albumNames[i]); } AlbumListScreen albumListScreen = this.getAlbumListScreen(); System.out.println("[AlbumController]albumListScreen="+albumListScreen); albumListScreen.repaintListAlbum( albumNames ); //add commands to screen albumListScreen.initMenu(); this.setCurrentScreen( albumListScreen ); ScreenSingleton.getInstance().setCurrentScreenName(Constants.ALBUMLIST_SCREEN); albumListScreen.setCommandListener(this); System.out.println("[AlbumController] going to album list screen..."); } /*protected void initAlbum(){ //Get all MobilePhoto defined albums from the record store IManager manager = ComponentFactory.createInstance(); IFilesystem filesystem = (IFilesystem) manager.getRequiredInterface("IFilesystem"); String[] albumNames = filesystem.getAlbumNames(); IAlbum album = (IAlbum) manager.getRequiredInterface("IAlbum"); AlbumListScreen albumListScreen = super.getAlbumListScreen(); album.initAlbumListScreen( albumNames ); albumListScreen.setCommandListener( this ); }*/ /** * Set the current screen for display */ public void setCurrentScreen(Displayable d) { IManager manager = ComponentFactory.createInstance(); IMobileResources iMobileResources = (IMobileResources)manager.getRequiredInterface("IMobileResources"); MIDlet midlet = iMobileResources.getMainMIDlet(); Display.getDisplay(midlet).setCurrent(d); } /** * Set the current screen for display */ protected void setCurrentScreen(Alert a , Displayable d) { IManager manager = ComponentFactory.createInstance(); IMobileResources iMobileResources = (IMobileResources)manager.getRequiredInterface("IMobileResources"); MIDlet midlet = iMobileResources.getMainMIDlet(); Display.getDisplay(midlet).setCurrent(a , d); } private void deletePhotoAlbum(){ System.out.println("Delete Photo Album here"); List down = (List) Display.getDisplay(midlet).getCurrent(); ScreenSingleton.getInstance().setCurrentScreenName(Constants.CONFIRMDELETEALBUM_SCREEN); ScreenSingleton.getInstance().setCurrentStoreName(down.getString(down.getSelectedIndex())); String message = "Would you like to remove the album "+ScreenSingleton.getInstance().getCurrentStoreName(); Alert deleteConfAlert = new Alert("Delete Photo Album", message,null,AlertType.CONFIRMATION); deleteConfAlert.setTimeout(Alert.FOREVER); deleteConfAlert.addCommand(new Command("Yes - Delete", Command.OK, 2)); deleteConfAlert.addCommand(new Command("No - Delete", Command.CANCEL, 2)); setAlbumListAsCurrentScreen(deleteConfAlert); deleteConfAlert.setCommandListener(this); } }
package com.remind.me.fninaber; import android.app.Activity; import android.app.AlertDialog; import android.app.LoaderManager; import android.app.SearchManager; import android.content.Context; import android.content.CursorLoader; import android.content.DialogInterface; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.os.Bundle; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ListView; import com.remind.me.fninaber.adapter.TaskAdapter; import com.remind.me.fninaber.db.TableTask; import com.remind.me.fninaber.db.TaskHelper; import com.remind.me.fninaber.model.Task; import com.remind.me.fninaber.util.DateUtil; import com.remind.me.fninaber.util.TaskManager; import com.remind.me.fninaber.widget.BaseFragment; public class HistoryFragment extends BaseFragment implements OnClickListener, LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener, OnItemLongClickListener { private static final String TAG = HistoryFragment.class.getSimpleName(); private static final int CURSOR_LOADER_TASK = 102; private ListView mListView; private TaskAdapter mAdapter; private String mOrder; private static final String ASC = " ASC"; private View root; private BaseActivity activity; private static final String KEY_SELECTION = "selection"; public static final String KEY_DAY = "day"; @Override public void onAttach(Activity activity) { super.onAttach(activity); this.activity = (BaseActivity) activity; } @Override public void onDetach() { super.onDetach(); this.activity = null; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setHasOptionsMenu(true); // mSelection = null; mOrder = TableTask.Column.TIMESTAMP + ASC; mAdapter = new TaskAdapter(activity, null, false); activity.getLoaderManager().initLoader(CURSOR_LOADER_TASK, null, this); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); activity.getMenuInflater().inflate(R.menu.search, menu); SearchManager manager = (SearchManager) activity.getSystemService(Context.SEARCH_SERVICE); SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView(); search.setSearchableInfo(manager.getSearchableInfo(activity.getComponentName())); search.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextChange(String query) { Bundle args = new Bundle(); if (!TextUtils.isEmpty(query)) { StringBuilder selection = new StringBuilder(); selection.append(TableTask.Column.TITLE + " LIKE " + "\"%" + query + "%\""); selection.append(" OR "); selection.append(TableTask.Column.NOTES + " LIKE " + "\"%" + query + "%\""); args.putString(KEY_SELECTION, selection.toString()); } activity.getLoaderManager().restartLoader(CURSOR_LOADER_TASK, args, HistoryFragment.this); return true; } @Override public boolean onQueryTextSubmit(String query) { Bundle args = new Bundle(); if (!TextUtils.isEmpty(query)) { StringBuilder selection = new StringBuilder(); selection.append(TableTask.Column.TITLE + " LIKE " + "\"%" + query + "%\""); selection.append(" OR "); selection.append(TableTask.Column.NOTES + " LIKE " + "\"%" + query + "%\""); args.putString(KEY_SELECTION, selection.toString()); } activity.getLoaderManager().restartLoader(CURSOR_LOADER_TASK, args, HistoryFragment.this); return true; } }); } @Override public void onResume() { super.onResume(); // Start - Update alarm TaskManager.getInstance(activity).startTaskAlarm(activity.getContentResolver(), System.currentTimeMillis()); ((Toolbar)activity.findViewById(R.id.toolbar)).setTitle(activity.getResources().getString(R.string.history)); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { root = inflater.inflate(R.layout.fragment_home, container, false); mListView = (ListView) root.findViewById(R.id.list_task); mListView.setAdapter(mAdapter); mListView.setOnItemClickListener(this); mListView.setOnItemLongClickListener(this); return root; } @Override public void onClick(View v) { } @Override public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) { if (null != cursor && null != mAdapter) { mAdapter.changeCursor(cursor); } } @Override public void onLoaderReset(Loader<Cursor> arg0) { if (null != mAdapter) { mAdapter.swapCursor(null); } } @Override public Loader<Cursor> onCreateLoader(int arg0, Bundle bundle) { String mSelection = null; if (null != bundle) { mSelection = bundle.getString(KEY_SELECTION); } return new CursorLoader(activity, TableTask.CONTENT_URI, null, mSelection, null, mOrder); } @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if (null != mAdapter) { final Task task = TaskHelper.getInstance().cursorToTask((Cursor) mAdapter.getItem(position)); DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int position) { switch (position) { case Constants.MENU_EDIT: { Task task = TaskHelper.getInstance().cursorToTask((Cursor) mAdapter.getItem(position)); Intent i = new Intent(activity, AddTaskActivity.class); i.putExtra(Constants.TASK, task); activity.startActivity(i); break; } case Constants.MENU_DELETE: { TaskHelper.getInstance().deleteByTID(activity.getContentResolver(), task.getTID()); break; } } dialog.dismiss(); } }; AlertDialog dialog = createDialog(task.getTID(), listener); dialog.show(); } return true; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (null != mAdapter) { Task task = TaskHelper.getInstance().cursorToTask((Cursor) mAdapter.getItem(position)); Intent i = new Intent(activity, AddTaskActivity.class); i.putExtra(Constants.TASK, task); i.putExtra(Constants.VIEW, true); activity.startActivity(i); } } private AlertDialog createDialog(String TID, DialogInterface.OnClickListener listener) { String[] menuItems = { activity.getResources().getString(R.string.menu_edit), activity.getResources().getString(R.string.menu_delete) }; AlertDialog.Builder dialog = new AlertDialog.Builder(activity); dialog.setTitle("Select").setCancelable(true).setItems(menuItems, listener); return dialog.create(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_calendar: { if(TaskHelper.getInstance().getCursorCount(activity.getContentResolver()) > 0){ Intent i = new Intent(activity, CalendarActivity.class); startActivityForResult(i, 0); } break; } default: break; } return true; } @Override public void onDestroy() { super.onDestroy(); getLoaderManager().destroyLoader(CURSOR_LOADER_TASK); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == Activity.RESULT_OK){ String day = data.getStringExtra(KEY_DAY); long timestamp = DateUtil.timestampDay(day); long oneDayAfter = timestamp + (24 * 60 * 60 * 1000); // one day Bundle args = new Bundle(); String selection = TableTask.Column.TIMESTAMP + " > " + "\"" + timestamp + "\"" + " AND " + TableTask.Column.TIMESTAMP + " < " + "\"" + oneDayAfter + "\""; args.putString(KEY_SELECTION, selection); activity.getLoaderManager().restartLoader(CURSOR_LOADER_TASK, args, HistoryFragment.this); } } }
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.workers.internal; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.gradle.api.file.FileCollection; import org.gradle.api.internal.file.FileResolver; import org.gradle.process.JavaForkOptions; import org.gradle.process.ProcessForkOptions; import org.gradle.process.internal.DefaultJavaForkOptions; import org.gradle.process.internal.JavaForkOptionsInternal; import java.io.File; import java.util.Collections; import java.util.List; import java.util.Map; public class DaemonForkOptionsBuilder { private final JavaForkOptionsInternal javaForkOptions; private final FileResolver fileResolver; private Iterable<File> classpath = Collections.emptyList(); private Iterable<String> sharedPackages = Collections.emptyList(); private KeepAliveMode keepAliveMode = KeepAliveMode.DAEMON; public DaemonForkOptionsBuilder(FileResolver resolver) { this.fileResolver = resolver; javaForkOptions = new DefaultJavaForkOptions(resolver); } public DaemonForkOptionsBuilder classpath(Iterable<File> classpath) { this.classpath = classpath; return this; } public DaemonForkOptionsBuilder sharedPackages(Iterable<String> sharedPackages) { this.sharedPackages = sharedPackages; return this; } public DaemonForkOptionsBuilder keepAliveMode(KeepAliveMode keepAliveMode) { this.keepAliveMode = keepAliveMode; return this; } public DaemonForkOptionsBuilder javaForkOptions(JavaForkOptions javaForkOptions) { javaForkOptions.copyTo(this.javaForkOptions); return this; } public DaemonForkOptions build() { return new DaemonForkOptions(buildJavaForkOptions(), classpath, sharedPackages, keepAliveMode); } private ImmutableJavaForkOptions buildJavaForkOptions() { JavaForkOptionsInternal delegate = new DefaultJavaForkOptions(fileResolver); javaForkOptions.copyTo(delegate); return new ImmutableJavaForkOptions(delegate); } private static class ImmutableJavaForkOptions implements JavaForkOptionsInternal { private final JavaForkOptionsInternal delegate; public ImmutableJavaForkOptions(JavaForkOptionsInternal delegate) { this.delegate = delegate; } @Override public String getExecutable() { return delegate.getExecutable(); } @Override public void setExecutable(String executable) { throw new UnsupportedOperationException(); } @Override public Map<String, Object> getSystemProperties() { return ImmutableMap.copyOf(delegate.getSystemProperties()); } @Override public void setExecutable(Object executable) { throw new UnsupportedOperationException(); } @Override public void setSystemProperties(Map<String, ?> properties) { throw new UnsupportedOperationException(); } @Override public ProcessForkOptions executable(Object executable) { throw new UnsupportedOperationException(); } @Override public JavaForkOptions systemProperties(Map<String, ?> properties) { throw new UnsupportedOperationException(); } @Override public File getWorkingDir() { return delegate.getWorkingDir(); } @Override public void setWorkingDir(File dir) { throw new UnsupportedOperationException(); } @Override public JavaForkOptions systemProperty(String name, Object value) { throw new UnsupportedOperationException(); } @Override public void setWorkingDir(Object dir) { throw new UnsupportedOperationException(); } @Override public String getDefaultCharacterEncoding() { return delegate.getDefaultCharacterEncoding(); } @Override public ProcessForkOptions workingDir(Object dir) { throw new UnsupportedOperationException(); } @Override public Map<String, Object> getEnvironment() { return ImmutableMap.copyOf(delegate.getEnvironment()); } @Override public void setEnvironment(Map<String, ?> environmentVariables) { throw new UnsupportedOperationException(); } @Override public void setDefaultCharacterEncoding(String defaultCharacterEncoding) { throw new UnsupportedOperationException(); } @Override public ProcessForkOptions environment(Map<String, ?> environmentVariables) { throw new UnsupportedOperationException(); } @Override public String getMinHeapSize() { return delegate.getMinHeapSize(); } @Override public void setMinHeapSize(String heapSize) { throw new UnsupportedOperationException(); } @Override public ProcessForkOptions environment(String name, Object value) { throw new UnsupportedOperationException(); } @Override public ProcessForkOptions copyTo(ProcessForkOptions options) { throw new UnsupportedOperationException(); } @Override public String getMaxHeapSize() { return delegate.getMaxHeapSize(); } @Override public void setMaxHeapSize(String heapSize) { throw new UnsupportedOperationException(); } @Override public List<String> getJvmArgs() { return ImmutableList.copyOf(delegate.getJvmArgs()); } @Override public void setJvmArgs(List<String> arguments) { throw new UnsupportedOperationException(); } @Override public void setJvmArgs(Iterable<?> arguments) { throw new UnsupportedOperationException(); } @Override public JavaForkOptions jvmArgs(Iterable<?> arguments) { throw new UnsupportedOperationException(); } @Override public JavaForkOptions jvmArgs(Object... arguments) { throw new UnsupportedOperationException(); } @Override public FileCollection getBootstrapClasspath() { return delegate.getBootstrapClasspath(); } @Override public void setBootstrapClasspath(FileCollection classpath) { throw new UnsupportedOperationException(); } @Override public JavaForkOptions bootstrapClasspath(Object... classpath) { throw new UnsupportedOperationException(); } @Override public boolean getEnableAssertions() { return delegate.getEnableAssertions(); } @Override public void setEnableAssertions(boolean enabled) { throw new UnsupportedOperationException(); } @Override public boolean getDebug() { return delegate.getDebug(); } @Override public void setDebug(boolean enabled) { throw new UnsupportedOperationException(); } @Override public List<String> getAllJvmArgs() { return ImmutableList.copyOf(delegate.getAllJvmArgs()); } @Override public void setAllJvmArgs(List<String> arguments) { throw new UnsupportedOperationException(); } @Override public void setAllJvmArgs(Iterable<?> arguments) { throw new UnsupportedOperationException(); } @Override public JavaForkOptions copyTo(JavaForkOptions options) { return delegate.copyTo(options); } @Override public JavaForkOptionsInternal mergeWith(JavaForkOptions options) { return new ImmutableJavaForkOptions(delegate.mergeWith(options)); } @Override public boolean isCompatibleWith(JavaForkOptions options) { return delegate.isCompatibleWith(options); } } }
/* * Copyright 2015-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.cxx; import com.facebook.buck.graph.AbstractBreadthFirstTraversal; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.Flavor; import com.facebook.buck.model.ImmutableFlavor; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.TargetGraph; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicates; import com.google.common.base.Suppliers; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; import java.nio.file.Path; public final class CxxInferEnhancer { private CxxInferEnhancer() {} public static final Flavor INFER = ImmutableFlavor.of("infer"); public static final Flavor INFER_ANALYZE = ImmutableFlavor.of("infer-analyze"); static class CxxInferCaptureAndAnalyzeRules { final ImmutableSet<CxxInferCapture> captureRules; final ImmutableSet<CxxInferAnalyze> allAnalyzeRules; CxxInferCaptureAndAnalyzeRules( ImmutableSet<CxxInferCapture> captureRules, ImmutableSet<CxxInferAnalyze> allAnalyzeRules) { this.captureRules = captureRules; this.allAnalyzeRules = allAnalyzeRules; } } public static BuildTarget createInferAnalyzeBuildTarget(BuildTarget target) { return BuildTarget .builder(target) .addFlavors( ImmutableFlavor.of(INFER_ANALYZE.toString())) .build(); } public static CxxInferReport requireInferAnalyzeAndReportBuildRuleForCxxDescriptionArg( TargetGraph targetGraph, BuildRuleParams params, BuildRuleResolver resolver, SourcePathResolver pathResolver, CxxPlatform cxxPlatform, CxxConstructorArg args, CxxInferTools inferTools) { Optional<CxxInferReport> existingRule = resolver.getRuleOptionalWithType( params.getBuildTarget(), CxxInferReport.class); if (existingRule.isPresent()) { return existingRule.get(); } BuildRuleParams paramsWithoutInferFlavorWithInferAnalyzeFlavor = params .withoutFlavor(INFER) .withFlavor(INFER_ANALYZE); CxxInferAnalyze analysisRule = requireInferAnalyzeBuildRuleForCxxDescriptionArg( targetGraph, paramsWithoutInferFlavorWithInferAnalyzeFlavor, resolver, pathResolver, cxxPlatform, args, inferTools); return createInferReportRule( params, resolver, pathResolver, analysisRule); } public static CxxInferAnalyze requireInferAnalyzeBuildRuleForCxxDescriptionArg( TargetGraph targetGraph, BuildRuleParams params, BuildRuleResolver resolver, SourcePathResolver pathResolver, CxxPlatform cxxPlatform, CxxConstructorArg args, CxxInferTools inferTools) { BuildTarget inferAnalyzeBuildTarget = createInferAnalyzeBuildTarget(params.getBuildTarget()); Optional<CxxInferAnalyze> existingRule = resolver.getRuleOptionalWithType( inferAnalyzeBuildTarget, CxxInferAnalyze.class); if (existingRule.isPresent()) { return existingRule.get(); } BuildRuleParams paramsWithoutInferFlavor = params.withoutFlavor(INFER_ANALYZE); ImmutableMap<Path, SourcePath> headers = CxxDescriptionEnhancer.parseHeaders( paramsWithoutInferFlavor, resolver, cxxPlatform, args); ImmutableMap<String, SourcePath> lexSrcs = CxxDescriptionEnhancer.parseLexSources( paramsWithoutInferFlavor, resolver, args); ImmutableMap<String, SourcePath> yaccSrcs = CxxDescriptionEnhancer.parseYaccSources( paramsWithoutInferFlavor, resolver, args); // Setup the header symlink tree and combine all the preprocessor input from this rule // and all dependencies. HeaderSymlinkTree headerSymlinkTree = CxxDescriptionEnhancer.requireHeaderSymlinkTree( paramsWithoutInferFlavor, resolver, pathResolver, cxxPlatform, /* includeLexYaccHeaders */ true, lexSrcs, yaccSrcs, headers, HeaderVisibility.PRIVATE); ImmutableList<CxxPreprocessorInput> preprocessorInputs; if (args instanceof CxxBinaryDescription.Arg) { preprocessorInputs = computePreprocessorInputForCxxBinaryDescriptionArg( targetGraph, paramsWithoutInferFlavor, pathResolver, cxxPlatform, (CxxBinaryDescription.Arg) args, headerSymlinkTree); } else if (args instanceof CxxLibraryDescription.Arg) { preprocessorInputs = computePreprocessorInputForCxxLibraryDescriptionArg( targetGraph, paramsWithoutInferFlavor, resolver, pathResolver, cxxPlatform, (CxxLibraryDescription.Arg) args, headerSymlinkTree); } else { throw new IllegalStateException("Only Binary and Library args supported."); } // Build all the transitive dependencies build rules with the Infer's flavor ImmutableSet<CxxInferAnalyze> transitiveDepsLibraryRules = requireTransitiveDependentLibraries( targetGraph, cxxPlatform, paramsWithoutInferFlavor.getDeps()); // Setup the rules to run lex/yacc. CxxHeaderSourceSpec lexYaccSources = CxxDescriptionEnhancer.requireLexYaccSources( paramsWithoutInferFlavor, resolver, pathResolver, cxxPlatform, lexSrcs, yaccSrcs); ImmutableMap<String, CxxSource> srcs = CxxDescriptionEnhancer.parseCxxSources( paramsWithoutInferFlavor, resolver, cxxPlatform, args); // The complete list of input sources. ImmutableMap<String, CxxSource> sources = ImmutableMap.<String, CxxSource>builder() .putAll(srcs) .putAll(lexYaccSources.getCxxSources()) .build(); CxxInferCaptureAndAnalyzeRules cxxInferCaptureAndAnalyzeRules = new CxxInferCaptureAndAnalyzeRules( createInferCaptureBuildRules( paramsWithoutInferFlavor, resolver, cxxPlatform, sources, CxxSourceRuleFactory.PicType.PDC, inferTools, preprocessorInputs, CxxFlags.getFlags( args.compilerFlags, args.platformCompilerFlags, cxxPlatform), args.prefixHeader), transitiveDepsLibraryRules); return createInferAnalyzeRule( params, resolver, inferAnalyzeBuildTarget, pathResolver, inferTools, cxxInferCaptureAndAnalyzeRules); } private static ImmutableSet<CxxInferAnalyze> requireTransitiveDependentLibraries( final TargetGraph targetGraph, final CxxPlatform cxxPlatform, final Iterable<? extends BuildRule> deps) { final ImmutableSet.Builder<CxxInferAnalyze> depsBuilder = ImmutableSet.builder(); AbstractBreadthFirstTraversal<BuildRule> visitor = new AbstractBreadthFirstTraversal<BuildRule>(deps) { @Override public ImmutableSet<BuildRule> visit(BuildRule buildRule) { if (buildRule instanceof CxxLibrary) { CxxLibrary library = (CxxLibrary) buildRule; depsBuilder.add( (CxxInferAnalyze) library.requireBuildRule( targetGraph, INFER_ANALYZE, cxxPlatform.getFlavor())); return buildRule.getDeps(); } return ImmutableSet.of(); } }; visitor.start(); return depsBuilder.build(); } private static ImmutableList<CxxPreprocessorInput> computePreprocessorInputForCxxBinaryDescriptionArg( TargetGraph targetGraph, BuildRuleParams params, SourcePathResolver pathResolver, CxxPlatform cxxPlatform, CxxBinaryDescription.Arg args, HeaderSymlinkTree headerSymlinkTree) { return CxxDescriptionEnhancer.collectCxxPreprocessorInput( targetGraph, params, cxxPlatform, CxxFlags.getLanguageFlags( args.preprocessorFlags, args.platformPreprocessorFlags, args.langPreprocessorFlags, cxxPlatform), ImmutableList.of(headerSymlinkTree), CxxDescriptionEnhancer.getFrameworkSearchPaths( args.frameworks, cxxPlatform, pathResolver), CxxPreprocessables.getTransitiveCxxPreprocessorInput( targetGraph, cxxPlatform, FluentIterable.from(params.getDeps()) .filter(Predicates.instanceOf(CxxPreprocessorDep.class)))); } private static ImmutableList<CxxPreprocessorInput> computePreprocessorInputForCxxLibraryDescriptionArg( TargetGraph targetGraph, BuildRuleParams params, BuildRuleResolver resolver, SourcePathResolver pathResolver, CxxPlatform cxxPlatform, CxxLibraryDescription.Arg args, HeaderSymlinkTree headerSymlinkTree) { return CxxDescriptionEnhancer.collectCxxPreprocessorInput( targetGraph, params, cxxPlatform, CxxFlags.getLanguageFlags( args.preprocessorFlags, args.platformPreprocessorFlags, args.langPreprocessorFlags, cxxPlatform), ImmutableList.of(headerSymlinkTree), ImmutableSet.<Path>of(), CxxLibraryDescription.getTransitiveCxxPreprocessorInput( targetGraph, params, resolver, pathResolver, cxxPlatform, CxxFlags.getLanguageFlags( args.exportedPreprocessorFlags, args.exportedPlatformPreprocessorFlags, args.exportedLangPreprocessorFlags, cxxPlatform), CxxDescriptionEnhancer.parseExportedHeaders(params, resolver, cxxPlatform, args), CxxDescriptionEnhancer.getFrameworkSearchPaths( args.frameworks, cxxPlatform, pathResolver))); } private static ImmutableSet<CxxInferCapture> createInferCaptureBuildRules( final BuildRuleParams params, final BuildRuleResolver resolver, CxxPlatform cxxPlatform, ImmutableMap<String, CxxSource> sources, CxxSourceRuleFactory.PicType picType, CxxInferTools inferTools, ImmutableList<CxxPreprocessorInput> cxxPreprocessorInputs, ImmutableList<String> compilerFlags, Optional<SourcePath> prefixHeader) { CxxSourceRuleFactory factory = new CxxSourceRuleFactory( params, resolver, new SourcePathResolver(resolver), cxxPlatform, cxxPreprocessorInputs, compilerFlags, prefixHeader); return factory.createInferCaptureBuildRules( sources, picType, inferTools); } private static CxxInferAnalyze createInferAnalyzeRule( BuildRuleParams buildRuleParams, BuildRuleResolver resolver, BuildTarget inferAnalyzeBuildTarget, SourcePathResolver pathResolver, CxxInferTools inferTools, CxxInferCaptureAndAnalyzeRules captureAnalyzeRules) { return resolver.addToIndex( new CxxInferAnalyze( buildRuleParams.copyWithChanges( inferAnalyzeBuildTarget, Suppliers.ofInstance( ImmutableSortedSet.<BuildRule>naturalOrder() .addAll(captureAnalyzeRules.captureRules) .addAll(captureAnalyzeRules.allAnalyzeRules) .build()), Suppliers.ofInstance(buildRuleParams.getExtraDeps())), pathResolver, inferTools, captureAnalyzeRules)); } private static CxxInferReport createInferReportRule( BuildRuleParams buildRuleParams, BuildRuleResolver buildRuleResolver, SourcePathResolver sourcePathResolver, CxxInferAnalyze analysisToReport) { ImmutableSortedSet<Path> reportsToMergeFromDeps = FluentIterable.from(analysisToReport.getTransitiveAnalyzeRules()) .transform( new Function<CxxInferAnalyze, Path>() { @Override public Path apply(CxxInferAnalyze input) { return input.getPathToOutput(); } }).toSortedSet(Ordering.natural()); ImmutableSortedSet<Path> reportsToMerge = ImmutableSortedSet.<Path>naturalOrder() .addAll(reportsToMergeFromDeps) .add(analysisToReport.getPathToOutput()) .build(); return buildRuleResolver.addToIndex( new CxxInferReport( buildRuleParams.copyWithDeps( Suppliers.ofInstance( ImmutableSortedSet.<BuildRule>naturalOrder() .addAll(analysisToReport.getTransitiveAnalyzeRules()) .add(analysisToReport) .build()), Suppliers.ofInstance(buildRuleParams.getExtraDeps())), sourcePathResolver, reportsToMerge)); } }
// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.analysis; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.devtools.build.lib.packages.RuleClass.Builder.RuleClassType.ABSTRACT; import static com.google.devtools.build.lib.packages.RuleClass.Builder.RuleClassType.TEST; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.io.ByteStreams; import com.google.devtools.build.lib.actions.ActionEnvironment; import com.google.devtools.build.lib.analysis.RuleContext.PrerequisiteValidator; import com.google.devtools.build.lib.analysis.buildinfo.BuildInfoFactory; import com.google.devtools.build.lib.analysis.buildinfo.BuildInfoKey; import com.google.devtools.build.lib.analysis.config.BuildConfigurationValue; import com.google.devtools.build.lib.analysis.config.BuildOptions; import com.google.devtools.build.lib.analysis.config.Fragment; import com.google.devtools.build.lib.analysis.config.FragmentClassSet; import com.google.devtools.build.lib.analysis.config.FragmentOptions; import com.google.devtools.build.lib.analysis.config.FragmentRegistry; import com.google.devtools.build.lib.analysis.config.SymlinkDefinition; import com.google.devtools.build.lib.analysis.config.transitions.ComposingTransitionFactory; import com.google.devtools.build.lib.analysis.config.transitions.PatchTransition; import com.google.devtools.build.lib.analysis.config.transitions.TransitionFactory; import com.google.devtools.build.lib.analysis.constraints.ConstraintSemantics; import com.google.devtools.build.lib.analysis.constraints.RuleContextConstraintSemantics; import com.google.devtools.build.lib.analysis.starlark.StarlarkModules; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.cmdline.LabelSyntaxException; import com.google.devtools.build.lib.graph.Digraph; import com.google.devtools.build.lib.graph.Node; import com.google.devtools.build.lib.packages.BazelStarlarkContext; import com.google.devtools.build.lib.packages.NativeAspectClass; import com.google.devtools.build.lib.packages.RuleClass; import com.google.devtools.build.lib.packages.RuleClass.Builder.ThirdPartyLicenseExistencePolicy; import com.google.devtools.build.lib.packages.RuleClassProvider; import com.google.devtools.build.lib.packages.RuleTransitionData; import com.google.devtools.build.lib.packages.SymbolGenerator; import com.google.devtools.build.lib.starlarkbuildapi.core.Bootstrap; import com.google.devtools.build.lib.vfs.DigestHashFunction; import com.google.devtools.build.lib.vfs.Path; import com.google.devtools.build.lib.vfs.PathFragment; import com.google.devtools.build.lib.vfs.Root; import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem; import com.google.devtools.common.options.OptionDefinition; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.annotation.Nullable; import net.starlark.java.annot.StarlarkAnnotations; import net.starlark.java.annot.StarlarkBuiltin; import net.starlark.java.eval.StarlarkThread; /** * Knows about every rule Blaze supports and the associated configuration options. * * <p>This class is initialized on server startup and the set of rules, build info factories and * configuration options is guaranteed not to change over the life time of the Blaze server. */ // This class has no subclasses except those created by the evil that is mockery. public /*final*/ class ConfiguredRuleClassProvider implements RuleClassProvider { /** * A coherent set of options, fragments, aspects and rules; each of these may declare a dependency * on other such sets. */ public interface RuleSet { /** Add stuff to the configured rule class provider builder. */ void init(ConfiguredRuleClassProvider.Builder builder); /** List of required modules. */ ImmutableList<RuleSet> requires(); } /** An InMemoryFileSystem for bundled builtins .bzl files. */ public static class BundledFileSystem extends InMemoryFileSystem { private static final byte[] EMPTY_DIGEST = new byte[0]; public BundledFileSystem() { super(DigestHashFunction.SHA256); } // Bundled files are guaranteed to not change throughout the lifetime of the Bazel server, so it // is permissible to use a fake digest. This helps avoid peculiarities in the interaction of // InMemoryFileSystem and Skyframe. See cl/354809138 for further discussion, including of // possible (but unlikely) future caveats of this approach. @Override protected synchronized byte[] getFastDigest(PathFragment path) { return EMPTY_DIGEST; } @Override protected synchronized byte[] getDigest(PathFragment path) throws IOException { return EMPTY_DIGEST; } } /** Builder for {@link ConfiguredRuleClassProvider}. */ public static final class Builder implements RuleDefinitionEnvironment { private final StringBuilder defaultWorkspaceFilePrefix = new StringBuilder(); private final StringBuilder defaultWorkspaceFileSuffix = new StringBuilder(); private Label preludeLabel; private String runfilesPrefix; private String toolsRepository; @Nullable private String builtinsBzlZipResource; private boolean useDummyBuiltinsBzlInsteadOfResource = false; @Nullable private String builtinsBzlPackagePathInSource; private final List<Class<? extends Fragment>> configurationFragmentClasses = new ArrayList<>(); private final List<BuildInfoFactory> buildInfoFactories = new ArrayList<>(); private final List<Class<? extends FragmentOptions>> configurationOptions = new ArrayList<>(); private final Map<String, RuleClass> ruleClassMap = new HashMap<>(); private final Map<String, RuleDefinition> ruleDefinitionMap = new HashMap<>(); private final Map<String, NativeAspectClass> nativeAspectClassMap = new HashMap<>(); private final Map<Class<? extends RuleDefinition>, RuleClass> ruleMap = new HashMap<>(); private final Digraph<Class<? extends RuleDefinition>> dependencyGraph = new Digraph<>(); private final List<Class<? extends Fragment>> universalFragments = new ArrayList<>(); @Nullable private TransitionFactory<RuleTransitionData> trimmingTransitionFactory = null; @Nullable private PatchTransition toolchainTaggedTrimmingTransition = null; private OptionsDiffPredicate shouldInvalidateCacheForOptionDiff = OptionsDiffPredicate.ALWAYS_INVALIDATE; private PrerequisiteValidator prerequisiteValidator; private final ImmutableList.Builder<Bootstrap> starlarkBootstraps = ImmutableList.builder(); private final ImmutableMap.Builder<String, Object> starlarkAccessibleTopLevels = ImmutableMap.builder(); private final ImmutableMap.Builder<String, Object> starlarkBuiltinsInternals = ImmutableMap.builder(); private final ImmutableList.Builder<SymlinkDefinition> symlinkDefinitions = ImmutableList.builder(); private final Set<String> reservedActionMnemonics = new TreeSet<>(); private BuildConfigurationValue.ActionEnvironmentProvider actionEnvironmentProvider = (BuildOptions options) -> ActionEnvironment.EMPTY; private ConstraintSemantics<RuleContext> constraintSemantics = new RuleContextConstraintSemantics(); private ThirdPartyLicenseExistencePolicy thirdPartyLicenseExistencePolicy = ThirdPartyLicenseExistencePolicy.USER_CONTROLLABLE; // TODO(b/192694287): Remove once we migrate all tests from the allowlist @Nullable private Label networkAllowlistForTests; public Builder addWorkspaceFilePrefix(String contents) { defaultWorkspaceFilePrefix.append(contents); return this; } public Builder addWorkspaceFileSuffix(String contents) { defaultWorkspaceFileSuffix.append(contents); return this; } @VisibleForTesting public Builder clearWorkspaceFileSuffixForTesting() { defaultWorkspaceFileSuffix.delete(0, defaultWorkspaceFileSuffix.length()); return this; } public Builder setPrelude(String preludeLabelString) { try { this.preludeLabel = Label.parseAbsolute(preludeLabelString, ImmutableMap.of()); } catch (LabelSyntaxException e) { String errorMsg = String.format("Prelude label '%s' is invalid: %s", preludeLabelString, e.getMessage()); throw new IllegalArgumentException(errorMsg); } return this; } public Builder setRunfilesPrefix(String runfilesPrefix) { this.runfilesPrefix = runfilesPrefix; return this; } public Builder setToolsRepository(String toolsRepository) { this.toolsRepository = toolsRepository; return this; } /** * Sets the resource path to the builtins_bzl.zip resource. * * <p>This value is required for production uses. For uses in tests, this may be left null, but * the resulting rule class provider will not work with {@code * --experimental_builtins_bzl_path=%bundled%}. Alternatively, tests may call {@link * #useDummyBuiltinsBzl} if they do not rely on any native rules that may be migratable to * Starlark. */ public Builder setBuiltinsBzlZipResource(String name) { this.builtinsBzlZipResource = name; this.useDummyBuiltinsBzlInsteadOfResource = false; return this; } /** * Instructs the rule class provider to use a set of dummy builtins definitions that inject no * symbols. * * <p>This is only suitable for use in tests, and only when the test does not depend (even * implicitly) on native rules. For example, pure tests of package loading behavior may call * this method, but not tests that use AnalysisMock. Otherwise the test may break when a native * rule is migrated to Starlark via builtins injection. */ public Builder useDummyBuiltinsBzl() { this.builtinsBzlZipResource = null; this.useDummyBuiltinsBzlInsteadOfResource = true; return this; } /** * Sets the relative location of the builtins_bzl directory within a Bazel source tree. * * <p>This is required if the rule class provider will be used with {@code * --experimental_builtins_bzl_path=%workspace%}, but can be skipped in unit tests. */ public Builder setBuiltinsBzlPackagePathInSource(String path) { this.builtinsBzlPackagePathInSource = path; return this; } public Builder setPrerequisiteValidator(PrerequisiteValidator prerequisiteValidator) { this.prerequisiteValidator = prerequisiteValidator; return this; } public Builder addBuildInfoFactory(BuildInfoFactory factory) { buildInfoFactories.add(factory); return this; } public Builder addRuleDefinition(RuleDefinition ruleDefinition) { Class<? extends RuleDefinition> ruleDefinitionClass = ruleDefinition.getClass(); ruleDefinitionMap.put(ruleDefinitionClass.getName(), ruleDefinition); dependencyGraph.createNode(ruleDefinitionClass); for (Class<? extends RuleDefinition> ancestor : ruleDefinition.getMetadata().ancestors()) { dependencyGraph.addEdge(ancestor, ruleDefinitionClass); } return this; } public Builder addNativeAspectClass(NativeAspectClass aspectFactoryClass) { nativeAspectClassMap.put(aspectFactoryClass.getName(), aspectFactoryClass); return this; } /** * Adds a configuration fragment and all build options required by its fragment. * * <p>Note that configuration fragments annotated with a Starlark name must have a unique name; * no two different configuration fragments can share the same name. */ public Builder addConfigurationFragment(Class<? extends Fragment> fragmentClass) { configurationFragmentClasses.add(fragmentClass); return this; } /** * Adds configuration options that aren't required by configuration fragments. * * <p>If {@link #addConfigurationFragment} adds a fragment that also requires these options, * this method is redundant. */ public Builder addConfigurationOptions(Class<? extends FragmentOptions> configurationOptions) { this.configurationOptions.add(configurationOptions); return this; } public Builder addUniversalConfigurationFragment(Class<? extends Fragment> fragment) { this.universalFragments.add(fragment); addConfigurationFragment(fragment); return this; } public Builder addStarlarkBootstrap(Bootstrap bootstrap) { this.starlarkBootstraps.add(bootstrap); return this; } public Builder addStarlarkAccessibleTopLevels(String name, Object object) { this.starlarkAccessibleTopLevels.put(name, object); return this; } public Builder addStarlarkBuiltinsInternal(String name, Object object) { this.starlarkBuiltinsInternals.put(name, object); return this; } public Builder addSymlinkDefinition(SymlinkDefinition symlinkDefinition) { this.symlinkDefinitions.add(symlinkDefinition); return this; } public Builder addReservedActionMnemonic(String mnemonic) { this.reservedActionMnemonics.add(mnemonic); return this; } public Builder setActionEnvironmentProvider( BuildConfigurationValue.ActionEnvironmentProvider actionEnvironmentProvider) { this.actionEnvironmentProvider = actionEnvironmentProvider; return this; } /** * Sets the logic that lets rules declare which environments they support and validates rules * don't depend on rules that aren't compatible with the same environments. Defaults to {@link * ConstraintSemantics}. See {@link ConstraintSemantics} for more details. */ public Builder setConstraintSemantics(ConstraintSemantics<RuleContext> constraintSemantics) { this.constraintSemantics = constraintSemantics; return this; } /** * Sets the policy for checking if third_party rules declare <code>licenses()</code>. See {@link * #thirdPartyLicenseExistencePolicy} for the default value. */ public Builder setThirdPartyLicenseExistencePolicy(ThirdPartyLicenseExistencePolicy policy) { this.thirdPartyLicenseExistencePolicy = policy; return this; } /** * Adds a transition factory that produces a trimming transition to be run over all targets * after other transitions. * * <p>Transitions are run in the order they're added. * * <p>This is a temporary measure for supporting trimming of test rules and manual trimming of * feature flags, and support for this transition factory will likely be removed at some point * in the future (whenever automatic trimming is sufficiently workable). */ public Builder addTrimmingTransitionFactory(TransitionFactory<RuleTransitionData> factory) { Preconditions.checkNotNull(factory); Preconditions.checkArgument(!factory.isSplit()); if (trimmingTransitionFactory == null) { trimmingTransitionFactory = factory; } else { trimmingTransitionFactory = ComposingTransitionFactory.of(trimmingTransitionFactory, factory); } return this; } /** Sets the transition manual feature flag trimming should apply to toolchain deps. */ public Builder setToolchainTaggedTrimmingTransition(PatchTransition transition) { Preconditions.checkNotNull(transition); Preconditions.checkState(toolchainTaggedTrimmingTransition == null); this.toolchainTaggedTrimmingTransition = transition; return this; } /** * Overrides the transition factory run over all targets. * * @see #addTrimmingTransitionFactory(TransitionFactory) */ @VisibleForTesting(/* for testing trimming transition factories without relying on prod use */ ) public Builder overrideTrimmingTransitionFactoryForTesting( TransitionFactory<RuleTransitionData> factory) { trimmingTransitionFactory = null; return this.addTrimmingTransitionFactory(factory); } /** * Sets the predicate which determines whether the analysis cache should be invalidated for the * given options diff. */ public Builder setShouldInvalidateCacheForOptionDiff( OptionsDiffPredicate shouldInvalidateCacheForOptionDiff) { Preconditions.checkState( this.shouldInvalidateCacheForOptionDiff.equals(OptionsDiffPredicate.ALWAYS_INVALIDATE), "Cache invalidation function was already set"); this.shouldInvalidateCacheForOptionDiff = shouldInvalidateCacheForOptionDiff; return this; } /** * Overrides the predicate which determines whether the analysis cache should be invalidated for * the given options diff. */ @VisibleForTesting(/* for testing cache invalidation without relying on prod use */ ) Builder overrideShouldInvalidateCacheForOptionDiffForTesting( OptionsDiffPredicate shouldInvalidateCacheForOptionDiff) { this.shouldInvalidateCacheForOptionDiff = OptionsDiffPredicate.ALWAYS_INVALIDATE; return this.setShouldInvalidateCacheForOptionDiff(shouldInvalidateCacheForOptionDiff); } private static RuleConfiguredTargetFactory createFactory( Class<? extends RuleConfiguredTargetFactory> factoryClass) { try { Constructor<? extends RuleConfiguredTargetFactory> ctor = factoryClass.getConstructor(); return ctor.newInstance(); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { throw new IllegalStateException(e); } } private void commitRuleDefinition(Class<? extends RuleDefinition> definitionClass) { RuleDefinition instance = checkNotNull( ruleDefinitionMap.get(definitionClass.getName()), "addRuleDefinition(new %s()) should be called before build()", definitionClass.getName()); RuleDefinition.Metadata metadata = instance.getMetadata(); checkArgument( ruleClassMap.get(metadata.name()) == null, "The rule " + metadata.name() + " was committed already, use another name"); List<Class<? extends RuleDefinition>> ancestors = metadata.ancestors(); checkArgument( metadata.type() == ABSTRACT ^ metadata.factoryClass() != RuleConfiguredTargetFactory.class); checkArgument( (metadata.type() != TEST) || ancestors.contains(BaseRuleClasses.TestBaseRule.class)); RuleClass[] ancestorClasses = new RuleClass[ancestors.size()]; for (int i = 0; i < ancestorClasses.length; i++) { ancestorClasses[i] = ruleMap.get(ancestors.get(i)); if (ancestorClasses[i] == null) { // Ancestors should have been initialized by now throw new IllegalStateException( "Ancestor " + ancestors.get(i) + " of " + metadata.name() + " is not initialized"); } } RuleConfiguredTargetFactory factory = null; if (metadata.type() != ABSTRACT) { factory = createFactory(metadata.factoryClass()); } RuleClass.Builder builder = new RuleClass.Builder(metadata.name(), metadata.type(), false, ancestorClasses); builder.factory(factory); builder.setThirdPartyLicenseExistencePolicy(thirdPartyLicenseExistencePolicy); RuleClass ruleClass = instance.build(builder, this); ruleMap.put(definitionClass, ruleClass); ruleClassMap.put(ruleClass.getName(), ruleClass); ruleDefinitionMap.put(ruleClass.getName(), instance); } /** * Locates the builtins zip file as a Java resource, and unpacks it into the given directory. * Note that the builtins_bzl/ entry itself in the zip is not copied, just its children. */ private static void unpackBuiltinsBzlZipResource(String builtinsResourceName, Path targetRoot) { ClassLoader loader = ConfiguredRuleClassProvider.class.getClassLoader(); try (InputStream builtinsZip = loader.getResourceAsStream(builtinsResourceName)) { Preconditions.checkArgument( builtinsZip != null, "No resource with name %s", builtinsResourceName); try (ZipInputStream zip = new ZipInputStream(builtinsZip)) { for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { String entryName = entry.getName(); Preconditions.checkArgument(entryName.startsWith("builtins_bzl/")); Path dest = targetRoot.getRelative(entryName.substring("builtins_bzl/".length())); dest.getParentDirectory().createDirectoryAndParents(); try (OutputStream os = dest.getOutputStream()) { ByteStreams.copy(zip, os); } } } } catch (IOException ex) { throw new IllegalArgumentException( "Error while unpacking builtins_bzl zip resource file", ex); } } public ConfiguredRuleClassProvider build() { for (Node<Class<? extends RuleDefinition>> ruleDefinition : dependencyGraph.getTopologicalOrder()) { commitRuleDefinition(ruleDefinition.getLabel()); } // Determine the bundled builtins root, if it exists. Root builtinsRoot; if (builtinsBzlZipResource == null && !useDummyBuiltinsBzlInsteadOfResource) { // Use of --experimental_builtins_bzl_path=%bundled% is disallowed. builtinsRoot = null; } else { BundledFileSystem fs = new BundledFileSystem(); Path builtinsPath = fs.getPath("/virtual_builtins_bzl"); if (builtinsBzlZipResource != null) { // Production case. unpackBuiltinsBzlZipResource(builtinsBzlZipResource, builtinsPath); } else { // Dummy case, use empty bundled builtins content. try { builtinsPath.createDirectoryAndParents(); try (OutputStream os = builtinsPath.getRelative("exports.bzl").getOutputStream()) { String emptyExports = ("exported_rules = {}\n" // + "exported_toplevels = {}\n" + "exported_to_java = {}\n"); os.write(emptyExports.getBytes(UTF_8)); } } catch (IOException ex) { throw new IllegalStateException("Failed to write dummy builtins root", ex); } } builtinsRoot = Root.fromPath(builtinsPath); } return new ConfiguredRuleClassProvider( preludeLabel, runfilesPrefix, toolsRepository, builtinsRoot, builtinsBzlPackagePathInSource, ImmutableMap.copyOf(ruleClassMap), ImmutableMap.copyOf(ruleDefinitionMap), ImmutableMap.copyOf(nativeAspectClassMap), FragmentRegistry.create( configurationFragmentClasses, universalFragments, configurationOptions), defaultWorkspaceFilePrefix.toString(), defaultWorkspaceFileSuffix.toString(), ImmutableList.copyOf(buildInfoFactories), trimmingTransitionFactory, toolchainTaggedTrimmingTransition, shouldInvalidateCacheForOptionDiff, prerequisiteValidator, starlarkAccessibleTopLevels.build(), starlarkBuiltinsInternals.build(), starlarkBootstraps.build(), symlinkDefinitions.build(), ImmutableSet.copyOf(reservedActionMnemonics), actionEnvironmentProvider, constraintSemantics, thirdPartyLicenseExistencePolicy, networkAllowlistForTests); } @Override public String getToolsRepository() { return toolsRepository; } @Override public Optional<Label> getNetworkAllowlistForTests() { return Optional.ofNullable(networkAllowlistForTests); } public Builder setNetworkAllowlistForTests(Label allowlist) { networkAllowlistForTests = allowlist; return this; } } /** Default content that should be added at the beginning of the WORKSPACE file. */ private final String defaultWorkspaceFilePrefix; /** Default content that should be added at the end of the WORKSPACE file. */ private final String defaultWorkspaceFileSuffix; /** Label for the prelude file. */ private final Label preludeLabel; /** The default runfiles prefix. */ private final String runfilesPrefix; /** The path to the tools repository. */ private final String toolsRepository; /** * Where the builtins bzl files are located (if not overridden by * --experimental_builtins_bzl_path). Note that this lives in a separate InMemoryFileSystem. * * <p>May be null in tests, in which case --experimental_builtins_bzl_path must point to a * builtins root. */ @Nullable private final Root bundledBuiltinsRoot; /** * The relative location of the builtins_bzl directory within a Bazel source tree. * * <p>May be null in tests, in which case --experimental_builtins_bzl_path may not be * "%workspace%". */ @Nullable private final String builtinsBzlPackagePathInSource; /** Maps rule class name to the metaclass instance for that rule. */ private final ImmutableMap<String, RuleClass> ruleClassMap; /** Maps rule class name to the rule definition objects. */ private final ImmutableMap<String, RuleDefinition> ruleDefinitionMap; /** Maps aspect name to the aspect factory meta class. */ private final ImmutableMap<String, NativeAspectClass> nativeAspectClassMap; private final FragmentRegistry fragmentRegistry; /** The transition factory used to produce the transition that will trim targets. */ @Nullable private final TransitionFactory<RuleTransitionData> trimmingTransitionFactory; /** The transition to apply to toolchain deps for manual trimming. */ @Nullable private final PatchTransition toolchainTaggedTrimmingTransition; /** The predicate used to determine whether a diff requires the cache to be invalidated. */ private final OptionsDiffPredicate shouldInvalidateCacheForOptionDiff; private final ImmutableList<BuildInfoFactory> buildInfoFactories; private final PrerequisiteValidator prerequisiteValidator; private final ImmutableMap<String, Object> nativeRuleSpecificBindings; private final ImmutableMap<String, Object> starlarkBuiltinsInternals; private final ImmutableMap<String, Object> environment; private final ImmutableList<SymlinkDefinition> symlinkDefinitions; private final ImmutableSet<String> reservedActionMnemonics; private final BuildConfigurationValue.ActionEnvironmentProvider actionEnvironmentProvider; private final ImmutableMap<String, Class<?>> configurationFragmentMap; private final ConstraintSemantics<RuleContext> constraintSemantics; private final ThirdPartyLicenseExistencePolicy thirdPartyLicenseExistencePolicy; // TODO(b/192694287): Remove once we migrate all tests from the allowlist @Nullable private final Label networkAllowlistForTests; private ConfiguredRuleClassProvider( Label preludeLabel, String runfilesPrefix, String toolsRepository, @Nullable Root bundledBuiltinsRoot, @Nullable String builtinsBzlPackagePathInSource, ImmutableMap<String, RuleClass> ruleClassMap, ImmutableMap<String, RuleDefinition> ruleDefinitionMap, ImmutableMap<String, NativeAspectClass> nativeAspectClassMap, FragmentRegistry fragmentRegistry, String defaultWorkspaceFilePrefix, String defaultWorkspaceFileSuffix, ImmutableList<BuildInfoFactory> buildInfoFactories, @Nullable TransitionFactory<RuleTransitionData> trimmingTransitionFactory, PatchTransition toolchainTaggedTrimmingTransition, OptionsDiffPredicate shouldInvalidateCacheForOptionDiff, PrerequisiteValidator prerequisiteValidator, ImmutableMap<String, Object> starlarkAccessibleTopLevels, ImmutableMap<String, Object> starlarkBuiltinsInternals, ImmutableList<Bootstrap> starlarkBootstraps, ImmutableList<SymlinkDefinition> symlinkDefinitions, ImmutableSet<String> reservedActionMnemonics, BuildConfigurationValue.ActionEnvironmentProvider actionEnvironmentProvider, ConstraintSemantics<RuleContext> constraintSemantics, ThirdPartyLicenseExistencePolicy thirdPartyLicenseExistencePolicy, @Nullable Label networkAllowlistForTests) { this.preludeLabel = preludeLabel; this.runfilesPrefix = runfilesPrefix; this.toolsRepository = toolsRepository; this.bundledBuiltinsRoot = bundledBuiltinsRoot; this.builtinsBzlPackagePathInSource = builtinsBzlPackagePathInSource; this.ruleClassMap = ruleClassMap; this.ruleDefinitionMap = ruleDefinitionMap; this.nativeAspectClassMap = nativeAspectClassMap; this.fragmentRegistry = fragmentRegistry; this.defaultWorkspaceFilePrefix = defaultWorkspaceFilePrefix; this.defaultWorkspaceFileSuffix = defaultWorkspaceFileSuffix; this.buildInfoFactories = buildInfoFactories; this.trimmingTransitionFactory = trimmingTransitionFactory; this.toolchainTaggedTrimmingTransition = toolchainTaggedTrimmingTransition; this.shouldInvalidateCacheForOptionDiff = shouldInvalidateCacheForOptionDiff; this.prerequisiteValidator = prerequisiteValidator; this.nativeRuleSpecificBindings = createNativeRuleSpecificBindings(starlarkAccessibleTopLevels, starlarkBootstraps); this.starlarkBuiltinsInternals = starlarkBuiltinsInternals; this.environment = createEnvironment(nativeRuleSpecificBindings); this.symlinkDefinitions = symlinkDefinitions; this.reservedActionMnemonics = reservedActionMnemonics; this.actionEnvironmentProvider = actionEnvironmentProvider; this.configurationFragmentMap = createFragmentMap(fragmentRegistry.getAllFragments()); this.constraintSemantics = constraintSemantics; this.thirdPartyLicenseExistencePolicy = thirdPartyLicenseExistencePolicy; this.networkAllowlistForTests = networkAllowlistForTests; } public PrerequisiteValidator getPrerequisiteValidator() { return prerequisiteValidator; } @Override public Label getPreludeLabel() { return preludeLabel; } @Override public String getRunfilesPrefix() { return runfilesPrefix; } @Override public String getToolsRepository() { return toolsRepository; } @Override @Nullable public Root getBundledBuiltinsRoot() { return bundledBuiltinsRoot; } @Override @Nullable public String getBuiltinsBzlPackagePathInSource() { return builtinsBzlPackagePathInSource; } @Override public Map<String, RuleClass> getRuleClassMap() { return ruleClassMap; } @Override public Map<String, NativeAspectClass> getNativeAspectClassMap() { return nativeAspectClassMap; } @Override public NativeAspectClass getNativeAspectClass(String key) { return nativeAspectClassMap.get(key); } public FragmentRegistry getFragmentRegistry() { return fragmentRegistry; } public Map<BuildInfoKey, BuildInfoFactory> getBuildInfoFactoriesAsMap() { ImmutableMap.Builder<BuildInfoKey, BuildInfoFactory> factoryMapBuilder = ImmutableMap.builder(); for (BuildInfoFactory factory : buildInfoFactories) { factoryMapBuilder.put(factory.getKey(), factory); } return factoryMapBuilder.build(); } /** * Returns the transition factory used to produce the transition to trim targets. * * <p>This is a temporary measure for supporting manual trimming of feature flags, and support for * this transition factory will likely be removed at some point in the future (whenever automatic * trimming is sufficiently workable */ @Nullable public TransitionFactory<RuleTransitionData> getTrimmingTransitionFactory() { return trimmingTransitionFactory; } /** * Returns the transition manual feature flag trimming should apply to toolchain deps. * * <p>See extra notes on {@link #getTrimmingTransitionFactory()}. */ @Nullable public PatchTransition getToolchainTaggedTrimmingTransition() { return toolchainTaggedTrimmingTransition; } /** Returns whether the analysis cache should be invalidated for the given option diff. */ public boolean shouldInvalidateCacheForOptionDiff( BuildOptions newOptions, OptionDefinition changedOption, Object oldValue, Object newValue) { return shouldInvalidateCacheForOptionDiff.apply(newOptions, changedOption, oldValue, newValue); } /** Returns the definition of the rule class definition with the specified name. */ public RuleDefinition getRuleClassDefinition(String ruleClassName) { return ruleDefinitionMap.get(ruleClassName); } private static ImmutableMap<String, Object> createNativeRuleSpecificBindings( ImmutableMap<String, Object> starlarkAccessibleTopLevels, ImmutableList<Bootstrap> bootstraps) { ImmutableMap.Builder<String, Object> bindings = ImmutableMap.builder(); bindings.putAll(starlarkAccessibleTopLevels); for (Bootstrap bootstrap : bootstraps) { bootstrap.addBindingsToBuilder(bindings); } return bindings.build(); } private static ImmutableMap<String, Object> createEnvironment( ImmutableMap<String, Object> nativeRuleSpecificBindings) { ImmutableMap.Builder<String, Object> envBuilder = ImmutableMap.builder(); // Add predeclared symbols of the Bazel build language. StarlarkModules.addPredeclared(envBuilder); // Add all the extensions registered with the rule class provider. envBuilder.putAll(nativeRuleSpecificBindings); return envBuilder.build(); } private static ImmutableMap<String, Class<?>> createFragmentMap( FragmentClassSet configurationFragments) { ImmutableMap.Builder<String, Class<?>> mapBuilder = ImmutableMap.builder(); for (Class<? extends Fragment> fragmentClass : configurationFragments) { StarlarkBuiltin fragmentModule = StarlarkAnnotations.getStarlarkBuiltin(fragmentClass); if (fragmentModule != null) { mapBuilder.put(fragmentModule.name(), fragmentClass); } } return mapBuilder.build(); } @Override public ImmutableMap<String, Object> getNativeRuleSpecificBindings() { // Include rule-related stuff like CcInfo, but not core stuff like rule(). Essentially, this // is intended to include things that could in principle be migrated to Starlark (and hence // should be overridable by @_builtins); in practice it means anything specifically // registered with the RuleClassProvider. return nativeRuleSpecificBindings; } @Override public ImmutableMap<String, Object> getStarlarkBuiltinsInternals() { return starlarkBuiltinsInternals; } @Override public ImmutableMap<String, Object> getEnvironment() { return environment; } @Override public void setStarlarkThreadContext(StarlarkThread thread, Label fileLabel) { new BazelStarlarkContext( BazelStarlarkContext.Phase.LOADING, toolsRepository, configurationFragmentMap, /*convertedLabelsInPackage=*/ new HashMap<>(), new SymbolGenerator<>(fileLabel), /*analysisRuleLabel=*/ null, networkAllowlistForTests) .storeInThread(thread); } @Override public String getDefaultWorkspacePrefix() { return defaultWorkspaceFilePrefix; } @Override public String getDefaultWorkspaceSuffix() { return defaultWorkspaceFileSuffix; } @Override public Map<String, Class<?>> getConfigurationFragmentMap() { return configurationFragmentMap; } /** * Returns the symlink definitions introduced by the fragments registered with this rule class * provider. * * <p>This only includes definitions added by {@link Builder#addSymlinkDefinition}, not the * standard symlinks in {@link com.google.devtools.build.lib.buildtool.OutputDirectoryLinksUtils}. * * <p>Note: Usages of custom symlink definitions should be rare. Currently it is only used to * implement the py2-bin / py3-bin symlinks. */ public ImmutableList<SymlinkDefinition> getSymlinkDefinitions() { return symlinkDefinitions; } public ConstraintSemantics<RuleContext> getConstraintSemantics() { return constraintSemantics; } @Override public ThirdPartyLicenseExistencePolicy getThirdPartyLicenseExistencePolicy() { return thirdPartyLicenseExistencePolicy; } /** Returns a reserved set of action mnemonics. These cannot be used from a Starlark action. */ public ImmutableSet<String> getReservedActionMnemonics() { return reservedActionMnemonics; } public BuildConfigurationValue.ActionEnvironmentProvider getActionEnvironmentProvider() { return actionEnvironmentProvider; } }
/* * Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.swing.plaf.metal; import javax.swing.plaf.*; import javax.swing.*; import java.awt.*; import java.awt.image.*; import java.lang.ref.*; import java.util.*; import sun.swing.CachedPainter; import sun.swing.ImageIconUIResource; /** * This is a dumping ground for random stuff we want to use in several places. * * @author Steve Wilson */ class MetalUtils { static void drawFlush3DBorder(Graphics g, Rectangle r) { drawFlush3DBorder(g, r.x, r.y, r.width, r.height); } /** * This draws the "Flush 3D Border" which is used throughout the Metal L&F */ static void drawFlush3DBorder(Graphics g, int x, int y, int w, int h) { g.translate( x, y); g.setColor( MetalLookAndFeel.getControlDarkShadow() ); g.drawRect( 0, 0, w-2, h-2 ); g.setColor( MetalLookAndFeel.getControlHighlight() ); g.drawRect( 1, 1, w-2, h-2 ); g.setColor( MetalLookAndFeel.getControl() ); g.drawLine( 0, h-1, 1, h-2 ); g.drawLine( w-1, 0, w-2, 1 ); g.translate( -x, -y); } /** * This draws a variant "Flush 3D Border" * It is used for things like pressed buttons. */ static void drawPressed3DBorder(Graphics g, Rectangle r) { drawPressed3DBorder( g, r.x, r.y, r.width, r.height ); } static void drawDisabledBorder(Graphics g, int x, int y, int w, int h) { g.translate( x, y); g.setColor( MetalLookAndFeel.getControlShadow() ); g.drawRect( 0, 0, w-1, h-1 ); g.translate(-x, -y); } /** * This draws a variant "Flush 3D Border" * It is used for things like pressed buttons. */ static void drawPressed3DBorder(Graphics g, int x, int y, int w, int h) { g.translate( x, y); drawFlush3DBorder(g, 0, 0, w, h); g.setColor( MetalLookAndFeel.getControlShadow() ); g.drawLine( 1, 1, 1, h-2 ); g.drawLine( 1, 1, w-2, 1 ); g.translate( -x, -y); } /** * This draws a variant "Flush 3D Border" * It is used for things like active toggle buttons. * This is used rarely. */ static void drawDark3DBorder(Graphics g, Rectangle r) { drawDark3DBorder(g, r.x, r.y, r.width, r.height); } /** * This draws a variant "Flush 3D Border" * It is used for things like active toggle buttons. * This is used rarely. */ static void drawDark3DBorder(Graphics g, int x, int y, int w, int h) { g.translate( x, y); drawFlush3DBorder(g, 0, 0, w, h); g.setColor( MetalLookAndFeel.getControl() ); g.drawLine( 1, 1, 1, h-2 ); g.drawLine( 1, 1, w-2, 1 ); g.setColor( MetalLookAndFeel.getControlShadow() ); g.drawLine( 1, h-2, 1, h-2 ); g.drawLine( w-2, 1, w-2, 1 ); g.translate( -x, -y); } static void drawButtonBorder(Graphics g, int x, int y, int w, int h, boolean active) { if (active) { drawActiveButtonBorder(g, x, y, w, h); } else { drawFlush3DBorder(g, x, y, w, h); } } static void drawActiveButtonBorder(Graphics g, int x, int y, int w, int h) { drawFlush3DBorder(g, x, y, w, h); g.setColor( MetalLookAndFeel.getPrimaryControl() ); g.drawLine( x+1, y+1, x+1, h-3 ); g.drawLine( x+1, y+1, w-3, x+1 ); g.setColor( MetalLookAndFeel.getPrimaryControlDarkShadow() ); g.drawLine( x+2, h-2, w-2, h-2 ); g.drawLine( w-2, y+2, w-2, h-2 ); } static void drawDefaultButtonBorder(Graphics g, int x, int y, int w, int h, boolean active) { drawButtonBorder(g, x+1, y+1, w-1, h-1, active); g.translate(x, y); g.setColor( MetalLookAndFeel.getControlDarkShadow() ); g.drawRect( 0, 0, w-3, h-3 ); g.drawLine( w-2, 0, w-2, 0); g.drawLine( 0, h-2, 0, h-2); g.translate(-x, -y); } static void drawDefaultButtonPressedBorder(Graphics g, int x, int y, int w, int h) { drawPressed3DBorder(g, x + 1, y + 1, w - 1, h - 1); g.translate(x, y); g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawRect(0, 0, w - 3, h - 3); g.drawLine(w - 2, 0, w - 2, 0); g.drawLine(0, h - 2, 0, h - 2); g.setColor(MetalLookAndFeel.getControl()); g.drawLine(w - 1, 0, w - 1, 0); g.drawLine(0, h - 1, 0, h - 1); g.translate(-x, -y); } /* * Convenience function for determining ComponentOrientation. Helps us * avoid having Munge directives throughout the code. */ static boolean isLeftToRight( Component c ) { return c.getComponentOrientation().isLeftToRight(); } static int getInt(Object key, int defaultValue) { Object value = UIManager.get(key); if (value instanceof Integer) { return ((Integer)value).intValue(); } if (value instanceof String) { try { return Integer.parseInt((String)value); } catch (NumberFormatException nfe) {} } return defaultValue; } // // Ocean specific stuff. // /** * Draws a radial type gradient. The gradient will be drawn vertically if * <code>vertical</code> is true, otherwise horizontally. * The UIManager key consists of five values: * r1 r2 c1 c2 c3. The gradient is broken down into four chunks drawn * in order from the origin. * <ol> * <li>Gradient r1 % of the size from c1 to c2 * <li>Rectangle r2 % of the size in c2. * <li>Gradient r1 % of the size from c2 to c1 * <li>The remaining size will be filled with a gradient from c1 to c3. * </ol> * * @param c Component rendering to * @param g Graphics to draw to. * @param key UIManager key used to look up gradient values. * @param x X coordinate to draw from * @param y Y coordinate to draw from * @param w Width to draw to * @param h Height to draw to * @param vertical Direction of the gradient * @return true if <code>key</code> exists, otherwise false. */ static boolean drawGradient(Component c, Graphics g, String key, int x, int y, int w, int h, boolean vertical) { java.util.List gradient = (java.util.List)UIManager.get(key); if (gradient == null || !(g instanceof Graphics2D)) { return false; } if (w <= 0 || h <= 0) { return true; } GradientPainter.INSTANCE.paint( c, (Graphics2D)g, gradient, x, y, w, h, vertical); return true; } private static class GradientPainter extends CachedPainter { /** * Instance used for painting. This is the only instance that is * ever created. */ public static final GradientPainter INSTANCE = new GradientPainter(8); // Size of images to create. For vertical gradients this is the width, // otherwise it's the height. private static final int IMAGE_SIZE = 64; /** * This is the actual width we're painting in, or last painted to. */ private int w; /** * This is the actual height we're painting in, or last painted to */ private int h; GradientPainter(int count) { super(count); } public void paint(Component c, Graphics2D g, java.util.List gradient, int x, int y, int w, int h, boolean isVertical) { int imageWidth; int imageHeight; if (isVertical) { imageWidth = IMAGE_SIZE; imageHeight = h; } else { imageWidth = w; imageHeight = IMAGE_SIZE; } synchronized(c.getTreeLock()) { this.w = w; this.h = h; paint(c, g, x, y, imageWidth, imageHeight, gradient, isVertical); } } protected void paintToImage(Component c, Image image, Graphics g, int w, int h, Object[] args) { Graphics2D g2 = (Graphics2D)g; java.util.List gradient = (java.util.List)args[0]; boolean isVertical = ((Boolean)args[1]).booleanValue(); // Render to the VolatileImage if (isVertical) { drawVerticalGradient(g2, ((Number)gradient.get(0)).floatValue(), ((Number)gradient.get(1)).floatValue(), (Color)gradient.get(2), (Color)gradient.get(3), (Color)gradient.get(4), w, h); } else { drawHorizontalGradient(g2, ((Number)gradient.get(0)).floatValue(), ((Number)gradient.get(1)).floatValue(), (Color)gradient.get(2), (Color)gradient.get(3), (Color)gradient.get(4), w, h); } } protected void paintImage(Component c, Graphics g, int x, int y, int imageW, int imageH, Image image, Object[] args) { boolean isVertical = ((Boolean)args[1]).booleanValue(); // Render to the screen g.translate(x, y); if (isVertical) { for (int counter = 0; counter < w; counter += IMAGE_SIZE) { int tileSize = Math.min(IMAGE_SIZE, w - counter); g.drawImage(image, counter, 0, counter + tileSize, h, 0, 0, tileSize, h, null); } } else { for (int counter = 0; counter < h; counter += IMAGE_SIZE) { int tileSize = Math.min(IMAGE_SIZE, h - counter); g.drawImage(image, 0, counter, w, counter + tileSize, 0, 0, w, tileSize, null); } } g.translate(-x, -y); } private void drawVerticalGradient(Graphics2D g, float ratio1, float ratio2, Color c1,Color c2, Color c3, int w, int h) { int mid = (int)(ratio1 * h); int mid2 = (int)(ratio2 * h); if (mid > 0) { g.setPaint(getGradient((float)0, (float)0, c1, (float)0, (float)mid, c2)); g.fillRect(0, 0, w, mid); } if (mid2 > 0) { g.setColor(c2); g.fillRect(0, mid, w, mid2); } if (mid > 0) { g.setPaint(getGradient((float)0, (float)mid + mid2, c2, (float)0, (float)mid * 2 + mid2, c1)); g.fillRect(0, mid + mid2, w, mid); } if (h - mid * 2 - mid2 > 0) { g.setPaint(getGradient((float)0, (float)mid * 2 + mid2, c1, (float)0, (float)h, c3)); g.fillRect(0, mid * 2 + mid2, w, h - mid * 2 - mid2); } } private void drawHorizontalGradient(Graphics2D g, float ratio1, float ratio2, Color c1,Color c2, Color c3, int w, int h) { int mid = (int)(ratio1 * w); int mid2 = (int)(ratio2 * w); if (mid > 0) { g.setPaint(getGradient((float)0, (float)0, c1, (float)mid, (float)0, c2)); g.fillRect(0, 0, mid, h); } if (mid2 > 0) { g.setColor(c2); g.fillRect(mid, 0, mid2, h); } if (mid > 0) { g.setPaint(getGradient((float)mid + mid2, (float)0, c2, (float)mid * 2 + mid2, (float)0, c1)); g.fillRect(mid + mid2, 0, mid, h); } if (w - mid * 2 - mid2 > 0) { g.setPaint(getGradient((float)mid * 2 + mid2, (float)0, c1, w, (float)0, c3)); g.fillRect(mid * 2 + mid2, 0, w - mid * 2 - mid2, h); } } private GradientPaint getGradient(float x1, float y1, Color c1, float x2, float y2, Color c2) { return new GradientPaint(x1, y1, c1, x2, y2, c2, true); } } /** * Returns true if the specified widget is in a toolbar. */ static boolean isToolBarButton(JComponent c) { return (c.getParent() instanceof JToolBar); } static Icon getOceanToolBarIcon(Image i) { ImageProducer prod = new FilteredImageSource(i.getSource(), new OceanToolBarImageFilter()); return new ImageIconUIResource(Toolkit.getDefaultToolkit().createImage(prod)); } static Icon getOceanDisabledButtonIcon(Image image) { Object[] range = (Object[])UIManager.get("Button.disabledGrayRange"); int min = 180; int max = 215; if (range != null) { min = ((Integer)range[0]).intValue(); max = ((Integer)range[1]).intValue(); } ImageProducer prod = new FilteredImageSource(image.getSource(), new OceanDisabledButtonImageFilter(min , max)); return new ImageIconUIResource(Toolkit.getDefaultToolkit().createImage(prod)); } /** * Used to create a disabled Icon with the ocean look. */ private static class OceanDisabledButtonImageFilter extends RGBImageFilter{ private float min; private float factor; OceanDisabledButtonImageFilter(int min, int max) { canFilterIndexColorModel = true; this.min = (float)min; this.factor = (max - min) / 255f; } public int filterRGB(int x, int y, int rgb) { // Coefficients are from the sRGB color space: int gray = Math.min(255, (int)(((0.2125f * ((rgb >> 16) & 0xFF)) + (0.7154f * ((rgb >> 8) & 0xFF)) + (0.0721f * (rgb & 0xFF)) + .5f) * factor + min)); return (rgb & 0xff000000) | (gray << 16) | (gray << 8) | (gray << 0); } } /** * Used to create the rollover icons with the ocean look. */ private static class OceanToolBarImageFilter extends RGBImageFilter { OceanToolBarImageFilter() { canFilterIndexColorModel = true; } public int filterRGB(int x, int y, int rgb) { int r = ((rgb >> 16) & 0xff); int g = ((rgb >> 8) & 0xff); int b = (rgb & 0xff); int gray = Math.max(Math.max(r, g), b); return (rgb & 0xff000000) | (gray << 16) | (gray << 8) | (gray << 0); } } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.log; import java.io.PrintWriter; import java.io.StringWriter; import java.util.concurrent.Future; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.spi.ExchangeFormatter; import org.apache.camel.util.MessageHelper; import org.apache.camel.util.ObjectHelper; /** * Logger formatter to format the logging output. */ public class LogFormatter implements ExchangeFormatter { protected static final String LS = System.getProperty("line.separator"); private boolean showExchangeId; private boolean showExchangePattern = true; private boolean showProperties; private boolean showHeaders; private boolean showBodyType = true; private boolean showBody = true; private boolean showOut; private boolean showException; private boolean showCaughtException; private boolean showStackTrace; private boolean showAll; private boolean multiline; private boolean showFuture; private boolean showStreams; private boolean showFiles; private int maxChars = 10000; public String format(Exchange exchange) { Message in = exchange.getIn(); StringBuilder sb = new StringBuilder(); if (showAll || showExchangeId) { if (multiline) { sb.append(LS); } sb.append(", Id:").append(exchange.getExchangeId()); } if (showAll || showExchangePattern) { if (multiline) { sb.append(LS); } sb.append(", ExchangePattern:").append(exchange.getPattern()); } if (showAll || showProperties) { if (multiline) { sb.append(LS); } sb.append(", Properties:").append(exchange.getProperties()); } if (showAll || showHeaders) { if (multiline) { sb.append(LS); } sb.append(", Headers:").append(in.getHeaders()); } if (showAll || showBodyType) { if (multiline) { sb.append(LS); } sb.append(", BodyType:").append(getBodyTypeAsString(in)); } if (showAll || showBody) { if (multiline) { sb.append(LS); } sb.append(", Body:").append(getBodyAsString(in)); } if (showAll || showException || showCaughtException) { // try exception on exchange first Exception exception = exchange.getException(); boolean caught = false; if ((showAll || showCaughtException) && exception == null) { // fallback to caught exception exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); caught = true; } if (exception != null) { if (multiline) { sb.append(LS); } if (caught) { sb.append(", CaughtExceptionType:").append(exception.getClass().getCanonicalName()); sb.append(", CaughtExceptionMessage:").append(exception.getMessage()); } else { sb.append(", ExceptionType:").append(exception.getClass().getCanonicalName()); sb.append(", ExceptionMessage:").append(exception.getMessage()); } if (showAll || showStackTrace) { StringWriter sw = new StringWriter(); exception.printStackTrace(new PrintWriter(sw)); sb.append(", StackTrace:").append(sw.toString()); } } } if (showAll || showOut) { if (exchange.hasOut()) { Message out = exchange.getOut(); if (showAll || showHeaders) { if (multiline) { sb.append(LS); } sb.append(", OutHeaders:").append(out.getHeaders()); } if (showAll || showBodyType) { if (multiline) { sb.append(LS); } sb.append(", OutBodyType:").append(getBodyTypeAsString(out)); } if (showAll || showBody) { if (multiline) { sb.append(LS); } sb.append(", OutBody:").append(getBodyAsString(out)); } } else { if (multiline) { sb.append(LS); } sb.append(", Out: null"); } } if (maxChars > 0) { StringBuilder answer = new StringBuilder(); for (String s : sb.toString().split(LS)) { if (s != null) { if (s.length() > maxChars) { s = s.substring(0, maxChars); answer.append(s).append("..."); } else { answer.append(s); } if (multiline) { answer.append(LS); } } } // switch string buffer sb = answer; } if (multiline) { sb.insert(0, "Exchange["); sb.append("]"); return sb.toString(); } else { // get rid of the leading space comma if needed if (sb.length() > 0 && sb.charAt(0) == ',' && sb.charAt(1) == ' ') { sb.replace(0, 2, ""); } sb.insert(0, "Exchange["); sb.append("]"); return sb.toString(); } } public boolean isShowExchangeId() { return showExchangeId; } public void setShowExchangeId(boolean showExchangeId) { this.showExchangeId = showExchangeId; } public boolean isShowProperties() { return showProperties; } public void setShowProperties(boolean showProperties) { this.showProperties = showProperties; } public boolean isShowHeaders() { return showHeaders; } public void setShowHeaders(boolean showHeaders) { this.showHeaders = showHeaders; } public boolean isShowBodyType() { return showBodyType; } public void setShowBodyType(boolean showBodyType) { this.showBodyType = showBodyType; } public boolean isShowBody() { return showBody; } public void setShowBody(boolean showBody) { this.showBody = showBody; } public boolean isShowOut() { return showOut; } public void setShowOut(boolean showOut) { this.showOut = showOut; } public boolean isShowAll() { return showAll; } public void setShowAll(boolean showAll) { this.showAll = showAll; } public boolean isShowException() { return showException; } public void setShowException(boolean showException) { this.showException = showException; } public boolean isShowStackTrace() { return showStackTrace; } public void setShowStackTrace(boolean showStackTrace) { this.showStackTrace = showStackTrace; } public boolean isShowCaughtException() { return showCaughtException; } public void setShowCaughtException(boolean showCaughtException) { this.showCaughtException = showCaughtException; } public boolean isMultiline() { return multiline; } public int getMaxChars() { return maxChars; } public void setMaxChars(int maxChars) { this.maxChars = maxChars; } /** * If enabled then each information is outputted on a newline. */ public void setMultiline(boolean multiline) { this.multiline = multiline; } public boolean isShowFuture() { return showFuture; } /** * If enabled Camel will on Future objects wait for it to complete to obtain the payload to be logged. * <p/> * Is default disabled. */ public void setShowFuture(boolean showFuture) { this.showFuture = showFuture; } public boolean isShowExchangePattern() { return showExchangePattern; } public void setShowExchangePattern(boolean showExchangePattern) { this.showExchangePattern = showExchangePattern; } public boolean isShowStreams() { return showStreams; } /** * If enabled Camel will output stream objects * <p/> * Is default disabled. */ public void setShowStreams(boolean showStreams) { this.showStreams = showStreams; } public boolean isShowFiles() { return showFiles; } /** * If enabled Camel will output files * <p/> * Is default disabled. */ public void setShowFiles(boolean showFiles) { this.showFiles = showFiles; } // Implementation methods //------------------------------------------------------------------------- protected String getBodyAsString(Message message) { if (message.getBody() instanceof Future) { if (!isShowFuture()) { // just use a to string of the future object return message.getBody().toString(); } } return MessageHelper.extractBodyForLogging(message, "", isShowStreams(), isShowFiles(), -1); } protected String getBodyTypeAsString(Message message) { String answer = ObjectHelper.classCanonicalName(message.getBody()); if (answer != null && answer.startsWith("java.lang.")) { return answer.substring(10); } return answer; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.fs.shell; import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SHELL_MISSING_DEFAULT_FS_WARNING_KEY; import static org.junit.Assert.*; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.URI; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FilterFileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.AclEntry; import org.apache.hadoop.fs.permission.AclStatus; import org.apache.hadoop.fs.permission.FsPermission; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.InOrder; /** * JUnit test class for {@link org.apache.hadoop.fs.shell.Ls} * */ public class TestLs { private static Configuration conf; private static FileSystem mockFs; private static final Date NOW = new Date(); @BeforeClass public static void setup() throws IOException { conf = new Configuration(); conf.set("fs.defaultFS", "mockfs:///"); conf.setClass("fs.mockfs.impl", MockFileSystem.class, FileSystem.class); mockFs = mock(FileSystem.class); } @Before public void resetMock() throws IOException { reset(mockFs); AclStatus mockAclStatus = mock(AclStatus.class); when(mockAclStatus.getEntries()).thenReturn(new ArrayList<AclEntry>()); when(mockFs.getAclStatus(any(Path.class))).thenReturn(mockAclStatus); } // check that default options are correct @Test public void processOptionsNone() throws IOException { LinkedList<String> options = new LinkedList<String>(); Ls ls = new Ls(); ls.processOptions(options); assertFalse(ls.isPathOnly()); assertTrue(ls.isDirRecurse()); assertFalse(ls.isHumanReadable()); assertFalse(ls.isRecursive()); assertFalse(ls.isOrderReverse()); assertFalse(ls.isOrderSize()); assertFalse(ls.isOrderTime()); assertFalse(ls.isUseAtime()); } // check the -C option is recognised @Test public void processOptionsPathOnly() throws IOException { LinkedList<String> options = new LinkedList<String>(); options.add("-C"); Ls ls = new Ls(); ls.processOptions(options); assertTrue(ls.isPathOnly()); assertTrue(ls.isDirRecurse()); assertFalse(ls.isHumanReadable()); assertFalse(ls.isRecursive()); assertFalse(ls.isOrderReverse()); assertFalse(ls.isOrderSize()); assertFalse(ls.isOrderTime()); assertFalse(ls.isUseAtime()); } // check the -d option is recognised @Test public void processOptionsDirectory() throws IOException { LinkedList<String> options = new LinkedList<String>(); options.add("-d"); Ls ls = new Ls(); ls.processOptions(options); assertFalse(ls.isPathOnly()); assertFalse(ls.isDirRecurse()); assertFalse(ls.isHumanReadable()); assertFalse(ls.isRecursive()); assertFalse(ls.isOrderReverse()); assertFalse(ls.isOrderSize()); assertFalse(ls.isOrderTime()); assertFalse(ls.isUseAtime()); } // check the -h option is recognised @Test public void processOptionsHuman() throws IOException { LinkedList<String> options = new LinkedList<String>(); options.add("-h"); Ls ls = new Ls(); ls.processOptions(options); assertFalse(ls.isPathOnly()); assertTrue(ls.isDirRecurse()); assertTrue(ls.isHumanReadable()); assertFalse(ls.isRecursive()); assertFalse(ls.isOrderReverse()); assertFalse(ls.isOrderSize()); assertFalse(ls.isOrderTime()); assertFalse(ls.isUseAtime()); } // check the -R option is recognised @Test public void processOptionsRecursive() throws IOException { LinkedList<String> options = new LinkedList<String>(); options.add("-R"); Ls ls = new Ls(); ls.processOptions(options); assertFalse(ls.isPathOnly()); assertTrue(ls.isDirRecurse()); assertFalse(ls.isHumanReadable()); assertTrue(ls.isRecursive()); assertFalse(ls.isOrderReverse()); assertFalse(ls.isOrderSize()); assertFalse(ls.isOrderTime()); assertFalse(ls.isUseAtime()); } // check the -r option is recognised @Test public void processOptionsReverse() throws IOException { LinkedList<String> options = new LinkedList<String>(); options.add("-r"); Ls ls = new Ls(); ls.processOptions(options); assertFalse(ls.isPathOnly()); assertTrue(ls.isDirRecurse()); assertFalse(ls.isHumanReadable()); assertFalse(ls.isRecursive()); assertTrue(ls.isOrderReverse()); assertFalse(ls.isOrderSize()); assertFalse(ls.isOrderTime()); assertFalse(ls.isUseAtime()); } // check the -S option is recognised @Test public void processOptionsSize() throws IOException { LinkedList<String> options = new LinkedList<String>(); options.add("-S"); Ls ls = new Ls(); ls.processOptions(options); assertFalse(ls.isPathOnly()); assertTrue(ls.isDirRecurse()); assertFalse(ls.isHumanReadable()); assertFalse(ls.isRecursive()); assertFalse(ls.isOrderReverse()); assertTrue(ls.isOrderSize()); assertFalse(ls.isOrderTime()); assertFalse(ls.isUseAtime()); } // check the -t option is recognised @Test public void processOptionsMtime() throws IOException { LinkedList<String> options = new LinkedList<String>(); options.add("-t"); Ls ls = new Ls(); ls.processOptions(options); assertFalse(ls.isPathOnly()); assertTrue(ls.isDirRecurse()); assertFalse(ls.isHumanReadable()); assertFalse(ls.isRecursive()); assertFalse(ls.isOrderReverse()); assertFalse(ls.isOrderSize()); assertTrue(ls.isOrderTime()); assertFalse(ls.isUseAtime()); } // check the precedence of the -t and -S options @Test public void processOptionsMtimeSize() throws IOException { LinkedList<String> options = new LinkedList<String>(); options.add("-t"); options.add("-S"); Ls ls = new Ls(); ls.processOptions(options); assertFalse(ls.isPathOnly()); assertTrue(ls.isDirRecurse()); assertFalse(ls.isHumanReadable()); assertFalse(ls.isRecursive()); assertFalse(ls.isOrderReverse()); assertFalse(ls.isOrderSize()); assertTrue(ls.isOrderTime()); assertFalse(ls.isUseAtime()); } // check the precedence of the -t, -S and -r options @Test public void processOptionsMtimeSizeReverse() throws IOException { LinkedList<String> options = new LinkedList<String>(); options.add("-t"); options.add("-S"); options.add("-r"); Ls ls = new Ls(); ls.processOptions(options); assertFalse(ls.isPathOnly()); assertTrue(ls.isDirRecurse()); assertFalse(ls.isHumanReadable()); assertFalse(ls.isRecursive()); assertTrue(ls.isOrderReverse()); assertFalse(ls.isOrderSize()); assertTrue(ls.isOrderTime()); assertFalse(ls.isUseAtime()); } // chheck the -u option is recognised @Test public void processOptionsAtime() throws IOException { LinkedList<String> options = new LinkedList<String>(); options.add("-u"); Ls ls = new Ls(); ls.processOptions(options); assertFalse(ls.isPathOnly()); assertTrue(ls.isDirRecurse()); assertFalse(ls.isHumanReadable()); assertFalse(ls.isRecursive()); assertFalse(ls.isOrderReverse()); assertFalse(ls.isOrderSize()); assertFalse(ls.isOrderTime()); assertTrue(ls.isUseAtime()); } // check all options is handled correctly @Test public void processOptionsAll() throws IOException { LinkedList<String> options = new LinkedList<String>(); options.add("-C"); // show file path only options.add("-d"); // directory options.add("-h"); // human readable options.add("-R"); // recursive options.add("-r"); // reverse order options.add("-t"); // time order options.add("-S"); // size order options.add("-u"); // show atime Ls ls = new Ls(); ls.processOptions(options); assertTrue(ls.isPathOnly()); assertFalse(ls.isDirRecurse()); assertTrue(ls.isHumanReadable()); assertFalse(ls.isRecursive()); // -d overrules -R assertTrue(ls.isOrderReverse()); assertFalse(ls.isOrderSize()); // -t overrules -S assertTrue(ls.isOrderTime()); assertTrue(ls.isUseAtime()); } // check listing of a single file @Test public void processPathFile() throws IOException { TestFile testfile = new TestFile("testDir", "testFile"); LinkedList<PathData> pathData = new LinkedList<PathData>(); pathData.add(testfile.getPathData()); PrintStream out = mock(PrintStream.class); Ls ls = new Ls(); ls.out = out; LinkedList<String> options = new LinkedList<String>(); ls.processOptions(options); String lineFormat = TestFile.computeLineFormat(pathData); ls.processArguments(pathData); InOrder inOrder = inOrder(out); inOrder.verify(out).println(testfile.formatLineMtime(lineFormat)); verifyNoMoreInteractions(out); } // check listing of multiple files @Test public void processPathFiles() throws IOException { TestFile testfile01 = new TestFile("testDir01", "testFile01"); TestFile testfile02 = new TestFile("testDir02", "testFile02"); TestFile testfile03 = new TestFile("testDir03", "testFile03"); TestFile testfile04 = new TestFile("testDir04", "testFile04"); TestFile testfile05 = new TestFile("testDir05", "testFile05"); TestFile testfile06 = new TestFile("testDir06", "testFile06"); LinkedList<PathData> pathData = new LinkedList<PathData>(); pathData.add(testfile01.getPathData()); pathData.add(testfile02.getPathData()); pathData.add(testfile03.getPathData()); pathData.add(testfile04.getPathData()); pathData.add(testfile05.getPathData()); pathData.add(testfile06.getPathData()); PrintStream out = mock(PrintStream.class); Ls ls = new Ls(); ls.out = out; LinkedList<String> options = new LinkedList<String>(); ls.processOptions(options); String lineFormat = TestFile.computeLineFormat(pathData); ls.processArguments(pathData); InOrder inOrder = inOrder(out); inOrder.verify(out).println(testfile01.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile02.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile03.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile04.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile05.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile06.formatLineMtime(lineFormat)); verifyNoMoreInteractions(out); } // check listing of a single directory @Test public void processPathDirectory() throws IOException { TestFile testfile01 = new TestFile("testDirectory", "testFile01"); TestFile testfile02 = new TestFile("testDirectory", "testFile02"); TestFile testfile03 = new TestFile("testDirectory", "testFile03"); TestFile testfile04 = new TestFile("testDirectory", "testFile04"); TestFile testfile05 = new TestFile("testDirectory", "testFile05"); TestFile testfile06 = new TestFile("testDirectory", "testFile06"); TestFile testDir = new TestFile("", "testDirectory"); testDir.setIsDir(true); testDir.addContents(testfile01, testfile02, testfile03, testfile04, testfile05, testfile06); LinkedList<PathData> pathData = new LinkedList<PathData>(); pathData.add(testDir.getPathData()); PrintStream out = mock(PrintStream.class); Ls ls = new Ls(); ls.out = out; LinkedList<String> options = new LinkedList<String>(); ls.processOptions(options); String lineFormat = TestFile.computeLineFormat(pathData); ls.processArguments(pathData); InOrder inOrder = inOrder(out); inOrder.verify(out).println("Found 6 items"); inOrder.verify(out).println(testfile01.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile02.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile03.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile04.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile05.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile06.formatLineMtime(lineFormat)); verifyNoMoreInteractions(out); } // check listing of multiple directories @Test public void processPathDirectories() throws IOException { TestFile testfile01 = new TestFile("testDirectory01", "testFile01"); TestFile testfile02 = new TestFile("testDirectory01", "testFile02"); TestFile testfile03 = new TestFile("testDirectory01", "testFile03"); TestFile testDir01 = new TestFile("", "testDirectory01"); testDir01.setIsDir(true); testDir01.addContents(testfile01, testfile02, testfile03); TestFile testfile04 = new TestFile("testDirectory02", "testFile04"); TestFile testfile05 = new TestFile("testDirectory02", "testFile05"); TestFile testfile06 = new TestFile("testDirectory02", "testFile06"); TestFile testDir02 = new TestFile("", "testDirectory02"); testDir02.setIsDir(true); testDir02.addContents(testfile04, testfile05, testfile06); LinkedList<PathData> pathData = new LinkedList<PathData>(); pathData.add(testDir01.getPathData()); pathData.add(testDir02.getPathData()); PrintStream out = mock(PrintStream.class); Ls ls = new Ls(); ls.out = out; LinkedList<String> options = new LinkedList<String>(); ls.processOptions(options); String lineFormat = TestFile.computeLineFormat(pathData); ls.processArguments(pathData); InOrder inOrder = inOrder(out); inOrder.verify(out).println("Found 3 items"); inOrder.verify(out).println(testfile01.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile02.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile03.formatLineMtime(lineFormat)); inOrder.verify(out).println("Found 3 items"); inOrder.verify(out).println(testfile04.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile05.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile06.formatLineMtime(lineFormat)); verifyNoMoreInteractions(out); } // check the default ordering @Test public void processPathDirOrderDefault() throws IOException { TestFile testfile01 = new TestFile("testDirectory", "testFile01"); TestFile testfile02 = new TestFile("testDirectory", "testFile02"); TestFile testfile03 = new TestFile("testDirectory", "testFile03"); TestFile testfile04 = new TestFile("testDirectory", "testFile04"); TestFile testfile05 = new TestFile("testDirectory", "testFile05"); TestFile testfile06 = new TestFile("testDirectory", "testFile06"); TestFile testDir = new TestFile("", "testDirectory"); testDir.setIsDir(true); // add contents in non-lexigraphic order to show they get sorted testDir.addContents(testfile01, testfile03, testfile05, testfile02, testfile04, testfile06); LinkedList<PathData> pathData = new LinkedList<PathData>(); pathData.add(testDir.getPathData()); PrintStream out = mock(PrintStream.class); Ls ls = new Ls(); ls.out = out; LinkedList<String> options = new LinkedList<String>(); ls.processOptions(options); String lineFormat = TestFile.computeLineFormat(pathData); ls.processArguments(pathData); InOrder inOrder = inOrder(out); inOrder.verify(out).println("Found 6 items"); inOrder.verify(out).println(testfile01.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile02.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile03.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile04.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile05.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile06.formatLineMtime(lineFormat)); verifyNoMoreInteractions(out); } // check reverse default ordering @Test public void processPathDirOrderDefaultReverse() throws IOException { TestFile testfile01 = new TestFile("testDirectory", "testFile01"); TestFile testfile02 = new TestFile("testDirectory", "testFile02"); TestFile testfile03 = new TestFile("testDirectory", "testFile03"); TestFile testfile04 = new TestFile("testDirectory", "testFile04"); TestFile testfile05 = new TestFile("testDirectory", "testFile05"); TestFile testfile06 = new TestFile("testDirectory", "testFile06"); TestFile testDir = new TestFile("", "testDirectory"); testDir.setIsDir(true); // add contents in non-lexigraphic order to show they get sorted testDir.addContents(testfile01, testfile03, testfile05, testfile02, testfile04, testfile06); LinkedList<PathData> pathData = new LinkedList<PathData>(); pathData.add(testDir.getPathData()); PrintStream out = mock(PrintStream.class); Ls ls = new Ls(); ls.out = out; LinkedList<String> options = new LinkedList<String>(); options.add("-r"); ls.processOptions(options); String lineFormat = TestFile.computeLineFormat(pathData); ls.processArguments(pathData); InOrder inOrder = inOrder(out); inOrder.verify(out).println("Found 6 items"); inOrder.verify(out).println(testfile06.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile05.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile04.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile03.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile02.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile01.formatLineMtime(lineFormat)); verifyNoMoreInteractions(out); } // check mtime ordering (-t option); most recent first in line with unix // convention @Test public void processPathDirOrderMtime() throws IOException { TestFile testfile01 = new TestFile("testDirectory", "testFile01"); TestFile testfile02 = new TestFile("testDirectory", "testFile02"); TestFile testfile03 = new TestFile("testDirectory", "testFile03"); TestFile testfile04 = new TestFile("testDirectory", "testFile04"); TestFile testfile05 = new TestFile("testDirectory", "testFile05"); TestFile testfile06 = new TestFile("testDirectory", "testFile06"); // set file mtime in different order to file names testfile01.setMtime(NOW.getTime() + 10); testfile02.setMtime(NOW.getTime() + 30); testfile03.setMtime(NOW.getTime() + 20); testfile04.setMtime(NOW.getTime() + 60); testfile05.setMtime(NOW.getTime() + 50); testfile06.setMtime(NOW.getTime() + 40); TestFile testDir = new TestFile("", "testDirectory"); testDir.setIsDir(true); testDir.addContents(testfile01, testfile02, testfile03, testfile04, testfile05, testfile06); LinkedList<PathData> pathData = new LinkedList<PathData>(); pathData.add(testDir.getPathData()); PrintStream out = mock(PrintStream.class); Ls ls = new Ls(); ls.out = out; LinkedList<String> options = new LinkedList<String>(); options.add("-t"); ls.processOptions(options); String lineFormat = TestFile.computeLineFormat(pathData); ls.processArguments(pathData); InOrder inOrder = inOrder(out); inOrder.verify(out).println("Found 6 items"); inOrder.verify(out).println(testfile04.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile05.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile06.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile02.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile03.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile01.formatLineMtime(lineFormat)); verifyNoMoreInteractions(out); } // check reverse mtime ordering (-t -r options) @Test public void processPathDirOrderMtimeReverse() throws IOException { TestFile testfile01 = new TestFile("testDirectory", "testFile01"); TestFile testfile02 = new TestFile("testDirectory", "testFile02"); TestFile testfile03 = new TestFile("testDirectory", "testFile03"); TestFile testfile04 = new TestFile("testDirectory", "testFile04"); TestFile testfile05 = new TestFile("testDirectory", "testFile05"); TestFile testfile06 = new TestFile("testDirectory", "testFile06"); // set file mtime in different order to file names testfile01.setMtime(NOW.getTime() + 10); testfile02.setMtime(NOW.getTime() + 30); testfile03.setMtime(NOW.getTime() + 20); testfile04.setMtime(NOW.getTime() + 60); testfile05.setMtime(NOW.getTime() + 50); testfile06.setMtime(NOW.getTime() + 40); TestFile testDir = new TestFile("", "testDirectory"); testDir.setIsDir(true); testDir.addContents(testfile01, testfile02, testfile03, testfile04, testfile05, testfile06); LinkedList<PathData> pathData = new LinkedList<PathData>(); pathData.add(testDir.getPathData()); PrintStream out = mock(PrintStream.class); Ls ls = new Ls(); ls.out = out; LinkedList<String> options = new LinkedList<String>(); options.add("-t"); options.add("-r"); ls.processOptions(options); String lineFormat = TestFile.computeLineFormat(pathData); ls.processArguments(pathData); InOrder inOrder = inOrder(out); inOrder.verify(out).println("Found 6 items"); inOrder.verify(out).println(testfile01.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile03.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile02.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile06.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile05.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile04.formatLineMtime(lineFormat)); verifyNoMoreInteractions(out); } // check multiple directories are order independently @Test public void processPathDirsOrderMtime() throws IOException { TestFile testfile01 = new TestFile("testDirectory01", "testFile01"); TestFile testfile02 = new TestFile("testDirectory01", "testFile02"); TestFile testfile03 = new TestFile("testDirectory01", "testFile03"); TestFile testfile04 = new TestFile("testDirectory02", "testFile04"); TestFile testfile05 = new TestFile("testDirectory02", "testFile05"); TestFile testfile06 = new TestFile("testDirectory02", "testFile06"); // set file mtime in different order to file names testfile01.setMtime(NOW.getTime() + 10); testfile02.setMtime(NOW.getTime() + 30); testfile03.setMtime(NOW.getTime() + 20); testfile04.setMtime(NOW.getTime() + 60); testfile05.setMtime(NOW.getTime() + 40); testfile06.setMtime(NOW.getTime() + 50); TestFile testDir01 = new TestFile("", "testDirectory01"); testDir01.setIsDir(true); testDir01.addContents(testfile01, testfile02, testfile03); TestFile testDir02 = new TestFile("", "testDirectory02"); testDir02.setIsDir(true); testDir02.addContents(testfile04, testfile05, testfile06); LinkedList<PathData> pathData = new LinkedList<PathData>(); pathData.add(testDir01.getPathData()); pathData.add(testDir02.getPathData()); PrintStream out = mock(PrintStream.class); Ls ls = new Ls(); ls.out = out; LinkedList<String> options = new LinkedList<String>(); options.add("-t"); ls.processOptions(options); String lineFormat = TestFile.computeLineFormat(pathData); ls.processArguments(pathData); InOrder inOrder = inOrder(out); inOrder.verify(out).println("Found 3 items"); inOrder.verify(out).println(testfile02.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile03.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile01.formatLineMtime(lineFormat)); inOrder.verify(out).println("Found 3 items"); inOrder.verify(out).println(testfile04.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile06.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile05.formatLineMtime(lineFormat)); verifyNoMoreInteractions(out); } // check mtime ordering with large time gaps between files (checks integer // overflow issues) @Test public void processPathDirOrderMtimeYears() throws IOException { TestFile testfile01 = new TestFile("testDirectory", "testFile01"); TestFile testfile02 = new TestFile("testDirectory", "testFile02"); TestFile testfile03 = new TestFile("testDirectory", "testFile03"); TestFile testfile04 = new TestFile("testDirectory", "testFile04"); TestFile testfile05 = new TestFile("testDirectory", "testFile05"); TestFile testfile06 = new TestFile("testDirectory", "testFile06"); // set file mtime in different order to file names testfile01.setMtime(NOW.getTime() + Integer.MAX_VALUE); testfile02.setMtime(NOW.getTime() + Integer.MIN_VALUE); testfile03.setMtime(NOW.getTime() + 0); testfile04.setMtime(NOW.getTime() + Integer.MAX_VALUE + Integer.MAX_VALUE); testfile05.setMtime(NOW.getTime() + 0); testfile06.setMtime(NOW.getTime() + Integer.MIN_VALUE + Integer.MIN_VALUE); TestFile testDir = new TestFile("", "testDirectory"); testDir.setIsDir(true); testDir.addContents(testfile01, testfile02, testfile03, testfile04, testfile05, testfile06); LinkedList<PathData> pathData = new LinkedList<PathData>(); pathData.add(testDir.getPathData()); PrintStream out = mock(PrintStream.class); Ls ls = new Ls(); ls.out = out; LinkedList<String> options = new LinkedList<String>(); options.add("-t"); ls.processOptions(options); String lineFormat = TestFile.computeLineFormat(pathData); ls.processArguments(pathData); InOrder inOrder = inOrder(out); inOrder.verify(out).println("Found 6 items"); inOrder.verify(out).println(testfile04.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile01.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile03.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile05.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile02.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile06.formatLineMtime(lineFormat)); verifyNoMoreInteractions(out); } // check length order (-S option) @Test public void processPathDirOrderLength() throws IOException { TestFile testfile01 = new TestFile("testDirectory", "testFile01"); TestFile testfile02 = new TestFile("testDirectory", "testFile02"); TestFile testfile03 = new TestFile("testDirectory", "testFile03"); TestFile testfile04 = new TestFile("testDirectory", "testFile04"); TestFile testfile05 = new TestFile("testDirectory", "testFile05"); TestFile testfile06 = new TestFile("testDirectory", "testFile06"); // set file length in different order to file names long length = 1234567890; testfile01.setLength(length + 10); testfile02.setLength(length + 30); testfile03.setLength(length + 20); testfile04.setLength(length + 60); testfile05.setLength(length + 50); testfile06.setLength(length + 40); TestFile testDir = new TestFile("", "testDirectory"); testDir.setIsDir(true); testDir.addContents(testfile01, testfile02, testfile03, testfile04, testfile05, testfile06); LinkedList<PathData> pathData = new LinkedList<PathData>(); pathData.add(testDir.getPathData()); PrintStream out = mock(PrintStream.class); Ls ls = new Ls(); ls.out = out; LinkedList<String> options = new LinkedList<String>(); options.add("-S"); ls.processOptions(options); String lineFormat = TestFile.computeLineFormat(pathData); ls.processArguments(pathData); InOrder inOrder = inOrder(out); inOrder.verify(out).println("Found 6 items"); inOrder.verify(out).println(testfile04.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile05.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile06.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile02.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile03.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile01.formatLineMtime(lineFormat)); verifyNoMoreInteractions(out); } // check reverse length order (-S -r options) @Test public void processPathDirOrderLengthReverse() throws IOException { TestFile testfile01 = new TestFile("testDirectory", "testFile01"); TestFile testfile02 = new TestFile("testDirectory", "testFile02"); TestFile testfile03 = new TestFile("testDirectory", "testFile03"); TestFile testfile04 = new TestFile("testDirectory", "testFile04"); TestFile testfile05 = new TestFile("testDirectory", "testFile05"); TestFile testfile06 = new TestFile("testDirectory", "testFile06"); // set file length in different order to file names long length = 1234567890; testfile01.setLength(length + 10); testfile02.setLength(length + 30); testfile03.setLength(length + 20); testfile04.setLength(length + 60); testfile05.setLength(length + 50); testfile06.setLength(length + 40); TestFile testDir = new TestFile("", "testDirectory"); testDir.setIsDir(true); testDir.addContents(testfile01, testfile02, testfile03, testfile04, testfile05, testfile06); LinkedList<PathData> pathData = new LinkedList<PathData>(); pathData.add(testDir.getPathData()); PrintStream out = mock(PrintStream.class); Ls ls = new Ls(); ls.out = out; LinkedList<String> options = new LinkedList<String>(); options.add("-S"); options.add("-r"); ls.processOptions(options); String lineFormat = TestFile.computeLineFormat(pathData); ls.processArguments(pathData); InOrder inOrder = inOrder(out); inOrder.verify(out).println("Found 6 items"); inOrder.verify(out).println(testfile01.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile03.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile02.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile06.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile05.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile04.formatLineMtime(lineFormat)); verifyNoMoreInteractions(out); } // check length ordering with large size gaps between files (checks integer // overflow issues) @Test public void processPathDirOrderLengthLarge() throws IOException { TestFile testfile01 = new TestFile("testDirectory", "testFile01"); TestFile testfile02 = new TestFile("testDirectory", "testFile02"); TestFile testfile03 = new TestFile("testDirectory", "testFile03"); TestFile testfile04 = new TestFile("testDirectory", "testFile04"); TestFile testfile05 = new TestFile("testDirectory", "testFile05"); TestFile testfile06 = new TestFile("testDirectory", "testFile06"); // set file length in different order to file names long length = 1234567890; testfile01.setLength(length + 3l * Integer.MAX_VALUE); testfile02.setLength(length + Integer.MAX_VALUE); testfile03.setLength(length + 2l * Integer.MAX_VALUE); testfile04.setLength(length + 4l * Integer.MAX_VALUE); testfile05.setLength(length + 2l * Integer.MAX_VALUE); testfile06.setLength(length + 0); TestFile testDir = new TestFile("", "testDirectory"); testDir.setIsDir(true); testDir.addContents(testfile01, testfile02, testfile03, testfile04, testfile05, testfile06); LinkedList<PathData> pathData = new LinkedList<PathData>(); pathData.add(testDir.getPathData()); PrintStream out = mock(PrintStream.class); Ls ls = new Ls(); ls.out = out; LinkedList<String> options = new LinkedList<String>(); options.add("-S"); ls.processOptions(options); String lineFormat = TestFile.computeLineFormat(pathData); ls.processArguments(pathData); InOrder inOrder = inOrder(out); inOrder.verify(out).println("Found 6 items"); inOrder.verify(out).println(testfile04.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile01.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile03.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile05.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile02.formatLineMtime(lineFormat)); inOrder.verify(out).println(testfile06.formatLineMtime(lineFormat)); verifyNoMoreInteractions(out); } // check access time display (-u option) @Test public void processPathDirectoryAtime() throws IOException { TestFile testfile01 = new TestFile("testDirectory", "testFile01"); TestFile testfile02 = new TestFile("testDirectory", "testFile02"); TestFile testfile03 = new TestFile("testDirectory", "testFile03"); TestFile testfile04 = new TestFile("testDirectory", "testFile04"); TestFile testfile05 = new TestFile("testDirectory", "testFile05"); TestFile testfile06 = new TestFile("testDirectory", "testFile06"); TestFile testDir = new TestFile("", "testDirectory"); testDir.setIsDir(true); testDir.addContents(testfile01, testfile02, testfile03, testfile04, testfile05, testfile06); LinkedList<PathData> pathData = new LinkedList<PathData>(); pathData.add(testDir.getPathData()); PrintStream out = mock(PrintStream.class); Ls ls = new Ls(); ls.out = out; LinkedList<String> options = new LinkedList<String>(); options.add("-u"); ls.processOptions(options); String lineFormat = TestFile.computeLineFormat(pathData); ls.processArguments(pathData); InOrder inOrder = inOrder(out); inOrder.verify(out).println("Found 6 items"); inOrder.verify(out).println(testfile01.formatLineAtime(lineFormat)); inOrder.verify(out).println(testfile02.formatLineAtime(lineFormat)); inOrder.verify(out).println(testfile03.formatLineAtime(lineFormat)); inOrder.verify(out).println(testfile04.formatLineAtime(lineFormat)); inOrder.verify(out).println(testfile05.formatLineAtime(lineFormat)); inOrder.verify(out).println(testfile06.formatLineAtime(lineFormat)); verifyNoMoreInteractions(out); } // check access time order (-u -t options) @Test public void processPathDirOrderAtime() throws IOException { TestFile testfile01 = new TestFile("testDirectory", "testFile01"); TestFile testfile02 = new TestFile("testDirectory", "testFile02"); TestFile testfile03 = new TestFile("testDirectory", "testFile03"); TestFile testfile04 = new TestFile("testDirectory", "testFile04"); TestFile testfile05 = new TestFile("testDirectory", "testFile05"); TestFile testfile06 = new TestFile("testDirectory", "testFile06"); // set file atime in different order to file names testfile01.setAtime(NOW.getTime() + 10); testfile02.setAtime(NOW.getTime() + 30); testfile03.setAtime(NOW.getTime() + 20); testfile04.setAtime(NOW.getTime() + 60); testfile05.setAtime(NOW.getTime() + 50); testfile06.setAtime(NOW.getTime() + 40); // set file mtime in different order to atime testfile01.setMtime(NOW.getTime() + 60); testfile02.setMtime(NOW.getTime() + 50); testfile03.setMtime(NOW.getTime() + 20); testfile04.setMtime(NOW.getTime() + 30); testfile05.setMtime(NOW.getTime() + 10); testfile06.setMtime(NOW.getTime() + 40); TestFile testDir = new TestFile("", "testDirectory"); testDir.setIsDir(true); testDir.addContents(testfile01, testfile02, testfile03, testfile04, testfile05, testfile06); LinkedList<PathData> pathData = new LinkedList<PathData>(); pathData.add(testDir.getPathData()); PrintStream out = mock(PrintStream.class); Ls ls = new Ls(); ls.out = out; LinkedList<String> options = new LinkedList<String>(); options.add("-t"); options.add("-u"); ls.processOptions(options); String lineFormat = TestFile.computeLineFormat(pathData); ls.processArguments(pathData); InOrder inOrder = inOrder(out); inOrder.verify(out).println("Found 6 items"); inOrder.verify(out).println(testfile04.formatLineAtime(lineFormat)); inOrder.verify(out).println(testfile05.formatLineAtime(lineFormat)); inOrder.verify(out).println(testfile06.formatLineAtime(lineFormat)); inOrder.verify(out).println(testfile02.formatLineAtime(lineFormat)); inOrder.verify(out).println(testfile03.formatLineAtime(lineFormat)); inOrder.verify(out).println(testfile01.formatLineAtime(lineFormat)); verifyNoMoreInteractions(out); } // check reverse access time order (-u -t -r options) @Test public void processPathDirOrderAtimeReverse() throws IOException { TestFile testfile01 = new TestFile("testDirectory", "testFile01"); TestFile testfile02 = new TestFile("testDirectory", "testFile02"); TestFile testfile03 = new TestFile("testDirectory", "testFile03"); TestFile testfile04 = new TestFile("testDirectory", "testFile04"); TestFile testfile05 = new TestFile("testDirectory", "testFile05"); TestFile testfile06 = new TestFile("testDirectory", "testFile06"); // set file atime in different order to file names testfile01.setAtime(NOW.getTime() + 10); testfile02.setAtime(NOW.getTime() + 30); testfile03.setAtime(NOW.getTime() + 20); testfile04.setAtime(NOW.getTime() + 60); testfile05.setAtime(NOW.getTime() + 50); testfile06.setAtime(NOW.getTime() + 40); // set file mtime in different order to atime testfile01.setMtime(NOW.getTime() + 60); testfile02.setMtime(NOW.getTime() + 50); testfile03.setMtime(NOW.getTime() + 20); testfile04.setMtime(NOW.getTime() + 30); testfile05.setMtime(NOW.getTime() + 10); testfile06.setMtime(NOW.getTime() + 40); TestFile testDir = new TestFile("", "testDirectory"); testDir.setIsDir(true); testDir.addContents(testfile01, testfile02, testfile03, testfile04, testfile05, testfile06); LinkedList<PathData> pathData = new LinkedList<PathData>(); pathData.add(testDir.getPathData()); PrintStream out = mock(PrintStream.class); Ls ls = new Ls(); ls.out = out; LinkedList<String> options = new LinkedList<String>(); options.add("-t"); options.add("-u"); options.add("-r"); ls.processOptions(options); String lineFormat = TestFile.computeLineFormat(pathData); ls.processArguments(pathData); InOrder inOrder = inOrder(out); inOrder.verify(out).println("Found 6 items"); inOrder.verify(out).println(testfile01.formatLineAtime(lineFormat)); inOrder.verify(out).println(testfile03.formatLineAtime(lineFormat)); inOrder.verify(out).println(testfile02.formatLineAtime(lineFormat)); inOrder.verify(out).println(testfile06.formatLineAtime(lineFormat)); inOrder.verify(out).println(testfile05.formatLineAtime(lineFormat)); inOrder.verify(out).println(testfile04.formatLineAtime(lineFormat)); verifyNoMoreInteractions(out); } // check path only display (-C option) @Test public void processPathDirectoryPathOnly() throws IOException { TestFile testfile01 = new TestFile("testDirectory", "testFile01"); TestFile testfile02 = new TestFile("testDirectory", "testFile02"); TestFile testfile03 = new TestFile("testDirectory", "testFile03"); TestFile testfile04 = new TestFile("testDirectory", "testFile04"); TestFile testfile05 = new TestFile("testDirectory", "testFile05"); TestFile testfile06 = new TestFile("testDirectory", "testFile06"); TestFile testDir = new TestFile("", "testDirectory"); testDir.setIsDir(true); testDir.addContents(testfile01, testfile02, testfile03, testfile04, testfile05, testfile06); LinkedList<PathData> pathData = new LinkedList<PathData>(); pathData.add(testDir.getPathData()); PrintStream out = mock(PrintStream.class); Ls ls = new Ls(); ls.out = out; LinkedList<String> options = new LinkedList<String>(); options.add("-C"); ls.processOptions(options); ls.processArguments(pathData); InOrder inOrder = inOrder(out); inOrder.verify(out).println(testfile01.getPath().toString()); inOrder.verify(out).println(testfile02.getPath().toString()); inOrder.verify(out).println(testfile03.getPath().toString()); inOrder.verify(out).println(testfile04.getPath().toString()); inOrder.verify(out).println(testfile05.getPath().toString()); inOrder.verify(out).println(testfile06.getPath().toString()); verifyNoMoreInteractions(out); } private static void displayWarningOnLocalFileSystem(boolean shouldDisplay) throws IOException { Configuration conf = new Configuration(); conf.setBoolean( HADOOP_SHELL_MISSING_DEFAULT_FS_WARNING_KEY, shouldDisplay); ByteArrayOutputStream buf = new ByteArrayOutputStream(); PrintStream err = new PrintStream(buf, true); Ls ls = new Ls(conf); ls.err = err; ls.run("file:///."); assertEquals(shouldDisplay, buf.toString().contains( "Warning: fs.defaultFS is not set when running \"ls\" command.")); } @Test public void displayWarningsOnLocalFileSystem() throws IOException { // Display warnings. displayWarningOnLocalFileSystem(true); // Does not display warnings. displayWarningOnLocalFileSystem(false); } // check the deprecated flag isn't set @Test public void isDeprecated() { Ls ls = new Ls(); boolean actual = ls.isDeprecated(); boolean expected = false; assertEquals("Ls.isDeprecated", expected, actual); } // check there's no replacement command @Test public void getReplacementCommand() { Ls ls = new Ls(); String actual = ls.getReplacementCommand(); String expected = null; assertEquals("Ls.getReplacementCommand", expected, actual); } // check the correct name is returned @Test public void getName() { Ls ls = new Ls(); String actual = ls.getName(); String expected = "ls"; assertEquals("Ls.getName", expected, actual); } // test class representing a file to be listed static class TestFile { private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat( "yyyy-MM-dd HH:mm"); private static final boolean DEFAULT_ISDIR = false; private static final String DEFAULT_MODE = "750"; private static final int DEFAULT_REPLICATION = 3; private static final String DEFAULT_OWNER = "test_owner"; private static final String DEFAULT_GROUP = "test_group"; private static final long DEFAULT_LENGTH = 1234567890L; private static final long DEFAULT_MTIME = NOW.getTime() - 86400000; private static final long DEFAULT_ATIME = NOW.getTime() + 86400000; private static final long DEFAULT_BLOCKSIZE = 64L * 1024 * 1024; private String dirname; private String filename; private boolean isDir; private FsPermission permission; private int replication; private String owner; private String group; private long length; private long mtime; private long atime; private long blocksize; private ArrayList<FileStatus> contents = new ArrayList<FileStatus>(); private Path path = null; private FileStatus fileStatus = null; private PathData pathData = null; public TestFile(String dirname, String filename) { setDirname(dirname); setFilename(filename); setIsDir(DEFAULT_ISDIR); setPermission(DEFAULT_MODE); setReplication(DEFAULT_REPLICATION); setOwner(DEFAULT_OWNER); setGroup(DEFAULT_GROUP); setLength(DEFAULT_LENGTH); setMtime(DEFAULT_MTIME); setAtime(DEFAULT_ATIME); setBlocksize(DEFAULT_BLOCKSIZE); } public void setDirname(String dirname) { this.dirname = dirname; } public void setFilename(String filename) { this.filename = filename; } public void setIsDir(boolean isDir) { this.isDir = isDir; } public void setPermission(String mode) { setPermission(new FsPermission(mode)); } public void setPermission(FsPermission permission) { this.permission = permission; } public void setReplication(int replication) { this.replication = replication; } public void setOwner(String owner) { this.owner = owner; } public void setGroup(String group) { this.group = group; } public void setLength(long length) { this.length = length; } public void setMtime(long mtime) { this.mtime = mtime; } public void setAtime(long atime) { this.atime = atime; } public void setBlocksize(long blocksize) { this.blocksize = blocksize; } public void addContents(TestFile... contents) { for (TestFile testFile : contents) { this.contents.add(testFile.getFileStatus()); } } private String getDirname() { return this.dirname; } private String getFilename() { return this.filename; } private String getPathname() { return getDirname() + "/" + getFilename(); } private boolean isDir() { return this.isDir; } private boolean isFile() { return !this.isDir(); } private FsPermission getPermission() { return this.permission; } private int getReplication() { return this.replication; } private String getOwner() { return this.owner; } private String getGroup() { return this.group; } private long getLength() { return this.length; } private long getMtime() { return this.mtime; } private long getAtime() { return this.atime; } private long getBlocksize() { return this.blocksize; } private FileStatus[] getContents() { return this.contents.toArray(new FileStatus[0]); } /** * Returns a formated output line based on the given format mask, file * status and file name. * * @param lineFormat * format mask * @param fileStatus * file status * @param fileName * file name * @return formated line */ private String formatLineMtime(String lineFormat) { return String.format(lineFormat, (isDir() ? "d" : "-"), getPermission(), (isFile() ? getReplication() : "-"), getOwner(), getGroup(), String.valueOf(getLength()), DATE_FORMAT.format(new Date(getMtime())), getPathname()); } /** * Returns a formated output line based on the given format mask, file * status and file name. * * @param lineFormat * format mask * @param fileStatus * file status * @param fileName * file name * @return formated line */ private String formatLineAtime(String lineFormat) { return String.format(lineFormat, (isDir() ? "d" : "-"), getPermission(), (isFile() ? getReplication() : "-"), getOwner(), getGroup(), String.valueOf(getLength()), DATE_FORMAT.format(new Date(getAtime())), getPathname()); } public FileStatus getFileStatus() { if (fileStatus == null) { Path path = getPath(); fileStatus = new FileStatus(getLength(), isDir(), getReplication(), getBlocksize(), getMtime(), getAtime(), getPermission(), getOwner(), getGroup(), path); } return fileStatus; } public Path getPath() { if (path == null) { if ((getDirname() != null) && (!getDirname().equals(""))) { path = new Path(getDirname(), getFilename()); } else { path = new Path(getFilename()); } } return path; } public PathData getPathData() throws IOException { if (pathData == null) { FileStatus fileStatus = getFileStatus(); Path path = getPath(); when(mockFs.getFileStatus(eq(path))).thenReturn(fileStatus); pathData = new PathData(path.toString(), conf); if (getContents().length != 0) { when(mockFs.listStatus(eq(path))).thenReturn(getContents()); } } return pathData; } /** * Compute format string based on maximum column widths. Copied from * Ls.adjustColumnWidths as these tests are more interested in proving * regression rather than absolute format. * * @param items * to find the max field width for each column */ public static String computeLineFormat(LinkedList<PathData> items) { int maxRepl = 3, maxLen = 10, maxOwner = 0, maxGroup = 0; for (PathData item : items) { FileStatus stat = item.stat; maxRepl = maxLength(maxRepl, stat.getReplication()); maxLen = maxLength(maxLen, stat.getLen()); maxOwner = maxLength(maxOwner, stat.getOwner()); maxGroup = maxLength(maxGroup, stat.getGroup()); } StringBuilder fmt = new StringBuilder(); fmt.append("%s%s "); // permission string fmt.append("%" + maxRepl + "s "); // Do not use '%-0s' as a formatting conversion, since it will throw a // a MissingFormatWidthException if it is used in String.format(). // http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#intFlags fmt.append((maxOwner > 0) ? "%-" + maxOwner + "s " : "%s"); fmt.append((maxGroup > 0) ? "%-" + maxGroup + "s " : "%s"); fmt.append("%" + maxLen + "s "); fmt.append("%s %s"); // mod time & path return fmt.toString(); } /** * Return the maximum of two values, treating null as 0 * * @param n * integer to be compared * @param value * value to be compared * @return maximum of the two inputs */ private static int maxLength(int n, Object value) { return Math.max(n, (value != null) ? String.valueOf(value).length() : 0); } } static class MockFileSystem extends FilterFileSystem { Configuration conf; MockFileSystem() { super(mockFs); } @Override public void initialize(URI uri, Configuration conf) { this.conf = conf; } @Override public Path makeQualified(Path path) { return path; } @Override public Configuration getConf() { return conf; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.rpc.akka; import org.apache.flink.runtime.rpc.MainThreadValidatorUtil; import org.apache.flink.runtime.rpc.RpcEndpoint; import org.apache.flink.runtime.rpc.RpcGateway; import org.apache.flink.runtime.rpc.akka.exceptions.AkkaRpcException; import org.apache.flink.runtime.rpc.akka.exceptions.AkkaUnknownMessageException; import org.apache.flink.runtime.rpc.akka.messages.Processing; import org.apache.flink.runtime.rpc.exceptions.RpcConnectionException; import org.apache.flink.runtime.rpc.messages.CallAsync; import org.apache.flink.runtime.rpc.messages.LocalRpcInvocation; import org.apache.flink.runtime.rpc.messages.RpcInvocation; import org.apache.flink.runtime.rpc.messages.RunAsync; import org.apache.flink.util.ExceptionUtils; import akka.actor.ActorRef; import akka.actor.Status; import akka.actor.UntypedActor; import akka.pattern.Patterns; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import scala.concurrent.duration.FiniteDuration; import scala.concurrent.impl.Promise; import static org.apache.flink.util.Preconditions.checkNotNull; /** * Akka rpc actor which receives {@link LocalRpcInvocation}, {@link RunAsync} and {@link CallAsync} * {@link Processing} messages. * <p> * The {@link LocalRpcInvocation} designates a rpc and is dispatched to the given {@link RpcEndpoint} * instance. * <p> * The {@link RunAsync} and {@link CallAsync} messages contain executable code which is executed * in the context of the actor thread. * <p> * The {@link Processing} message controls the processing behaviour of the akka rpc actor. A * {@link Processing#START} starts processing incoming messages. A {@link Processing#STOP} message * stops processing messages. All messages which arrive when the processing is stopped, will be * discarded. * * @param <T> Type of the {@link RpcEndpoint} */ class AkkaRpcActor<T extends RpcEndpoint & RpcGateway> extends UntypedActor { protected final Logger log = LoggerFactory.getLogger(getClass()); /** the endpoint to invoke the methods on. */ protected final T rpcEndpoint; /** the helper that tracks whether calls come from the main thread. */ private final MainThreadValidatorUtil mainThreadValidator; private final CompletableFuture<Void> internalTerminationFuture; AkkaRpcActor(final T rpcEndpoint, final CompletableFuture<Void> internalTerminationFuture) { this.rpcEndpoint = checkNotNull(rpcEndpoint, "rpc endpoint"); this.mainThreadValidator = new MainThreadValidatorUtil(rpcEndpoint); this.internalTerminationFuture = checkNotNull(internalTerminationFuture); } @Override public void postStop() throws Exception { mainThreadValidator.enterMainThread(); try { Throwable shutdownThrowable = null; try { rpcEndpoint.postStop(); } catch (Throwable throwable) { shutdownThrowable = throwable; } super.postStop(); // IMPORTANT: This only works if we don't use a restarting supervisor strategy. Otherwise // we would complete the future and let the actor system restart the actor with a completed // future. // Complete the termination future so that others know that we've stopped. if (shutdownThrowable != null) { internalTerminationFuture.completeExceptionally(shutdownThrowable); } else { internalTerminationFuture.complete(null); } } finally { mainThreadValidator.exitMainThread(); } } @Override public void onReceive(final Object message) { if (message.equals(Processing.START)) { getContext().become( (Object msg) -> { if (msg.equals(Processing.STOP)) { getContext().unbecome(); } else { mainThreadValidator.enterMainThread(); try { handleMessage(msg); } finally { mainThreadValidator.exitMainThread(); } } }); } else { log.info("The rpc endpoint {} has not been started yet. Discarding message {} until processing is started.", rpcEndpoint.getClass().getName(), message.getClass().getName()); sendErrorIfSender(new AkkaRpcException("Discard message, because " + "the rpc endpoint has not been started yet.")); } } protected void handleMessage(Object message) { if (message instanceof RunAsync) { handleRunAsync((RunAsync) message); } else if (message instanceof CallAsync) { handleCallAsync((CallAsync) message); } else if (message instanceof RpcInvocation) { handleRpcInvocation((RpcInvocation) message); } else { log.warn( "Received message of unknown type {} with value {}. Dropping this message!", message.getClass().getName(), message); sendErrorIfSender(new AkkaUnknownMessageException("Received unknown message " + message + " of type " + message.getClass().getSimpleName() + '.')); } } /** * Handle rpc invocations by looking up the rpc method on the rpc endpoint and calling this * method with the provided method arguments. If the method has a return value, it is returned * to the sender of the call. * * @param rpcInvocation Rpc invocation message */ private void handleRpcInvocation(RpcInvocation rpcInvocation) { Method rpcMethod = null; try { String methodName = rpcInvocation.getMethodName(); Class<?>[] parameterTypes = rpcInvocation.getParameterTypes(); rpcMethod = lookupRpcMethod(methodName, parameterTypes); } catch (ClassNotFoundException e) { log.error("Could not load method arguments.", e); RpcConnectionException rpcException = new RpcConnectionException("Could not load method arguments.", e); getSender().tell(new Status.Failure(rpcException), getSelf()); } catch (IOException e) { log.error("Could not deserialize rpc invocation message.", e); RpcConnectionException rpcException = new RpcConnectionException("Could not deserialize rpc invocation message.", e); getSender().tell(new Status.Failure(rpcException), getSelf()); } catch (final NoSuchMethodException e) { log.error("Could not find rpc method for rpc invocation.", e); RpcConnectionException rpcException = new RpcConnectionException("Could not find rpc method for rpc invocation.", e); getSender().tell(new Status.Failure(rpcException), getSelf()); } if (rpcMethod != null) { try { // this supports declaration of anonymous classes rpcMethod.setAccessible(true); if (rpcMethod.getReturnType().equals(Void.TYPE)) { // No return value to send back rpcMethod.invoke(rpcEndpoint, rpcInvocation.getArgs()); } else { final Object result; try { result = rpcMethod.invoke(rpcEndpoint, rpcInvocation.getArgs()); } catch (InvocationTargetException e) { log.trace("Reporting back error thrown in remote procedure {}", rpcMethod, e); // tell the sender about the failure getSender().tell(new Status.Failure(e.getTargetException()), getSelf()); return; } if (result instanceof CompletableFuture) { final CompletableFuture<?> future = (CompletableFuture<?>) result; Promise.DefaultPromise<Object> promise = new Promise.DefaultPromise<>(); future.whenComplete( (value, throwable) -> { if (throwable != null) { promise.failure(throwable); } else { promise.success(value); } }); Patterns.pipe(promise.future(), getContext().dispatcher()).to(getSender()); } else { // tell the sender the result of the computation getSender().tell(new Status.Success(result), getSelf()); } } } catch (Throwable e) { log.error("Error while executing remote procedure call {}.", rpcMethod, e); // tell the sender about the failure getSender().tell(new Status.Failure(e), getSelf()); } } } /** * Handle asynchronous {@link Callable}. This method simply executes the given {@link Callable} * in the context of the actor thread. * * @param callAsync Call async message */ private void handleCallAsync(CallAsync callAsync) { if (callAsync.getCallable() == null) { final String result = "Received a " + callAsync.getClass().getName() + " message with an empty " + "callable field. This indicates that this message has been serialized " + "prior to sending the message. The " + callAsync.getClass().getName() + " is only supported with local communication."; log.warn(result); getSender().tell(new Status.Failure(new AkkaRpcException(result)), getSelf()); } else { try { Object result = callAsync.getCallable().call(); getSender().tell(new Status.Success(result), getSelf()); } catch (Throwable e) { getSender().tell(new Status.Failure(e), getSelf()); } } } /** * Handle asynchronous {@link Runnable}. This method simply executes the given {@link Runnable} * in the context of the actor thread. * * @param runAsync Run async message */ private void handleRunAsync(RunAsync runAsync) { if (runAsync.getRunnable() == null) { log.warn("Received a {} message with an empty runnable field. This indicates " + "that this message has been serialized prior to sending the message. The " + "{} is only supported with local communication.", runAsync.getClass().getName(), runAsync.getClass().getName()); } else { final long timeToRun = runAsync.getTimeNanos(); final long delayNanos; if (timeToRun == 0 || (delayNanos = timeToRun - System.nanoTime()) <= 0) { // run immediately try { runAsync.getRunnable().run(); } catch (Throwable t) { log.error("Caught exception while executing runnable in main thread.", t); ExceptionUtils.rethrowIfFatalErrorOrOOM(t); } } else { // schedule for later. send a new message after the delay, which will then be immediately executed FiniteDuration delay = new FiniteDuration(delayNanos, TimeUnit.NANOSECONDS); RunAsync message = new RunAsync(runAsync.getRunnable(), timeToRun); getContext().system().scheduler().scheduleOnce(delay, getSelf(), message, getContext().dispatcher(), ActorRef.noSender()); } } } /** * Look up the rpc method on the given {@link RpcEndpoint} instance. * * @param methodName Name of the method * @param parameterTypes Parameter types of the method * @return Method of the rpc endpoint * @throws NoSuchMethodException Thrown if the method with the given name and parameter types * cannot be found at the rpc endpoint */ private Method lookupRpcMethod(final String methodName, final Class<?>[] parameterTypes) throws NoSuchMethodException { return rpcEndpoint.getClass().getMethod(methodName, parameterTypes); } /** * Send throwable to sender if the sender is specified. * * @param throwable to send to the sender */ protected void sendErrorIfSender(Throwable throwable) { if (!getSender().equals(ActorRef.noSender())) { getSender().tell(new Status.Failure(throwable), getSelf()); } } }
package org.mmymoney.gateway.domain; import org.mmymoney.gateway.config.Constants; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.validator.constraints.Email; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.HashSet; import java.util.Locale; import java.util.Set; import java.time.ZonedDateTime; /** * A user. */ @Entity @Table(name = "jhi_user") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class User extends AbstractAuditingEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotNull @Pattern(regexp = Constants.LOGIN_REGEX) @Size(min = 1, max = 50) @Column(length = 50, unique = true, nullable = false) private String login; @JsonIgnore @NotNull @Size(min = 60, max = 60) @Column(name = "password_hash",length = 60) private String password; @Size(max = 50) @Column(name = "first_name", length = 50) private String firstName; @Size(max = 50) @Column(name = "last_name", length = 50) private String lastName; @Email @Size(max = 100) @Column(length = 100, unique = true) private String email; @NotNull @Column(nullable = false) private boolean activated = false; @Size(min = 2, max = 5) @Column(name = "lang_key", length = 5) private String langKey; @Size(max = 20) @Column(name = "activation_key", length = 20) @JsonIgnore private String activationKey; @Size(max = 20) @Column(name = "reset_key", length = 20) private String resetKey; @Column(name = "reset_date", nullable = true) private ZonedDateTime resetDate = null; @JsonIgnore @ManyToMany @JoinTable( name = "jhi_user_authority", joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")}) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) private Set<Authority> authorities = new HashSet<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getLogin() { return login; } //Lowercase the login before saving it in database public void setLogin(String login) { this.login = login.toLowerCase(Locale.ENGLISH); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean getActivated() { return activated; } public void setActivated(boolean activated) { this.activated = activated; } public String getActivationKey() { return activationKey; } public void setActivationKey(String activationKey) { this.activationKey = activationKey; } public String getResetKey() { return resetKey; } public void setResetKey(String resetKey) { this.resetKey = resetKey; } public ZonedDateTime getResetDate() { return resetDate; } public void setResetDate(ZonedDateTime resetDate) { this.resetDate = resetDate; } public String getLangKey() { return langKey; } public void setLangKey(String langKey) { this.langKey = langKey; } public Set<Authority> getAuthorities() { return authorities; } public void setAuthorities(Set<Authority> authorities) { this.authorities = authorities; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } User user = (User) o; if (!login.equals(user.login)) { return false; } return true; } @Override public int hashCode() { return login.hashCode(); } @Override public String toString() { return "User{" + "login='" + login + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", activated='" + activated + '\'' + ", langKey='" + langKey + '\'' + ", activationKey='" + activationKey + '\'' + "}"; } }
package com.netflix.spinnaker.halyard.core.tasks.v1; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.longrunning.Operation; import com.netflix.spinnaker.halyard.core.DaemonResponse; import com.netflix.spinnaker.halyard.core.error.v1.HalException; import com.netflix.spinnaker.halyard.core.problem.v1.Problem; import com.netflix.spinnaker.halyard.core.problem.v1.ProblemBuilder; import com.netflix.spinnaker.halyard.core.problem.v1.ProblemSet; import com.netflix.spinnaker.halyard.core.secrets.v1.SecretSessionManager; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.function.Consumer; import java.util.function.Supplier; import lombok.Data; import lombok.Getter; import lombok.extern.slf4j.Slf4j; /** * This represents a long-running task managed by the Daemon that can be polled for status * information. It is made up of multiple stages, each of which have multiple events. */ @Data @Slf4j public class DaemonTask<C, T> { List<DaemonEvent> events = new ArrayList<>(); List<DaemonTask> children = new ArrayList<>(); final String name; final String uuid; boolean timedOut; final long timeout; final String version; State state = State.NOT_STARTED; DaemonResponse<T> response; Exception fatalError; List<String> runningJobs = new ArrayList<>(); @JsonIgnore Thread runner; @JsonIgnore C context; @JsonIgnore String currentStage; @JsonCreator public DaemonTask(@JsonProperty("name") String name, @JsonProperty("timeout") long timeout) { this.name = name; this.uuid = UUID.randomUUID().toString(); this.timeout = timeout; this.version = Optional.ofNullable(DaemonTask.class.getPackage().getImplementationVersion()) .orElse("Unknown"); } @JsonIgnore public Operation getLRO() { // TODO(brnelson): This shouldn't do this, it should set name to name and add the UUID as // metadata. return Operation.newBuilder().setName(this.uuid).setDone(this.state.isTerminal()).build(); } void newStage(String name) { currentStage = name; } void writeMessage(String message) { if (currentStage == null) { throw new IllegalStateException( "Illegal attempt to write an event when no stage has started"); } events.add( new DaemonEvent() .setStage(currentStage) .setMessage(message) .setTimestamp(System.currentTimeMillis())); } public void consumeTaskTree(Consumer<DaemonTask> c) { c.accept(this); children.stream().forEach((t) -> t.consumeTaskTree(c)); } public enum State { NOT_STARTED(false), RUNNING(false), SUCCEEDED(true), INTERRUPTED(true), TIMED_OUT(true), FAILED(true); @Getter boolean terminal; State(boolean terminal) { this.terminal = terminal; } } void timeout() { timedOut = true; interrupt(); } private boolean isInterrupted() { return runner.isInterrupted(); } public void interrupt() { runner.interrupt(); } void cleanupResources() { log.info(this + " killing all jobs created by this task " + String.join(", ", runningJobs)); DaemonTaskHandler.getJobExecutor().cancelJobs(new ArrayList<>(runningJobs)); SecretSessionManager.clearSession(); for (DaemonTask child : children) { if (child != null) { log.info(this + " interrupting child " + child); if (timedOut) { child.timeout(); } else { child.interrupt(); } } } } private void inSucceededState() { state = State.SUCCEEDED; } private void inFailedState() { if (isTimedOut()) { state = State.TIMED_OUT; } else if (isInterrupted()) { state = State.INTERRUPTED; } else { state = State.FAILED; } } public void success(DaemonResponse<T> response) { inSucceededState(); this.response = response; } public void failure(Exception e) { inFailedState(); fatalError = e; Problem problem = new ProblemBuilder(Problem.Severity.FATAL, "Unexpected exception: " + e).build(); response = new DaemonResponse<>(null, new ProblemSet(problem)); } public void failure(HalException e) { inFailedState(); fatalError = e; response = new DaemonResponse<>(null, e.getProblems()); } <Q, P> DaemonTask<Q, P> spawnChild( Supplier<DaemonResponse<P>> childRunner, String name, long timeout) { DaemonTask child = TaskRepository.submitTask(childRunner, name, timeout); children.add(child); return child; } <P> DaemonResponse<P> reapChild(DaemonTask task) throws InterruptedException { DaemonTask childTask = children.stream() .filter(c -> c.getUuid().equals(task.getUuid())) .findFirst() .orElseThrow( () -> new IllegalArgumentException( "Child " + task + " does not belong to this task " + this + "")); // Spin due to spurious wakeups while (!childTask.getState().isTerminal()) { try { synchronized (childTask) { childTask.wait(); } } catch (InterruptedException e) { throw e; } } TaskRepository.getTask(childTask.getUuid()); log.info(this + " Collected child task " + childTask + " with state " + childTask.getState()); if (childTask.getResponse() == null) { throw new RuntimeException("Child response may not be null."); } return childTask.getResponse(); } @Override public String toString() { return "[" + name + "] (" + uuid + ") - " + state; } }
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import org.hibernate.JDBCException; import org.hibernate.LockOptions; import org.hibernate.PessimisticLockException; import org.hibernate.cfg.Environment; import org.hibernate.dialect.function.NoArgSQLFunction; import org.hibernate.dialect.function.PositionSubstringFunction; import org.hibernate.dialect.function.SQLFunctionTemplate; import org.hibernate.dialect.function.StandardSQLFunction; import org.hibernate.dialect.function.VarArgsSQLFunction; import org.hibernate.exception.LockAcquisitionException; import org.hibernate.exception.spi.SQLExceptionConversionDelegate; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; import org.hibernate.id.SequenceGenerator; import org.hibernate.internal.util.JdbcExceptionHelper; import org.hibernate.type.StandardBasicTypes; import org.hibernate.type.descriptor.sql.BlobTypeDescriptor; import org.hibernate.type.descriptor.sql.ClobTypeDescriptor; import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; /** * An SQL dialect for Postgres * <p/> * For discussion of BLOB support in Postgres, as of 8.4, have a peek at * <a href="http://jdbc.postgresql.org/documentation/84/binary-data.html">http://jdbc.postgresql.org/documentation/84/binary-data.html</a>. * For the effects in regards to Hibernate see <a href="http://in.relation.to/15492.lace">http://in.relation.to/15492.lace</a> * * @author Gavin King */ public class PostgreSQL81Dialect extends Dialect { public PostgreSQL81Dialect() { super(); registerColumnType( Types.BIT, "bool" ); registerColumnType( Types.BIGINT, "int8" ); registerColumnType( Types.SMALLINT, "int2" ); registerColumnType( Types.TINYINT, "int2" ); registerColumnType( Types.INTEGER, "int4" ); registerColumnType( Types.CHAR, "char(1)" ); registerColumnType( Types.VARCHAR, "varchar($l)" ); registerColumnType( Types.FLOAT, "float4" ); registerColumnType( Types.DOUBLE, "float8" ); registerColumnType( Types.DATE, "date" ); registerColumnType( Types.TIME, "time" ); registerColumnType( Types.TIMESTAMP, "timestamp" ); registerColumnType( Types.VARBINARY, "bytea" ); registerColumnType( Types.BINARY, "bytea" ); registerColumnType( Types.LONGVARCHAR, "text" ); registerColumnType( Types.LONGVARBINARY, "bytea" ); registerColumnType( Types.CLOB, "text" ); registerColumnType( Types.BLOB, "oid" ); registerColumnType( Types.NUMERIC, "numeric($p, $s)" ); registerColumnType( Types.OTHER, "uuid" ); registerFunction( "abs", new StandardSQLFunction("abs") ); registerFunction( "sign", new StandardSQLFunction("sign", StandardBasicTypes.INTEGER) ); registerFunction( "acos", new StandardSQLFunction("acos", StandardBasicTypes.DOUBLE) ); registerFunction( "asin", new StandardSQLFunction("asin", StandardBasicTypes.DOUBLE) ); registerFunction( "atan", new StandardSQLFunction("atan", StandardBasicTypes.DOUBLE) ); registerFunction( "cos", new StandardSQLFunction("cos", StandardBasicTypes.DOUBLE) ); registerFunction( "cot", new StandardSQLFunction("cot", StandardBasicTypes.DOUBLE) ); registerFunction( "exp", new StandardSQLFunction("exp", StandardBasicTypes.DOUBLE) ); registerFunction( "ln", new StandardSQLFunction("ln", StandardBasicTypes.DOUBLE) ); registerFunction( "log", new StandardSQLFunction("log", StandardBasicTypes.DOUBLE) ); registerFunction( "sin", new StandardSQLFunction("sin", StandardBasicTypes.DOUBLE) ); registerFunction( "sqrt", new StandardSQLFunction("sqrt", StandardBasicTypes.DOUBLE) ); registerFunction( "cbrt", new StandardSQLFunction("cbrt", StandardBasicTypes.DOUBLE) ); registerFunction( "tan", new StandardSQLFunction("tan", StandardBasicTypes.DOUBLE) ); registerFunction( "radians", new StandardSQLFunction("radians", StandardBasicTypes.DOUBLE) ); registerFunction( "degrees", new StandardSQLFunction("degrees", StandardBasicTypes.DOUBLE) ); registerFunction( "stddev", new StandardSQLFunction("stddev", StandardBasicTypes.DOUBLE) ); registerFunction( "variance", new StandardSQLFunction("variance", StandardBasicTypes.DOUBLE) ); registerFunction( "random", new NoArgSQLFunction("random", StandardBasicTypes.DOUBLE) ); registerFunction( "rand", new NoArgSQLFunction("random", StandardBasicTypes.DOUBLE) ); registerFunction( "round", new StandardSQLFunction("round") ); registerFunction( "trunc", new StandardSQLFunction("trunc") ); registerFunction( "ceil", new StandardSQLFunction("ceil") ); registerFunction( "floor", new StandardSQLFunction("floor") ); registerFunction( "chr", new StandardSQLFunction("chr", StandardBasicTypes.CHARACTER) ); registerFunction( "lower", new StandardSQLFunction("lower") ); registerFunction( "upper", new StandardSQLFunction("upper") ); registerFunction( "substr", new StandardSQLFunction("substr", StandardBasicTypes.STRING) ); registerFunction( "initcap", new StandardSQLFunction("initcap") ); registerFunction( "to_ascii", new StandardSQLFunction("to_ascii") ); registerFunction( "quote_ident", new StandardSQLFunction("quote_ident", StandardBasicTypes.STRING) ); registerFunction( "quote_literal", new StandardSQLFunction("quote_literal", StandardBasicTypes.STRING) ); registerFunction( "md5", new StandardSQLFunction("md5", StandardBasicTypes.STRING) ); registerFunction( "ascii", new StandardSQLFunction("ascii", StandardBasicTypes.INTEGER) ); registerFunction( "char_length", new StandardSQLFunction("char_length", StandardBasicTypes.LONG) ); registerFunction( "bit_length", new StandardSQLFunction("bit_length", StandardBasicTypes.LONG) ); registerFunction( "octet_length", new StandardSQLFunction("octet_length", StandardBasicTypes.LONG) ); registerFunction( "age", new StandardSQLFunction("age") ); registerFunction( "current_date", new NoArgSQLFunction("current_date", StandardBasicTypes.DATE, false) ); registerFunction( "current_time", new NoArgSQLFunction("current_time", StandardBasicTypes.TIME, false) ); registerFunction( "current_timestamp", new NoArgSQLFunction("current_timestamp", StandardBasicTypes.TIMESTAMP, false) ); registerFunction( "date_trunc", new StandardSQLFunction( "date_trunc", StandardBasicTypes.TIMESTAMP ) ); registerFunction( "localtime", new NoArgSQLFunction("localtime", StandardBasicTypes.TIME, false) ); registerFunction( "localtimestamp", new NoArgSQLFunction("localtimestamp", StandardBasicTypes.TIMESTAMP, false) ); registerFunction( "now", new NoArgSQLFunction("now", StandardBasicTypes.TIMESTAMP) ); registerFunction( "timeofday", new NoArgSQLFunction("timeofday", StandardBasicTypes.STRING) ); registerFunction( "current_user", new NoArgSQLFunction("current_user", StandardBasicTypes.STRING, false) ); registerFunction( "session_user", new NoArgSQLFunction("session_user", StandardBasicTypes.STRING, false) ); registerFunction( "user", new NoArgSQLFunction("user", StandardBasicTypes.STRING, false) ); registerFunction( "current_database", new NoArgSQLFunction("current_database", StandardBasicTypes.STRING, true) ); registerFunction( "current_schema", new NoArgSQLFunction("current_schema", StandardBasicTypes.STRING, true) ); registerFunction( "to_char", new StandardSQLFunction("to_char", StandardBasicTypes.STRING) ); registerFunction( "to_date", new StandardSQLFunction("to_date", StandardBasicTypes.DATE) ); registerFunction( "to_timestamp", new StandardSQLFunction("to_timestamp", StandardBasicTypes.TIMESTAMP) ); registerFunction( "to_number", new StandardSQLFunction("to_number", StandardBasicTypes.BIG_DECIMAL) ); registerFunction( "concat", new VarArgsSQLFunction( StandardBasicTypes.STRING, "(","||",")" ) ); registerFunction( "locate", new PositionSubstringFunction() ); registerFunction( "str", new SQLFunctionTemplate(StandardBasicTypes.STRING, "cast(?1 as varchar)") ); getDefaultProperties().setProperty(Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE); getDefaultProperties().setProperty( Environment.NON_CONTEXTUAL_LOB_CREATION, "true" ); } /** * {@inheritDoc} */ @Override public SqlTypeDescriptor getSqlTypeDescriptorOverride(int sqlCode) { SqlTypeDescriptor descriptor; switch ( sqlCode ) { case Types.BLOB: { // Force BLOB binding. Otherwise, byte[] fields annotated // with @Lob will attempt to use // BlobTypeDescriptor.PRIMITIVE_ARRAY_BINDING. Since the // dialect uses oid for Blobs, byte arrays cannot be used. descriptor = BlobTypeDescriptor.BLOB_BINDING; break; } case Types.CLOB: { descriptor = ClobTypeDescriptor.CLOB_BINDING; break; } default: { descriptor = super.getSqlTypeDescriptorOverride( sqlCode ); break; } } return descriptor; } public String getAddColumnString() { return "add column"; } public String getSequenceNextValString(String sequenceName) { return "select " + getSelectSequenceNextValString( sequenceName ); } public String getSelectSequenceNextValString(String sequenceName) { return "nextval ('" + sequenceName + "')"; } public String getCreateSequenceString(String sequenceName) { return "create sequence " + sequenceName; //starts with 1, implicitly } public String getDropSequenceString(String sequenceName) { return "drop sequence " + sequenceName; } public String getCascadeConstraintsString() { return " cascade"; } public boolean dropConstraints() { return true; } public boolean supportsSequences() { return true; } public String getQuerySequencesString() { return "select relname from pg_class where relkind='S'"; } public boolean supportsLimit() { return true; } public String getLimitString(String sql, boolean hasOffset) { return new StringBuilder( sql.length()+20 ) .append( sql ) .append( hasOffset ? " limit ? offset ?" : " limit ?" ) .toString(); } public boolean bindLimitParametersInReverseOrder() { return true; } public boolean supportsIdentityColumns() { return true; } public String getForUpdateString(String aliases) { return getForUpdateString() + " of " + aliases; } public String getIdentitySelectString(String table, String column, int type) { return new StringBuilder().append("select currval('") .append(table) .append('_') .append(column) .append("_seq')") .toString(); } public String getIdentityColumnString(int type) { return type==Types.BIGINT ? "bigserial not null" : "serial not null"; } public boolean hasDataTypeInIdentityColumn() { return false; } public String getNoColumnsInsertString() { return "default values"; } public String getCaseInsensitiveLike(){ return "ilike"; } @Override public boolean supportsCaseInsensitiveLike() { return true; } public Class getNativeIdentifierGeneratorClass() { return SequenceGenerator.class; } public boolean supportsOuterJoinForUpdate() { return false; } public boolean useInputStreamToInsertBlob() { return false; } public boolean supportsUnionAll() { return true; } /** * Workaround for postgres bug #1453 */ public String getSelectClauseNullString(int sqlType) { String typeName = getTypeName(sqlType, 1, 1, 0); //trim off the length/precision/scale int loc = typeName.indexOf('('); if (loc>-1) { typeName = typeName.substring(0, loc); } return "null::" + typeName; } public boolean supportsCommentOn() { return true; } public boolean supportsTemporaryTables() { return true; } public String getCreateTemporaryTableString() { return "create temporary table"; } public String getCreateTemporaryTablePostfix() { return "on commit drop"; } /*public boolean dropTemporaryTableAfterUse() { //we have to, because postgres sets current tx //to rollback only after a failed create table return true; }*/ public boolean supportsCurrentTimestampSelection() { return true; } public boolean isCurrentTimestampSelectStringCallable() { return false; } public String getCurrentTimestampSelectString() { return "select now()"; } public boolean supportsTupleDistinctCounts() { return false; } public String toBooleanValueString(boolean bool) { return bool ? "true" : "false"; } public ViolatedConstraintNameExtracter getViolatedConstraintNameExtracter() { return EXTRACTER; } /** * Constraint-name extractor for Postgres constraint violation exceptions. * Orginally contributed by Denny Bartelt. */ private static ViolatedConstraintNameExtracter EXTRACTER = new TemplatedViolatedConstraintNameExtracter() { public String extractConstraintName(SQLException sqle) { try { int sqlState = Integer.valueOf( JdbcExceptionHelper.extractSqlState( sqle )).intValue(); switch (sqlState) { // CHECK VIOLATION case 23514: return extractUsingTemplate("violates check constraint \"","\"", sqle.getMessage()); // UNIQUE VIOLATION case 23505: return extractUsingTemplate("violates unique constraint \"","\"", sqle.getMessage()); // FOREIGN KEY VIOLATION case 23503: return extractUsingTemplate("violates foreign key constraint \"","\"", sqle.getMessage()); // NOT NULL VIOLATION case 23502: return extractUsingTemplate("null value in column \"","\" violates not-null constraint", sqle.getMessage()); // TODO: RESTRICT VIOLATION case 23001: return null; // ALL OTHER default: return null; } } catch (NumberFormatException nfe) { return null; } } }; @Override public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() { return new SQLExceptionConversionDelegate() { @Override public JDBCException convert(SQLException sqlException, String message, String sql) { final String sqlState = JdbcExceptionHelper.extractSqlState( sqlException ); if ( "40P01".equals( sqlState ) ) { // DEADLOCK DETECTED return new LockAcquisitionException( message, sqlException, sql ); } if ( "55P03".equals( sqlState ) ) { // LOCK NOT AVAILABLE return new PessimisticLockException( message, sqlException, sql ); } // returning null allows other delegates to operate return null; } }; } public int registerResultSetOutParameter(CallableStatement statement, int col) throws SQLException { // Register the type of the out param - PostgreSQL uses Types.OTHER statement.registerOutParameter(col++, Types.OTHER); return col; } public ResultSet getResultSet(CallableStatement ps) throws SQLException { ps.execute(); return (ResultSet) ps.getObject(1); } public boolean supportsPooledSequences() { return true; } //only necessary for postgre < 7.4 //http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/doc/src/sgml/ref/create_sequence.sgml protected String getCreateSequenceString(String sequenceName, int initialValue, int incrementSize) { return getCreateSequenceString( sequenceName ) + " start " + initialValue + " increment " + incrementSize; } // Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // seems to not really... // public boolean supportsRowValueConstructorSyntax() { // return true; // } public boolean supportsEmptyInList() { return false; } @Override public boolean supportsExpectedLobUsagePattern() { return true; } @Override public boolean supportsLobValueChangePropogation() { return false; } @Override public boolean supportsUnboundedLobLocatorMaterialization() { return false; } // locking support public String getForUpdateString() { return " for update"; } public String getWriteLockString(int timeout) { if ( timeout == LockOptions.NO_WAIT ) return " for update nowait"; else return " for update"; } public String getReadLockString(int timeout) { if ( timeout == LockOptions.NO_WAIT ) return " for share nowait"; else return " for share"; } public boolean supportsRowValueConstructorSyntax() { return true; } @Override public String getForUpdateNowaitString() { return getForUpdateString() + " nowait "; } @Override public String getForUpdateNowaitString(String aliases) { return getForUpdateString(aliases) + " nowait "; } }
package org.elasticsearch.plugin.readonlyrest.acl; import com.google.common.base.Joiner; import com.google.common.collect.ObjectArrays; import com.google.common.collect.Sets; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.CompositeIndicesRequest; import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.aliases.IndexAliasesService; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.plugin.readonlyrest.SecurityPermissionException; import org.elasticsearch.plugin.readonlyrest.acl.blocks.rules.MatcherWithWildcards; import org.elasticsearch.rest.RestChannel; import org.elasticsearch.rest.RestRequest; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetSocketAddress; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.regex.Pattern; /** * Created by sscarduzio on 20/02/2016. */ public class RequestContext { private final static ESLogger logger = Loggers.getLogger(RequestContext.class); /* * A regular expression to match the various representations of "localhost" */ private final static Pattern localhostRe = Pattern.compile("^(127(\\.\\d+){1,3}|[0:]+1)$"); private final static String LOCALHOST = "127.0.0.1"; private final RestChannel channel; private final RestRequest request; private final String action; private final ActionRequest actionRequest; private Set<String> indices = null; private String content = null; private IndicesService indexService = null; public RequestContext(RestChannel channel, RestRequest request, String action, ActionRequest actionRequest, IndicesService indicesService) { this.channel = channel; this.request = request; this.action = action; this.actionRequest = actionRequest; this.indexService = indicesService; } public RequestContext(RestChannel channel, RestRequest request, String action, ActionRequest actionRequest) { this.channel = channel; this.request = request; this.action = action; this.actionRequest = actionRequest; } public String getRemoteAddress() { String remoteHost = ((InetSocketAddress) request.getRemoteAddress()).getAddress().getHostAddress(); // Make sure we recognize localhost even when IPV6 is involved if (localhostRe.matcher(remoteHost).find()) { remoteHost = LOCALHOST; } return remoteHost; } public String getContent() { if (content == null) { try { content = new String(request.content().array()); } catch (Exception e) { content = "<not available>"; } } return content; } public Set<String> getAvailableIndicesAndAliases() { final HashSet<String> harvested = new HashSet<>(); final Iterator<IndexService> i = indexService.iterator(); AccessController.doPrivileged( new PrivilegedAction<Void>() { @Override public Void run() { while (i.hasNext()) { IndexService theIndexSvc = i.next(); harvested.add(theIndexSvc.index().getName()); final IndexAliasesService aliasSvc = theIndexSvc.aliasesService(); try { Field field = aliasSvc.getClass().getDeclaredField("aliases"); field.setAccessible(true); ImmutableOpenMap<String, String> aliases = (ImmutableOpenMap<String, String>) field.get(aliasSvc); System.out.printf(aliases.toString()); for (Object o : aliases.keys().toArray()) { String a = (String) o; harvested.add(a); } // harvested.addAll(aliases.keys().toArray(new String[aliases.keys().size()])); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return null; } }); return harvested; } public void setIndices(final Set<String> newIndices) { AccessController.doPrivileged( new PrivilegedAction<Void>() { @Override public Void run() { try { Field field = actionRequest.getClass().getDeclaredField("indices"); field.setAccessible(true); String[] idxArray = newIndices.toArray(new String[newIndices.size()]); field.set(actionRequest, idxArray); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } indices.clear(); indices.addAll(newIndices); return null; } }); } public Set<String> getIndices() { if (indices != null) { return indices; } final String[][] out = {new String[1]}; AccessController.doPrivileged( new PrivilegedAction<Void>() { @Override public Void run() { String[] indices = new String[0]; ActionRequest ar = actionRequest; if (ar instanceof CompositeIndicesRequest) { CompositeIndicesRequest cir = (CompositeIndicesRequest) ar; for (IndicesRequest ir : cir.subRequests()) { indices = ObjectArrays.concat(indices, ir.indices(), String.class); } } else { try { Method m = ar.getClass().getMethod("indices"); if (m.getReturnType() != String[].class) { out[0] = new String[]{}; return null; } m.setAccessible(true); indices = (String[]) m.invoke(ar); } catch (SecurityException e) { logger.error("Can't get indices for request: " + toString()); throw new SecurityPermissionException("Insufficient permissions to extract the indices. Abort! Cause: " + e.getMessage(), e); } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { logger.debug("Failed to discover indices associated to this request: " + this); } } if (indices == null) { indices = new String[0]; } HashSet<String> tempSet = new HashSet<>(Arrays.asList(indices)); // Finding indices from payload and deduping them if (actionRequest instanceof SearchRequest) { // Translate any wildcards in the request into real indices (easier to reason about in indices rule) MatcherWithWildcards realIndexMatcher = new MatcherWithWildcards(tempSet); for (String realIdx : getAvailableIndicesAndAliases()) { if (realIndexMatcher.match(realIdx)) { tempSet.add(realIdx); } } // Hack #FIXME if (tempSet.size() == 0 || tempSet.contains("_all") || tempSet.contains("_search")) { tempSet.clear(); tempSet.add("_all"); } } // DONE indices = tempSet.toArray(new String[tempSet.size()]); if (logger.isDebugEnabled()) { String idxs = Joiner.on(',').skipNulls().join(indices); logger.debug("Discovered indices: " + idxs); } out[0] = indices; return null; } } ); indices = Sets.newHashSet(out[0]); return indices; } public RestChannel getChannel() { return channel; } public RestRequest getRequest() { return request; } public String getAction() { return action; } public ActionRequest getActionRequest() { return actionRequest; } @Override public String toString() { StringBuilder idxsb = new StringBuilder(); idxsb.append("["); try { for (String i : getIndices()) { idxsb.append(i).append(' '); } } catch (Exception e) { idxsb.append("<CANNOT GET INDICES>"); } String idxs = idxsb.toString().trim() + "]"; return "{ action: " + action + ", OA:" + getRemoteAddress() + ", indices:" + idxs + ", M:" + request.method() + ", P:" + request.path() + ", C:" + getContent() + ", Headers:" + request.getHeaders() + "}"; } }
package de.onyxbits.raccoon.io; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Properties; import java.util.Vector; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.HttpClient; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.impl.conn.SchemeRegistryFactory; import com.akdeniz.googleplaycrawler.Utils; /** * An archive is a container for managing downloaded apk files and credentials. * The idea here is that the user should be able to keep around different apk * versions of an app and should also be able to maintain different download * folders (e.g. one for anonymously downloading apps and one for downloading * bought apps or one downloadfolder per device/account). The later means that * credentials have to be kept within the archive. * * @author patrick * */ public class Archive { /** * Relative path to where we keep APK files. This directory contains one * subdirectory per app, which in turn holds the apks. */ private static final String APKDIR = "apk_storage"; /** * Name of the logdir (relative to the root dir). */ public static final String LOGDIR = "logs"; /** * Name of the file containing the credentials for connecting to GPlay. */ private static final String CREDCFG = "credentials.cfg"; /** * Name of the file containing the network config */ public static final String NETCFG = "network.cfg"; public static final String PASSWORD = "password"; public static final String USERID = "userid"; public static final String ANDROIDID = "androidid"; public static final String PROXYHOST = "proxyhost"; public static final String PROXYPORT = "proxyport"; public static final String USERAGENT = "useragent"; public static final String PROXYUSER = "proxyuser"; public static final String PROXYPASS = "proxypass"; private File root; private Properties credentials; /** * Cache of the auth token. This is not persisted. This may be null. */ private String authToken; /** * Query the cached auth cookie. * * @return the authToken */ public String getAuthToken() { return authToken; } /** * Cache an auth cookie. WARNING: In a multithread environment, make sure that * you don't perform logins simultaneously, so you don't race for cookies. * * @param authToken * the authToken to set */ public void setAuthToken(String authToken) { this.authToken = authToken; } /** * @return the androidId */ public String getAndroidId() { return credentials.getProperty(ANDROIDID, ""); } /** * @param androidId * the androidId to set */ public void setAndroidId(String androidId) { credentials.setProperty(ANDROIDID, androidId); } /** * @return the password */ public String getPassword() { return credentials.getProperty(PASSWORD, ""); } /** * @param password * the password to set */ public void setPassword(String password) { credentials.setProperty(PASSWORD, password); } /** * @return the userId */ public String getUserId() { return credentials.getProperty(USERID, ""); } /** * @param userId * the userId to set */ public void setUserId(String userId) { credentials.setProperty(USERID, userId); } /** * Create a new archive in the designated place * * @param root * directory in which to generate the archive */ public Archive(File root) { this.root = root; try { credentials = new Properties(); credentials.load(new FileInputStream(new File(root, CREDCFG))); } catch (Exception e) { // e.printStackTrace(); } } /** * Get a proxy client, if it is configured. * * @return either a client or null * @throws IOException * if reading the config file fails * @throws KeyManagementException * @throws NumberFormatException * if that port could not be parsed. * @throws NoSuchAlgorithmException */ public HttpClient getProxyClient() throws IOException, KeyManagementException, NoSuchAlgorithmException, NumberFormatException { File cfgfile = new File(root, NETCFG); if (cfgfile.exists()) { Properties cfg = new Properties(); cfg.load(new FileInputStream(cfgfile)); String ph = cfg.getProperty(PROXYHOST, null); String pp = cfg.getProperty(PROXYPORT, null); String pu = cfg.getProperty(PROXYUSER, null); String pw = cfg.getProperty(PROXYPASS, null); if (ph == null || pp == null) { return null; } PoolingClientConnectionManager connManager = new PoolingClientConnectionManager( SchemeRegistryFactory.createDefault()); connManager.setMaxTotal(100); connManager.setDefaultMaxPerRoute(30); DefaultHttpClient client = new DefaultHttpClient(connManager); client.getConnectionManager().getSchemeRegistry().register(Utils.getMockedScheme()); HttpHost proxy = new HttpHost(ph, Integer.parseInt(pp)); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (pu != null && pw != null) { client.getCredentialsProvider().setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(pu, pw)); } return client; } return null; } /** * Query the location of the archive * * @return the directory in which the archive is kept. */ public File getRoot() { return root; } /** * Persist credentials to the CREDS file. * * @throws IOException * if saving goes wrong. */ public void saveCredentials() throws IOException { root.mkdirs(); credentials.store(new FileOutputStream(new File(root, CREDCFG)), ""); } /** * Figure out where to save an app * * @param packName * packagename of the app * @param vc * versioncode of the app * @return the file where to save this app. */ public File fileUnder(String packName, int vc) { File appRoot = new File(new File(root, APKDIR), packName.replace('.', '-')); return new File(appRoot, packName.replace('.', '_') + "-" + vc + ".apk"); } /** * Figure our where to save an expansion file for an app * * @param type * this should either be "main" or "patch", depending on which * expansion to file * @param packName * package name of the app. * @param vc * version code of the expansion * @return where to save. */ public File fileExpansionUnder(String type, String packName, int vc) { File appRoot = new File(new File(root, APKDIR), packName.replace('.', '-')); return new File(appRoot, type + "." + vc + "." + packName + ".obb"); } /** * List all apps in the archive * * @return a list of packagenames. */ public List<String> list() { File storage = new File(root, APKDIR); storage.mkdirs(); File[] lst = storage.listFiles(); Vector<String> tmp = new Vector<String>(); for (File f : lst) { if (f.isDirectory()) { tmp.add(f.getName().replace('-', '.')); } } return tmp; } /** * Statistics: count apps in this archive * * @return the number of subdirectories in the APK_STORAGE */ public int countApps() { int ret = 0; try { File[] lst = new File(root, APKDIR).listFiles(); for (File f : lst) { if (f.isDirectory()) { ret++; } } } catch (Exception e) { // Obviously no apps. } return ret; } /** * Turn a raw filesize into a human readable one * * @param bytes * raw size * @param si * use SI units * @return formated string. */ public static String humanReadableByteCount(long bytes, boolean si) { int unit = si ? 1000 : 1024; if (bytes < unit) return bytes + " B"; int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); } public String getUserAgent() { return credentials.getProperty(USERAGENT,null); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.managers.communication; import org.apache.ignite.*; import org.apache.ignite.internal.*; import org.apache.ignite.internal.managers.checkpoint.*; import org.apache.ignite.internal.managers.deployment.*; import org.apache.ignite.internal.managers.eventstorage.*; import org.apache.ignite.internal.portable.*; import org.apache.ignite.internal.processors.affinity.*; import org.apache.ignite.internal.processors.cache.*; import org.apache.ignite.internal.processors.cache.distributed.*; import org.apache.ignite.internal.processors.cache.distributed.dht.*; import org.apache.ignite.internal.processors.cache.distributed.dht.atomic.*; import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.*; import org.apache.ignite.internal.processors.cache.distributed.near.*; import org.apache.ignite.internal.processors.cache.query.*; import org.apache.ignite.internal.processors.cache.query.continuous.*; import org.apache.ignite.internal.processors.cache.transactions.*; import org.apache.ignite.internal.processors.cache.version.*; import org.apache.ignite.internal.processors.clock.*; import org.apache.ignite.internal.processors.continuous.*; import org.apache.ignite.internal.processors.datastreamer.*; import org.apache.ignite.internal.processors.igfs.*; import org.apache.ignite.internal.processors.query.h2.twostep.messages.*; import org.apache.ignite.internal.processors.rest.handlers.task.*; import org.apache.ignite.internal.util.*; import org.apache.ignite.lang.*; import org.apache.ignite.plugin.extensions.communication.*; import org.apache.ignite.spi.collision.jobstealing.*; import org.apache.ignite.spi.communication.tcp.*; import org.jsr166.*; import java.util.*; /** * Message factory implementation. */ public class GridIoMessageFactory implements MessageFactory { /** Custom messages registry. Used for test purposes. */ private static final Map<Byte, IgniteOutClosure<Message>> CUSTOM = new ConcurrentHashMap8<>(); /** Extensions. */ private final MessageFactory[] ext; /** * @param ext Extensions. */ public GridIoMessageFactory(MessageFactory[] ext) { this.ext = ext; } /** {@inheritDoc} */ @Override public Message create(byte type) { Message msg = null; switch (type) { case TcpCommunicationSpi.NODE_ID_MSG_TYPE: msg = new TcpCommunicationSpi.NodeIdMessage(); break; case TcpCommunicationSpi.RECOVERY_LAST_ID_MSG_TYPE: msg = new TcpCommunicationSpi.RecoveryLastReceivedMessage(); break; case TcpCommunicationSpi.HANDSHAKE_MSG_TYPE: msg = new TcpCommunicationSpi.HandshakeMessage(); break; case 0: msg = new GridJobCancelRequest(); break; case 1: msg = new GridJobExecuteRequest(); break; case 2: msg = new GridJobExecuteResponse(); break; case 3: msg = new GridJobSiblingsRequest(); break; case 4: msg = new GridJobSiblingsResponse(); break; case 5: msg = new GridTaskCancelRequest(); break; case 6: msg = new GridTaskSessionRequest(); break; case 7: msg = new GridCheckpointRequest(); break; case 8: msg = new GridIoMessage(); break; case 9: msg = new GridIoUserMessage(); break; case 10: msg = new GridDeploymentInfoBean(); break; case 11: msg = new GridDeploymentRequest(); break; case 12: msg = new GridDeploymentResponse(); break; case 13: msg = new GridEventStorageMessage(); break; case 14: msg = new GridCacheEvictionRequest(); break; case 15: msg = new GridCacheEvictionResponse(); break; case 16: msg = new GridCacheTxRecoveryRequest(); break; case 17: msg = new GridCacheTxRecoveryResponse(); break; case 20: msg = new GridCacheTtlUpdateRequest(); break; case 21: msg = new GridDistributedLockRequest(); break; case 22: msg = new GridDistributedLockResponse(); break; case 23: msg = new GridDistributedTxFinishRequest(); break; case 24: msg = new GridDistributedTxFinishResponse(); break; case 25: msg = new GridDistributedTxPrepareRequest(); break; case 26: msg = new GridDistributedTxPrepareResponse(); break; case 27: msg = new GridDistributedUnlockRequest(); break; case 28: msg = new GridDhtAffinityAssignmentRequest(); break; case 29: msg = new GridDhtAffinityAssignmentResponse(); break; case 30: msg = new GridDhtLockRequest(); break; case 31: msg = new GridDhtLockResponse(); break; case 32: msg = new GridDhtTxFinishRequest(); break; case 33: msg = new GridDhtTxFinishResponse(); break; case 34: msg = new GridDhtTxPrepareRequest(); break; case 35: msg = new GridDhtTxPrepareResponse(); break; case 36: msg = new GridDhtUnlockRequest(); break; case 37: msg = new GridDhtAtomicDeferredUpdateResponse(); break; case 38: msg = new GridDhtAtomicUpdateRequest(); break; case 39: msg = new GridDhtAtomicUpdateResponse(); break; case 40: msg = new GridNearAtomicUpdateRequest(); break; case 41: msg = new GridNearAtomicUpdateResponse(); break; case 42: msg = new GridDhtForceKeysRequest(); break; case 43: msg = new GridDhtForceKeysResponse(); break; case 44: msg = new GridDhtPartitionDemandMessage(); break; case 45: msg = new GridDhtPartitionSupplyMessage(); break; case 46: msg = new GridDhtPartitionsFullMessage(); break; case 47: msg = new GridDhtPartitionsSingleMessage(); break; case 48: msg = new GridDhtPartitionsSingleRequest(); break; case 49: msg = new GridNearGetRequest(); break; case 50: msg = new GridNearGetResponse(); break; case 51: msg = new GridNearLockRequest(); break; case 52: msg = new GridNearLockResponse(); break; case 53: msg = new GridNearTxFinishRequest(); break; case 54: msg = new GridNearTxFinishResponse(); break; case 55: msg = new GridNearTxPrepareRequest(); break; case 56: msg = new GridNearTxPrepareResponse(); break; case 57: msg = new GridNearUnlockRequest(); break; case 58: msg = new GridCacheQueryRequest(); break; case 59: msg = new GridCacheQueryResponse(); break; case 60: msg = new GridClockDeltaSnapshotMessage(); break; case 61: msg = new GridContinuousMessage(); break; case 62: msg = new DataStreamerRequest(); break; case 63: msg = new DataStreamerResponse(); break; case 64: msg = new IgfsAckMessage(); break; case 65: msg = new IgfsBlockKey(); break; case 66: msg = new IgfsBlocksMessage(); break; case 67: msg = new IgfsDeleteMessage(); break; case 68: msg = new IgfsFileAffinityRange(); break; case 69: msg = new IgfsFragmentizerRequest(); break; case 70: msg = new IgfsFragmentizerResponse(); break; case 71: msg = new IgfsSyncMessage(); break; case 76: msg = new GridTaskResultRequest(); break; case 77: msg = new GridTaskResultResponse(); break; case 82: msg = new JobStealingRequest(); break; case 83: msg = new GridClockDeltaVersion(); break; case 84: msg = new GridByteArrayList(); break; case 85: msg = new GridLongList(); break; case 86: msg = new GridCacheVersion(); break; case 87: msg = new GridDhtPartitionExchangeId(); break; case 88: msg = new GridCacheReturn(); break; case 89: msg = new CacheObjectImpl(); break; case 90: msg = new KeyCacheObjectImpl(); break; case 91: msg = new GridCacheEntryInfo(); break; case 92: msg = new CacheEntryInfoCollection(); break; case 93: msg = new CacheInvokeDirectResult(); break; case 94: msg = new IgniteTxKey(); break; case 95: msg = new DataStreamerEntry(); break; case 96: msg = new CacheContinuousQueryEntry(); break; case 97: msg = new CacheEvictionEntry(); break; case 98: msg = new CacheEntryPredicateContainsValue(); break; case 99: msg = new CacheEntrySerializablePredicate(); break; case 100: msg = new IgniteTxEntry(); break; case 101: msg = new TxEntryValueHolder(); break; case 102: msg = new CacheVersionedValue(); break; case 103: msg = new GridCacheRawVersionedEntry<>(); break; case 104: msg = new GridCacheVersionEx(); break; case 105: msg = new CacheObjectByteArrayImpl(); break; case 106: msg = new GridQueryCancelRequest(); break; case 107: msg = new GridQueryFailResponse(); break; case 108: msg = new GridQueryNextPageRequest(); break; case 109: msg = new GridQueryNextPageResponse(); break; case 110: msg = new GridQueryRequest(); break; case 111: msg = new AffinityTopologyVersion(); break; case 112: msg = new GridCacheSqlQuery(); break; case 113: msg = new PortableObjectImpl(); break; // [-3..112] - this // [120..123] - DR // [-4..-22] - SQL default: if (ext != null) { for (MessageFactory factory : ext) { msg = factory.create(type); if (msg != null) break; } } if (msg == null) { IgniteOutClosure<Message> c = CUSTOM.get(type); if (c != null) msg = c.apply(); } } if (msg == null) throw new IgniteException("Invalid message type: " + type); return msg; } /** * Registers factory for custom message. Used for test purposes. * * @param type Message type. * @param c Message producer. */ public static void registerCustom(byte type, IgniteOutClosure<Message> c) { assert c != null; CUSTOM.put(type, c); } }
package org.basex.query.expr.path; import static org.basex.query.expr.path.Axis.*; import java.util.*; import java.util.function.*; import org.basex.core.locks.*; import org.basex.data.*; import org.basex.index.path.*; import org.basex.query.*; import org.basex.query.CompileContext.*; import org.basex.query.expr.*; import org.basex.query.expr.List; import org.basex.query.expr.index.*; import org.basex.query.func.Function; import org.basex.query.util.*; import org.basex.query.util.index.*; import org.basex.query.util.list.*; import org.basex.query.value.item.*; import org.basex.query.value.seq.*; import org.basex.query.value.type.*; import org.basex.query.var.*; import org.basex.util.*; /** * Path expression. * * @author BaseX Team 2005-20, BSD License * @author Christian Gruen */ public abstract class Path extends ParseExpr { /** Root expression (can be {@code null}). */ public Expr root; /** Path steps. */ public Expr[] steps; /** Data reference (can be {@code null}). */ private Data data; /** * Constructor. * @param info input info * @param root root expression (can be {@code null}) * @param steps steps */ protected Path(final InputInfo info, final Expr root, final Expr... steps) { super(info, SeqType.ITEM_ZM); this.root = root; this.steps = steps; } /** * Returns a new path instance. * A path implementation is chosen that works fastest for the given steps. * @param ii input info * @param root root expression (can be temporary {@link Dummy} item or {@code null}) * @param steps steps * @return path instance */ public static Path get(final InputInfo ii, final Expr root, final Expr... steps) { // add steps of input array final ExprList tmp = new ExprList(steps.length); for(final Expr step : steps) { Expr expr = step; if(expr instanceof ContextValue) { // rewrite context item to self step expr = Step.get(((ContextValue) expr).info, SELF, KindTest.NOD); } else if(expr instanceof Filter) { // rewrite filter expression to self step with predicates final Filter f = (Filter) expr; if(f.root instanceof ContextValue) expr = Step.get(f.info, SELF, KindTest.NOD, f.exprs); } tmp.add(expr); } final Expr[] stps = tmp.finish(); // check if path can be evaluated iteratively Expr rt = root; boolean axes = true; for(final Expr expr : stps) axes &= expr instanceof Step; final boolean iterative = axes && iterative(rt, stps); // normalize root context if(rt instanceof ContextValue || rt instanceof Dummy) rt = null; final boolean single = iterative && rt == null && stps.length == 1 && !stps[0].has(Flag.POS); return single ? new SingleIterPath(ii, stps[0]) : iterative ? new IterPath(ii, rt, stps) : axes ? new CachedPath(ii, rt, stps) : new MixedPath(ii, rt, stps); } @Override public final void checkUp() throws QueryException { checkNoUp(root); final int ss = steps.length; for(int s = 0; s < ss - 1; s++) checkNoUp(steps[s]); steps[ss - 1].checkUp(); } @Override public final Expr compile(final CompileContext cc) throws QueryException { final Expr rt; if(root != null) { root = root.compile(cc); rt = root; } else { rt = cc.qc.focus.value; } cc.pushFocus(rt); final int sl = steps.length; for(int s = 0; s < sl; s++) { Expr step = steps[s]; try { step = step.compile(cc); } catch(final QueryException ex) { // replace original expression with error step = cc.error(ex, this); } steps[s] = step; cc.updateFocus(step); } cc.removeFocus(); return optimize(cc); } @Override public final Expr optimize(final CompileContext cc) throws QueryException { // no root, no nesting: assign context value (may be null) if(root == null && !cc.nestedFocus()) root = cc.qc.focus.value; // remove redundant steps, find empty steps Expr expr = simplify(cc); if(expr != this) return expr; // flatten nested path expressions expr = flatten(cc); // rewrite list to union expressions if(expr == this) expr = toUnion(cc); // merge descendant-or-self steps if(expr == this) expr = mergeSteps(cc); // return optimized expression if(expr != this) return expr.optimize(cc); // assign sequence type, compute result size final Expr rt = root != null ? root : cc.qc.focus.value; seqType(rt); // remove paths that will yield no result expr = removeEmpty(cc, rt); // rewrite to simple map if(expr == this) expr = toMap(cc); // check index access if(expr == this) expr = index(cc, rt); /* rewrite descendant to child steps. this optimization is called after the index rewritings, * as it is cheaper to invert a descendant step. examples: * - //B [. = '...'] -> IA('...', B) * - /A/B[. = '...'] -> IA('...', B)/parent::A *[parent::document-node()] */ if(expr == this) expr = children(cc, rt); // return optimized expression if(expr != this) return expr.optimize(cc); // choose best path implementation (dummy will be used for type checking) final Path path = get(info, root == null && rt instanceof Dummy ? rt : root, steps); path.data = data; return copyType(path); } @Override public final Expr simplifyFor(final Simplify mode, final CompileContext cc) throws QueryException { if(mode == Simplify.EBV) { final Expr last = steps[steps.length - 1]; if(last instanceof Step) { final Step step = (Step) last; if(step.exprs.length == 1 && step.seqType().type instanceof NodeType && !step.exprs[0].seqType().mayBeNumber()) { // merge nested predicates. example: if(a[b]) -> if(a/b) final Expr s = step.simplify(this, cc); if(s != step) { step.exprs = new Expr[0]; return cc.simplify(this, s); } } } } return super.simplifyFor(mode, cc); } @Override public final boolean has(final Flag... flags) { /* Context dependency: check if no root exists, or if it depends on context. * Examples: text(); ./abc */ if(Flag.CTX.in(flags) && (root == null || root.has(Flag.CTX))) return true; /* Positional access: only check root node (steps will refer to result of root node). * Example: position()/a */ if(Flag.POS.in(flags) && (root != null && root.has(Flag.POS))) return true; // check remaining flags final Flag[] flgs = Flag.POS.remove(Flag.CTX.remove(flags)); if(flgs.length != 0) { for(final Expr step : steps) { if(step.has(flgs)) return true; } return root != null && root.has(flgs); } return false; } /** * Tries to cast the specified step into an axis step. * @param index index * @return axis step, or {@code null}) */ private Step axisStep(final int index) { return steps[index] instanceof Step ? (Step) steps[index] : null; } /** * Flattens nested path expressions. * @param cc compilation context * @return original or optimized expression */ private Expr flatten(final CompileContext cc) { // new list with steps boolean changed = false; final ExprList tmp = new ExprList(steps.length); // flatten nested path Expr rt = root; if(rt instanceof Path) { final Path path = (Path) rt; tmp.add(path.steps); rt = path.root; cc.info(QueryText.OPTFLAT_X_X, (Supplier<?>) path::description, path); changed = true; } // add steps of input array for(final Expr step : steps) { Expr expr = step; if(expr instanceof Path) { // rewrite nested path to axis steps final Path path = (Path) expr; if(path.root != null && !(path.root instanceof ContextValue)) tmp.add(path.root); final int pl = path.steps.length - 1; for(int i = 0; i < pl; i++) tmp.add(path.steps[i]); expr = path.steps[pl]; cc.info(QueryText.OPTFLAT_X_X, (Supplier<?>) path::description, path); changed = true; } tmp.add(expr); } return changed ? get(info, rt, tmp.finish()) : this; } /** * Simplifies the path expression. * @param cc compilation context * @return original or optimized expression * @throws QueryException query exception */ private Expr simplify(final CompileContext cc) throws QueryException { // return root if it yields no result if(root != null && root.seqType().zero()) return cc.replaceWith(this, root); // find empty results, remove redundant steps final int sl = steps.length; Step self = null; final ExprList list = new ExprList(sl); for(int s = 0; s < sl; s++) { // remove redundant steps. example: <xml/>/self::node() -> <xml/> final Step st = axisStep(s); if(st != null && st.axis == SELF && st.exprs.length == 0 && st.test instanceof KindTest) { final Expr prev = list.isEmpty() ? root : list.peek(); if(prev != null && prev.seqType().type.instanceOf(st.test.type)) { self = st; continue; } } // step is empty sequence. example: $doc/NON-EXISTING-STEP -> $doc/() -> () final Expr expr = steps[s]; if(expr == Empty.VALUE) return cc.emptySeq(this); // add step to list list.add(expr); // ignore remaining steps if step yields no results // example: A/prof:void(.)/B -> A/prof:void(.) if(expr.seqType().zero() && s + 1 < sl) { cc.info(QueryText.OPTSIMPLE_X_X, (Supplier<?>) this::description, this); break; } } // self step was removed: ensure that result will be in distinct document order if(self != null && (list.isEmpty() || !list.get(0).seqType().type.instanceOf(NodeType.NOD))) { if(root == null) root = new ContextValue(info).optimize(cc); if(!root.seqType().zeroOrOne() || root instanceof DBNodeSeq) { root = cc.replaceWith(root, cc.function(Function._UTIL_DDO, info, root)); } } // no steps left: return root steps = list.finish(); return steps.length == 0 ? cc.replaceWith(this, root) : this; } /** * Returns the path nodes that will result from this path. * @param rt root at compile time (can be {@code null}) * @return path nodes or {@code null} if nodes cannot be evaluated */ public final ArrayList<PathNode> pathNodes(final Expr rt) { // ensure that path starts with document nodes if(rt == null || !rt.seqType().type.instanceOf(NodeType.DOC) || data == null || !data.meta.uptodate) return null; ArrayList<PathNode> nodes = data.paths.root(); final int sl = steps.length; for(int s = 0; s < sl; s++) { final Step curr = axisStep(s); if(curr == null) return null; nodes = curr.nodes(nodes, data); if(nodes == null) return null; } return nodes; } /** * Checks if the specified axis steps can be evaluated iteratively. * @param root root expression (can be {@code null}) * @param steps path steps * @return result of check */ private static boolean iterative(final Expr root, final Expr... steps) { if(root == null || !root.ddo()) return false; final SeqType st = root.seqType(); boolean atMostOne = st.zeroOrOne(); boolean sameDepth = atMostOne || st.type.instanceOf(NodeType.DOC); for(final Expr expr : steps) { final Step step = (Step) expr; switch(step.axis) { case ANCESTOR: case ANCESTOR_OR_SELF: case PRECEDING: case PRECEDING_SIBLING: // backwards axes must be reordered return false; case FOLLOWING: // can overlap if(!atMostOne) return false; atMostOne = false; sameDepth = false; break; case FOLLOWING_SIBLING: // can overlap, preserves level if(!atMostOne) return false; atMostOne = false; break; case ATTRIBUTE: // only unique for exact QName matching atMostOne &= step.test instanceof NameTest && ((NameTest) step.test).part == NamePart.FULL; break; case CHILD: // order is only ensured if all nodes are on the same level if(!sameDepth) return false; atMostOne = false; break; case DESCENDANT: case DESCENDANT_OR_SELF: // non-overlapping if all nodes are on the same level if(!sameDepth) return false; atMostOne = false; sameDepth = false; break; case PARENT: // overlaps if(!atMostOne) return false; break; case SELF: // nothing changes break; default: throw Util.notExpected(); } } return true; } /** * Assigns a sequence type and (if statically known) result size. * @param rt compile time root (can be {@code null}) */ private void seqType(final Expr rt) { if(rt != null) data = rt.data(); final Type type = steps[steps.length - 1].seqType().type; Occ occ = Occ.ZERO_MORE; long size = size(rt); if(size == -1 && rt != null) { size = rt.size(); occ = rt.seqType().occ; for(final Expr step : steps) { final long sz = step.size(); size = size != -1 && sz != -1 ? size * sz : -1; occ = occ.union(step.seqType().occ); } // more than one result: final size is unknown due to DDO if(size > 1) size = -1; } exprType.assign(type, occ, size); } /** * Computes the result size via database statistics. * @param rt compile time root (can be {@code null}) * @return number of results (or {@code -1}) */ private long size(final Expr rt) { // check if path will yield any results if(root != null && root.size() == 0) return 0; for(final Expr step : steps) { if(step.size() == 0) return 0; } // skip computation if: // - path does not start with document nodes, // - no database instance is available, outdated, or // - if context does not contain all database nodes if(rt == null || !rt.seqType().type.instanceOf(NodeType.DOC) || data == null || !data.meta.uptodate || data.meta.ndocs != rt.size()) return -1; ArrayList<PathNode> nodes = data.paths.root(); long lastSize = 1; final int sl = steps.length; for(int s = 0; s < sl; s++) { final Step curr = axisStep(s); if(curr != null) { nodes = curr.nodes(nodes, data); if(nodes == null) return -1; } else if(s + 1 == sl) { lastSize = steps[s].size(); if(lastSize == -1) return -1; } else { // stop if a non-axis step is not placed last return -1; } } long size = 0; for(final PathNode pn : nodes) size += pn.stats.count; return size * lastSize; } /** * Returns all summary path nodes for the specified location step. * @param last last step to be checked * @return path nodes, or {@code null} if nodes cannot be retrieved */ private ArrayList<PathNode> pathNodes(final int last) { // skip request if no path index exists or might be out-of-date if(data == null || !data.meta.uptodate) return null; ArrayList<PathNode> nodes = data.paths.root(); for(int s = 0; s <= last; s++) { // only follow axis steps final Step curr = axisStep(s); if(curr == null) return null; final boolean desc = curr.axis == DESCENDANT; if(!desc && curr.axis != CHILD || !(curr.test instanceof NameTest)) return null; final NameTest test = (NameTest) curr.test; if(test.part != NamePart.LOCAL) return null; final int name = data.elemNames.id(test.qname.local()); final ArrayList<PathNode> tmp = new ArrayList<>(); for(final PathNode node : PathIndex.desc(nodes, desc)) { if(node.kind == Data.ELEM && name == node.name) { // skip test if an element name occurs on different levels if(!tmp.isEmpty() && tmp.get(0).level() != node.level()) return null; tmp.add(node); } } if(tmp.isEmpty()) return null; nodes = tmp; } return nodes; } /** * Returns an empty sequence if the path will yield no results. * @param cc compilation context * @param rt compile time root (can be {@code null}) * @return original or new expression */ private Expr removeEmpty(final CompileContext cc, final Expr rt) { final Check emptySteps = () -> { Expr prev = rt; for(final Expr step : steps) { if(step instanceof Step && prev != null) { final Type type = prev.seqType().type; if(type instanceof NodeType && ((Step) step).emptyStep((NodeType) type)) return true; } prev = step; } return false; }; final ArrayList<PathNode> nodes = pathNodes(rt); if(nodes != null ? nodes.isEmpty() : emptySteps.ok()) { cc.info(QueryText.OPTPATH_X, this); return Empty.VALUE; } return this; } /** * Converts descendant to child steps. * @param cc compilation context * @param rt compile time root (can be {@code null}) * @return original or new expression * @throws QueryException query exception */ private Expr children(final CompileContext cc, final Expr rt) throws QueryException { // skip optimization... // - if path does not start with document nodes // - if index does not exist or is out-dated // - if several namespaces occur in the input if(rt == null || !rt.seqType().type.instanceOf(NodeType.DOC) || data == null || !data.meta.uptodate || data.defaultNs() == null) return this; final int sl = steps.length; for(int s = 0; s < sl; s++) { // don't allow predicates in preceding location steps final Step prev = s > 0 ? axisStep(s - 1) : null; if(prev != null && prev.exprs.length != 0) break; // ignore axes other than descendant, or numeric predicates final Step curr = axisStep(s); if(curr == null || curr.axis != DESCENDANT || curr.positional()) continue; // check if child steps can be retrieved for current step ArrayList<PathNode> nodes = pathNodes(s); if(nodes == null) continue; // cache child steps final ArrayList<QNm> qNames = new ArrayList<>(); while(nodes.get(0).parent != null) { QNm qName = new QNm(data.elemNames.key(nodes.get(0).name)); // skip children with prefixes if(qName.hasPrefix()) return this; for(final PathNode node : nodes) { if(nodes.get(0).name != node.name) { qName = null; break; } } qNames.add(qName); nodes = PathIndex.parent(nodes); } cc.info(QueryText.OPTCHILD_X, steps[s]); // build new steps int ts = qNames.size(); final Expr[] stps = new Expr[ts + sl - s - 1]; for(int t = 0; t < ts; t++) { final Expr[] preds = t == ts - 1 ? ((Preds) steps[s]).exprs : new Expr[0]; final QNm qName = qNames.get(ts - t - 1); final Test test = qName == null ? KindTest.ELM : new NameTest(NodeType.ELM, qName, NamePart.LOCAL, null); stps[t] = new StepBuilder(curr.info).axis(CHILD).test(test).preds(preds).finish(cc, root); } while(++s < sl) stps[ts++] = steps[s]; return get(info, root, stps); } return this; } /** * Tries to rewrite the path to a simple map expression. * @param cc compilation context * @return original or new expression * @throws QueryException query exception */ private Expr toMap(final CompileContext cc) throws QueryException { // do not rewrite relative paths with single step final int sl = steps.length; if(root == null && sl == 1) return this; Expr s1 = sl > 1 ? steps[sl - 2] : root, s2 = steps[sl - 1]; final Type type1 = s1.seqType().type, type2 = s2.seqType().type; /* rewrite if: * - previous expression yields nodes (otherwise, an error must be raised at runtime) * - last expression is no step, and yields a single result or no node */ if(!type1.instanceOf(NodeType.NOD) || s2 instanceof Step || size() != 1 && !type2.instanceOf(AtomType.AAT) && !type2.instanceOf(SeqType.ANY_FUNC)) return this; /* remove last step from new root expression. examples: * - (<a/>, <b/>)/map { name(): . } -> (<a/>, <b/>) ! map { name(): . } * - <a/>/<b/> -> <a/> ! <b/> * - $a/b/string -> $a/b ! string() */ if(sl > 1) s1 = get(info, root, Arrays.copyOfRange(steps, 0, sl - 1)).optimize(cc); if(s1 != null) s2 = SimpleMap.get(info, s1, s2); return cc.replaceWith(this, s2); } /** * Returns an equivalent expression which accesses an index. * If the expression cannot be rewritten, the original expression is returned. * * The following types of queries can be rewritten (in the examples, the equality comparison * is used, which will be rewritten to {@link ValueAccess} instances): * * <pre> * 1. A[text() = '...'] : IA('...', A) * 2. A[. = '...'] : IA('...', A) * 3. text()[. = '...'] : IA('...') * 4. A[B = '...'] : IA('...', B)/parent::A * 5. A[B/text() = '...'] : IA('...')/parent::B/parent::A * 6. A[B/C = '...'] : IA('...', C)/parent::B/parent::A * 7. A[@a = '...'] : IA('...', @a)/parent::A * 8. @a[. = '...'] : IA('...', @a)</pre> * * Queries of type 1, 3, 5 will not yield any results if the string to be compared is empty. * * @param cc compilation context * @param rt compile time root (can be {@code null}) * @return original or new expression * @throws QueryException query exception */ private Expr index(final CompileContext cc, final Expr rt) throws QueryException { // skip optimization if path does not start with document nodes if(rt == null || !rt.seqType().type.instanceOf(NodeType.DOC)) return this; // cache index access costs IndexInfo index = null; // cheapest predicate and step int indexPred = 0, indexStep = 0; // check if path can be converted to an index access final int sl = steps.length; for(int s = 0; s < sl; s++) { // only accept descendant steps without positional predicates // Example for position predicate: child:x[1] != parent::x[1] final Step step = axisStep(s); if(step == null || !step.axis.down || step.positional()) break; final int el = step.exprs.length; if(el > 0) { // static vs dynamic access final IndexDb db = data != null ? new IndexStaticDb(data, info) : new IndexDynDb(root == null ? new ContextValue(info) : root, info); // choose cheapest index access for(int e = 0; e < el; e++) { final IndexInfo ii = new IndexInfo(db, cc, step); if(!step.exprs[e].indexAccessible(ii)) continue; if(ii.costs.results() == 0) { // no results... cc.info(QueryText.OPTNORESULTS_X, ii.step); return Empty.VALUE; } if(index == null || index.costs.compareTo(ii.costs) > 0) { index = ii; indexPred = e; indexStep = s; } } } } // skip rewriting if no index access is possible, or if it is too expensive if(index == null || data != null && index.costs.tooExpensive(data)) return this; // skip optimization if it is not enforced if(rt instanceof Dummy && !index.enforce()) return this; // rewrite for index access cc.info(index.optInfo); // create new root expression final ExprList resultSteps = new ExprList(); final Expr resultRoot; if(index.expr instanceof Path) { final Path path = (Path) index.expr; resultRoot = path.root; resultSteps.add(path.steps); } else { resultRoot = index.expr; } // only one hit: update sequence type if(index.costs.results() == 1 && resultRoot instanceof ParseExpr) { final Occ occ = resultRoot instanceof IndexAccess ? Occ.ONE : Occ.ZERO_ONE; ((ParseExpr) resultRoot).exprType.assign(occ); } // invert steps that occur before index step and add them as predicate final ExprList newPreds = new ExprList(); final Test rootTest = InvDocTest.get(rt); final ExprList invSteps = new ExprList(); if(rootTest != KindTest.DOC || data == null || !data.meta.uptodate || invertSteps(indexStep)) { for(int s = indexStep; s >= 0; s--) { final Axis invAxis = axisStep(s).axis.invert(); if(s == 0) { // add document test for collections and axes other than ancestors if(rootTest != KindTest.DOC || invAxis != ANCESTOR && invAxis != ANCESTOR_OR_SELF) { invSteps.add(new StepBuilder(info).axis(invAxis).test(rootTest).finish(cc, resultRoot)); } } else { final Step prevStep = axisStep(s - 1); final Axis newAxis = prevStep.axis == ATTRIBUTE ? ATTRIBUTE : invAxis; final Expr newStep = new StepBuilder(prevStep.info).axis(newAxis).test(prevStep.test). preds(prevStep.exprs).finish(cc, resultRoot); invSteps.add(newStep); } } } if(!invSteps.isEmpty()) newPreds.add(get(info, null, invSteps.finish())); // add remaining predicates final Expr[] preds = index.step.exprs; final int pl = preds.length; for(int p = 0; p < pl; p++) { if(p != indexPred) newPreds.add(preds[p]); } // add predicates to end of path if(!newPreds.isEmpty()) { int ls = resultSteps.size() - 1; final Expr step; if(ls < 0 || !(resultSteps.get(ls) instanceof Step)) { // add at least one self axis step step = new StepBuilder(info).preds(newPreds.finish()).finish(cc, resultRoot); ls++; } else { step = ((Step) resultSteps.get(ls)).addPreds(newPreds.finish()); } resultSteps.set(ls, step); } // add remaining steps for(int s = indexStep + 1; s < sl; s++) { resultSteps.add(steps[s]); } return resultSteps.isEmpty() ? resultRoot : get(info, resultRoot, resultSteps.finish()); } /** * Checks if steps before index step need to be inverted and traversed. * @param i index step * @return result of check */ private boolean invertSteps(final int i) { for(int s = i; s >= 0; s--) { final Step step = axisStep(s); // ensure that the index step does not use wildcard if(step.test instanceof KindTest && s != i) continue; // consider child steps with name test and without predicates if(step.axis != CHILD || s != i && step.exprs.length > 0 || !(step.test instanceof NameTest)) return true; // only consider local name tests final NameTest test = (NameTest) step.test; if(test.part != NamePart.LOCAL) return true; // only support unique paths with nodes on the correct level final ArrayList<PathNode> pn = data.paths.desc(test.qname.local()); if(pn.size() != 1 || pn.get(0).level() != s + 1) return true; } return false; } /** * Tries to rewrite lists to union expressions. * @param cc compilation context * @return original or new expression * @throws QueryException query exception */ private Expr toUnion(final CompileContext cc) throws QueryException { // function for rewriting a list to a union expression final QueryFunction<Expr, Expr> rewrite = step -> { if(step instanceof List) { return ((List) step).toUnion(cc); } if(step instanceof Filter) { final Filter filter = (Filter) step; if(!filter.positional() && filter.root instanceof List) { final Expr st = ((List) filter.root).toUnion(cc); if(st != filter.root) return Filter.get(filter.info, st, filter.exprs).optimize(cc); } } return step; }; // only rewrite root expression if subsequent step yields nodes boolean changed = false; if(steps[0].seqType().type instanceof NodeType) { final Expr rt = rewrite.apply(root); if(rt != root) { root = rt; changed = true; } } cc.pushFocus(root); try { final int sl = steps.length; for(int s = 0; s < sl; s++) { final Expr step = rewrite.apply(steps[s]); if(step != steps[s]) { steps[s] = step; changed = true; } cc.updateFocus(step); } } finally { cc.removeFocus(); } return changed ? get(info, root, steps) : this; } /** * Merges adjacent steps. * @param cc compilation context * @return original or new expression * @throws QueryException query exception */ private Expr mergeSteps(final CompileContext cc) throws QueryException { final int sl = steps.length; final ExprList stps = new ExprList(sl); cc.pushFocus(root); try { for(int s = 0; s < sl; s++) { Expr curr = steps[s]; final Expr next = s < sl - 1 ? mergeStep(curr, steps[s + 1], cc) : null; if(next != null) { cc.info(QueryText.OPTMERGE_X, next); curr = next; s++; } stps.add(curr); cc.updateFocus(curr); } } finally { cc.removeFocus(); } return stps.size() != steps.length ? get(info, root, stps.finish()) : this; } /** * Merges adjacent steps. * @param curr current step * @param next next step * @param cc compilation context * @return merged expression or {@code null} * @throws QueryException query exception */ private static Expr mergeStep(final Expr curr, final Expr next, final CompileContext cc) throws QueryException { if(!(curr instanceof Step)) return null; final Step crr = (Step) curr, nxt = next instanceof Step ? (Step) next : null; // merge self steps if(nxt != null && nxt.axis == SELF && !nxt.positional()) { final Test test = crr.test.intersect(nxt.test); if(test == null) return null; crr.test = test; return crr.addPreds(nxt.exprs); } if(crr.axis != DESCENDANT_OR_SELF || crr.test != KindTest.NOD || crr.exprs.length > 0) return null; // function for merging steps inside union expressions final QueryFunction<Expr, Expr> rewrite = expr -> { final Checks<Expr> startWithChild = ex -> { if(!(ex instanceof Path)) return false; final Path path = (Path) ex; return path.root == null && simpleChild(path.steps[0]); }; if(expr instanceof Union) { final Union union = (Union) expr; if(startWithChild.all(union.exprs)) { for(final Expr path : union.exprs) { ((Step) ((Path) path).steps[0]).axis = DESCENDANT; } return union.optimize(cc); } } return null; }; // example: //child::* -> descendant::* if(simpleChild(nxt)) { nxt.axis = DESCENDANT; return nxt; } // example: //(text()|*) -> (descendant::text() | descendant::*) if(next instanceof Union) { return rewrite.apply(next); } // example: //(text()|*)[..] -> (/descendant::text() | /descendant::*)[..] if(next instanceof Filter) { final Filter filter = (Filter) next; if(!filter.positional()) { final Expr expr = rewrite.apply(filter.root); if(expr != null) return Filter.get(filter.info, expr, filter.exprs).optimize(cc); } } return null; } /** * Checks if the expressions is a simple child step. * @param expr expression to be checked * @return result of check */ private static boolean simpleChild(final Expr expr) { if(expr instanceof Step) { final Step step = (Step) expr; return step.axis == CHILD && !step.positional(); } return false; } @Override public final boolean inlineable(final Var var) { for(final Expr step : steps) { if(step.uses(var)) return false; } return root == null || root.inlineable(var); } @Override public final VarUsage count(final Var var) { final VarUsage inRoot = root == null ? VarUsage.NEVER : root.count(var); return VarUsage.sum(var, steps) == VarUsage.NEVER ? inRoot : VarUsage.MORE_THAN_ONCE; } @Override public final Expr inline(final Var var, final Expr ex, final CompileContext cc) throws QueryException { boolean changed = false; if(root == null) { if(var == null) { root = ex; changed = true; } } else { final Expr rt = root.inline(var, ex, cc); if(rt != null) { root = rt; changed = true; } } // #1202: during inlining, expressions will be optimized, which are based on the context value if(var != null) { cc.pushFocus(root != null ? root : cc.qc.focus.value); try { final int sl = steps.length; for(int s = 0; s < sl; s++) { final Expr step = steps[s].inline(var, ex, cc); if(step != null) { steps[s] = step; changed = true; } cc.updateFocus(steps[s]); } } finally { cc.removeFocus(); } } return changed ? optimize(cc) : null; } @Override public final boolean accept(final ASTVisitor visitor) { if(root == null) { visitor.lock(Locking.CONTEXT, false); } else if(!root.accept(visitor)) { return false; } visitor.enterFocus(); if(!visitAll(visitor, steps)) return false; visitor.exitFocus(); return true; } @Override public final int exprSize() { int size = 1; for(final Expr step : steps) size += step.exprSize(); return root == null ? size : size + root.exprSize(); } @Override public final Data data() { return data; } @Override public final boolean equals(final Object obj) { if(!(obj instanceof Path)) return false; final Path path = (Path) obj; return Objects.equals(root, path.root) && Array.equals(steps, path.steps); } @Override public final void plan(final QueryPlan plan) { plan.add(plan.create(this), root, steps); } @Override public final String toString() { final StringBuilder sb = new StringBuilder(); if(root != null) sb.append(root); for(final Expr step : steps) { if(sb.length() != 0) sb.append('/'); sb.append(step); } return sb.toString(); } }
/* * 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.schemaorg.core; import com.google.schemaorg.JsonLdContext; import com.google.schemaorg.SchemaOrgType; import com.google.schemaorg.core.datatype.DateTime; import com.google.schemaorg.core.datatype.Text; import com.google.schemaorg.core.datatype.URL; import com.google.schemaorg.goog.PopularityScoreSpecification; import javax.annotation.Nullable; /** Interface of <a href="http://schema.org/CancelAction}">http://schema.org/CancelAction}</a>. */ public interface CancelAction extends PlanAction { /** * Builder interface of <a * href="http://schema.org/CancelAction}">http://schema.org/CancelAction}</a>. */ public interface Builder extends PlanAction.Builder { @Override Builder addJsonLdContext(@Nullable JsonLdContext context); @Override Builder addJsonLdContext(@Nullable JsonLdContext.Builder context); @Override Builder setJsonLdId(@Nullable String value); @Override Builder setJsonLdReverse(String property, Thing obj); @Override Builder setJsonLdReverse(String property, Thing.Builder builder); /** Add a value to property actionStatus. */ Builder addActionStatus(ActionStatusType value); /** Add a value to property actionStatus. */ Builder addActionStatus(String value); /** Add a value to property additionalType. */ Builder addAdditionalType(URL value); /** Add a value to property additionalType. */ Builder addAdditionalType(String value); /** Add a value to property agent. */ Builder addAgent(Organization value); /** Add a value to property agent. */ Builder addAgent(Organization.Builder value); /** Add a value to property agent. */ Builder addAgent(Person value); /** Add a value to property agent. */ Builder addAgent(Person.Builder value); /** Add a value to property agent. */ Builder addAgent(String value); /** Add a value to property alternateName. */ Builder addAlternateName(Text value); /** Add a value to property alternateName. */ Builder addAlternateName(String value); /** Add a value to property description. */ Builder addDescription(Text value); /** Add a value to property description. */ Builder addDescription(String value); /** Add a value to property endTime. */ Builder addEndTime(DateTime value); /** Add a value to property endTime. */ Builder addEndTime(String value); /** Add a value to property error. */ Builder addError(Thing value); /** Add a value to property error. */ Builder addError(Thing.Builder value); /** Add a value to property error. */ Builder addError(String value); /** Add a value to property image. */ Builder addImage(ImageObject value); /** Add a value to property image. */ Builder addImage(ImageObject.Builder value); /** Add a value to property image. */ Builder addImage(URL value); /** Add a value to property image. */ Builder addImage(String value); /** Add a value to property instrument. */ Builder addInstrument(Thing value); /** Add a value to property instrument. */ Builder addInstrument(Thing.Builder value); /** Add a value to property instrument. */ Builder addInstrument(String value); /** Add a value to property location. */ Builder addLocation(Place value); /** Add a value to property location. */ Builder addLocation(Place.Builder value); /** Add a value to property location. */ Builder addLocation(PostalAddress value); /** Add a value to property location. */ Builder addLocation(PostalAddress.Builder value); /** Add a value to property location. */ Builder addLocation(Text value); /** Add a value to property location. */ Builder addLocation(String value); /** Add a value to property mainEntityOfPage. */ Builder addMainEntityOfPage(CreativeWork value); /** Add a value to property mainEntityOfPage. */ Builder addMainEntityOfPage(CreativeWork.Builder value); /** Add a value to property mainEntityOfPage. */ Builder addMainEntityOfPage(URL value); /** Add a value to property mainEntityOfPage. */ Builder addMainEntityOfPage(String value); /** Add a value to property name. */ Builder addName(Text value); /** Add a value to property name. */ Builder addName(String value); /** Add a value to property object. */ Builder addObject(Thing value); /** Add a value to property object. */ Builder addObject(Thing.Builder value); /** Add a value to property object. */ Builder addObject(String value); /** Add a value to property participant. */ Builder addParticipant(Organization value); /** Add a value to property participant. */ Builder addParticipant(Organization.Builder value); /** Add a value to property participant. */ Builder addParticipant(Person value); /** Add a value to property participant. */ Builder addParticipant(Person.Builder value); /** Add a value to property participant. */ Builder addParticipant(String value); /** Add a value to property potentialAction. */ Builder addPotentialAction(Action value); /** Add a value to property potentialAction. */ Builder addPotentialAction(Action.Builder value); /** Add a value to property potentialAction. */ Builder addPotentialAction(String value); /** Add a value to property result. */ Builder addResult(Thing value); /** Add a value to property result. */ Builder addResult(Thing.Builder value); /** Add a value to property result. */ Builder addResult(String value); /** Add a value to property sameAs. */ Builder addSameAs(URL value); /** Add a value to property sameAs. */ Builder addSameAs(String value); /** Add a value to property scheduledTime. */ Builder addScheduledTime(DateTime value); /** Add a value to property scheduledTime. */ Builder addScheduledTime(String value); /** Add a value to property startTime. */ Builder addStartTime(DateTime value); /** Add a value to property startTime. */ Builder addStartTime(String value); /** Add a value to property target. */ Builder addTarget(EntryPoint value); /** Add a value to property target. */ Builder addTarget(EntryPoint.Builder value); /** Add a value to property target. */ Builder addTarget(String value); /** Add a value to property url. */ Builder addUrl(URL value); /** Add a value to property url. */ Builder addUrl(String value); /** Add a value to property detailedDescription. */ Builder addDetailedDescription(Article value); /** Add a value to property detailedDescription. */ Builder addDetailedDescription(Article.Builder value); /** Add a value to property detailedDescription. */ Builder addDetailedDescription(String value); /** Add a value to property popularityScore. */ Builder addPopularityScore(PopularityScoreSpecification value); /** Add a value to property popularityScore. */ Builder addPopularityScore(PopularityScoreSpecification.Builder value); /** Add a value to property popularityScore. */ Builder addPopularityScore(String value); /** * Add a value to property. * * @param name The property name. * @param value The value of the property. */ Builder addProperty(String name, SchemaOrgType value); /** * Add a value to property. * * @param name The property name. * @param builder The schema.org object builder for the property value. */ Builder addProperty(String name, Thing.Builder builder); /** * Add a value to property. * * @param name The property name. * @param value The string value of the property. */ Builder addProperty(String name, String value); /** Build a {@link CancelAction} object. */ CancelAction build(); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.execution; import com.google.common.base.Ticker; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.airlift.testing.TestingTicker; import io.airlift.units.Duration; import io.prestosql.Session; import io.prestosql.client.FailureInfo; import io.prestosql.connector.CatalogName; import io.prestosql.execution.warnings.WarningCollector; import io.prestosql.memory.VersionedMemoryPoolId; import io.prestosql.metadata.Metadata; import io.prestosql.metadata.MetadataManager; import io.prestosql.security.AccessControl; import io.prestosql.security.AccessControlManager; import io.prestosql.spi.PrestoException; import io.prestosql.spi.memory.MemoryPoolId; import io.prestosql.spi.resourcegroups.ResourceGroupId; import io.prestosql.spi.type.Type; import io.prestosql.transaction.TransactionManager; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; import java.io.IOException; import java.net.URI; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.function.Consumer; import static io.airlift.concurrent.MoreFutures.tryGetFutureValue; import static io.prestosql.SessionTestUtils.TEST_SESSION; import static io.prestosql.execution.QueryState.FAILED; import static io.prestosql.execution.QueryState.FINISHED; import static io.prestosql.execution.QueryState.FINISHING; import static io.prestosql.execution.QueryState.PLANNING; import static io.prestosql.execution.QueryState.QUEUED; import static io.prestosql.execution.QueryState.RUNNING; import static io.prestosql.execution.QueryState.STARTING; import static io.prestosql.execution.QueryState.WAITING_FOR_RESOURCES; import static io.prestosql.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR; import static io.prestosql.spi.StandardErrorCode.USER_CANCELED; import static io.prestosql.spi.type.BigintType.BIGINT; import static io.prestosql.transaction.InMemoryTransactionManager.createTestTransactionManager; import static java.util.concurrent.Executors.newCachedThreadPool; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertSame; import static org.testng.Assert.assertTrue; public class TestQueryStateMachine { private static final String QUERY = "sql"; private static final URI LOCATION = URI.create("fake://fake-query"); private static final SQLException FAILED_CAUSE = new SQLException("FAILED"); private static final List<Input> INPUTS = ImmutableList.of(new Input(new CatalogName("connector"), "schema", "table", Optional.empty(), ImmutableList.of(new Column("a", "varchar")))); private static final Optional<Output> OUTPUT = Optional.empty(); private static final List<String> OUTPUT_FIELD_NAMES = ImmutableList.of("a", "b", "c"); private static final List<Type> OUTPUT_FIELD_TYPES = ImmutableList.of(BIGINT, BIGINT, BIGINT); private static final String UPDATE_TYPE = "update type"; private static final VersionedMemoryPoolId MEMORY_POOL = new VersionedMemoryPoolId(new MemoryPoolId("pool"), 42); private static final Map<String, String> SET_SESSION_PROPERTIES = ImmutableMap.<String, String>builder() .put("fruit", "apple") .put("drink", "coffee") .build(); private static final List<String> RESET_SESSION_PROPERTIES = ImmutableList.of("candy"); private final ExecutorService executor = newCachedThreadPool(); @AfterClass(alwaysRun = true) public void tearDown() { executor.shutdownNow(); } @Test public void testBasicStateChanges() { QueryStateMachine stateMachine = createQueryStateMachine(); assertState(stateMachine, QUEUED); assertTrue(stateMachine.transitionToPlanning()); assertState(stateMachine, PLANNING); assertTrue(stateMachine.transitionToStarting()); assertState(stateMachine, STARTING); assertTrue(stateMachine.transitionToRunning()); assertState(stateMachine, RUNNING); assertTrue(stateMachine.transitionToFinishing()); tryGetFutureValue(stateMachine.getStateChange(FINISHING), 2, SECONDS); assertState(stateMachine, FINISHED); } @Test public void testStateChangesWithResourceWaiting() { QueryStateMachine stateMachine = createQueryStateMachine(); assertState(stateMachine, QUEUED); assertTrue(stateMachine.transitionToWaitingForResources()); assertState(stateMachine, WAITING_FOR_RESOURCES); assertTrue(stateMachine.transitionToPlanning()); assertState(stateMachine, PLANNING); assertTrue(stateMachine.transitionToStarting()); assertState(stateMachine, STARTING); assertTrue(stateMachine.transitionToRunning()); assertState(stateMachine, RUNNING); assertTrue(stateMachine.transitionToFinishing()); tryGetFutureValue(stateMachine.getStateChange(FINISHING), 2, SECONDS); assertState(stateMachine, FINISHED); } @Test public void testQueued() { // all time before the first state transition is accounted to queueing assertAllTimeSpentInQueueing(QUEUED, queryStateMachine -> {}); assertAllTimeSpentInQueueing(WAITING_FOR_RESOURCES, QueryStateMachine::transitionToWaitingForResources); assertAllTimeSpentInQueueing(PLANNING, QueryStateMachine::transitionToPlanning); assertAllTimeSpentInQueueing(STARTING, QueryStateMachine::transitionToStarting); assertAllTimeSpentInQueueing(RUNNING, QueryStateMachine::transitionToRunning); assertAllTimeSpentInQueueing(FINISHED, stateMachine -> { stateMachine.transitionToFinishing(); tryGetFutureValue(stateMachine.getStateChange(FINISHING), 2, SECONDS); }); assertAllTimeSpentInQueueing(FAILED, stateMachine -> stateMachine.transitionToFailed(FAILED_CAUSE)); } private void assertAllTimeSpentInQueueing(QueryState expectedState, Consumer<QueryStateMachine> stateTransition) { TestingTicker ticker = new TestingTicker(); QueryStateMachine stateMachine = createQueryStateMachineWithTicker(ticker); ticker.increment(7, MILLISECONDS); stateTransition.accept(stateMachine); assertEquals(stateMachine.getQueryState(), expectedState); QueryStats queryStats = stateMachine.getQueryInfo(Optional.empty()).getQueryStats(); assertEquals(queryStats.getQueuedTime(), new Duration(7, MILLISECONDS)); assertEquals(queryStats.getResourceWaitingTime(), new Duration(0, MILLISECONDS)); assertEquals(queryStats.getTotalPlanningTime(), new Duration(0, MILLISECONDS)); assertEquals(queryStats.getExecutionTime(), new Duration(0, MILLISECONDS)); assertEquals(queryStats.getFinishingTime(), new Duration(0, MILLISECONDS)); } @Test public void testPlanning() { QueryStateMachine stateMachine = createQueryStateMachine(); assertTrue(stateMachine.transitionToPlanning()); assertState(stateMachine, PLANNING); assertFalse(stateMachine.transitionToPlanning()); assertState(stateMachine, PLANNING); assertTrue(stateMachine.transitionToStarting()); assertState(stateMachine, STARTING); stateMachine = createQueryStateMachine(); stateMachine.transitionToPlanning(); assertTrue(stateMachine.transitionToRunning()); assertState(stateMachine, RUNNING); stateMachine = createQueryStateMachine(); stateMachine.transitionToPlanning(); assertTrue(stateMachine.transitionToFinishing()); tryGetFutureValue(stateMachine.getStateChange(FINISHING), 2, SECONDS); assertState(stateMachine, FINISHED); stateMachine = createQueryStateMachine(); stateMachine.transitionToPlanning(); assertTrue(stateMachine.transitionToFailed(FAILED_CAUSE)); assertState(stateMachine, FAILED, FAILED_CAUSE); } @Test public void testStarting() { QueryStateMachine stateMachine = createQueryStateMachine(); assertTrue(stateMachine.transitionToStarting()); assertState(stateMachine, STARTING); assertFalse(stateMachine.transitionToPlanning()); assertState(stateMachine, STARTING); assertFalse(stateMachine.transitionToStarting()); assertState(stateMachine, STARTING); assertTrue(stateMachine.transitionToRunning()); assertState(stateMachine, RUNNING); stateMachine = createQueryStateMachine(); stateMachine.transitionToStarting(); assertTrue(stateMachine.transitionToFinishing()); tryGetFutureValue(stateMachine.getStateChange(FINISHING), 2, SECONDS); assertState(stateMachine, FINISHED); stateMachine = createQueryStateMachine(); stateMachine.transitionToStarting(); assertTrue(stateMachine.transitionToFailed(FAILED_CAUSE)); assertState(stateMachine, FAILED, FAILED_CAUSE); } @Test public void testRunning() { QueryStateMachine stateMachine = createQueryStateMachine(); assertTrue(stateMachine.transitionToRunning()); assertState(stateMachine, RUNNING); assertFalse(stateMachine.transitionToPlanning()); assertState(stateMachine, RUNNING); assertFalse(stateMachine.transitionToStarting()); assertState(stateMachine, RUNNING); assertFalse(stateMachine.transitionToRunning()); assertState(stateMachine, RUNNING); assertTrue(stateMachine.transitionToFinishing()); tryGetFutureValue(stateMachine.getStateChange(FINISHING), 2, SECONDS); assertState(stateMachine, FINISHED); stateMachine = createQueryStateMachine(); stateMachine.transitionToRunning(); assertTrue(stateMachine.transitionToFailed(FAILED_CAUSE)); assertState(stateMachine, FAILED, FAILED_CAUSE); } @Test public void testFinished() { QueryStateMachine stateMachine = createQueryStateMachine(); assertTrue(stateMachine.transitionToFinishing()); tryGetFutureValue(stateMachine.getStateChange(FINISHING), 2, SECONDS); assertFinalState(stateMachine, FINISHED); } @Test public void testFailed() { QueryStateMachine stateMachine = createQueryStateMachine(); assertTrue(stateMachine.transitionToFailed(FAILED_CAUSE)); assertFinalState(stateMachine, FAILED, FAILED_CAUSE); } @Test public void testCanceled() { QueryStateMachine stateMachine = createQueryStateMachine(); assertTrue(stateMachine.transitionToCanceled()); assertFinalState(stateMachine, FAILED, new PrestoException(USER_CANCELED, "canceled")); } @Test public void testPlanningTimeDuration() { TestingTicker mockTicker = new TestingTicker(); QueryStateMachine stateMachine = createQueryStateMachineWithTicker(mockTicker); assertState(stateMachine, QUEUED); mockTicker.increment(50, MILLISECONDS); assertTrue(stateMachine.transitionToWaitingForResources()); assertState(stateMachine, WAITING_FOR_RESOURCES); mockTicker.increment(100, MILLISECONDS); assertTrue(stateMachine.transitionToPlanning()); assertState(stateMachine, PLANNING); mockTicker.increment(200, MILLISECONDS); assertTrue(stateMachine.transitionToStarting()); assertState(stateMachine, STARTING); mockTicker.increment(300, MILLISECONDS); assertTrue(stateMachine.transitionToRunning()); assertState(stateMachine, RUNNING); mockTicker.increment(400, MILLISECONDS); assertTrue(stateMachine.transitionToFinishing()); tryGetFutureValue(stateMachine.getStateChange(FINISHING), 2, SECONDS); assertState(stateMachine, FINISHED); QueryStats queryStats = stateMachine.getQueryInfo(Optional.empty()).getQueryStats(); assertEquals(queryStats.getElapsedTime().toMillis(), 1050); assertEquals(queryStats.getQueuedTime().toMillis(), 50); assertEquals(queryStats.getResourceWaitingTime().toMillis(), 100); assertEquals(queryStats.getTotalPlanningTime().toMillis(), 200); // there is no way to induce finishing time without a transaction and connector assertEquals(queryStats.getFinishingTime().toMillis(), 0); // query execution time is starts when query transitions to planning assertEquals(queryStats.getExecutionTime().toMillis(), 900); } @Test public void testUpdateMemoryUsage() { QueryStateMachine stateMachine = createQueryStateMachine(); stateMachine.updateMemoryUsage(5, 15, 10, 1, 5, 3); assertEquals(stateMachine.getPeakUserMemoryInBytes(), 5); assertEquals(stateMachine.getPeakTotalMemoryInBytes(), 10); assertEquals(stateMachine.getPeakRevocableMemoryInBytes(), 15); assertEquals(stateMachine.getPeakTaskUserMemory(), 1); assertEquals(stateMachine.getPeakTaskTotalMemory(), 3); assertEquals(stateMachine.getPeakTaskRevocableMemory(), 5); stateMachine.updateMemoryUsage(0, 0, 0, 2, 2, 2); assertEquals(stateMachine.getPeakUserMemoryInBytes(), 5); assertEquals(stateMachine.getPeakTotalMemoryInBytes(), 10); assertEquals(stateMachine.getPeakRevocableMemoryInBytes(), 15); assertEquals(stateMachine.getPeakTaskUserMemory(), 2); assertEquals(stateMachine.getPeakTaskTotalMemory(), 3); assertEquals(stateMachine.getPeakTaskRevocableMemory(), 5); stateMachine.updateMemoryUsage(1, 1, 1, 1, 10, 5); assertEquals(stateMachine.getPeakUserMemoryInBytes(), 6); assertEquals(stateMachine.getPeakTotalMemoryInBytes(), 11); assertEquals(stateMachine.getPeakRevocableMemoryInBytes(), 16); assertEquals(stateMachine.getPeakTaskUserMemory(), 2); assertEquals(stateMachine.getPeakTaskTotalMemory(), 5); assertEquals(stateMachine.getPeakTaskRevocableMemory(), 10); stateMachine.updateMemoryUsage(3, 3, 3, 5, 1, 2); assertEquals(stateMachine.getPeakUserMemoryInBytes(), 9); assertEquals(stateMachine.getPeakTotalMemoryInBytes(), 14); assertEquals(stateMachine.getPeakRevocableMemoryInBytes(), 19); assertEquals(stateMachine.getPeakTaskUserMemory(), 5); assertEquals(stateMachine.getPeakTaskTotalMemory(), 5); assertEquals(stateMachine.getPeakTaskRevocableMemory(), 10); } private static void assertFinalState(QueryStateMachine stateMachine, QueryState expectedState) { assertFinalState(stateMachine, expectedState, null); } private static void assertFinalState(QueryStateMachine stateMachine, QueryState expectedState, Exception expectedException) { assertTrue(expectedState.isDone()); assertState(stateMachine, expectedState, expectedException); assertFalse(stateMachine.transitionToPlanning()); assertState(stateMachine, expectedState, expectedException); assertFalse(stateMachine.transitionToStarting()); assertState(stateMachine, expectedState, expectedException); assertFalse(stateMachine.transitionToRunning()); assertState(stateMachine, expectedState, expectedException); assertFalse(stateMachine.transitionToFinishing()); assertState(stateMachine, expectedState, expectedException); assertFalse(stateMachine.transitionToFailed(FAILED_CAUSE)); assertState(stateMachine, expectedState, expectedException); // attempt to fail with another exception, which will fail assertFalse(stateMachine.transitionToFailed(new IOException("failure after finish"))); assertState(stateMachine, expectedState, expectedException); } private static void assertState(QueryStateMachine stateMachine, QueryState expectedState) { assertState(stateMachine, expectedState, null); } private static void assertState(QueryStateMachine stateMachine, QueryState expectedState, Exception expectedException) { assertEquals(stateMachine.getQueryId(), TEST_SESSION.getQueryId()); assertEqualSessionsWithoutTransactionId(stateMachine.getSession(), TEST_SESSION); assertSame(stateMachine.getMemoryPool(), MEMORY_POOL); assertEquals(stateMachine.getSetSessionProperties(), SET_SESSION_PROPERTIES); assertEquals(stateMachine.getResetSessionProperties(), RESET_SESSION_PROPERTIES); QueryInfo queryInfo = stateMachine.getQueryInfo(Optional.empty()); assertEquals(queryInfo.getQueryId(), TEST_SESSION.getQueryId()); assertEquals(queryInfo.getSelf(), LOCATION); assertFalse(queryInfo.getOutputStage().isPresent()); assertEquals(queryInfo.getQuery(), QUERY); assertEquals(queryInfo.getInputs(), INPUTS); assertEquals(queryInfo.getOutput(), OUTPUT); assertEquals(queryInfo.getFieldNames(), OUTPUT_FIELD_NAMES); assertEquals(queryInfo.getUpdateType(), UPDATE_TYPE); assertEquals(queryInfo.getMemoryPool(), MEMORY_POOL.getId()); QueryStats queryStats = queryInfo.getQueryStats(); assertNotNull(queryStats.getElapsedTime()); assertNotNull(queryStats.getQueuedTime()); assertNotNull(queryStats.getResourceWaitingTime()); assertNotNull(queryStats.getExecutionTime()); assertNotNull(queryStats.getTotalPlanningTime()); assertNotNull(queryStats.getFinishingTime()); assertNotNull(queryStats.getCreateTime()); if (queryInfo.getState() == QUEUED || queryInfo.getState() == WAITING_FOR_RESOURCES) { assertNull(queryStats.getExecutionStartTime()); } else { assertNotNull(queryStats.getExecutionStartTime()); } if (queryInfo.getState().isDone()) { assertNotNull(queryStats.getEndTime()); } else { assertNull(queryStats.getEndTime()); } assertEquals(stateMachine.getQueryState(), expectedState); assertEquals(queryInfo.getState(), expectedState); assertEquals(stateMachine.isDone(), expectedState.isDone()); if (expectedState == FAILED) { assertNotNull(queryInfo.getFailureInfo()); FailureInfo failure = queryInfo.getFailureInfo().toFailureInfo(); assertNotNull(failure); assertEquals(failure.getType(), expectedException.getClass().getName()); if (expectedException instanceof PrestoException) { assertEquals(queryInfo.getErrorCode(), ((PrestoException) expectedException).getErrorCode()); } else { assertEquals(queryInfo.getErrorCode(), GENERIC_INTERNAL_ERROR.toErrorCode()); } } else { assertNull(queryInfo.getFailureInfo()); } } private QueryStateMachine createQueryStateMachine() { return createQueryStateMachineWithTicker(Ticker.systemTicker()); } private QueryStateMachine createQueryStateMachineWithTicker(Ticker ticker) { Metadata metadata = MetadataManager.createTestMetadataManager(); TransactionManager transactionManager = createTestTransactionManager(); AccessControl accessControl = new AccessControlManager(transactionManager); QueryStateMachine stateMachine = QueryStateMachine.beginWithTicker( QUERY, TEST_SESSION, LOCATION, new ResourceGroupId("test"), false, transactionManager, accessControl, executor, ticker, metadata, WarningCollector.NOOP); stateMachine.setInputs(INPUTS); stateMachine.setOutput(OUTPUT); stateMachine.setColumns(OUTPUT_FIELD_NAMES, OUTPUT_FIELD_TYPES); stateMachine.setUpdateType(UPDATE_TYPE); stateMachine.setMemoryPool(MEMORY_POOL); for (Entry<String, String> entry : SET_SESSION_PROPERTIES.entrySet()) { stateMachine.addSetSessionProperties(entry.getKey(), entry.getValue()); } RESET_SESSION_PROPERTIES.forEach(stateMachine::addResetSessionProperties); return stateMachine; } private static void assertEqualSessionsWithoutTransactionId(Session actual, Session expected) { assertEquals(actual.getQueryId(), expected.getQueryId()); assertEquals(actual.getIdentity(), expected.getIdentity()); assertEquals(actual.getSource(), expected.getSource()); assertEquals(actual.getCatalog(), expected.getCatalog()); assertEquals(actual.getSchema(), expected.getSchema()); assertEquals(actual.getTimeZoneKey(), expected.getTimeZoneKey()); assertEquals(actual.getLocale(), expected.getLocale()); assertEquals(actual.getRemoteUserAddress(), expected.getRemoteUserAddress()); assertEquals(actual.getUserAgent(), expected.getUserAgent()); assertEquals(actual.getStartTime(), expected.getStartTime()); assertEquals(actual.getSystemProperties(), expected.getSystemProperties()); assertEquals(actual.getConnectorProperties(), expected.getConnectorProperties()); } }
/* * Copyright (C) 2017-2019 Dremio Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dremio.service.scheduler; import java.time.DayOfWeek; import java.time.Duration; import java.time.Instant; import java.time.LocalTime; import java.time.Period; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; import java.time.temporal.Temporal; import java.time.temporal.TemporalAdjuster; import java.time.temporal.TemporalAdjusters; import java.time.temporal.TemporalAmount; import java.util.Iterator; import java.util.concurrent.TimeUnit; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; /** * A recurring task schedule. * * A schedule is comprised of a starting point and a set of periods * and is used to generate a sequence of instants where a task should be * run. */ public interface Schedule extends Iterable<Instant> { /** * Builder to create {@code Schedule} instances */ final class Builder { private final Instant start; private final TemporalAmount amount; private final TemporalAdjuster adjuster; private final ZoneId zoneId; private final String taskName; private final Long scheduledOwnershipRelease; private final CleanupListener cleanupListener; private Builder(TemporalAmount amount) { this(Instant.now(), amount, NO_ADJUSTMENT, ZoneOffset.UTC); } private Builder(TemporalAmount amount, TemporalAdjuster adjuster) { this(Instant.now(), amount, adjuster, ZoneOffset.UTC); } private Builder(Instant start, TemporalAmount amount, TemporalAdjuster adjuster, ZoneId zoneId) { this(start, amount, adjuster, zoneId, null, null); } private Builder(Instant start, TemporalAmount amount, TemporalAdjuster adjuster, ZoneId zoneId, String taskName, Long scheduledOwnershipRelease) { this(start, amount, adjuster, zoneId, taskName, scheduledOwnershipRelease, () -> { /*do nothing */ }); } private Builder(Instant start, TemporalAmount amount, TemporalAdjuster adjuster, ZoneId zoneId, String taskName, Long scheduledOwnershipRelease, CleanupListener cleanupListener) { this.start = start; this.amount = amount; this.adjuster = adjuster; this.zoneId = zoneId; this.taskName = taskName; this.scheduledOwnershipRelease = scheduledOwnershipRelease; this.cleanupListener = cleanupListener; } private Builder withAdjuster(TemporalAdjuster adjuster) { return new Builder(this.start, this.amount, adjuster, zoneId, this.taskName, this.scheduledOwnershipRelease, this.cleanupListener); } public Builder withTimeZone(ZoneId zoneId) { return new Builder(this.start, this.amount, this.adjuster, zoneId, this.taskName, this.scheduledOwnershipRelease, this.cleanupListener); } public Builder startingAt(Instant start) { return new Builder(start, this.amount, this.adjuster, zoneId, this.taskName, this.scheduledOwnershipRelease, this.cleanupListener); } public final Schedule build() { return new BaseSchedule( start, amount, adjuster, zoneId, taskName, scheduledOwnershipRelease, cleanupListener); } public Builder asClusteredSingleton(String taskName) { return new Builder( start, amount, adjuster, zoneId, taskName, scheduledOwnershipRelease); } public Builder withCleanup(CleanupListener cleanupListener) { return new Builder( start, amount, adjuster, zoneId, taskName, scheduledOwnershipRelease, cleanupListener); } public Builder releaseOwnershipAfter(long number, TimeUnit timeUnit) { return new Builder( start, amount, adjuster, zoneId, taskName, timeUnit.toMillis(number)); } /** * Create a schedule builder where events are triggered every {@code seconds} * * @param millis the number of milliseconds between events * @return a schedule builder generating events every {@code seconds} * @throws IllegalArgumentException if {@code minutes} is negative */ public static Builder everyMillis(long millis) { return new Builder(Duration.ofMillis(millis)); } /** * Create a schedule builder where events are triggered every {@code seconds} * * @param seconds the number of seconds between events * @return a schedule builder generating events every {@code seconds} * @throws IllegalArgumentException if {@code minutes} is negative */ public static Builder everySeconds(long seconds) { return new Builder(Duration.ofSeconds(seconds)); } /** * Create a schedule builder where events are triggered every {@code minutes} * * @param minutes the number of minutes between events * @return a schedule builder generating events every {@code minutes} * @throws IllegalArgumentException if {@code minutes} is negative */ public static Builder everyMinutes(long minutes) { return new Builder(Duration.ofMinutes(minutes)); } /** * Create a schedule builder where events are triggered every {@code hours} * * @param hours the number of hours between events * @return a schedule builder generating events every {@code hours} * @throws IllegalArgumentException if {@code hours} is negative */ public static Builder everyHours(int hours) { return new Builder(Duration.ofHours(checkInterval(hours))); } /** * Create a schedule builder where events are triggered every {@code days} * * @param days the number of days between events * @return a schedule builder generating events every {@code days} * @throws IllegalArgumentException if {@code days} is negative */ public static Builder everyDays(int days) { return new Builder(Period.ofDays(checkInterval(days))); } /** * Create a schedule builder where events are triggered every {@code days}, at a specific time * * @param days the number of days between events * @param at the specific time to generate the events at * @return a schedule builder generating events every {@code days} * @throws IllegalArgumentException if {@code days} is negative * @throws NullPointerException if {@code at} is null */ public static Builder everyDays(int days, LocalTime at) { Preconditions.checkNotNull(at); return everyDays(days).withAdjuster(sameOrNext(Period.ofDays(1), at)); } /** * Create a schedule builder where events are triggered every {@code weeks} * * @param weeks the number of weeks between events * @return a schedule builder generating events every {@code weeks} * @throws IllegalArgumentException if {@code weeks} is negative */ public static Builder everyWeeks(int weeks) { return new Builder(Period.ofWeeks(checkInterval(weeks))); } /** * Create a schedule build where events are triggered every {@code weeks}, at a specific day of week and time * * @param weeks the number of weeks between events * @param dayOfWeek the day of week when to generate events for * @param at the specific time to generate the events at * @return a schedule builder generating events every {@code weeks} * @throws IllegalArgumentException if {@code weeks} is negative * @throws NullPointerException if {@code dayOfWeek} or {@code at} is null */ public static Builder everyWeeks(int weeks, DayOfWeek dayOfWeek, LocalTime at) { Preconditions.checkNotNull(dayOfWeek); Preconditions.checkNotNull(at); return everyWeeks(weeks).withAdjuster(sameOrNext(Period.ofWeeks(1), combine(dayOfWeek, at))); } /** * Create a schedule builder where events are triggered every {@code months} * * @param months the number of months between events * @return a schedule builder generating events every {@code months} * @throws IllegalArgumentException if {@code months} is negative */ public static Builder everyMonths(int months) { return new Builder(Period.ofMonths(checkInterval(months))); } /** * Create a schedule builder where events are triggered every {@code months}, on a given day of the month and time * * The specific day of the month is expressed as a day of the week and a week number, which * is useful to represent schedule like every 2nd tuesday of the month. * * @param months the number of months between events * @param weekOfMonth the ordinal week of the month (1st week is 1) * @param dayOfWeek the day of week when to generate events for * @param at the specific time to generate the events at * @return a schedule builder generating events every {@code months} * @throws IllegalArgumentException if {@code months} is negative, or if {@code weekOfMonth} is invalid. * @throws NullPointerException if {@code dayOfWeek} or {@code at} is null */ public static Builder everyMonths(int months, int weekOfMonth, DayOfWeek dayOfWeek, LocalTime at) { ChronoField.ALIGNED_WEEK_OF_MONTH.checkValidValue(weekOfMonth); Preconditions.checkNotNull(dayOfWeek); Preconditions.checkNotNull(at); return everyMonths(months).withAdjuster(sameOrNext(Period.ofMonths(1), combine(TemporalAdjusters.dayOfWeekInMonth(weekOfMonth, dayOfWeek), at))); } /** * Create a new schedule where events are triggered every {@code months}, on a given day of the month and time * * @param months the number of months between events * @param dayOfMonth the day of the month when to triggered events for. It * might be adjusted if too large for a specific month * (31 would be adjusted to 30 for an event triggered in April). * @param at the specific time to generate the events at * @return a schedule builder generating events every {@code months} * @throws IllegalArgumentException if {@code months} is negative, or if {@code dayOfMonth} is invalid. * @throws NullPointerException if {@code at} is null */ public static Builder everyMonths(int months, int dayOfMonth, LocalTime at) { ChronoField.DAY_OF_MONTH.checkValidIntValue(dayOfMonth); Preconditions.checkNotNull(at); return everyMonths(months).withAdjuster(sameOrNext(Period.ofMonths(1), combine(dayOfMonth(dayOfMonth), at))); } /** * Combine temporal adjusters by executing them sequentially. * Order matters obviously... * * @param adjusters the adjusters to combine * @return an adjuster */ private static TemporalAdjuster combine(TemporalAdjuster... adjusters) { final ImmutableList<TemporalAdjuster> copyOf = ImmutableList.copyOf(adjusters); return new TemporalAdjuster() { @Override public Temporal adjustInto(Temporal temporal) { Temporal result = temporal; for(TemporalAdjuster adjuster: copyOf) { result = result.with(adjuster); } return result; } }; } /** * A temporal adjuster which leaves the temporal untouched. * In a Java8 world, this helper can probably be removed safely * and replaced by identity */ private static final TemporalAdjuster NO_ADJUSTMENT = new TemporalAdjuster() { @Override public Temporal adjustInto(Temporal temporal) { return temporal; } }; /** * Wraps an adjuster to round the temporal to the next period if the adjusted time is before * the temporal instant. * * @param amount the amount to add to the adjusted time if before the temporal argument of * {@code TemporarlAdjuster#adjustInto()} is after the adjusted time * @param adjuster the adjuster to wrap * @return an adjuster */ private static TemporalAdjuster sameOrNext(final TemporalAmount amount, final TemporalAdjuster adjuster) { return new TemporalAdjuster() { @Override public Temporal adjustInto(Temporal temporal) { Temporal adjusted = temporal.with(adjuster); return (ChronoUnit.NANOS.between(temporal, adjusted) >= 0) ? adjusted : temporal.plus(amount).with(adjuster); } }; } /** * Adjust a temporal to the given day of the month * * @param dayOfMonth the day of the month to adjust the temporal to * @return a temporal adjuster * @throws IllegalArgumentException if {@code dayOfMonth} is invalid */ private static final TemporalAdjuster dayOfMonth(final int dayOfMonth) { ChronoField.DAY_OF_MONTH.checkValidIntValue(dayOfMonth); return new TemporalAdjuster() { @Override public Temporal adjustInto(Temporal temporal) { long adjustedDayOfMonth = Math.min(dayOfMonth, temporal.range(ChronoField.DAY_OF_MONTH).getMaximum()); return temporal.with(ChronoField.DAY_OF_MONTH, adjustedDayOfMonth); } }; } /** * Check that interval (as X hours, hours, weeks...) is strictly positive * @param interval the value to check * @return interval */ private static int checkInterval(int interval) { Preconditions.checkArgument(interval > 0, "interval should be greater than 0, was %s", interval); return interval; } } /** * Return the amount of time between two instants created by the schedule. * * The information is approximative and not absolute as the schedule might be adjusted * based on schedule constraints (like every week, or every 2nd Tuesday of every other month). * * @return the amount of time between events */ TemporalAmount getPeriod(); /** * Return an iterator over next scheduled events * * Each sequence of events created by this method starts at the current * time (so the sequence doesn't contain events from the past). More precisely * the first event should be the closest instant greater or equals to now which satisfies the * schedule conditions. * * @return the iterator */ @Override Iterator<Instant> iterator(); /** * To get name of distributed singleton task * @return */ String getTaskName(); /** * Time period after which to release leadership * in milliseconds * @return */ Long getScheduledOwnershipReleaseInMillis(); /** * To define if it is distributed singleton task * @return */ default boolean isDistributedSingleton() { return (getTaskName() != null); } /** * To run exactly once - leader executes once and everyone * else backs off. * @return */ default boolean isToRunExactlyOnce() { return false; } /** * To get CleanupListener that will be used * to clean up during distributed singleton task * losing/abandoning leadership * This can/should be used by tasks that need * to clearly differentiate their state while they are leaders * or not leaders * @return CleanupListener */ default CleanupListener getCleanupListener() { return () -> { // do nothing by default }; } }
package src.main.java.br.pucrs.fds.monopoly; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; public class Player { //the key of colorGroups is the name of the color group. private Hashtable colorGroups = new Hashtable(); private boolean inJail; private int money; private String name; private Cell position; private ArrayList properties = new ArrayList(); private ArrayList railroads = new ArrayList(); private ArrayList utilities = new ArrayList(); public Player() { GameBoard gb = GameMaster.instance().getGameBoard(); inJail = false; if(gb != null) { position = gb.queryCell("Go"); } } public void buyProperty(IOwnable property, int amount) { property.setOwner(this); if(property instanceof PropertyCell) { PropertyCell cell = (PropertyCell)property; properties.add(cell); colorGroups.put( cell.getColorGroup(), new Integer(getPropertyNumberForColor(cell.getColorGroup())+1)); } if(property instanceof RailRoadCell) { railroads.add(property); colorGroups.put( RailRoadCell.COLOR_GROUP, new Integer(getPropertyNumberForColor(RailRoadCell.COLOR_GROUP)+1)); } if(property instanceof UtilityCell) { utilities.add(property); colorGroups.put( UtilityCell.COLOR_GROUP, new Integer(getPropertyNumberForColor(UtilityCell.COLOR_GROUP)+1)); } setMoney(getMoney() - amount); } public boolean canBuyHouse() { return (getMonopolies().length != 0); } public boolean checkProperty(String property) { for(int i=0;i<properties.size();i++) { Cell cell = (Cell)properties.get(i); if(cell.getName().equals(property)) { return true; } } return false; } public void exchangeProperty(Player player) { for(int i = 0; i < getPropertyNumber(); i++ ) { PropertyCell cell = getProperty(i); cell.setOwner(player); if(player == null) { cell.setAvailable(true); cell.setNumHouses(0); } else { player.properties.add(cell); colorGroups.put( cell.getColorGroup(), new Integer(getPropertyNumberForColor(cell.getColorGroup())+1)); } } properties.clear(); } public IOwnable[] getAllProperties() { ArrayList list = new ArrayList(); list.addAll(properties); list.addAll(utilities); list.addAll(railroads); return (IOwnable[])list.toArray(new IOwnable[list.size()]); } public int getMoney() { return this.money; } public String[] getMonopolies() { ArrayList monopolies = new ArrayList(); Enumeration colors = colorGroups.keys(); while(colors.hasMoreElements()) { String color = (String)colors.nextElement(); if(!(color.equals(RailRoadCell.COLOR_GROUP)) && !(color.equals(UtilityCell.COLOR_GROUP))) { Integer num = (Integer)colorGroups.get(color); GameBoard gameBoard = GameMaster.instance().getGameBoard(); if(num.intValue() == gameBoard.getPropertyNumberForColor(color)) { monopolies.add(color); } } } return (String[])monopolies.toArray(new String[monopolies.size()]); } public String getName() { return name; } public void getOutOfJail() { money -= JailCell.BAIL; if(isBankrupt()) { money = 0; exchangeProperty(null); } inJail = false; GameMaster.instance().updateGUI(); } public Cell getPosition() { return this.position; } public PropertyCell getProperty(int index) { return (PropertyCell)properties.get(index); } public int getPropertyNumber() { return properties.size(); } private int getPropertyNumberForColor(String name) { Integer number = (Integer)colorGroups.get(name); if(number != null) { return number.intValue(); } return 0; } public boolean isBankrupt() { return money <= 0; } public boolean isInJail() { return inJail; } public int numberOfRR() { return getPropertyNumberForColor(RailRoadCell.COLOR_GROUP); } public int numberOfUtil() { return getPropertyNumberForColor(UtilityCell.COLOR_GROUP); } public void payRentTo(Player owner, int rentValue) { if(money < rentValue) { owner.money += money; money -= rentValue; } else { money -= rentValue; owner.money +=rentValue; } if(isBankrupt()) { money = 0; exchangeProperty(owner); } } public void purchase() { if(getPosition().isAvailable()) { Cell c = getPosition(); c.setAvailable(false); if(c instanceof PropertyCell) { PropertyCell cell = (PropertyCell)c; purchaseProperty(cell); } if(c instanceof RailRoadCell) { RailRoadCell cell = (RailRoadCell)c; purchaseRailRoad(cell); } if(c instanceof UtilityCell) { UtilityCell cell = (UtilityCell)c; purchaseUtility(cell); } } } public void purchaseHouse(String selectedMonopoly, int houses) { GameBoard gb = GameMaster.instance().getGameBoard(); PropertyCell[] cells = gb.getPropertiesInMonopoly(selectedMonopoly); if((money >= (cells.length * (cells[0].getHousePrice() * houses)))) { for(int i = 0; i < cells.length; i++) { int newNumber = cells[i].getNumHouses() + houses; if (newNumber <= 5) { cells[i].setNumHouses(newNumber); this.setMoney(money - (cells[i].getHousePrice() * houses)); GameMaster.instance().updateGUI(); } } } } private void purchaseProperty(PropertyCell cell) { buyProperty(cell, cell.getPrice()); } private void purchaseRailRoad(RailRoadCell cell) { buyProperty(cell, cell.getPrice()); } private void purchaseUtility(UtilityCell cell) { buyProperty(cell, cell.getPrice()); } public void sellProperty(IOwnable property, int amount) { property.setOwner(null); if(property instanceof PropertyCell) { properties.remove(property); } if(property instanceof RailRoadCell) { railroads.remove(property); } if(property instanceof UtilityCell) { utilities.remove(property); } setMoney(getMoney() + amount); } public void setInJail(boolean inJail) { this.inJail = inJail; } public void setMoney(int money) { this.money = money; } public void setName(String name) { this.name = name; } public void setPosition(Cell newPosition) { this.position = newPosition; } public String toString() { return name; } public void resetProperty() { properties = new ArrayList(); railroads = new ArrayList(); utilities = new ArrayList(); } }
package com.whatdoyouwanttodo.config; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import java.util.zip.Deflater; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import org.xmlpull.v1.XmlSerializer; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.util.Xml; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import com.whatdoyouwanttodo.R; import com.whatdoyouwanttodo.application.ActiveListening; import com.whatdoyouwanttodo.application.Cell; import com.whatdoyouwanttodo.application.Chessboard; import com.whatdoyouwanttodo.application.ChessboardApplication; import com.whatdoyouwanttodo.application.Abrakadabra; import com.whatdoyouwanttodo.application.VideoPlaylist; import com.whatdoyouwanttodo.db.ActiveListeningCursor; import com.whatdoyouwanttodo.db.ChessboardDbUtility; import com.whatdoyouwanttodo.db.AbrakadabraCursor; import com.whatdoyouwanttodo.db.VideoPlaylistCursor; import com.whatdoyouwanttodo.settings.Configurations; import com.whatdoyouwanttodo.settings.Constants; import com.whatdoyouwanttodo.utils.FileUtils; /** * Attivita' che conclude un'importazione o un'esportazione */ public class ChooseDestinationActivity extends ActionBarActivity { private static Chessboard[] cbParam = null; private static Cell[][] cbCellsParam = null; private static String importParam = null; public static Intent getStartIntent(Activity caller, Chessboard[] cb, Cell[][] cbCells) { Intent intent = new Intent(caller, ChooseDestinationActivity.class); cbParam = cb; cbCellsParam = cbCells; importParam = null; return intent; } public static Intent getStartIntent(Activity caller, String path) { Intent intent = new Intent(caller, ChooseDestinationActivity.class); cbParam = null; cbCellsParam = null; importParam = path; return intent; } private Chessboard[] cbs; private Cell[][] cbCells; private String importPath; private TreeMap<String, String> filenameset; private Abrakadabra[] abrakadabra; private ActiveListening[] activeListening; private VideoPlaylist[] videoPlaylist; private TextView helpText; private TextView filePathText; private Button openFile; private Button close; private File outFile; private boolean overwrite = false; private String dateStr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.cbs = cbParam; this.cbCells = cbCellsParam; this.importPath = importParam; cbParam = null; cbCellsParam = null; importParam = null; if(importPath == null && cbs != null && cbCells != null) { setContentView(R.layout.activity_choose_destination); this.helpText = (TextView) findViewById(R.id.help_text); this.filePathText = (TextView) findViewById(R.id.file_path_text); this.openFile = (Button) findViewById(R.id.open_file); this.close = (Button) findViewById(R.id.close); close.setOnClickListener(this.onClose); SaveOnFile task = new SaveOnFile(); task.execute(); } else if (importPath != null && cbs == null && cbCells == null) { setContentView(R.layout.activity_choose_destination_import); this.helpText = (TextView) findViewById(R.id.help_text); this.filePathText = (TextView) findViewById(R.id.file_path_text); this.openFile = (Button) findViewById(R.id.open_file); this.close = (Button) findViewById(R.id.close); SimpleDateFormat df = new SimpleDateFormat(Configurations.EXPORT_DATA_FORMAT, Locale.getDefault()); this.dateStr = df.format(new Date()); openFile.setOnClickListener(this.onOverwriteImport); close.setOnClickListener(this.onAppendImport); } } @Override protected void onDestroy() { super.onDestroy(); // clear pointer this.cbs = null; this.cbCells = null; this.importPath = null; cbParam = null; cbCellsParam = null; importParam = null; openFile.setOnClickListener(null); close.setOnClickListener(null); this.helpText = null; this.filePathText = null; this.openFile = null; this.close = null; } private class SaveOnFile extends AsyncTask<Void, Void, Boolean> { @Override protected Boolean doInBackground(Void... voids) { return writeOnFile(); } @Override protected void onPostExecute(Boolean ret) { if (helpText != null && filePathText != null && openFile != null && close != null) { Resources res = getResources(); if (ret == true) { String exportTitle = res.getString(R.string.activity_choose_destination_export_title); String exportMessage = res.getString(R.string.activity_choose_destination_export_message); helpText.setText(exportTitle); filePathText.setText(exportMessage); filePathText.setVisibility(View.VISIBLE); openFile.setVisibility(View.GONE); close.setVisibility(View.VISIBLE); } else { String exportTitle = res.getString(R.string.activity_choose_destination_export_failed_title); String exportMessage = res.getString(R.string.activity_choose_destination_export_failed_message); helpText.setText(exportTitle); filePathText.setText(exportMessage); filePathText.setVisibility(View.VISIBLE); openFile.setVisibility(View.GONE); close.setVisibility(View.VISIBLE); } } } } private class LoadFromFile extends AsyncTask<Void, Void, Boolean> { @Override protected Boolean doInBackground(Void... voids) { return loadFromFile(); } @Override protected void onPostExecute(Boolean ret) { if (helpText != null && filePathText != null && openFile != null && close != null) { Resources res = getResources(); if (ret == true) { String importTitle = res.getString(R.string.activity_choose_destination_import_title); helpText.setText(importTitle); filePathText.setVisibility(View.GONE); openFile.setVisibility(View.GONE); close.setOnClickListener(onClose); close.setText(res.getString(R.string.activity_choose_destination_close)); close.setVisibility(View.VISIBLE); } else { String importTitle = res.getString(R.string.activity_choose_destination_import_failed_title); String importMessage = res.getString(R.string.activity_choose_destination_import_failed_message); helpText.setText(importTitle); filePathText.setText(importMessage); filePathText.setVisibility(View.VISIBLE); openFile.setVisibility(View.GONE); close.setOnClickListener(onClose); close.setText(res.getString(R.string.activity_choose_destination_close)); close.setVisibility(View.VISIBLE); } } } } private boolean writeOnFile() { // get a file name outFile = FileUtils.getWritableDocumentFile(this, Constants.getInstance(this).EXPORT_DIR, Constants.getInstance(this).FILE_DIR, Configurations.EXPORT_PREFIX); ZipOutputStream zipOutStream = null; boolean success = true; try { OutputStream outStream = new FileOutputStream(outFile); zipOutStream = new ZipOutputStream(new BufferedOutputStream(outStream)); zipOutStream.setLevel(Deflater.BEST_COMPRESSION); filenameset = new TreeMap<String, String>(); putXmlIndex(zipOutStream); Iterator<String> filenameIt = filenameset.keySet().iterator(); while (filenameIt.hasNext()) { String filename = filenameIt.next(); File file = FileUtils.getResourceFile(filenameset.get(filename)); ZipEntry zipEntry = new ZipEntry(filename); zipOutStream.putNextEntry(zipEntry); BufferedInputStream bufInStream = null; try { int bufferSize = 8192; FileInputStream fileInStream = new FileInputStream(file); bufInStream = new BufferedInputStream(fileInStream, bufferSize); byte data[] = new byte[bufferSize]; int count; while ((count = bufInStream.read(data, 0, bufferSize)) != -1) { zipOutStream.write(data, 0, count); } } catch (IOException ex) { Log.e(getClass().getName(), "error on export", ex); success = false; } finally { try { bufInStream.close(); } catch (IOException ex) { Log.e(getClass().getName(), "error on export", ex); success = false; } } zipOutStream.closeEntry(); } } catch (IOException ex) { Log.e(getClass().getName(), "error on export", ex); success = false; } finally { try { zipOutStream.close(); } catch (IOException ex) { Log.e(getClass().getName(), "error on export", ex); success = false; } } if(filenameset != null) { filenameset.clear(); filenameset = null; } return success; } private void putXmlIndex(ZipOutputStream zos) throws IOException { ZipEntry entry = new ZipEntry(Configurations.EXPORT_CONTENT_NAME); zos.putNextEntry(entry); // get temporary file File cacheDir = getCacheDir(); File tempFile = File.createTempFile(Configurations.EXPORT_CONTENT_PREFIX, Configurations.EXPORT_CONTENT_POSTFIX, cacheDir); FileOutputStream fow = new FileOutputStream(tempFile); XmlSerializer xmlSerializer = Xml.newSerializer(); xmlSerializer.setOutput(fow, Configurations.EXPORT_ENCODING); // write temporary file xmlSerializer.startDocument(Configurations.EXPORT_ENCODING, true); writeXmlIndex(xmlSerializer); xmlSerializer.endDocument(); fow.close(); // zip temp file int bufferSize = 8192; byte data[] = new byte[bufferSize]; FileInputStream fi = new FileInputStream(tempFile); BufferedInputStream origin = new BufferedInputStream(fi, bufferSize); int count; while ((count = origin.read(data, 0, bufferSize)) != -1) { zos.write(data, 0, count); } origin.close(); zos.closeEntry(); } private void writeXmlIndex(XmlSerializer xmlSerializer) throws IllegalArgumentException, IllegalStateException, IOException { xmlSerializer.startTag("", "tables"); ArrayList<Long> abrakadabra = new ArrayList<Long>(); ArrayList<Long> activelistening = new ArrayList<Long>(); ArrayList<Long> playvideo = new ArrayList<Long>(); for (int i = 0; i < cbs.length; i++) { Chessboard cb = cbs[i]; Cell[] cells = cbCells[i]; // write chessboard xmlSerializer.startTag("", "table"); long id = cb.getId(); long parentId = cb.getParentId(); String name = cb.getName(); int rowCount = cb.getRowCount(); int columnCount = cb.getColumnCount(); int bgColor = cb.getBackgroundColor(); int borderWidth = cb.getBorderWidth(); xmlSerializer.attribute("", "id", Long.toString(id)); xmlSerializer.attribute("", "parent", Long.toString(parentId)); xmlSerializer.attribute("", "name", name); xmlSerializer.attribute("", "rows", Integer.toString(rowCount)); xmlSerializer.attribute("", "columns", Integer.toString(columnCount)); xmlSerializer.attribute("", "color", Integer.toString(bgColor)); xmlSerializer.attribute("", "border", Integer.toString(borderWidth)); // write cells for(int j = 0; j < cells.length; j++) { Cell cell = cells[j]; xmlSerializer.startTag("", "symbol"); // long chessboard = cell.getChessboard(); long cellId = cell.getId(); int row = cell.getRow(); int column = cell.getColumn(); String cellName = cell.getName(); String imagePath = cell.getImagePath(); String audioPath = cell.getAudioPath(); String text = cell.getText(); long activityType = cell.getActivityType(); long activityParam = cell.getActivityParam(); int cellBgColor = cell.getBackgroundColor(); int borderColor = cell.getBorderColor(); int cellBorderWidth = cell.getBorderWidth(); int textColor = cell.getTextColor(); int textWidth = cell.getTextWidth(); imagePath = putExternalFile(imagePath); audioPath = putExternalFile(audioPath); xmlSerializer.attribute("", "id", Long.toString(cellId)); xmlSerializer.attribute("", "row", Integer.toString(row)); xmlSerializer.attribute("", "column", Integer.toString(column)); xmlSerializer.attribute("", "name", cellName); xmlSerializer.attribute("", "image", imagePath); xmlSerializer.attribute("", "audio", audioPath); xmlSerializer.attribute("", "text", text); xmlSerializer.attribute("", "type", Long.toString(activityType)); xmlSerializer.attribute("", "linkto", Long.toString(activityParam)); xmlSerializer.attribute("", "color", Integer.toString(cellBgColor)); xmlSerializer.attribute("", "bordercolor", Integer.toString(borderColor)); xmlSerializer.attribute("", "borderwidth", Integer.toString(cellBorderWidth)); xmlSerializer.attribute("", "textcolor", Integer.toString(textColor)); xmlSerializer.attribute("", "textwidth", Integer.toString(textWidth)); if (activityType == Cell.ACTIVITY_TYPE_ABRAKADABRA) { abrakadabra.add(activityParam); } else if (activityType == Cell.ACTIVITY_TYPE_ACTIVE_LISTENING) { activelistening.add(activityParam); } else if (activityType == Cell.ACTIVITY_TYPE_PLAY_VIDEO) { playvideo.add(activityParam); } xmlSerializer.endTag("", "symbol"); } xmlSerializer.endTag("", "table"); } // write activities (if exist) ChessboardDbUtility dbu = null; if (abrakadabra.size() > 0 || activelistening.size() > 0 || playvideo.size() > 0) { dbu = new ChessboardDbUtility(this); dbu.openReadable(); xmlSerializer.startTag("", "interactions"); } if (abrakadabra.size() > 0) { for (int j = 0; j < abrakadabra.size(); j++) { AbrakadabraCursor cursor = dbu .getCursorOnAbrakadabra(abrakadabra.get(j)); while (cursor.moveToNext()) { Abrakadabra ak = cursor.getAbrakadabra(); xmlSerializer.startTag("", "abrakadabra"); long mId = ak.getId(); String mName = ak.getName(); String[] mImages = ak.getImagePaths(); String mSound = ak.getSoundPath(); String mMusic = ak.getMusicPath(); int mImageEffect = ak.getImageEffect(); int mAudioDuration = ak.getMusicDurationTime(); mSound = putExternalFile(mSound); mMusic = putExternalFile(mMusic); xmlSerializer.attribute("", "id", Long.toString(mId)); xmlSerializer.attribute("", "name", mName); StringBuilder sb = new StringBuilder(); for (int z = 0; z < mImages.length; z++) { mImages[z] = putExternalFile(mImages[z]); if (z > 0) sb.append(";"); sb.append(mImages[z]); } xmlSerializer.attribute("", "images", sb.toString()); xmlSerializer.attribute("", "sound", mSound); xmlSerializer.attribute("", "audio", mMusic); xmlSerializer.attribute("", "audioduration", Integer.toString(mAudioDuration)); xmlSerializer.attribute("", "imageeffect", Integer.toString(mImageEffect)); xmlSerializer.endTag("", "abrakadabra"); } cursor.close(); } } abrakadabra.clear(); abrakadabra = null; if (activelistening.size() > 0) { for (int j = 0; j < activelistening.size(); j++) { ActiveListeningCursor cursor = dbu .getCursorOnActiveListening(activelistening.get(j)); while (cursor.moveToNext()) { ActiveListening al = cursor.getActiveListening(); xmlSerializer.startTag("", "activelistening"); long mId = al.getId(); String mName = al.getName(); String mImage = al.getBackground(); String[] mAudio = al.getMusicPath(); int mInterval = al.getInterval(); int mPause = al.getPause(); String mRegistration = al.getRegistrationPath(); int mmInterval = al.getPauseInterval(); mImage = putExternalFile(mImage); mRegistration = putExternalFile(mRegistration); xmlSerializer.attribute("", "id", Long.toString(mId)); xmlSerializer.attribute("", "name", mName); xmlSerializer.attribute("", "image", mImage); StringBuilder sb = new StringBuilder(); for (int z = 0; z < mAudio.length; z++) { mAudio[z] = putExternalFile(mAudio[z]); if (z > 0) sb.append(";"); sb.append(mAudio[z]); } xmlSerializer.attribute("", "audio", sb.toString()); xmlSerializer.attribute("", "playinterval", Integer.toString(mInterval)); xmlSerializer.attribute("", "playpause", Integer.toString(mPause)); xmlSerializer.attribute("", "message", mRegistration); xmlSerializer.attribute("", "messagepause", Long.toString(mmInterval)); xmlSerializer.endTag("", "activelistening"); } cursor.close(); } } activelistening.clear(); activelistening = null; if (playvideo.size() > 0) { for (int j = 0; j < playvideo.size(); j++) { VideoPlaylistCursor cursor = dbu .getCursorOnVideoPlaylist(playvideo.get(j)); while (cursor.moveToNext()) { VideoPlaylist ms = cursor.getVideoPlaylist(); xmlSerializer.startTag("", "playvideo"); long mId = ms.getId(); String mName = ms.getName(); String[] mVideo = ms.getVideoUrl(); xmlSerializer.attribute("", "id", Long.toString(mId)); xmlSerializer.attribute("", "name", mName); StringBuilder sb = new StringBuilder(); for (int z = 0; z < mVideo.length; z++) { mVideo[z] = putExternalFile(mVideo[z]); if (z > 0) sb.append(";"); sb.append(mVideo[z]); } xmlSerializer.attribute("", "video", sb.toString()); xmlSerializer.endTag("", "playvideo"); } cursor.close(); } } playvideo.clear(); playvideo = null; if (dbu != null) { dbu.close(); xmlSerializer.endTag("", "interactions"); } dbu = null; xmlSerializer.endTag("", "tables"); } private String putExternalFile(String filePath) { if(filePath == null) return ""; if (filePath.equals(Configurations.IMAGE_BACK_NAME)) { return filePath; } else if (filePath.equals(Configurations.IMAGE_NEW_NAME)) { return filePath; } else if(filePath.startsWith(Configurations.YOUTUBE_PREFIX)) { return filePath; } else if(filePath.startsWith(Configurations.TTS_PREFIX)) { return filePath; } File file = FileUtils.getResourceFile(filePath); if(file == null) { return filePath; } String name = "file_" + file.getName(); int count = 1; while(this.filenameset.containsKey(name) == true) { name = "file__" + count + "_" + file.getName(); count++; } this.filenameset.put(name, filePath); return name; } private Boolean loadFromFile() { // get file path File inFile = new File(importPath); ZipInputStream zipInStream = null; boolean success = true; try { InputStream os = new FileInputStream(inFile); zipInStream = new ZipInputStream(new BufferedInputStream(os)); getXmlIndex(zipInStream); ZipEntry entry = zipInStream.getNextEntry(); while(entry != null) { String entryName = entry.getName(); String destinationPath = filenameset.get(entryName); File destinationFile = FileUtils.getResourceFileForWrite(destinationPath); FileOutputStream destOutStream = new FileOutputStream(destinationFile); if(ChessboardApplication.DEBUG_IMPORT_EXPORT) { Log.w(getClass().getName(), "start import " + importPath + " -> " + destinationFile.getPath()); } int bufferSize = 8192; byte data[] = new byte[bufferSize]; int count; while ((count = zipInStream.read(data, 0, bufferSize)) != -1) { destOutStream.write(data, 0, count); } destOutStream.close(); if(ChessboardApplication.DEBUG_IMPORT_EXPORT) { Log.w(getClass().getName(), "stop import " + importPath + " -> " + destinationFile.getPath()); } entry = zipInStream.getNextEntry(); } } catch (IOException e) { Log.d(getClass().getName(), e.getMessage()); success = false; } catch (XmlPullParserException e) { Log.d(getClass().getName(), e.getMessage()); success = false; } finally { try { zipInStream.close(); } catch (IOException e) { Log.d(getClass().getName(), e.getMessage()); success = false; } } if (filenameset != null) { filenameset.clear(); filenameset = null; } ChessboardDbUtility dbu = new ChessboardDbUtility(this); dbu.openWritable(); if (overwrite == true) { dbu.clear(); } appendToDatabase(dbu); dbu.close(); return success; } private void getXmlIndex(ZipInputStream zis) throws IOException, XmlPullParserException { ZipEntry entry = zis.getNextEntry(); if(ChessboardApplication.DEBUG_IMPORT_EXPORT) { if(entry.getName().equals("content.xml") == false) { Log.e(getClass().getName(), "expected content.xml"); } Log.w(getClass().getName(), "start import xml file"); } // get temporary file File cacheDir = getCacheDir(); File tempFile = File.createTempFile(Configurations.EXPORT_CONTENT_PREFIX, Configurations.EXPORT_CONTENT_POSTFIX, cacheDir); FileOutputStream fow = new FileOutputStream(tempFile); byte[] buffer = new byte[8192]; int count; while ((count = zis.read(buffer)) != -1) { fow.write(buffer, 0, count); } fow.close(); FileInputStream inputStream = new FileInputStream(tempFile); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(false); XmlPullParser xmlParser = factory.newPullParser(); xmlParser.setInput(inputStream, null); parseXmlIndex(xmlParser); xmlParser = null; inputStream.close(); if(ChessboardApplication.DEBUG_IMPORT_EXPORT) { Log.w(getClass().getName(), "end import xml file"); } } private void parseXmlIndex(XmlPullParser xmlParser) throws IllegalArgumentException, IllegalStateException, IOException, XmlPullParserException { int cTag = xmlParser.nextTag(); // skip tables filenameset = new TreeMap<String, String>(); LinkedList<Chessboard> cbs = new LinkedList<Chessboard>(); LinkedList<Cell[]> cbCells = new LinkedList<Cell[]>(); cTag = xmlParser.nextTag(); while(cTag == XmlPullParser.START_TAG && xmlParser.getName().equals("table")) { Chessboard cb = null; LinkedList<Cell> cells = new LinkedList<Cell>(); long id = Long.parseLong(xmlParser.getAttributeValue(null, "id")); int parentId = Integer.parseInt(xmlParser.getAttributeValue(null, "parent")); String name = xmlParser.getAttributeValue(null, "name"); int rowCount = Integer.parseInt(xmlParser.getAttributeValue(null, "rows")); int columnCount = Integer.parseInt(xmlParser.getAttributeValue(null, "columns")); int bgColor = Integer.parseInt(xmlParser.getAttributeValue(null, "color")); int borderWidth = Integer.parseInt(xmlParser.getAttributeValue(null, "border")); cb = new Chessboard(id, parentId, name, rowCount, columnCount, bgColor, borderWidth); cTag = xmlParser.nextTag(); while(cTag == XmlPullParser.START_TAG && xmlParser.getName().equals("symbol")) { long chessboard = cb.getId(); long cellId = Long.parseLong(xmlParser.getAttributeValue(null, "id")); int row = Integer.parseInt(xmlParser.getAttributeValue(null, "row")); int column = Integer.parseInt(xmlParser.getAttributeValue(null, "column")); String cellName = xmlParser.getAttributeValue(null, "name"); String imagePath = xmlParser.getAttributeValue(null, "image"); String audioPath = xmlParser.getAttributeValue(null, "audio"); String text = xmlParser.getAttributeValue(null, "text"); int activityType = Integer.parseInt(xmlParser.getAttributeValue(null, "type")); long activityParam = Long.parseLong(xmlParser.getAttributeValue(null, "linkto")); int cellBgColor = Integer.parseInt(xmlParser.getAttributeValue(null, "color")); int borderColor = Integer.parseInt(xmlParser.getAttributeValue(null, "bordercolor")); int cellBorderWidth = Integer.parseInt(xmlParser.getAttributeValue(null, "borderwidth")); int textColor = Integer.parseInt(xmlParser.getAttributeValue(null, "textcolor")); int textWidth = Integer.parseInt(xmlParser.getAttributeValue(null, "textwidth")); imagePath = getExternalFile(imagePath); audioPath = getExternalFile(audioPath); Cell cell = new Cell(cellId, chessboard, cellName, row, column, cellBgColor, cellBorderWidth, borderColor, text, textWidth, textColor, imagePath, audioPath, activityType, activityParam); cells.add(cell); cTag = xmlParser.nextTag(); // </symbol> cTag = xmlParser.nextTag(); if(cTag == XmlPullParser.END_TAG) { cTag = xmlParser.nextTag(); } } cbs.add(cb); cbCells.add(cells.toArray(new Cell[cells.size()])); cells.clear(); cells = null; } this.cbs = cbs.toArray(new Chessboard[cbs.size()]); this.cbCells = cbCells.toArray(new Cell[cbCells.size()][]); cbs.clear(); cbCells.clear(); cbs = null; cbCells = null; if(cTag == XmlPullParser.START_TAG && xmlParser.getName().equals("interactions")) { ArrayList<Abrakadabra> abrakadabra = new ArrayList<Abrakadabra>(); ArrayList<ActiveListening> activelistening = new ArrayList<ActiveListening>(); ArrayList<VideoPlaylist> playvideo = new ArrayList<VideoPlaylist>(); cTag = xmlParser.nextTag(); while(cTag == XmlPullParser.START_TAG && xmlParser.getName().equals("abrakadabra")) { long mId = Long.parseLong(xmlParser.getAttributeValue(null, "id")); String mName = xmlParser.getAttributeValue(null, "name"); String[] mImages = xmlParser.getAttributeValue(null, "images").split(";"); String mSound = xmlParser.getAttributeValue(null, "sound"); String mMusic = xmlParser.getAttributeValue(null, "audio"); int mMusicDurationTime = Integer.parseInt(xmlParser.getAttributeValue(null, "audioduration")); int mImageEffect = Integer.parseInt(xmlParser.getAttributeValue(null, "imageeffect")); mImages = getExternalFile(mImages); mSound = getExternalFile(mSound); mMusic = getExternalFile(mMusic); Abrakadabra ms = new Abrakadabra(mId, mName, mImages, mSound, mMusic, mMusicDurationTime, mImageEffect); abrakadabra.add(ms); cTag = xmlParser.nextTag(); cTag = xmlParser.nextTag(); if(cTag == XmlPullParser.END_TAG) { cTag = xmlParser.nextTag(); } } while(cTag == XmlPullParser.START_TAG && xmlParser.getName().equals("activelistening")) { long mId = Long.parseLong(xmlParser.getAttributeValue(null, "id")); String mName = xmlParser.getAttributeValue(null, "name"); String mImage = xmlParser.getAttributeValue(null, "image"); String[] mAudio = xmlParser.getAttributeValue(null, "audio").split(";"); int mInterval = Integer.parseInt(xmlParser.getAttributeValue(null, "playinterval")); int mPause = Integer.parseInt(xmlParser.getAttributeValue(null, "playpause")); String mRegistration = xmlParser.getAttributeValue(null, "message"); int mmInterval = Integer.parseInt(xmlParser.getAttributeValue(null, "messagepause")); mAudio = getExternalFile(mAudio); mImage = getExternalFile(mImage); mRegistration = getExternalFile(mRegistration); ActiveListening al = new ActiveListening(mId, mName, mImage, mAudio, mInterval, mRegistration, mPause, mmInterval); activelistening.add(al); cTag = xmlParser.nextTag(); cTag = xmlParser.nextTag(); if(cTag == XmlPullParser.END_TAG) { cTag = xmlParser.nextTag(); } } while (cTag == XmlPullParser.START_TAG && xmlParser.getName().equals("playvideo")) { long mId = Long.parseLong(xmlParser.getAttributeValue(null, "id")); String mName = xmlParser.getAttributeValue(null, "name"); String[] mVideo = xmlParser.getAttributeValue(null, "video").split(";"); mVideo = getExternalFile(mVideo); VideoPlaylist vp = new VideoPlaylist(mId, mName, mVideo); playvideo.add(vp); cTag = xmlParser.nextTag(); cTag = xmlParser.nextTag(); if(cTag == XmlPullParser.END_TAG) { cTag = xmlParser.nextTag(); } } this.abrakadabra = abrakadabra.toArray(new Abrakadabra[abrakadabra.size()]); this.activeListening = activelistening.toArray(new ActiveListening[activelistening.size()]); this.videoPlaylist = playvideo.toArray(new VideoPlaylist[playvideo.size()]); } Log.d(getClass().getName(), xmlParser.getPositionDescription()); } private String[] getExternalFile(String[] files) { for(int i = 0; i < files.length; i++) { files[i] = getExternalFile(files[i]); } return files; } private String getExternalFile(String filePath) { if (filePath.equals(Configurations.IMAGE_BACK_NAME)) { return filePath; } else if (filePath.equals(Configurations.IMAGE_NEW_NAME)) { return filePath; } else if(filePath.startsWith(Configurations.YOUTUBE_PREFIX)) { return filePath; } else if(filePath.startsWith(Configurations.TTS_PREFIX)) { return filePath; } File destDirPrefix = new File(Constants.getInstance(this).FILE_DIR, Constants.getInstance(this).IMPORT_DIR + "__" + dateStr); File destFilePath = new File(destDirPrefix, filePath.substring("file_".length())); String destinationPath = destFilePath.getPath(); this.filenameset.put(filePath, destinationPath); return destinationPath; } private void appendToDatabase(ChessboardDbUtility dbu) { // track ids changes Map<Long, Long> abrakadabraIds = new TreeMap<Long, Long>(); Map<Long, Long> activeListeningIds = new TreeMap<Long, Long>(); Map<Long, Long> videoPlaylistIds = new TreeMap<Long, Long>(); Map<Long, Long> chessboardIds = new TreeMap<Long, Long>(); // add music slides data if(abrakadabra == null) { abrakadabra = new Abrakadabra[0]; } for(int i = 0; i < abrakadabra.length; i++) { Abrakadabra ms = abrakadabra[i]; long newId = dbu.addAbrakadabra(ms.getName(), ms.getImagePaths(), ms.getSoundPath(), ms.getMusicPath(), ms.getMusicDurationTime(), ms.getImageEffect()); abrakadabraIds.put(ms.getId(), newId); } // add active listening data if(activeListening == null) { activeListening = new ActiveListening[0]; } for(int i = 0; i < activeListening.length; i++) { ActiveListening al = activeListening[i]; long newId = dbu.addActiveListening(al.getName(), al.getBackground(), al.getMusicPath(), al.getInterval(), al.getRegistrationPath(), al.getPause(), al.getPauseInterval()); activeListeningIds.put(al.getId(), newId); } // add video playlist data if(videoPlaylist == null) { videoPlaylist = new VideoPlaylist[0]; } for(int i = 0; i < videoPlaylist.length; i++) { VideoPlaylist vp = videoPlaylist[i]; long newId = dbu.addVideoPlaylist(vp.getName(), vp.getVideoUrl()); videoPlaylistIds.put(vp.getId(), newId); } // add chessboards if(cbs == null) { cbs = new Chessboard[0]; } for(int i = 0; i < cbs.length; i++) { Chessboard cb = cbs[i]; long newId = dbu.addChessboard(cb.getParentId(), cb.getName(), cb.getRowCount(), cb.getColumnCount(), cb.getBackgroundColor(), cb.getBorderWidth()); chessboardIds.put(cb.getId(), newId); } // add cells for(int i = 0; i < cbCells.length; i++) { Cell[] cells = cbCells[i]; for(int j = 0; j < cells.length; j++) { Cell cell = cells[j]; // update ids long newChessboard = chessboardIds.get(cell.getChessboard()); int newActivityType = cell.getActivityType(); long newActivityParam = cell.getActivityParam(); if(newActivityType == Cell.ACTIVITY_TYPE_ABRAKADABRA) { if (abrakadabraIds.containsKey(newActivityParam)) { newActivityParam = abrakadabraIds.get(newActivityParam); } else { newActivityType = Cell.ACTIVITY_TYPE_NONE; newActivityParam = 0; } } else if(newActivityType == Cell.ACTIVITY_TYPE_ACTIVE_LISTENING) { if (activeListeningIds.containsKey(newActivityParam)) { newActivityParam = activeListeningIds.get(newActivityParam); } else { newActivityType = Cell.ACTIVITY_TYPE_NONE; newActivityParam = 0; } } else if(newActivityType == Cell.ACTIVITY_TYPE_PLAY_VIDEO) { if (videoPlaylistIds.containsKey(newActivityParam)) { newActivityParam = videoPlaylistIds.get(newActivityParam); } else { newActivityType = Cell.ACTIVITY_TYPE_NONE; newActivityParam = 0; } } else if(newActivityType == Cell.ACTIVITY_TYPE_CLOSE_CHESSBOARD) { newActivityParam = 0; } else if(newActivityType == Cell.ACTIVITY_TYPE_OPEN_CHESSBOARD) { if(chessboardIds.containsKey(newActivityParam)) { newActivityParam = chessboardIds.get(newActivityParam); } else { newActivityType = Cell.ACTIVITY_TYPE_NONE; newActivityParam = 0; } } else if(newActivityType == Cell.ACTIVITY_TYPE_NONE) { newActivityParam = 0; } /* long newId = */ dbu.addCell(newChessboard, cell.getName(), cell.getRow(), cell.getColumn(), cell.getBackgroundColor(), cell.getBorderWidth(), cell.getBorderColor(), cell.getText(), cell.getTextWidth(), cell.getTextColor(), cell.getImagePath(), cell.getAudioPath(), newActivityType, newActivityParam); } } // clear id maps (help gc) abrakadabraIds.clear(); activeListeningIds.clear(); videoPlaylistIds.clear(); chessboardIds.clear(); abrakadabraIds = null; activeListeningIds = null; videoPlaylistIds = null; chessboardIds = null; } private OnClickListener onOverwriteImport = new OnClickListener() { @Override public void onClick(View view) { Resources res = getResources(); String title = res.getString(R.string.activity_choose_destination_override_warning_title); String message = res.getString(R.string.activity_choose_destination_override_warning_message); String confirm = res.getString(R.string.activity_choose_destination_override_warning_confirm); String abort = res.getString(R.string.activity_choose_destination_override_warning_abort); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(ChooseDestinationActivity.this); dialogBuilder.setTitle(title); dialogBuilder.setMessage(message); dialogBuilder.setPositiveButton(confirm, new Dialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int witch) { Resources res = getResources(); helpText.setText(res.getString(R.string.activity_choose_destination_wait)); filePathText.setText(""); filePathText.setVisibility(View.INVISIBLE); openFile.setVisibility(View.INVISIBLE); close.setVisibility(View.INVISIBLE); overwrite = true; LoadFromFile task = new LoadFromFile(); task.execute(); } }); dialogBuilder.setNegativeButton(abort, new Dialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // do nothing } }); AlertDialog dialog = dialogBuilder.create(); dialog.show(); } }; private OnClickListener onAppendImport = new OnClickListener() { @Override public void onClick(View view) { Resources res = getResources(); helpText.setText(res.getString(R.string.activity_choose_destination_wait)); filePathText.setText(""); filePathText.setVisibility(View.INVISIBLE); openFile.setVisibility(View.INVISIBLE); close.setVisibility(View.INVISIBLE); overwrite = false; LoadFromFile task = new LoadFromFile(); task.execute(); } }; private OnClickListener onClose = new OnClickListener() { @Override public void onClick(View view) { finish(); } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.choose_destination, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.executiongraph; import org.apache.flink.api.common.JobID; import org.apache.flink.api.common.JobStatus; import org.apache.flink.api.common.accumulators.Accumulator; import org.apache.flink.api.common.accumulators.IntCounter; import org.apache.flink.api.common.time.Time; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.configuration.CheckpointingOptions; import org.apache.flink.configuration.Configuration; import org.apache.flink.metrics.groups.UnregisteredMetricsGroup; import org.apache.flink.runtime.accumulators.AccumulatorSnapshot; import org.apache.flink.runtime.blob.BlobWriter; import org.apache.flink.runtime.blob.PermanentBlobService; import org.apache.flink.runtime.blob.VoidBlobWriter; import org.apache.flink.runtime.checkpoint.CheckpointRetentionPolicy; import org.apache.flink.runtime.checkpoint.StandaloneCheckpointRecoveryFactory; import org.apache.flink.runtime.concurrent.ComponentMainThreadExecutorServiceAdapter; import org.apache.flink.runtime.concurrent.FutureUtils; import org.apache.flink.runtime.deployment.InputGateDeploymentDescriptor; import org.apache.flink.runtime.deployment.ResultPartitionDeploymentDescriptor; import org.apache.flink.runtime.deployment.TaskDeploymentDescriptor; import org.apache.flink.runtime.execution.ExecutionState; import org.apache.flink.runtime.executiongraph.restart.NoRestartStrategy; import org.apache.flink.runtime.executiongraph.utils.SimpleAckingTaskManagerGateway; import org.apache.flink.runtime.io.network.partition.NoOpJobMasterPartitionTracker; import org.apache.flink.runtime.io.network.partition.ResultPartitionType; import org.apache.flink.runtime.jobgraph.DistributionPattern; import org.apache.flink.runtime.jobgraph.JobGraph; import org.apache.flink.runtime.jobgraph.JobVertex; import org.apache.flink.runtime.jobgraph.JobVertexID; import org.apache.flink.runtime.jobgraph.ScheduleMode; import org.apache.flink.runtime.jobgraph.tasks.CheckpointCoordinatorConfiguration; import org.apache.flink.runtime.jobgraph.tasks.JobCheckpointingSettings; import org.apache.flink.runtime.jobmaster.JobMasterId; import org.apache.flink.runtime.jobmaster.LogicalSlot; import org.apache.flink.runtime.jobmaster.RpcTaskManagerGateway; import org.apache.flink.runtime.jobmaster.SlotRequestId; import org.apache.flink.runtime.jobmaster.TestingLogicalSlotBuilder; import org.apache.flink.runtime.jobmaster.slotpool.SlotProvider; import org.apache.flink.runtime.messages.Acknowledge; import org.apache.flink.runtime.operators.BatchTask; import org.apache.flink.runtime.shuffle.NettyShuffleMaster; import org.apache.flink.runtime.taskexecutor.TestingTaskExecutorGateway; import org.apache.flink.runtime.taskexecutor.TestingTaskExecutorGatewayBuilder; import org.apache.flink.runtime.taskmanager.LocalTaskManagerLocation; import org.apache.flink.runtime.taskmanager.TaskExecutionState; import org.apache.flink.runtime.taskmanager.TaskManagerLocation; import org.apache.flink.runtime.testingUtils.TestingUtils; import org.apache.flink.runtime.testtasks.NoOpInvokable; import org.apache.flink.runtime.testutils.DirectScheduledExecutorService; import org.apache.flink.util.FlinkException; import org.apache.flink.util.TestLogger; import org.apache.flink.util.function.FunctionUtils; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; import org.junit.Test; import org.slf4j.LoggerFactory; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.function.Function; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; /** * Tests for {@link ExecutionGraph} deployment. */ public class ExecutionGraphDeploymentTest extends TestLogger { /** * BLOB server instance to use for the job graph. */ protected BlobWriter blobWriter = VoidBlobWriter.getInstance(); /** * Permanent BLOB cache instance to use for the actor gateway that handles the {@link * TaskDeploymentDescriptor} loading (may be <tt>null</tt>). */ protected PermanentBlobService blobCache = null; /** * Checks that the job information for the given ID has been offloaded successfully (if * offloading is used). * * @param eg the execution graph that was created */ protected void checkJobOffloaded(ExecutionGraph eg) throws Exception { assertTrue(eg.getJobInformationOrBlobKey().isLeft()); } /** * Checks that the task information for the job vertex has been offloaded successfully (if * offloading is used). * * @param eg the execution graph that was created * @param jobVertexId job vertex ID */ protected void checkTaskOffloaded(ExecutionGraph eg, JobVertexID jobVertexId) throws Exception { assertTrue(eg.getJobVertex(jobVertexId).getTaskInformationOrBlobKey().isLeft()); } @Test public void testBuildDeploymentDescriptor() { try { final JobID jobId = new JobID(); final JobVertexID jid1 = new JobVertexID(); final JobVertexID jid2 = new JobVertexID(); final JobVertexID jid3 = new JobVertexID(); final JobVertexID jid4 = new JobVertexID(); JobVertex v1 = new JobVertex("v1", jid1); JobVertex v2 = new JobVertex("v2", jid2); JobVertex v3 = new JobVertex("v3", jid3); JobVertex v4 = new JobVertex("v4", jid4); v1.setParallelism(10); v2.setParallelism(10); v3.setParallelism(10); v4.setParallelism(10); v1.setInvokableClass(BatchTask.class); v2.setInvokableClass(BatchTask.class); v3.setInvokableClass(BatchTask.class); v4.setInvokableClass(BatchTask.class); v2.connectNewDataSetAsInput(v1, DistributionPattern.ALL_TO_ALL, ResultPartitionType.PIPELINED); v3.connectNewDataSetAsInput(v2, DistributionPattern.ALL_TO_ALL, ResultPartitionType.PIPELINED); v4.connectNewDataSetAsInput(v2, DistributionPattern.ALL_TO_ALL, ResultPartitionType.PIPELINED); DirectScheduledExecutorService executor = new DirectScheduledExecutorService(); ExecutionGraph eg = TestingExecutionGraphBuilder .newBuilder() .setJobGraph(new JobGraph(jobId, "Test Job")) .setFutureExecutor(executor) .setIoExecutor(executor) .setSlotProvider(new TestingSlotProvider(ignore -> new CompletableFuture<>())) .setBlobWriter(blobWriter) .build(); eg.start(ComponentMainThreadExecutorServiceAdapter.forMainThread()); checkJobOffloaded(eg); List<JobVertex> ordered = Arrays.asList(v1, v2, v3, v4); eg.attachJobGraph(ordered); ExecutionJobVertex ejv = eg.getAllVertices().get(jid2); ExecutionVertex vertex = ejv.getTaskVertices()[3]; final SimpleAckingTaskManagerGateway taskManagerGateway = new SimpleAckingTaskManagerGateway(); final CompletableFuture<TaskDeploymentDescriptor> tdd = new CompletableFuture<>(); taskManagerGateway.setSubmitConsumer(FunctionUtils.uncheckedConsumer(taskDeploymentDescriptor -> { taskDeploymentDescriptor.loadBigData(blobCache); tdd.complete(taskDeploymentDescriptor); })); final LogicalSlot slot = new TestingLogicalSlotBuilder().setTaskManagerGateway(taskManagerGateway).createTestingLogicalSlot(); assertEquals(ExecutionState.CREATED, vertex.getExecutionState()); vertex.getCurrentExecutionAttempt().registerProducedPartitions(slot.getTaskManagerLocation()).get(); vertex.deployToSlot(slot); assertEquals(ExecutionState.DEPLOYING, vertex.getExecutionState()); checkTaskOffloaded(eg, vertex.getJobvertexId()); TaskDeploymentDescriptor descr = tdd.get(); assertNotNull(descr); JobInformation jobInformation = descr.getSerializedJobInformation().deserializeValue(getClass().getClassLoader()); TaskInformation taskInformation = descr.getSerializedTaskInformation().deserializeValue(getClass().getClassLoader()); assertEquals(jobId, descr.getJobId()); assertEquals(jobId, jobInformation.getJobId()); assertEquals(jid2, taskInformation.getJobVertexId()); assertEquals(3, descr.getSubtaskIndex()); assertEquals(10, taskInformation.getNumberOfSubtasks()); assertEquals(BatchTask.class.getName(), taskInformation.getInvokableClassName()); assertEquals("v2", taskInformation.getTaskName()); Collection<ResultPartitionDeploymentDescriptor> producedPartitions = descr.getProducedPartitions(); Collection<InputGateDeploymentDescriptor> consumedPartitions = descr.getInputGates(); assertEquals(2, producedPartitions.size()); assertEquals(1, consumedPartitions.size()); Iterator<ResultPartitionDeploymentDescriptor> iteratorProducedPartitions = producedPartitions.iterator(); Iterator<InputGateDeploymentDescriptor> iteratorConsumedPartitions = consumedPartitions.iterator(); assertEquals(10, iteratorProducedPartitions.next().getNumberOfSubpartitions()); assertEquals(10, iteratorProducedPartitions.next().getNumberOfSubpartitions()); assertEquals(10, iteratorConsumedPartitions.next().getShuffleDescriptors().length); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testRegistrationOfExecutionsFinishing() { try { final JobVertexID jid1 = new JobVertexID(); final JobVertexID jid2 = new JobVertexID(); JobVertex v1 = new JobVertex("v1", jid1); JobVertex v2 = new JobVertex("v2", jid2); Tuple2<ExecutionGraph, Map<ExecutionAttemptID, Execution>> graphExecutionsTuple = setupExecution(v1, 7650, v2, 2350); ExecutionGraph testExecutionGraph = graphExecutionsTuple.f0; Collection<Execution> executions = new ArrayList<>(graphExecutionsTuple.f1.values()); for (Execution e : executions) { e.markFinished(); } assertEquals(0, testExecutionGraph.getRegisteredExecutions().size()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testRegistrationOfExecutionsFailing() { try { final JobVertexID jid1 = new JobVertexID(); final JobVertexID jid2 = new JobVertexID(); JobVertex v1 = new JobVertex("v1", jid1); JobVertex v2 = new JobVertex("v2", jid2); Tuple2<ExecutionGraph, Map<ExecutionAttemptID, Execution>> graphExecutionsTuple = setupExecution(v1, 7, v2, 6); ExecutionGraph testExecutionGraph = graphExecutionsTuple.f0; Collection<Execution> executions = new ArrayList<>(graphExecutionsTuple.f1.values()); for (Execution e : executions) { e.markFailed(null); } assertEquals(0, testExecutionGraph.getRegisteredExecutions().size()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testRegistrationOfExecutionsFailedExternally() { try { final JobVertexID jid1 = new JobVertexID(); final JobVertexID jid2 = new JobVertexID(); JobVertex v1 = new JobVertex("v1", jid1); JobVertex v2 = new JobVertex("v2", jid2); Tuple2<ExecutionGraph, Map<ExecutionAttemptID, Execution>> graphExecutionsTuple = setupExecution(v1, 7, v2, 6); ExecutionGraph testExecutionGraph = graphExecutionsTuple.f0; Collection<Execution> executions = new ArrayList<>(graphExecutionsTuple.f1.values()); for (Execution e : executions) { e.fail(null); } assertEquals(0, testExecutionGraph.getRegisteredExecutions().size()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } /** * Verifies that {@link ExecutionGraph#updateState(TaskExecutionState)} updates the accumulators and metrics for an * execution that failed or was canceled. */ @Test public void testAccumulatorsAndMetricsForwarding() throws Exception { final JobVertexID jid1 = new JobVertexID(); final JobVertexID jid2 = new JobVertexID(); JobVertex v1 = new JobVertex("v1", jid1); JobVertex v2 = new JobVertex("v2", jid2); Tuple2<ExecutionGraph, Map<ExecutionAttemptID, Execution>> graphAndExecutions = setupExecution(v1, 1, v2, 1); ExecutionGraph graph = graphAndExecutions.f0; // verify behavior for canceled executions Execution execution1 = graphAndExecutions.f1.values().iterator().next(); IOMetrics ioMetrics = new IOMetrics(0, 0, 0, 0); Map<String, Accumulator<?, ?>> accumulators = new HashMap<>(); accumulators.put("acc", new IntCounter(4)); AccumulatorSnapshot accumulatorSnapshot = new AccumulatorSnapshot(graph.getJobID(), execution1.getAttemptId(), accumulators); TaskExecutionState state = new TaskExecutionState(graph.getJobID(), execution1.getAttemptId(), ExecutionState.CANCELED, null, accumulatorSnapshot, ioMetrics); graph.updateState(state); assertEquals(ioMetrics, execution1.getIOMetrics()); assertNotNull(execution1.getUserAccumulators()); assertEquals(4, execution1.getUserAccumulators().get("acc").getLocalValue()); // verify behavior for failed executions Execution execution2 = graphAndExecutions.f1.values().iterator().next(); IOMetrics ioMetrics2 = new IOMetrics(0, 0, 0, 0); Map<String, Accumulator<?, ?>> accumulators2 = new HashMap<>(); accumulators2.put("acc", new IntCounter(8)); AccumulatorSnapshot accumulatorSnapshot2 = new AccumulatorSnapshot(graph.getJobID(), execution2.getAttemptId(), accumulators2); TaskExecutionState state2 = new TaskExecutionState(graph.getJobID(), execution2.getAttemptId(), ExecutionState.FAILED, null, accumulatorSnapshot2, ioMetrics2); graph.updateState(state2); assertEquals(ioMetrics2, execution2.getIOMetrics()); assertNotNull(execution2.getUserAccumulators()); assertEquals(8, execution2.getUserAccumulators().get("acc").getLocalValue()); } /** * Verifies that {@link Execution#completeCancelling(Map, IOMetrics, boolean)} * and {@link Execution#markFailed(Throwable, boolean, Map, IOMetrics, boolean, boolean)} * store the given accumulators and metrics correctly. */ @Test public void testAccumulatorsAndMetricsStorage() throws Exception { final JobVertexID jid1 = new JobVertexID(); final JobVertexID jid2 = new JobVertexID(); JobVertex v1 = new JobVertex("v1", jid1); JobVertex v2 = new JobVertex("v2", jid2); Map<ExecutionAttemptID, Execution> executions = setupExecution(v1, 1, v2, 1).f1; IOMetrics ioMetrics = new IOMetrics(0, 0, 0, 0); Map<String, Accumulator<?, ?>> accumulators = Collections.emptyMap(); Execution execution1 = executions.values().iterator().next(); execution1.cancel(); execution1.completeCancelling(accumulators, ioMetrics, false); assertEquals(ioMetrics, execution1.getIOMetrics()); assertEquals(accumulators, execution1.getUserAccumulators()); Execution execution2 = executions.values().iterator().next(); execution2.markFailed(new Throwable(), false, accumulators, ioMetrics, false, true); assertEquals(ioMetrics, execution2.getIOMetrics()); assertEquals(accumulators, execution2.getUserAccumulators()); } @Test public void testRegistrationOfExecutionsCanceled() { try { final JobVertexID jid1 = new JobVertexID(); final JobVertexID jid2 = new JobVertexID(); JobVertex v1 = new JobVertex("v1", jid1); JobVertex v2 = new JobVertex("v2", jid2); Tuple2<ExecutionGraph, Map<ExecutionAttemptID, Execution>> graphExecutionsTuple = setupExecution(v1, 19, v2, 37); ExecutionGraph testExecutionGraph = graphExecutionsTuple.f0; Collection<Execution> executions = new ArrayList<>(graphExecutionsTuple.f1.values()); for (Execution e : executions) { e.cancel(); e.completeCancelling(); } assertEquals(0, testExecutionGraph.getRegisteredExecutions().size()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } /** * Tests that a blocking batch job fails if there are not enough resources left to schedule the * succeeding tasks. This test case is related to [FLINK-4296] where finished producing tasks * swallow the fail exception when scheduling a consumer task. */ @Test public void testNoResourceAvailableFailure() throws Exception { final JobID jobId = new JobID(); JobVertex v1 = new JobVertex("source"); JobVertex v2 = new JobVertex("sink"); int dop1 = 1; int dop2 = 1; v1.setParallelism(dop1); v2.setParallelism(dop2); v1.setInvokableClass(BatchTask.class); v2.setInvokableClass(BatchTask.class); v2.connectNewDataSetAsInput(v1, DistributionPattern.POINTWISE, ResultPartitionType.BLOCKING); final ArrayDeque<CompletableFuture<LogicalSlot>> slotFutures = new ArrayDeque<>(); for (int i = 0; i < dop1; i++) { slotFutures.addLast(CompletableFuture.completedFuture(new TestingLogicalSlotBuilder().createTestingLogicalSlot())); } final SlotProvider slotProvider = new TestingSlotProvider(ignore -> slotFutures.removeFirst()); DirectScheduledExecutorService directExecutor = new DirectScheduledExecutorService(); // execution graph that executes actions synchronously ExecutionGraph eg = TestingExecutionGraphBuilder .newBuilder() .setJobGraph(new JobGraph(jobId, "Test Job")) .setFutureExecutor(directExecutor) .setSlotProvider(slotProvider) .setBlobWriter(blobWriter) .build(); eg.start(ComponentMainThreadExecutorServiceAdapter.forMainThread()); checkJobOffloaded(eg); List<JobVertex> ordered = Arrays.asList(v1, v2); eg.attachJobGraph(ordered); // schedule, this triggers mock deployment eg.scheduleForExecution(); ExecutionAttemptID attemptID = eg.getJobVertex(v1.getID()).getTaskVertices()[0].getCurrentExecutionAttempt().getAttemptId(); eg.updateState(new TaskExecutionState(jobId, attemptID, ExecutionState.RUNNING)); eg.updateState(new TaskExecutionState(jobId, attemptID, ExecutionState.FINISHED, null)); assertEquals(JobStatus.FAILED, eg.getState()); } // ------------------------------------------------------------------------ // retained checkpoints config test // ------------------------------------------------------------------------ @Test public void testSettingDefaultMaxNumberOfCheckpointsToRetain() throws Exception { final Configuration jobManagerConfig = new Configuration(); final ExecutionGraph eg = createExecutionGraph(jobManagerConfig); assertEquals(CheckpointingOptions.MAX_RETAINED_CHECKPOINTS.defaultValue().intValue(), eg.getCheckpointCoordinator().getCheckpointStore().getMaxNumberOfRetainedCheckpoints()); } @Test public void testSettingMaxNumberOfCheckpointsToRetain() throws Exception { final int maxNumberOfCheckpointsToRetain = 10; final Configuration jobManagerConfig = new Configuration(); jobManagerConfig.setInteger(CheckpointingOptions.MAX_RETAINED_CHECKPOINTS, maxNumberOfCheckpointsToRetain); final ExecutionGraph eg = createExecutionGraph(jobManagerConfig); assertEquals(maxNumberOfCheckpointsToRetain, eg.getCheckpointCoordinator().getCheckpointStore().getMaxNumberOfRetainedCheckpoints()); } private Tuple2<ExecutionGraph, Map<ExecutionAttemptID, Execution>> setupExecution(JobVertex v1, int dop1, JobVertex v2, int dop2) throws Exception { v1.setParallelism(dop1); v2.setParallelism(dop2); v1.setInvokableClass(BatchTask.class); v2.setInvokableClass(BatchTask.class); final ArrayDeque<CompletableFuture<LogicalSlot>> slotFutures = new ArrayDeque<>(); for (int i = 0; i < dop1 + dop2; i++) { slotFutures.addLast(CompletableFuture.completedFuture(new TestingLogicalSlotBuilder().createTestingLogicalSlot())); } final SlotProvider slotProvider = new TestingSlotProvider(ignore -> slotFutures.removeFirst()); DirectScheduledExecutorService executorService = new DirectScheduledExecutorService(); // execution graph that executes actions synchronously ExecutionGraph eg = TestingExecutionGraphBuilder .newBuilder() .setFutureExecutor(executorService) .setSlotProvider(slotProvider) .setBlobWriter(blobWriter) .build(); checkJobOffloaded(eg); eg.start(ComponentMainThreadExecutorServiceAdapter.forMainThread()); List<JobVertex> ordered = Arrays.asList(v1, v2); eg.attachJobGraph(ordered); // schedule, this triggers mock deployment eg.scheduleForExecution(); Map<ExecutionAttemptID, Execution> executions = eg.getRegisteredExecutions(); assertEquals(dop1 + dop2, executions.size()); return new Tuple2<>(eg, executions); } @Test public void testSettingIllegalMaxNumberOfCheckpointsToRetain() throws Exception { final int negativeMaxNumberOfCheckpointsToRetain = -10; final Configuration jobManagerConfig = new Configuration(); jobManagerConfig.setInteger(CheckpointingOptions.MAX_RETAINED_CHECKPOINTS, negativeMaxNumberOfCheckpointsToRetain); final ExecutionGraph eg = createExecutionGraph(jobManagerConfig); assertNotEquals(negativeMaxNumberOfCheckpointsToRetain, eg.getCheckpointCoordinator().getCheckpointStore().getMaxNumberOfRetainedCheckpoints()); assertEquals(CheckpointingOptions.MAX_RETAINED_CHECKPOINTS.defaultValue().intValue(), eg.getCheckpointCoordinator().getCheckpointStore().getMaxNumberOfRetainedCheckpoints()); } /** * Tests that eager scheduling will wait until all input locations have been set before * scheduling a task. */ @Test public void testEagerSchedulingWaitsOnAllInputPreferredLocations() throws Exception { final int parallelism = 2; final ProgrammedSlotProvider slotProvider = new ProgrammedSlotProvider(parallelism); final Time timeout = Time.hours(1L); final JobVertexID sourceVertexId = new JobVertexID(); final JobVertex sourceVertex = new JobVertex("Test source", sourceVertexId); sourceVertex.setInvokableClass(NoOpInvokable.class); sourceVertex.setParallelism(parallelism); final JobVertexID sinkVertexId = new JobVertexID(); final JobVertex sinkVertex = new JobVertex("Test sink", sinkVertexId); sinkVertex.setInvokableClass(NoOpInvokable.class); sinkVertex.setParallelism(parallelism); sinkVertex.connectNewDataSetAsInput(sourceVertex, DistributionPattern.ALL_TO_ALL, ResultPartitionType.PIPELINED); final Map<JobVertexID, CompletableFuture<LogicalSlot>[]> slotFutures = new HashMap<>(2); for (JobVertexID jobVertexID : Arrays.asList(sourceVertexId, sinkVertexId)) { CompletableFuture<LogicalSlot>[] slotFutureArray = new CompletableFuture[parallelism]; for (int i = 0; i < parallelism; i++) { slotFutureArray[i] = new CompletableFuture<>(); } slotFutures.put(jobVertexID, slotFutureArray); slotProvider.addSlots(jobVertexID, slotFutureArray); } final ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(3); final JobGraph jobGraph = new JobGraph(sourceVertex, sinkVertex); jobGraph.setScheduleMode(ScheduleMode.EAGER); final ExecutionGraph executionGraph = TestingExecutionGraphBuilder .newBuilder() .setJobGraph(jobGraph) .setSlotProvider(slotProvider) .setIoExecutor(scheduledExecutorService) .setFutureExecutor(scheduledExecutorService) .setAllocationTimeout(timeout) .setRpcTimeout(timeout) .build(); executionGraph.start(ComponentMainThreadExecutorServiceAdapter.forMainThread()); executionGraph.scheduleForExecution(); // all tasks should be in state SCHEDULED for (ExecutionVertex executionVertex : executionGraph.getAllExecutionVertices()) { assertEquals(ExecutionState.SCHEDULED, executionVertex.getCurrentExecutionAttempt().getState()); } // wait until the source vertex slots have been requested assertTrue(slotProvider.getSlotRequestedFuture(sourceVertexId, 0).get()); assertTrue(slotProvider.getSlotRequestedFuture(sourceVertexId, 1).get()); // check that the sinks have not requested their slots because they need the location // information of the sources assertFalse(slotProvider.getSlotRequestedFuture(sinkVertexId, 0).isDone()); assertFalse(slotProvider.getSlotRequestedFuture(sinkVertexId, 1).isDone()); final TaskManagerLocation localTaskManagerLocation = new LocalTaskManagerLocation(); final LogicalSlot sourceSlot1 = createSlot(localTaskManagerLocation, 0); final LogicalSlot sourceSlot2 = createSlot(localTaskManagerLocation, 1); final LogicalSlot sinkSlot1 = createSlot(localTaskManagerLocation, 0); final LogicalSlot sinkSlot2 = createSlot(localTaskManagerLocation, 1); slotFutures.get(sourceVertexId)[0].complete(sourceSlot1); slotFutures.get(sourceVertexId)[1].complete(sourceSlot2); // wait until the sink vertex slots have been requested after we completed the source slots assertTrue(slotProvider.getSlotRequestedFuture(sinkVertexId, 0).get()); assertTrue(slotProvider.getSlotRequestedFuture(sinkVertexId, 1).get()); slotFutures.get(sinkVertexId)[0].complete(sinkSlot1); slotFutures.get(sinkVertexId)[1].complete(sinkSlot2); for (ExecutionVertex executionVertex : executionGraph.getAllExecutionVertices()) { ExecutionGraphTestUtils.waitUntilExecutionState(executionVertex.getCurrentExecutionAttempt(), ExecutionState.DEPLOYING, 5000L); } } /** * Tests that the {@link ExecutionGraph} is deployed in topological order. */ @Test public void testExecutionGraphIsDeployedInTopologicalOrder() throws Exception { final int sourceParallelism = 2; final int sinkParallelism = 1; final JobVertex sourceVertex = new JobVertex("source"); sourceVertex.setInvokableClass(NoOpInvokable.class); sourceVertex.setParallelism(sourceParallelism); final JobVertex sinkVertex = new JobVertex("sink"); sinkVertex.setInvokableClass(NoOpInvokable.class); sinkVertex.setParallelism(sinkParallelism); sinkVertex.connectNewDataSetAsInput(sourceVertex, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED); final JobID jobId = new JobID(); final int numberTasks = sourceParallelism + sinkParallelism; final ArrayBlockingQueue<ExecutionAttemptID> submittedTasksQueue = new ArrayBlockingQueue<>(numberTasks); TestingTaskExecutorGatewayBuilder testingTaskExecutorGatewayBuilder = new TestingTaskExecutorGatewayBuilder(); testingTaskExecutorGatewayBuilder.setSubmitTaskConsumer((taskDeploymentDescriptor, jobMasterId) -> { submittedTasksQueue.offer(taskDeploymentDescriptor.getExecutionAttemptId()); return CompletableFuture.completedFuture(Acknowledge.get()); }); final TestingTaskExecutorGateway taskExecutorGateway = testingTaskExecutorGatewayBuilder.createTestingTaskExecutorGateway(); final RpcTaskManagerGateway taskManagerGateway = new RpcTaskManagerGateway(taskExecutorGateway, JobMasterId.generate()); final Collection<CompletableFuture<LogicalSlot>> slotFutures = new ArrayList<>(numberTasks); for (int i = 0; i < numberTasks; i++) { slotFutures.add(new CompletableFuture<>()); } final SlotProvider slotProvider = new IteratorTestingSlotProvider(slotFutures.iterator()); final JobGraph jobGraph = new JobGraph(jobId, "Test Job", sourceVertex, sinkVertex); jobGraph.setScheduleMode(ScheduleMode.EAGER); final ExecutionGraph executionGraph = TestingExecutionGraphBuilder .newBuilder() .setJobGraph(jobGraph) .setSlotProvider(slotProvider) .setFutureExecutor(new DirectScheduledExecutorService()) .build(); executionGraph.start(ComponentMainThreadExecutorServiceAdapter.forMainThread()); executionGraph.scheduleForExecution(); // change the order in which the futures are completed final List<CompletableFuture<LogicalSlot>> shuffledFutures = new ArrayList<>(slotFutures); Collections.shuffle(shuffledFutures); for (CompletableFuture<LogicalSlot> slotFuture : shuffledFutures) { slotFuture.complete(new TestingLogicalSlotBuilder().setTaskManagerGateway(taskManagerGateway).createTestingLogicalSlot()); } final List<ExecutionAttemptID> submittedTasks = new ArrayList<>(numberTasks); for (int i = 0; i < numberTasks; i++) { submittedTasks.add(submittedTasksQueue.take()); } final Collection<ExecutionAttemptID> firstStage = new ArrayList<>(sourceParallelism); for (ExecutionVertex taskVertex : executionGraph.getJobVertex(sourceVertex.getID()).getTaskVertices()) { firstStage.add(taskVertex.getCurrentExecutionAttempt().getAttemptId()); } final Collection<ExecutionAttemptID> secondStage = new ArrayList<>(sinkParallelism); for (ExecutionVertex taskVertex : executionGraph.getJobVertex(sinkVertex.getID()).getTaskVertices()) { secondStage.add(taskVertex.getCurrentExecutionAttempt().getAttemptId()); } assertThat(submittedTasks, new ExecutionStageMatcher(Arrays.asList(firstStage, secondStage))); } private static final class IteratorTestingSlotProvider extends TestingSlotProvider { private IteratorTestingSlotProvider(final Iterator<CompletableFuture<LogicalSlot>> slotIterator) { super(new IteratorSlotFutureFunction(slotIterator)); } private static class IteratorSlotFutureFunction implements Function<SlotRequestId, CompletableFuture<LogicalSlot>> { final Iterator<CompletableFuture<LogicalSlot>> slotIterator; IteratorSlotFutureFunction(Iterator<CompletableFuture<LogicalSlot>> slotIterator) { this.slotIterator = slotIterator; } @Override public CompletableFuture<LogicalSlot> apply(SlotRequestId slotRequestId) { if (slotIterator.hasNext()) { return slotIterator.next(); } else { return FutureUtils.completedExceptionally(new FlinkException("No more slots available.")); } } } } private LogicalSlot createSlot(TaskManagerLocation taskManagerLocation, int index) { return new TestingLogicalSlotBuilder() .setTaskManagerLocation(taskManagerLocation) .setSlotNumber(index) .createTestingLogicalSlot(); } private ExecutionGraph createExecutionGraph(Configuration configuration) throws Exception { final ScheduledExecutorService executor = TestingUtils.defaultExecutor(); final JobID jobId = new JobID(); final JobGraph jobGraph = new JobGraph(jobId, "test"); jobGraph.setSnapshotSettings( new JobCheckpointingSettings( Collections.<JobVertexID>emptyList(), Collections.<JobVertexID>emptyList(), Collections.<JobVertexID>emptyList(), new CheckpointCoordinatorConfiguration( 100, 10 * 60 * 1000, 0, 1, CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, false, false, false, 0), null)); final Time timeout = Time.seconds(10L); return ExecutionGraphBuilder.buildGraph( null, jobGraph, configuration, executor, executor, new ProgrammedSlotProvider(1), getClass().getClassLoader(), new StandaloneCheckpointRecoveryFactory(), timeout, new NoRestartStrategy(), new UnregisteredMetricsGroup(), blobWriter, timeout, LoggerFactory.getLogger(getClass()), NettyShuffleMaster.INSTANCE, NoOpJobMasterPartitionTracker.INSTANCE, System.currentTimeMillis()); } private static final class ExecutionStageMatcher extends TypeSafeMatcher<List<ExecutionAttemptID>> { private final List<Collection<ExecutionAttemptID>> executionStages; private ExecutionStageMatcher(List<Collection<ExecutionAttemptID>> executionStages) { this.executionStages = executionStages; } @Override protected boolean matchesSafely(List<ExecutionAttemptID> submissionOrder) { final Iterator<ExecutionAttemptID> submissionIterator = submissionOrder.iterator(); for (Collection<ExecutionAttemptID> stage : executionStages) { final Collection<ExecutionAttemptID> currentStage = new ArrayList<>(stage); while (!currentStage.isEmpty() && submissionIterator.hasNext()) { if (!currentStage.remove(submissionIterator.next())) { return false; } } if (!currentStage.isEmpty()) { return false; } } return !submissionIterator.hasNext(); } @Override public void describeTo(Description description) { description.appendValueList("<[", ", ", "]>", executionStages); } } }
/** * 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.tools.mapred; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.mapreduce.*; import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl; import org.apache.hadoop.mapreduce.task.JobContextImpl; import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat; import org.apache.hadoop.tools.CopyListing; import org.apache.hadoop.tools.DistCpConstants; import org.apache.hadoop.tools.DistCpOptions; import org.apache.hadoop.tools.DistCpOptions.FileAttribute; import org.apache.hadoop.tools.GlobbedCopyListing; import org.apache.hadoop.tools.util.TestDistCpUtils; import org.apache.hadoop.security.Credentials; import org.junit.*; import java.io.IOException; import java.util.*; public class TestCopyCommitter { private static final Log LOG = LogFactory.getLog(TestCopyCommitter.class); private static final Random rand = new Random(); private static final Credentials CREDENTIALS = new Credentials(); public static final int PORT = 39737; private static Configuration config; private static MiniDFSCluster cluster; private static Job getJobForClient() throws IOException { Job job = Job.getInstance(new Configuration()); job.getConfiguration().set("mapred.job.tracker", "localhost:" + PORT); job.setInputFormatClass(NullInputFormat.class); job.setOutputFormatClass(NullOutputFormat.class); job.setNumReduceTasks(0); return job; } @BeforeClass public static void create() throws IOException { config = getJobForClient().getConfiguration(); config.setLong(DistCpConstants.CONF_LABEL_TOTAL_BYTES_TO_BE_COPIED, 0); cluster = new MiniDFSCluster.Builder(config).numDataNodes(1).format(true) .build(); } @AfterClass public static void destroy() { if (cluster != null) { cluster.shutdown(); } } @Before public void createMetaFolder() { config.set(DistCpConstants.CONF_LABEL_META_FOLDER, "/meta"); Path meta = new Path("/meta"); try { cluster.getFileSystem().mkdirs(meta); } catch (IOException e) { LOG.error("Exception encountered while creating meta folder", e); Assert.fail("Unable to create meta folder"); } } @After public void cleanupMetaFolder() { Path meta = new Path("/meta"); try { if (cluster.getFileSystem().exists(meta)) { cluster.getFileSystem().delete(meta, true); Assert.fail("Expected meta folder to be deleted"); } } catch (IOException e) { LOG.error("Exception encountered while cleaning up folder", e); Assert.fail("Unable to clean up meta folder"); } } @Test public void testNoCommitAction() { TaskAttemptContext taskAttemptContext = getTaskAttemptContext(config); JobContext jobContext = new JobContextImpl(taskAttemptContext.getConfiguration(), taskAttemptContext.getTaskAttemptID().getJobID()); try { OutputCommitter committer = new CopyCommitter(null, taskAttemptContext); committer.commitJob(jobContext); Assert.assertEquals(taskAttemptContext.getStatus(), "Commit Successful"); //Test for idempotent commit committer.commitJob(jobContext); Assert.assertEquals(taskAttemptContext.getStatus(), "Commit Successful"); } catch (IOException e) { LOG.error("Exception encountered ", e); Assert.fail("Commit failed"); } } @Test public void testPreserveStatus() { TaskAttemptContext taskAttemptContext = getTaskAttemptContext(config); JobContext jobContext = new JobContextImpl(taskAttemptContext.getConfiguration(), taskAttemptContext.getTaskAttemptID().getJobID()); Configuration conf = jobContext.getConfiguration(); String sourceBase; String targetBase; FileSystem fs = null; try { OutputCommitter committer = new CopyCommitter(null, taskAttemptContext); fs = FileSystem.get(conf); FsPermission sourcePerm = new FsPermission((short) 511); FsPermission initialPerm = new FsPermission((short) 448); sourceBase = TestDistCpUtils.createTestSetup(fs, sourcePerm); targetBase = TestDistCpUtils.createTestSetup(fs, initialPerm); DistCpOptions options = new DistCpOptions(Arrays.asList(new Path(sourceBase)), new Path("/out")); options.preserve(FileAttribute.PERMISSION); options.appendToConf(conf); options.setTargetPathExists(false); CopyListing listing = new GlobbedCopyListing(conf, CREDENTIALS); Path listingFile = new Path("/tmp1/" + String.valueOf(rand.nextLong())); listing.buildListing(listingFile, options); conf.set(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH, targetBase); committer.commitJob(jobContext); if (!checkDirectoryPermissions(fs, targetBase, sourcePerm)) { Assert.fail("Permission don't match"); } //Test for idempotent commit committer.commitJob(jobContext); if (!checkDirectoryPermissions(fs, targetBase, sourcePerm)) { Assert.fail("Permission don't match"); } } catch (IOException e) { LOG.error("Exception encountered while testing for preserve status", e); Assert.fail("Preserve status failure"); } finally { TestDistCpUtils.delete(fs, "/tmp1"); conf.unset(DistCpConstants.CONF_LABEL_PRESERVE_STATUS); } } @Test public void testDeleteMissing() { TaskAttemptContext taskAttemptContext = getTaskAttemptContext(config); JobContext jobContext = new JobContextImpl(taskAttemptContext.getConfiguration(), taskAttemptContext.getTaskAttemptID().getJobID()); Configuration conf = jobContext.getConfiguration(); String sourceBase; String targetBase; FileSystem fs = null; try { OutputCommitter committer = new CopyCommitter(null, taskAttemptContext); fs = FileSystem.get(conf); sourceBase = TestDistCpUtils.createTestSetup(fs, FsPermission.getDefault()); targetBase = TestDistCpUtils.createTestSetup(fs, FsPermission.getDefault()); String targetBaseAdd = TestDistCpUtils.createTestSetup(fs, FsPermission.getDefault()); fs.rename(new Path(targetBaseAdd), new Path(targetBase)); DistCpOptions options = new DistCpOptions(Arrays.asList(new Path(sourceBase)), new Path("/out")); options.setSyncFolder(true); options.setDeleteMissing(true); options.appendToConf(conf); CopyListing listing = new GlobbedCopyListing(conf, CREDENTIALS); Path listingFile = new Path("/tmp1/" + String.valueOf(rand.nextLong())); listing.buildListing(listingFile, options); conf.set(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH, targetBase); conf.set(DistCpConstants.CONF_LABEL_TARGET_FINAL_PATH, targetBase); committer.commitJob(jobContext); if (!TestDistCpUtils.checkIfFoldersAreInSync(fs, targetBase, sourceBase)) { Assert.fail("Source and target folders are not in sync"); } if (!TestDistCpUtils.checkIfFoldersAreInSync(fs, sourceBase, targetBase)) { Assert.fail("Source and target folders are not in sync"); } //Test for idempotent commit committer.commitJob(jobContext); if (!TestDistCpUtils.checkIfFoldersAreInSync(fs, targetBase, sourceBase)) { Assert.fail("Source and target folders are not in sync"); } if (!TestDistCpUtils.checkIfFoldersAreInSync(fs, sourceBase, targetBase)) { Assert.fail("Source and target folders are not in sync"); } } catch (Throwable e) { LOG.error("Exception encountered while testing for delete missing", e); Assert.fail("Delete missing failure"); } finally { TestDistCpUtils.delete(fs, "/tmp1"); conf.set(DistCpConstants.CONF_LABEL_DELETE_MISSING, "false"); } } @Test public void testDeleteMissingFlatInterleavedFiles() { TaskAttemptContext taskAttemptContext = getTaskAttemptContext(config); JobContext jobContext = new JobContextImpl(taskAttemptContext.getConfiguration(), taskAttemptContext.getTaskAttemptID().getJobID()); Configuration conf = jobContext.getConfiguration(); String sourceBase; String targetBase; FileSystem fs = null; try { OutputCommitter committer = new CopyCommitter(null, taskAttemptContext); fs = FileSystem.get(conf); sourceBase = "/tmp1/" + String.valueOf(rand.nextLong()); targetBase = "/tmp1/" + String.valueOf(rand.nextLong()); TestDistCpUtils.createFile(fs, sourceBase + "/1"); TestDistCpUtils.createFile(fs, sourceBase + "/3"); TestDistCpUtils.createFile(fs, sourceBase + "/4"); TestDistCpUtils.createFile(fs, sourceBase + "/5"); TestDistCpUtils.createFile(fs, sourceBase + "/7"); TestDistCpUtils.createFile(fs, sourceBase + "/8"); TestDistCpUtils.createFile(fs, sourceBase + "/9"); TestDistCpUtils.createFile(fs, targetBase + "/2"); TestDistCpUtils.createFile(fs, targetBase + "/4"); TestDistCpUtils.createFile(fs, targetBase + "/5"); TestDistCpUtils.createFile(fs, targetBase + "/7"); TestDistCpUtils.createFile(fs, targetBase + "/9"); TestDistCpUtils.createFile(fs, targetBase + "/A"); DistCpOptions options = new DistCpOptions(Arrays.asList(new Path(sourceBase)), new Path("/out")); options.setSyncFolder(true); options.setDeleteMissing(true); options.appendToConf(conf); CopyListing listing = new GlobbedCopyListing(conf, CREDENTIALS); Path listingFile = new Path("/tmp1/" + String.valueOf(rand.nextLong())); listing.buildListing(listingFile, options); conf.set(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH, targetBase); conf.set(DistCpConstants.CONF_LABEL_TARGET_FINAL_PATH, targetBase); committer.commitJob(jobContext); if (!TestDistCpUtils.checkIfFoldersAreInSync(fs, targetBase, sourceBase)) { Assert.fail("Source and target folders are not in sync"); } Assert.assertEquals(fs.listStatus(new Path(targetBase)).length, 4); //Test for idempotent commit committer.commitJob(jobContext); if (!TestDistCpUtils.checkIfFoldersAreInSync(fs, targetBase, sourceBase)) { Assert.fail("Source and target folders are not in sync"); } Assert.assertEquals(fs.listStatus(new Path(targetBase)).length, 4); } catch (IOException e) { LOG.error("Exception encountered while testing for delete missing", e); Assert.fail("Delete missing failure"); } finally { TestDistCpUtils.delete(fs, "/tmp1"); conf.set(DistCpConstants.CONF_LABEL_DELETE_MISSING, "false"); } } @Test public void testAtomicCommitMissingFinal() { TaskAttemptContext taskAttemptContext = getTaskAttemptContext(config); JobContext jobContext = new JobContextImpl(taskAttemptContext.getConfiguration(), taskAttemptContext.getTaskAttemptID().getJobID()); Configuration conf = jobContext.getConfiguration(); String workPath = "/tmp1/" + String.valueOf(rand.nextLong()); String finalPath = "/tmp1/" + String.valueOf(rand.nextLong()); FileSystem fs = null; try { OutputCommitter committer = new CopyCommitter(null, taskAttemptContext); fs = FileSystem.get(conf); fs.mkdirs(new Path(workPath)); conf.set(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH, workPath); conf.set(DistCpConstants.CONF_LABEL_TARGET_FINAL_PATH, finalPath); conf.setBoolean(DistCpConstants.CONF_LABEL_ATOMIC_COPY, true); Assert.assertTrue(fs.exists(new Path(workPath))); Assert.assertFalse(fs.exists(new Path(finalPath))); committer.commitJob(jobContext); Assert.assertFalse(fs.exists(new Path(workPath))); Assert.assertTrue(fs.exists(new Path(finalPath))); //Test for idempotent commit committer.commitJob(jobContext); Assert.assertFalse(fs.exists(new Path(workPath))); Assert.assertTrue(fs.exists(new Path(finalPath))); } catch (IOException e) { LOG.error("Exception encountered while testing for preserve status", e); Assert.fail("Atomic commit failure"); } finally { TestDistCpUtils.delete(fs, workPath); TestDistCpUtils.delete(fs, finalPath); conf.setBoolean(DistCpConstants.CONF_LABEL_ATOMIC_COPY, false); } } @Test public void testAtomicCommitExistingFinal() { TaskAttemptContext taskAttemptContext = getTaskAttemptContext(config); JobContext jobContext = new JobContextImpl(taskAttemptContext.getConfiguration(), taskAttemptContext.getTaskAttemptID().getJobID()); Configuration conf = jobContext.getConfiguration(); String workPath = "/tmp1/" + String.valueOf(rand.nextLong()); String finalPath = "/tmp1/" + String.valueOf(rand.nextLong()); FileSystem fs = null; try { OutputCommitter committer = new CopyCommitter(null, taskAttemptContext); fs = FileSystem.get(conf); fs.mkdirs(new Path(workPath)); fs.mkdirs(new Path(finalPath)); conf.set(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH, workPath); conf.set(DistCpConstants.CONF_LABEL_TARGET_FINAL_PATH, finalPath); conf.setBoolean(DistCpConstants.CONF_LABEL_ATOMIC_COPY, true); Assert.assertTrue(fs.exists(new Path(workPath))); Assert.assertTrue(fs.exists(new Path(finalPath))); try { committer.commitJob(jobContext); Assert.fail("Should not be able to atomic-commit to pre-existing path."); } catch(Exception exception) { Assert.assertTrue(fs.exists(new Path(workPath))); Assert.assertTrue(fs.exists(new Path(finalPath))); LOG.info("Atomic-commit Test pass."); } } catch (IOException e) { LOG.error("Exception encountered while testing for atomic commit.", e); Assert.fail("Atomic commit failure"); } finally { TestDistCpUtils.delete(fs, workPath); TestDistCpUtils.delete(fs, finalPath); conf.setBoolean(DistCpConstants.CONF_LABEL_ATOMIC_COPY, false); } } private TaskAttemptContext getTaskAttemptContext(Configuration conf) { return new TaskAttemptContextImpl(conf, new TaskAttemptID("200707121733", 1, TaskType.MAP, 1, 1)); } private boolean checkDirectoryPermissions(FileSystem fs, String targetBase, FsPermission sourcePerm) throws IOException { Path base = new Path(targetBase); Stack<Path> stack = new Stack<Path>(); stack.push(base); while (!stack.isEmpty()) { Path file = stack.pop(); if (!fs.exists(file)) continue; FileStatus[] fStatus = fs.listStatus(file); if (fStatus == null || fStatus.length == 0) continue; for (FileStatus status : fStatus) { if (status.isDirectory()) { stack.push(status.getPath()); Assert.assertEquals(status.getPermission(), sourcePerm); } } } return true; } private static class NullInputFormat extends InputFormat { @Override public List getSplits(JobContext context) throws IOException, InterruptedException { return Collections.EMPTY_LIST; } @Override public RecordReader createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { return null; } } }
/* * Copyright 1997-2015 Optimatika (www.optimatika.se) * * 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.ojalgo.array; import java.util.RandomAccess; import java.util.Spliterator; import org.ojalgo.access.Access1D; import org.ojalgo.access.AccessUtils; import org.ojalgo.function.BinaryFunction; import org.ojalgo.function.NullaryFunction; import org.ojalgo.function.ParameterFunction; import org.ojalgo.function.UnaryFunction; import org.ojalgo.function.VoidFunction; import org.ojalgo.scalar.Scalar; /** * Represents a single dense array - casts long indices to int. * * @author apete */ abstract class DenseArray<N extends Number> extends BasicArray<N>implements RandomAccess { static abstract class DenseFactory<N extends Number> extends ArrayFactory<N> { abstract DenseArray<N> make(int size); @Override final DenseArray<N> makeStructuredZero(final long... structure) { return this.make((int) AccessUtils.count(structure)); } @Override final DenseArray<N> makeToBeFilled(final long... structure) { return this.make((int) AccessUtils.count(structure)); } abstract Scalar<N> zero(); } static final int CHARACTERISTICS = Spliterator.ORDERED | Spliterator.IMMUTABLE; DenseArray() { super(); } public void add(final long index, final double addend) { this.add((int) index, addend); } public void add(final long index, final Number addend) { this.add((int) index, addend); } public final long count() { return this.size(); } public final double doubleValue(final long index) { return this.doubleValue((int) index); } public final void fillAll(final N number) { this.fill(0, this.size(), 1, number); } public final void fillAll(final NullaryFunction<N> supplier) { this.fill(0, this.size(), 1, supplier); } public void fillOne(final long index, final N value) { this.fillOne((int) index, value); } public void fillOne(final long index, final NullaryFunction<N> supplier) { this.fillOne((int) index, supplier); } public final void fillRange(final long first, final long limit, final N number) { this.fill(first, limit, 1L, number); } public final void fillRange(final long first, final long limit, final NullaryFunction<N> supplier) { this.fill(first, limit, 1L, supplier); } public final N get(final long index) { return this.get((int) index); } /** * @see Scalar#isAbsolute() */ public final boolean isAbsolute(final long index) { return this.isAbsolute((int) index); } /** * @see Scalar#isSmall(double) */ public final boolean isSmall(final long index, final double comparedTo) { return this.isSmall((int) index, comparedTo); } public final void modifyOne(final long index, final UnaryFunction<N> function) { this.modify((int) index, function); } public final void set(final long index, final double value) { this.set((int) index, value); } public final void set(final long index, final Number number) { this.set((int) index, number); } public void visitOne(final long index, final VoidFunction<N> visitor) { this.visitOne((int) index, visitor); } private final boolean isSmall(final int first, final int limit, final int step, final double comparedTo) { boolean retVal = true; for (int i = first; retVal && (i < limit); i += step) { retVal &= this.isSmall(i, comparedTo); } return retVal; } protected abstract void add(int index, double addend); protected abstract void add(int index, Number addend); protected abstract double doubleValue(final int index); protected abstract void exchange(int firstA, int firstB, int step, int count); @Override protected final void exchange(final long firstA, final long firstB, final long step, final long count) { this.exchange((int) firstA, (int) firstB, (int) step, (int) count); } protected abstract void fill(final int first, final int limit, final Access1D<N> left, final BinaryFunction<N> function, final Access1D<N> right); protected abstract void fill(final int first, final int limit, final Access1D<N> left, final BinaryFunction<N> function, final N right); protected abstract void fill(int first, int limit, int step, N value); protected abstract void fill(int first, int limit, int step, NullaryFunction<N> supplier); protected abstract void fill(final int first, final int limit, final N left, final BinaryFunction<N> function, final Access1D<N> right); @Override protected final void fill(final long first, final long limit, final long step, final N value) { this.fill((int) first, (int) limit, (int) step, value); } @Override protected final void fill(final long first, final long limit, final long step, final NullaryFunction<N> supplier) { this.fill((int) first, (int) limit, (int) step, supplier); } protected abstract void fillOne(int index, N value); protected abstract void fillOne(int index, NullaryFunction<N> supplier); protected abstract N get(final int index); protected abstract int indexOfLargest(int first, int limit, int step); @Override protected final long indexOfLargest(final long first, final long limit, final long step) { return this.indexOfLargest((int) first, (int) limit, (int) step); } /** * @see Scalar#isAbsolute() */ protected abstract boolean isAbsolute(int index); /** * @see Scalar#isSmall(double) */ protected abstract boolean isSmall(int index, double comparedTo); @Override protected final boolean isSmall(final long first, final long limit, final long step, final double comparedTo) { return this.isSmall((int) first, (int) limit, (int) step, comparedTo); } protected abstract void modify(int index, Access1D<N> left, BinaryFunction<N> function); protected abstract void modify(int index, BinaryFunction<N> function, Access1D<N> right); protected abstract void modify(int first, int limit, int step, Access1D<N> left, BinaryFunction<N> function); protected abstract void modify(int first, int limit, int step, BinaryFunction<N> function, Access1D<N> right); protected abstract void modify(int first, int limit, int step, BinaryFunction<N> function, N right); protected abstract void modify(int first, int limit, int step, N left, BinaryFunction<N> function); protected abstract void modify(int first, int limit, int step, ParameterFunction<N> function, int parameter); protected abstract void modify(int first, int limit, int step, UnaryFunction<N> function); protected abstract void modify(int index, UnaryFunction<N> function); @Override protected final void modify(final long first, final long limit, final long step, final Access1D<N> left, final BinaryFunction<N> function) { this.modify((int) first, (int) limit, (int) step, left, function); } @Override protected final void modify(final long first, final long limit, final long step, final BinaryFunction<N> function, final Access1D<N> right) { this.modify((int) first, (int) limit, (int) step, function, right); } @Override protected final void modify(final long first, final long limit, final long step, final UnaryFunction<N> function) { this.modify((int) first, (int) limit, (int) step, function); } /** * @see java.util.Arrays#binarySearch(Object[], Object) * @see #sortAscending() * @throws UnsupportedOperationException if the this operation is not supported by this * implementation/subclass */ protected abstract int searchAscending(N number); protected abstract void set(final int index, final double value); protected abstract void set(final int index, final Number number); protected abstract int size(); /** * @see java.util.Arrays#sort(Object[]) * @see #searchAscending(Number) * @throws UnsupportedOperationException if the this operation is not supported by this * implementation/subclass */ protected abstract void sortAscending(); protected abstract void visit(int first, int limit, int step, VoidFunction<N> visitor); protected abstract void visit(int index, VoidFunction<N> visitor); @Override protected final void visit(final long first, final long limit, final long step, final VoidFunction<N> visitor) { this.visit((int) first, (int) limit, (int) step, visitor); } protected abstract void visitOne(final int index, final VoidFunction<N> visitor); abstract DenseArray<N> newInstance(int capacity); }
/*L * Copyright Ekagra Software Technologies Ltd. * Copyright SAIC, SAIC-Frederick * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cacore-sdk/LICENSE.txt for details. */ package test.xsd; import gov.nih.nci.cacoresdk.domain.inheritance.implicit.AngelFish; import gov.nih.nci.cacoresdk.domain.inheritance.implicit.DiscusFish; import gov.nih.nci.cacoresdk.domain.inheritance.implicit.Fish; import gov.nih.nci.cacoresdk.domain.inheritance.implicit.FishTank; import gov.nih.nci.cacoresdk.domain.inheritance.implicit.FreshwaterFishTank; import gov.nih.nci.cacoresdk.domain.inheritance.implicit.SaltwaterFishTank; import gov.nih.nci.cacoresdk.domain.inheritance.implicit.Substrate; import gov.nih.nci.cacoresdk.domain.inheritance.implicit.Tank; import gov.nih.nci.cacoresdk.domain.inheritance.implicit.TankAccessory; import org.jdom.Document; public class ImplicitParentWithAssociationXSDTest extends SDKXSDTestBase { private Document doc = null; public static String getTestCaseName() { return "Implicit Parent With Association XSD Test Case"; } protected void setUp() throws Exception { super.setUp(); String schemaFileName = "gov.nih.nci.cacoresdk.domain.inheritance.implicit.xsd"; doc = getDocument(schemaFileName); } public Document getDoc() { return doc; } /** * Uses xpath to query XSD * Verifies that common XSD elements are present * * @throws Exception */ public void testCommonSchemaElements() throws Exception { validateCommonSchemaElements(); } /** * Verifies that the 'element' and 'complexType' elements * corresponding to the Class are present in the XSD * Verifies that the Class attributes are present in the XSD * * @throws Exception */ public void testClassElement1() throws Exception { Class targetClass = Fish.class; validateClassElements(targetClass); validateAttributeElement(targetClass, "id", "ii"); validateAttributeElement(targetClass, "genera", "st.nt"); } /** * Verifies that the 'element' and 'complexType' elements * corresponding to the Subclass are present in the XSD * Verifies that the Class attributes are present in the XSD * * @throws Exception */ public void testClassElement2() throws Exception { Class targetClass = AngelFish.class; validateSubclassElements(targetClass); validateSubclassAttributeElement(targetClass, "finSize","int"); } /** * Verifies that the 'element' and 'complexType' elements * corresponding to the Class are present in the XSD * Verifies that the Class attributes are present in the XSD * * @throws Exception */ public void testClassElement3() throws Exception { Class targetClass = DiscusFish.class; validateSubclassElements(targetClass); validateSubclassAttributeElement(targetClass, "primaryColor", "st"); } /** * Verifies that the 'element' and 'complexType' elements * corresponding to the Class are present in the XSD * Verifies that the Class attributes are present in the XSD * * @throws Exception */ public void testClassElement4() throws Exception { Class targetClass = Tank.class; validateClassElements(targetClass); } /** * Verifies that the 'element' and 'complexType' elements * corresponding to the Class are present in the XSD * Verifies that the Class attributes are present in the XSD * * @throws Exception */ public void testClassElement5() throws Exception { Class targetClass = FishTank.class; validateSubclassElements(targetClass); validateSubclassAttributeElement(targetClass, "id", "ii"); validateSubclassAttributeElement(targetClass, "shape", "st"); validateSubclassAttributeElement(targetClass, "numGallons", "int"); } /** * Verifies that the 'element' and 'complexType' elements * corresponding to the Class are present in the XSD * Verifies that the Class attributes are present in the XSD * * @throws Exception */ public void testClassElement6() throws Exception { Class targetClass = FreshwaterFishTank.class; validateSubclassElements(targetClass); validateSubclassAttributeElement(targetClass, "filterModel", "st"); } /** * Verifies that the 'element' and 'complexType' elements * corresponding to the Class are present in the XSD * Verifies that the Class attributes are present in the XSD * * @throws Exception */ public void testClassElement7() throws Exception { Class targetClass = SaltwaterFishTank.class; validateSubclassElements(targetClass); validateSubclassAttributeElement(targetClass, "proteinSkimmerModel", "st"); } /** * Verifies that the 'element' and 'complexType' elements * corresponding to the Class are present in the XSD * Verifies that the Class attributes are present in the XSD * * @throws Exception */ public void testClassElement8() throws Exception { Class targetClass = TankAccessory.class; validateClassElements(targetClass); validateAttributeElement(targetClass, "id", "ii"); validateAttributeElement(targetClass, "name", "st"); } /** * Verifies that the 'element' and 'complexType' elements * corresponding to the Class are present in the XSD * Verifies that the Class attributes are present in the XSD * * @throws Exception */ public void testClassElement9() throws Exception { Class targetClass = Substrate.class; validateClassElements(targetClass); validateAttributeElement(targetClass, "id", "ii"); validateAttributeElement(targetClass, "name", "st"); } /** * Verifies that association elements * corresponding to the Class are present in the XSD * Verifies that the Class attributes are present in the XSD * * @throws Exception */ public void testAssociationElements2() throws Exception { Class targetClass = Fish.class; Class associatedClass = Tank.class; validateClassAssociationElements(targetClass, associatedClass, "tank","1","1"); } /** * Verifies that association elements * corresponding to the Class are present in the XSD * Verifies that the Class attributes are present in the XSD * * @throws Exception */ public void testAssociationElements4() throws Exception { Class targetClass = TankAccessory.class; Class associatedClass = Tank.class; validateClassAssociationElements(targetClass, associatedClass, "tankCollection","0","1"); } /** * Verifies that association elements * corresponding to the Class are present in the XSD * Verifies that the Class attributes are present in the XSD * * @throws Exception */ public void testAssociationElements5() throws Exception { Class targetClass = SaltwaterFishTank.class; Class associatedClass = Substrate.class; validateSubclassAssociationElements(targetClass, associatedClass, "substrateCollection","1","1"); } }
package com.flexdms.flexims.unit; import java.math.BigDecimal; import java.sql.Connection; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import com.flexdms.flexims.jpa.JpaHelper; import com.flexdms.flexims.jpa.eclipselink.FleximsDynamicEntityImpl; import com.flexdms.flexims.jpa.helper.ByteArray; import com.flexdms.flexims.jpa.helper.NameValueList; public class TestEntityUtil { public static void setIDandVersion(FleximsDynamicEntityImpl de) { de.setId(3); de.setVersion(new Timestamp(new Date().getTime())); } public static void setBasicType(FleximsDynamicEntityImpl de) { de.set("shortstring", "short"); de.set("mediumstring", "this is a medium string"); de.set("longstring", "this is a long string"); // number de.set("propint", 5); de.set("proplong", 5l); de.set("propfloat", 5.0f); de.set("propdouble", 5.9d); de.set("propcurrency", new BigDecimal(79.6545)); // boolean de.set("propboolean", true); de.set("propdate", Calendar.getInstance()); de.set("proptimestamp", Calendar.getInstance()); de.set("proptime", Calendar.getInstance()); } public static <T> List<T> fillList(T... vs) { return Arrays.asList(vs); } public static void setCollection1(FleximsDynamicEntityImpl de) { de.set("shortstring", fillList("short1", "shor][]t2")); // number de.set("propint", fillList(5, 6)); de.set("proplong", fillList(5l, 6l)); de.set("propfloat", fillList(5.0, 6.0)); de.set("propdouble", fillList(5.0d, 6.0d)); de.set("propcurrency", fillList(new BigDecimal(79.6545), new BigDecimal(78.32))); de.set("propdate", fillList(Calendar.getInstance(), Calendar.getInstance())); de.set("proptimestamp", fillList(Calendar.getInstance(), Calendar.getInstance())); de.set("proptime", fillList(Calendar.getInstance(), Calendar.getInstance())); de.set("propemail", fillList("j@example.com", "z@example.com")); } public static void setSpecialtype(FleximsDynamicEntityImpl de) { Map<String, String> map = new HashMap<>(2); map.put("first name", "jason"); map.put("last name", "zhang"); de.set("propobject", NameValueList.fromMap(map)); // collection of dates Set<Calendar> dates = new HashSet<>(); ; dates.add(Calendar.getInstance()); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, 1); dates.add(calendar); de.set("propdates", dates); de.set("propbyte", new ByteArray("this is a test".getBytes())); } public static FleximsDynamicEntityImpl setEmbeded(FleximsDynamicEntityImpl de, boolean single) { de.set("streetAddress", "Street Address"); if (single) { List<String> mStrings = new ArrayList<>(); mStrings.add("value1"); mStrings.add("value,"); de.set("mstr", mStrings); List<Integer> mints = new ArrayList<>(); mints.add(6); mints.add(7); mints.add(8); de.set("mint", mints); } return de; } public static void setEmbedmain(FleximsDynamicEntityImpl de, EntityManager em) { de.set("fname", "simple"); FleximsDynamicEntityImpl embed1 = JpaHelper.createNewEntity(em, "Embed1"); FleximsDynamicEntityImpl embed2 = JpaHelper.createNewEntity(em, "Embed2"); FleximsDynamicEntityImpl embed3 = JpaHelper.createNewEntity(em, "Embed2"); setEmbeded(embed2, false); setEmbeded(embed3, false); de.set("singleembed", setEmbeded(embed1, true)); de.set("multiembed", fillList(embed2, embed3)); } public static void deleteStudent(EntityManager em) throws SQLException { Connection connection = em.unwrap(Connection.class); connection.createStatement().execute("DELETE FROM MSTUDENT_MCOURSE"); connection.createStatement().execute("DELETE FROM MSTUDENT_MONEMANY"); connection.createStatement().execute("DELETE FROM MSTUDENT_PROPINT"); connection.createStatement().execute("DELETE FROM MCOURSE"); connection.createStatement().execute("DELETE FROM MONEMANY"); connection.createStatement().execute("DELETE FROM MSTUDENT"); connection.createStatement().execute("DELETE FROM MDOOMROOM"); connection.createStatement().execute("DELETE FROM MDOOMBUILD"); } public static FleximsDynamicEntityImpl createDoomBuild(EntityManager em) { EntityTransaction tx = em.getTransaction(); tx.begin(); FleximsDynamicEntityImpl doombuild = JpaHelper.createNewEntity(em, "Mdoombuild"); doombuild.set("name", "Porter"); em.persist(doombuild); em.flush(); FleximsDynamicEntityImpl doomroom; for (int i = 0; i < 5; i++) { doomroom = JpaHelper.createNewEntity(em, "Mdoomroom"); doomroom.set("number", 100 + i); doomroom.set("name", "name" + i); doomroom.set("doombuild", doombuild); em.persist(doomroom); } tx.commit(); return em.find(doombuild.getClass(), doombuild.getId()); } public static FleximsDynamicEntityImpl createStudentOneManys(EntityManager em) { FleximsDynamicEntityImpl OneMany1 = JpaHelper.createNewEntity(em, "MOneMany"); OneMany1.set("name", "OneMany1"); FleximsDynamicEntityImpl OneMany2 = JpaHelper.createNewEntity(em, "MOneMany"); OneMany2.set("name", "OneMany2"); FleximsDynamicEntityImpl student = JpaHelper.createNewEntity(em, "Mstudent"); List<FleximsDynamicEntityImpl> oneManysList = new ArrayList<>(); oneManysList.add(OneMany1); oneManysList.add(OneMany2); student.set("OneManys", oneManysList); return student; } public static FleximsDynamicEntityImpl createAndPersisteDemoRelationObject(EntityManager em) { EntityTransaction tx = em.getTransaction(); tx.begin(); FleximsDynamicEntityImpl OneMany1 = JpaHelper.createNewEntity(em, "MOneMany"); OneMany1.set("name", "OneMany1"); em.persist(OneMany1); FleximsDynamicEntityImpl OneMany2 = JpaHelper.createNewEntity(em, "MOneMany"); OneMany2.set("name", "OneMany2"); em.persist(OneMany2); em.flush(); FleximsDynamicEntityImpl doombuild = JpaHelper.createNewEntity(em, "Mdoombuild"); doombuild.set("name", "Porter"); em.persist(doombuild); em.flush(); FleximsDynamicEntityImpl doomroom = JpaHelper.createNewEntity(em, "Mdoomroom"); doomroom.set("number", 312); doomroom.set("doombuild", doombuild); em.persist(doomroom); // em.flush(); FleximsDynamicEntityImpl course1 = JpaHelper.createNewEntity(em, "Mcourse"); course1.set("name", "CS1"); em.persist(course1); FleximsDynamicEntityImpl course2 = JpaHelper.createNewEntity(em, "Mcourse"); course2.set("name", "CS2"); em.persist(course2); FleximsDynamicEntityImpl student = JpaHelper.createNewEntity(em, "Mstudent"); student.set("doombuild", doombuild); student.set("doomroom", doomroom); List<FleximsDynamicEntityImpl> oneManysList = new ArrayList<>(); oneManysList.add(OneMany1); oneManysList.add(OneMany2); student.set("OneManys", oneManysList); List<FleximsDynamicEntityImpl> courses = new ArrayList<>(); courses.add(course2); courses.add(course1); student.set("Courses", courses); course1.set("Students", Arrays.asList(student)); course2.set("Students", Arrays.asList(student)); em.persist(student); tx.commit(); return student; } }
/* * TopStack (c) Copyright 2012-2013 Transcend Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.msi.tough.utils; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.hibernate.Query; import org.hibernate.Session; import com.amazonaws.services.autoscaling.model.Instance; import com.msi.tough.cf.AccountType; import com.msi.tough.cf.ec2.InstanceType; import com.msi.tough.core.Appctx; import com.msi.tough.core.BaseException; import com.msi.tough.core.QueryBuilder; import com.msi.tough.core.StringHelper; import com.msi.tough.engine.aws.ec2.DescribeInstance; import com.msi.tough.engine.core.CallStruct; import com.msi.tough.model.InstanceBean; public class InstanceUtil implements Constants { public static InstanceBean createNewInstance(final Session s, final long acid, final String instanceId, final String avzone, final String logicalId, final String chefRoles) { return createNewInstance(s, acid, instanceId, avzone, logicalId, chefRoles, instanceId); } public static InstanceBean createNewInstance(final Session s, final long acid, final String instanceId, final String avzone, final String logicalId, final String chefRoles, final String uuid) { final InstanceBean b = new InstanceBean(); b.setInstanceId(instanceId); b.setEc2Id(uuid); b.setUserId(acid); b.setPublicIp("0.0.0.0"); b.setPrivateIp("0.0.0.0"); b.setAvzone(avzone); b.setHostname(InstanceUtil.getHostName(logicalId)); b.setChefRoles(chefRoles); b.setLogicalId(logicalId); b.setStatus("created"); return b; } @SuppressWarnings("unchecked") public static String endpointBasedId(final Session session, final String instanceId) { final Map<String, Object> endpointOptions = (Map<String, Object>) Appctx .getThreadMap(Constants.ENDPOINT_OPTIONS); if (endpointOptions == null) { return instanceId; } final String idType = (String) endpointOptions.get("INSTANCE_ID_TYPE"); String id = instanceId; if (idType != null && idType.equals("EC2")) { final InstanceBean ib = InstanceUtil.getInstance(session, id); id = ib.getEc2Id(); } return id; } public static String[] essexEC2Id(final String instanceId, final String desc) { if (!instanceId.startsWith("i-")) { throw new BaseException("ID should start with i- found " + instanceId); } final String s = instanceId.substring(2); final String[] ret = new String[3]; ret[0] = "instance-" + s; String tkn = desc.trim(); tkn = tkn.substring(1); tkn = tkn.substring(0, tkn.length() - 1).trim(); final String[] parts = tkn.split(","); ret[1] = parts[0].trim(); ret[2] = parts[1].trim(); return ret; } public static String getHostName(final String avzone) { if (avzone == null) { return null; } return StringHelper.randomStringFromTime().toLowerCase() + "." + ConfigurationUtil.getConfiguration(Arrays .asList(avzone == null ? new String[] { "FQDN_DOMAIN", avzone } : new String[] { "FQDN_DOMAIN", avzone })); } public static String getHostName(final String avzone, final String installId, final String service) { if (avzone == null) { return null; } return service + "-" + installId + "-" + StringHelper.randomStringFromTime().toLowerCase() + "." + ConfigurationUtil.getConfiguration(Arrays .asList(avzone == null ? new String[] { "FQDN_DOMAIN", avzone } : new String[] { "FQDN_DOMAIN", avzone })); } /** * Read an instance from the database * * @param session * hibernate session to use * @param name * name of the load balancer * @return load balancer from database */ @SuppressWarnings("unchecked") public static InstanceBean getInstance(final Session session, final String instanceId) { final Query q = session .createQuery("from InstanceBean where instanceId='" + instanceId + "'"); final List<InstanceBean> l = q.list(); if (l == null || l.size() == 0) { return null; } return l.get(0); } public static InstanceBean getInstanceByHostName(final Session session, final long acid, final String hostname) { return getInstanceByHostName(session, acid, hostname, false); } public static InstanceBean getInstanceByHostName(final Session session, final long acid, final String hostname, boolean useCloud) { final Query q = session .createQuery("from InstanceBean where hostname='" + hostname + "'"); @SuppressWarnings("unchecked") final List<InstanceBean> l = q.list(); if (l != null && l.size() > 0) { return l.get(0); } if (!useCloud) { return null; } // TODO: call describe instances by hostname to obtain instance. return null; } /** * Read an instance definition from datastore. * * @param session * hibernate session to use * @param id * unique ID for instance * @return instance definition */ @SuppressWarnings("unchecked") public static InstanceBean getInstanceByUID(final Session session, final String id) { final Query q = session.createQuery("from InstanceBean where uuid='" + id + "'"); final List<InstanceBean> l = q.list(); if (l == null || l.size() == 0) { return null; } return l.get(0); } /** * Read an instance definition from datastore. * * @param session * hibernate session to use * @param id * EC2-style identifier for instance * @return instance definition */ @SuppressWarnings("unchecked") public static InstanceBean getInstanceByEc2Id(final Session session, final String id) { final Query q = session.createQuery("from InstanceBean where ec2Id='" + id + "'"); final List<InstanceBean> l = q.list(); if (l == null || l.size() == 0) { return null; } return l.get(0); } /** * Look up an instance by ID, cache in DB, collect DNS information. * * @param session * @param ac * @param id * @return * @throws Exception */ public static String getInstanceDns(final Session session, final AccountType ac, final String id) throws Exception { final InstanceBean ib = getInstance(session, id); if (ib != null && ib.getPublicIpId() != null) { return ib.getPublicIpId(); } final CallStruct c = new CallStruct(); c.setAc(ac); c.setAvailabilityZone(ac.getDefZone()); final Map<String, Object> m = new HashMap<String, Object>(); m.put(AVAILABILITYZONE, ac.getDefZone()); m.put(INSTANCEIDS, id); c.setProperties(m); c.setType(DescribeInstance.TYPE); final DescribeInstance provider = new DescribeInstance(); final InstanceType l = (InstanceType) provider.create(c); if (l == null || l.getPublicIp() == null) { return null; } if (ib != null) { ib.setPublicIpId(l.getPublicIp()); ib.setPrivateIp(l.getPrivateIpAddress()); session.save(ib); } return l.getPublicIp(); } public static String getIP(final String dns, final String ip, final String avz) { final String useIpforInstances = (String) ConfigurationUtil .getConfiguration(Arrays.asList(new String[] { "useIpforInstances", avz })); if (useIpforInstances == null || useIpforInstances.toLowerCase().startsWith("y")) { return ip; } else { return dns; } } public static String idType(final String id) { if (id.startsWith("i-")) { return "EC2"; } if (id.startsWith("instance-")) { return "libvert"; } return "hypervisor"; } public static void putDefInstanceValues(final Map<String, Object> prop, final AccountType ac) { final String avz = (String) prop.get(AVAILABILITYZONE); final String installId = Appctx.getBean("INSTALL_ID"); final String service = (String) prop.get(SERVICE); for (final String str : new String[] { IMAGEID, INSTANCETYPE, KERNELID, RAMDISKID }) { if (!prop.containsKey(str)) { final Object c = ConfigurationUtil.getConfiguration(str, avz, "ElasticLoadBalancing"); if (c != null) { prop.put(str, c); } } } prop.put(KEYNAME, ac.getDefKeyName()); prop.put(HOSTNAME, InstanceUtil.getHostName(avz, installId, service)); prop.put(ACID, "" + ac.getId()); } public static Instance toInstance(final InstanceBean i) { final Instance b = new Instance(); b.setAvailabilityZone(i.getAvzone()); b.setInstanceId(i.getInstanceId()); b.setLifecycleState(i.getStatus()); b.setHealthStatus(i.getHealth()); return b; } public static InstanceType toInstanceType(final InstanceBean i) { final InstanceType b = new InstanceType(); b.setAvailabilityZone(i.getAvzone()); b.setInstanceId(i.getInstanceId()); b.setAcId(i.getId()); b.setChefRoles(i.getChefRoles()); b.setDatabag(i.getDatabag()); b.setHostname(i.getHostname()); b.setPublicIp(i.getPublicIpId()); b.setPrivateIpAddress(i.getPrivateIp()); return b; } public static String UUIDtoEc2(final Session session, final long acid, final String instId) throws Exception { final InstanceBean ib = InstanceUtil.getInstance(session, instId); if (ib != null && ib.getEc2Id() != null && ib.getEc2Id().length() > 0) { return ib.getEc2Id(); } // final AccountBean ac = AccountUtil.readAccount(session, acid); // final String ec2Id = OpenstackUtil.UUIDtoEc2(session, ac, instId, // ac.getDefZone()); // if (ec2Id == null) { // return null; // } // ib = InstanceUtil.getInstance(session, ec2Id); // if (ib == null) { // ib = new InstanceBean(); // ib.setUserId(acid); // ib.setInstanceId(ec2Id); // } // ib.setUuid(instId); // session.save(ib); // getInstanceDns(session, AccountUtil.toAccount(ac), // ib.getInstanceId()); // return ec2Id; return null; } /** * Convert a non-standard instance ID into a cloud-normal instance ID. In * some circumstances (e.g. essex instance data) an EC2 style ID (i-XXXXXX) * is returned rather than a native ID. This converts to native by reading * from instance table. * * @param session * @param instId * @return * @throws Exception */ public static String normalizeInstanceId(final Session session, final String instanceId) { if (instanceId == null || !instanceId.startsWith("i-")) { return instanceId; } final Query q = new QueryBuilder("from InstanceBean").equals("ec2Id", instanceId).toQuery(session); InstanceBean ib = (InstanceBean) q.uniqueResult(); if (ib != null && !StringHelper.isBlank(ib.getInstanceId())) { return ib.getInstanceId(); } return instanceId; } }
package org.altbeacon.beacon; import android.os.Parcel; import static android.test.MoreAsserts.assertNotEqual; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import org.robolectric.RobolectricTestRunner; import org.junit.runner.RunWith; import org.junit.Test; import org.robolectric.annotation.Config; import java.util.Arrays; import java.util.UUID; @Config(sdk = 18) @RunWith(RobolectricTestRunner.class) /* HOW TO SEE DEBUG LINES FROM YOUR UNIT TESTS: 1. set a line like this at the start of your test: org.robolectric.shadows.ShadowLog.stream = System.err; 2. run the tests from the command line 3. Look at the test report file in your web browser, e.g. file:///Users/dyoung/workspace/AndroidProximityLibrary/build/reports/tests/index.html 4. Expand the System.err section */ public class IdentifierTest { @Test public void testEqualsNormalizationIgnoresCase() { Identifier identifier1 = Identifier.parse("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6"); Identifier identifier2 = Identifier.parse("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6"); assertTrue("Identifiers of different case should match", identifier1.equals(identifier2)); } @Test public void testToStringNormalizesCase() { Identifier identifier1 = Identifier.parse("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6"); assertEquals("Identifiers of different case should match", "2f234454-cf6d-4a0f-adf2-f4911ba9ffa6", identifier1.toString()); } @Test public void testToStringEqualsUuid() { Identifier identifier1 = Identifier.parse("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6"); assertEquals("uuidString of Identifier should match", "2f234454-cf6d-4a0f-adf2-f4911ba9ffa6", identifier1.toUuidString()); } @Test public void testToUuidEqualsToUuidString() { Identifier identifier1 = Identifier.parse("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6"); assertEquals("uuidString of Identifier should match", identifier1.toUuid().toString(), identifier1.toUuidString()); } @Test public void testToByteArrayConvertsUuids() { Identifier identifier1 = Identifier.parse("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6"); byte[] bytes = identifier1.toByteArrayOfSpecifiedEndianness(true); assertEquals("byte array is correct length", bytes.length, 16); assertEquals("first byte of uuid converted properly", 0x2f, bytes[0] & 0xFF); assertEquals("second byte of uuid converted properly", 0x23, bytes[1] & 0xFF); assertEquals("last byte of uuid converted properly", 0xa6, bytes[15] & 0xFF); } @Test public void testToByteArrayConvertsUuidsAsLittleEndian() { Identifier identifier1 = Identifier.parse("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6"); byte[] bytes = identifier1.toByteArrayOfSpecifiedEndianness(false); assertEquals("byte array is correct length", bytes.length, 16); assertEquals("first byte of uuid converted properly", 0xa6, bytes[0] & 0xFF); assertEquals("last byte of uuid converted properly", 0x2f, bytes[15] & 0xFF); } @Test public void testToByteArrayConvertsHex() { Identifier identifier1 = Identifier.parse("0x010203040506"); byte[] bytes = identifier1.toByteArrayOfSpecifiedEndianness(true); assertEquals("byte array is correct length", bytes.length, 6); assertEquals("first byte of hex is converted properly", 0x01, bytes[0] & 0xFF); assertEquals("last byte of hex is converted properly", 0x06, bytes[5] & 0xFF); } @Test public void testToByteArrayConvertsDecimal() { Identifier identifier1 = Identifier.parse("65534"); byte[] bytes = identifier1.toByteArrayOfSpecifiedEndianness(true); assertEquals("byte array is correct length", bytes.length, 2); assertEquals("reported byte array is correct length", identifier1.getByteCount(), 2); assertEquals("first byte of decimal converted properly", 0xff, bytes[0] & 0xFF); assertEquals("last byte of decimal converted properly", 0xfe, bytes[1] & 0xFF); } @Test public void testToByteArrayConvertsInt() { Identifier identifier1 = Identifier.fromInt(65534); byte[] bytes = identifier1.toByteArrayOfSpecifiedEndianness(true); assertEquals("byte array is correct length", bytes.length, 2); assertEquals("reported byte array is correct length", identifier1.getByteCount(), 2); assertEquals("conversion back equals original value", identifier1.toInt(), 65534); assertEquals("first byte of decimal converted properly", 0xff, bytes[0] & 0xFF); assertEquals("last byte of decimal converted properly", 0xfe, bytes[1] & 0xFF); } @Test public void testToByteArrayFromByteArray() { byte[] value = new byte[] {(byte) 0xFF, (byte) 0xAB, 0x12, 0x25}; Identifier identifier1 = Identifier.fromBytes(value, 0, value.length, false); byte[] bytes = identifier1.toByteArrayOfSpecifiedEndianness(true); assertEquals("byte array is correct length", bytes.length, 4); assertEquals("correct string representation", identifier1.toString(), "0xffab1225"); assertTrue("arrays equal", Arrays.equals(value, bytes)); assertNotSame("arrays are copied", bytes, value); } @Test public void testComparableDifferentLength() { byte[] value1 = new byte[] {(byte) 0xFF, (byte) 0xAB, 0x12, 0x25}; Identifier identifier1 = Identifier.fromBytes(value1, 0, value1.length, false); byte[] value2 = new byte[] {(byte) 0xFF, (byte) 0xAB, 0x12, 0x25, 0x11, 0x11}; Identifier identifier2 = Identifier.fromBytes(value2, 0, value2.length, false); assertEquals("identifier1 is smaller than identifier2", identifier1.compareTo(identifier2), -1); assertEquals("identifier2 is larger than identifier1", identifier2.compareTo(identifier1), 1); } @Test public void testComparableSameLength() { byte[] value1 = new byte[] {(byte) 0xFF, (byte) 0xAB, 0x12, 0x25, 0x22, 0x25}; Identifier identifier1 = Identifier.fromBytes(value1, 0, value1.length, false); byte[] value2 = new byte[] {(byte) 0xFF, (byte) 0xAB, 0x12, 0x25, 0x11, 0x11}; Identifier identifier2 = Identifier.fromBytes(value2, 0, value2.length, false); assertEquals("identifier1 is equal to identifier2", identifier1.compareTo(identifier1), 0); assertEquals("identifier1 is larger than identifier2", identifier1.compareTo(identifier2), 1); assertEquals("identifier2 is smaller than identifier1", identifier2.compareTo(identifier1), -1); } @Test public void testParseIntegerMaxInclusive() { Identifier.parse("65535"); } @Test(expected = IllegalArgumentException.class) public void testParseIntegerAboveMax() { Identifier.parse("65536"); } @Test public void testParseIntegerMinInclusive() { Identifier.parse("0"); } @Test(expected = IllegalArgumentException.class) public void testParseIntegerBelowMin() { Identifier.parse("-1"); } @Test(expected = IllegalArgumentException.class) public void testParseIntegerWayTooBig() { Identifier.parse("3133742"); } /* * This is here because Identifier.parse wrongly accepts UUIDs without * dashes, but we want to be backward compatible. */ @Test public void testParseInvalidUuid() { UUID ref = UUID.fromString("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6"); Identifier id = Identifier.parse("2f234454cf6d4a0fadf2f4911ba9ffa6"); assertEquals("Malformed UUID was parsed as expected.", id.toUuid(), ref); } @Test public void testParseHexWithNoPrefix() { Identifier id = Identifier.parse("abcd"); assertEquals("Should parse and get back equivalent decimal value for small numbers", "43981", id.toString()); } @Test public void testParseBigHexWithNoPrefix() { Identifier id = Identifier.parse("123456789abcdef"); assertEquals("Should parse and get prefixed hex value for big numbers", "0x0123456789abcdef", id.toString()); } @Test public void testParseZeroPrefixedDecimalNumberAsHex() { Identifier id = Identifier.parse("0010"); assertEquals("Should be treated as hex in parse, but converted back to decimal because it is small", "16", id.toString()); } @Test public void testParseNonZeroPrefixedDecimalNumberAsDecimal() { Identifier id = Identifier.parse("10"); assertEquals("Should be treated as decimal", "10", id.toString()); } @Test public void testParseDecimalNumberWithSpecifiedLength() { Identifier id = Identifier.parse("10", 8); assertEquals("Should be treated as hex because it is long", "0x000000000000000a", id.toString()); assertEquals("Byte count should be as specified", 8, id.getByteCount()); } @Test public void testParseDecimalNumberWithSpecifiedShortLength() { Identifier id = Identifier.parse("10", 2); assertEquals("Should be treated as decimal because it is short", "10", id.toString()); assertEquals("Byte count should be as specified", 2, id.getByteCount()); } @Test public void testParseHexNumberWithSpecifiedLength() { Identifier id = Identifier.parse("2fffffffffffffffffff", 10); assertEquals("Should be treated as hex because it is long", "0x2fffffffffffffffffff", id.toString()); assertEquals("Byte count should be as specified", 10, id.getByteCount()); } @Test public void testParseZeroAsInteger() { Identifier id = Identifier.parse("0"); assertEquals("Should be treated as int because it is a common integer", "0", id.toString()); assertEquals("Byte count should be 2 for integers", 2, id.getByteCount()); } }
package com.RSen.Commandr.util; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract.Contacts; import android.telephony.PhoneNumberUtils; import android.telephony.SmsMessage; import android.telephony.SmsMessage.MessageClass; import android.text.format.DateUtils; public class SmsMmsMessage { // Message types public static final int MESSAGE_TYPE_SMS = 0; public static final int MESSAGE_TYPE_MMS = 1; public static final int MESSAGE_TYPE_MESSAGE = 2; // Timestamp compare buffer for incoming messages public static final int MESSAGE_COMPARE_TIME_BUFFER = 5000; // 5 seconds // Private EXTRAS strings private static final String PREFIX = "net.everythingandroid.smspopup."; private static final String EXTRAS_FROM_ADDRESS = PREFIX + "EXTRAS_FROM_ADDRESS"; private static final String EXTRAS_MESSAGE_BODY = PREFIX + "EXTRAS_MESSAGE_BODY"; private static final String EXTRAS_TIMESTAMP = PREFIX + "EXTRAS_TIMESTAMP"; private static final String EXTRAS_UNREAD_COUNT = PREFIX + "EXTRAS_UNREAD_COUNT"; private static final String EXTRAS_THREAD_ID = PREFIX + "EXTRAS_THREAD_ID"; private static final String EXTRAS_CONTACT_ID = PREFIX + "EXTRAS_CONTACT_ID"; private static final String EXTRAS_CONTACT_LOOKUP = PREFIX + "EXTRAS_CONTACT_LOOKUP"; private static final String EXTRAS_CONTACT_NAME = PREFIX + "EXTRAS_CONTACT_NAME"; private static final String EXTRAS_MESSAGE_TYPE = PREFIX + "EXTRAS_MESSAGE_TYPE"; private static final String EXTRAS_MESSAGE_ID = PREFIX + "EXTRAS_MESSAGE_ID"; private static final String EXTRAS_EMAIL_GATEWAY = PREFIX + "EXTRAS_EMAIL_GATEWAY"; // Public EXTRAS strings public static final String EXTRAS_NOTIFY = PREFIX + "EXTRAS_NOTIFY"; public static final String EXTRAS_REMINDER_COUNT = PREFIX + "EXTRAS_REMINDER_COUNT"; public static final String EXTRAS_REPLYING = PREFIX + "EXTRAS_REPLYING"; public static final String EXTRAS_QUICKREPLY = PREFIX + "EXTRAS_QUICKREPLY"; // Sprint vars to check for special voicemail messages private static final String SPRINT_BRAND = "sprint"; private static final String SPRINT_VOICEMAIL_PREFIX = "//ANDROID:"; // Main message object private vars private Context context; private String fromAddress = null; private String messageBody = null; private long timestamp = 0; private int unreadCount = 0; private long threadId = 0; private String contactId = null; private String contactLookupKey = null; private String contactName = null; private int messageType = 0; private boolean notify = true; private int reminderCount = 0; private long messageId = 0; private boolean fromEmailGateway = false; private MessageClass messageClass = null; private String replyText = ""; /** * Construct SmsMmsMessage given a raw message (created from pdu), used for * when a message is initially received via the network. */ public SmsMmsMessage(Context _context, SmsMessage[] messages, long _timestamp) { SmsMessage sms = messages[0]; context = _context; timestamp = _timestamp; messageType = MESSAGE_TYPE_SMS; /* * Fetch data from raw SMS */ fromAddress = sms.getDisplayOriginatingAddress(); fromEmailGateway = sms.isEmail(); messageClass = sms.getMessageClass(); String body = ""; try { if (messages.length == 1 || sms.isReplace()) { body = sms.getDisplayMessageBody(); } else { StringBuilder bodyText = new StringBuilder(); for (int i = 0; i < messages.length; i++) { bodyText.append(messages[i].getMessageBody()); } body = bodyText.toString(); } } catch (Exception e) { } messageBody = body; /* * Lookup the rest of the info from the system db */ SMSUtils.ContactIdentification contactIdentify = null; // If this SMS is from an email gateway then lookup contactId by email // address if (fromEmailGateway) { contactIdentify = SMSUtils.getPersonIdFromEmail(context, fromAddress); contactName = fromAddress; } else { // Else lookup contactId by phone number contactIdentify = SMSUtils.getPersonIdFromPhoneNumber(context, fromAddress); contactName = PhoneNumberUtils.formatNumber(fromAddress); } if (contactIdentify != null) { contactId = contactIdentify.contactId; contactLookupKey = contactIdentify.contactLookup; contactName = contactIdentify.contactName; } unreadCount = SMSUtils.getUnreadMessagesCount(context, timestamp, messageBody); } /** * Construct SmsMmsMessage for getMmsDetails() - fetched from the MMS * database table */ public SmsMmsMessage(Context _context, long _messageId, long _threadId, long _timestamp, String _messageBody, int _unreadCount, int _messageType) { context = _context; messageId = _messageId; threadId = _threadId; timestamp = _timestamp; messageBody = _messageBody; unreadCount = _unreadCount; messageType = _messageType; fromAddress = SMSUtils.getMmsAddress(context, messageId); fromEmailGateway = false; contactName = PhoneNumberUtils.formatNumber(fromAddress); // Look up by phone number first SMSUtils.ContactIdentification contactIdentify = SMSUtils.getPersonIdFromPhoneNumber(context, fromAddress); if (contactIdentify == null) { // Lookup by email contactIdentify = SMSUtils.getPersonIdFromEmail(context, fromAddress); if (contactIdentify != null) { // If found then set "from email" flag fromEmailGateway = true; } } // If a contact was found then set fields if (contactIdentify != null) { contactId = contactIdentify.contactId; contactLookupKey = contactIdentify.contactLookup; contactName = contactIdentify.contactName; } } /** * Construct SmsMmsMessage for getSmsDetails() - info fetched from the SMS * database table */ public SmsMmsMessage(Context _context, String _fromAddress, String _messageBody, long _timestamp, long _threadId, int _unreadCount, long _messageId, int _messageType) { context = _context; fromAddress = _fromAddress; messageBody = _messageBody; timestamp = _timestamp; messageType = _messageType; SMSUtils.ContactIdentification contactIdentify = null; if (PhoneNumberUtils.isWellFormedSmsAddress(fromAddress)) { contactIdentify = SMSUtils.getPersonIdFromPhoneNumber(context, fromAddress); contactName = PhoneNumberUtils.formatNumber(fromAddress); fromEmailGateway = false; } else { contactIdentify = SMSUtils.getPersonIdFromEmail(context, fromAddress); contactName = fromAddress; fromEmailGateway = true; } if (contactIdentify != null) { contactId = contactIdentify.contactId; contactLookupKey = contactIdentify.contactLookup; contactName = contactIdentify.contactName; } unreadCount = _unreadCount; threadId = _threadId; messageId = _messageId; } /** * Construct SmsMmsMessage from an extras bundle */ public SmsMmsMessage(Context _context, Bundle b) { context = _context; fromAddress = b.getString(EXTRAS_FROM_ADDRESS); messageBody = b.getString(EXTRAS_MESSAGE_BODY); timestamp = b.getLong(EXTRAS_TIMESTAMP); contactId = b.getString(EXTRAS_CONTACT_ID); contactLookupKey = b.getString(EXTRAS_CONTACT_LOOKUP); contactName = b.getString(EXTRAS_CONTACT_NAME); unreadCount = b.getInt(EXTRAS_UNREAD_COUNT, 1); threadId = b.getLong(EXTRAS_THREAD_ID, 0); messageType = b.getInt(EXTRAS_MESSAGE_TYPE, MESSAGE_TYPE_SMS); notify = b.getBoolean(EXTRAS_NOTIFY, false); reminderCount = b.getInt(EXTRAS_REMINDER_COUNT, 0); messageId = b.getLong(EXTRAS_MESSAGE_ID, 0); fromEmailGateway = b.getBoolean(EXTRAS_EMAIL_GATEWAY, false); } /** * Construct SmsMmsMessage by specifying all data, only used for testing the * notification from the preferences screen */ public SmsMmsMessage(Context _context, String _fromAddress, String _messageBody, long _timestamp, String _contactId, String _contactLookup, String _contactName, int _unreadCount, long _threadId, int _messageType) { context = _context; fromAddress = _fromAddress; messageBody = _messageBody; timestamp = _timestamp; contactId = _contactId; contactLookupKey = _contactLookup; contactName = _contactName; unreadCount = _unreadCount; threadId = _threadId; messageType = _messageType; } /** * Convert all SmsMmsMessage data to an extras bundle to send via an intent */ public Bundle toBundle() { Bundle b = new Bundle(); b.putString(EXTRAS_FROM_ADDRESS, fromAddress); b.putString(EXTRAS_MESSAGE_BODY, messageBody); b.putLong(EXTRAS_TIMESTAMP, timestamp); b.putString(EXTRAS_CONTACT_ID, contactId); b.putString(EXTRAS_CONTACT_LOOKUP, contactLookupKey); b.putString(EXTRAS_CONTACT_NAME, contactName); b.putInt(EXTRAS_UNREAD_COUNT, unreadCount); b.putLong(EXTRAS_THREAD_ID, threadId); b.putInt(EXTRAS_MESSAGE_TYPE, messageType); b.putBoolean(EXTRAS_NOTIFY, notify); b.putInt(EXTRAS_REMINDER_COUNT, reminderCount); b.putLong(EXTRAS_MESSAGE_ID, messageId); b.putBoolean(EXTRAS_EMAIL_GATEWAY, fromEmailGateway); return b; } /** * Fetch the "reply to" message intent * * @param replyToThread whether or not to reply using the message threadId * or using the sender address * @return the intent to pass to startActivity() */ public Intent getReplyIntent(boolean replyToThread) { if (messageType == MESSAGE_TYPE_MMS) { locateThreadId(); return SMSUtils.getSmsToIntent(context, threadId); } else if (messageType == MESSAGE_TYPE_SMS) { locateThreadId(); /* * There are two ways to reply to a message, by "viewing" the * threadId or by sending a new message to the address. In most * cases we should just execute the former, but in some cases its * better to send a new message to an address (apps like Google * Voice will intercept this intent as they don't seem to look at * the threadId). */ if (replyToThread && threadId > 0) { return SMSUtils.getSmsToIntent(context, threadId); } else { return SMSUtils.getSmsToIntent(context, fromAddress); } } return null; } public Intent getReplyIntent() { return getReplyIntent(true); } public void setThreadRead() { locateThreadId(); SMSUtils.setThreadRead(context, threadId); } public void setMessageRead() { locateMessageId(); SMSUtils.setMessageRead(context, messageId, messageType); } public int getUnreadCount() { return unreadCount; } public void setUnreadCount(int _unreadCount) { unreadCount = _unreadCount; } public long getTimestamp() { return timestamp; } public MessageClass getMessageClass() { return messageClass; } public CharSequence getFormattedTimestamp() { CharSequence formattedTime; try { formattedTime = DateUtils.formatDateTime(context, timestamp, DateUtils.FORMAT_SHOW_TIME); } catch (Exception e) { formattedTime = ""; } return formattedTime; } public String getContactName() { if (contactName == null) { contactName = context.getString(android.R.string.unknownName); } return contactName; } public String getMessageBody() { if (messageBody == null) { messageBody = ""; } return messageBody; } public int getMessageType() { return messageType; } public boolean isSms() { return messageType == MESSAGE_TYPE_SMS; } public boolean isMms() { return messageType == MESSAGE_TYPE_MMS; } public void setNotify(boolean mNotify) { notify = mNotify; } public boolean shouldNotify() { return notify; } public int getReminderCount() { return reminderCount; } public void updateReminderCount(int count) { reminderCount = count; } public void incrementReminderCount() { reminderCount++; } public void delete() { SMSUtils.deleteMessage(context, getMessageId(), threadId, messageType); } public void locateThreadId() { if (threadId == 0) { threadId = SMSUtils.findThreadIdFromAddress(context, fromAddress); } } public long getThreadId() { locateThreadId(); return threadId; } public void locateMessageId() { if (messageId == 0) { if (threadId == 0) { locateThreadId(); } messageId = SMSUtils.findMessageId( context, threadId, timestamp, messageBody, messageType); } } public long getMessageId() { locateMessageId(); return messageId; } public String getContactId() { return contactId; } public String getContactLookupKey() { return contactLookupKey; } public Uri getContactLookupUri() { if (contactId == null) { return null; } return Uri.withAppendedPath(Contacts.CONTENT_URI, contactId); // This seems to fail even though the docs say to use it. // return Contacts.getLookupUri(Long.valueOf(contactId), // contactLookupKey); } public String getAddress() { return fromAddress; } public boolean isEmail() { return fromEmailGateway; } public String getReplyText() { return replyText; } public void setReplyText(String text) { replyText = text; } /** * Sned a reply to this message * * @return true of the message was sent, false otherwise */ public boolean replyToMessage(String quickReply) { /* // Mark the message we're replying to as read setMessageRead(); // Send new message SmsMessageSender sender = new SmsMessageSender(context, new String[] {fromAddress}, quickReply, getThreadId()); return sender.sendMessage(); */ return false; } // Checks if user is on carrier Sprint and message is a special system message public boolean isSprintVisualVoicemail() { if (!SPRINT_BRAND.equals(Build.BRAND)) { return false; } if (messageBody != null) { if (messageBody.trim().startsWith(SPRINT_VOICEMAIL_PREFIX)) { return true; } } return false; } }
/* * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.devtools.autoconfigure; import java.io.File; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import org.apache.catalina.Container; import org.apache.catalina.core.StandardWrapper; import org.apache.jasper.EmbeddedServletOptions; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration; import org.springframework.boot.autoconfigure.web.ResourceProperties; import org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration; import org.springframework.boot.devtools.classpath.ClassPathChangedEvent; import org.springframework.boot.devtools.classpath.ClassPathFileSystemWatcher; import org.springframework.boot.devtools.livereload.LiveReloadServer; import org.springframework.boot.devtools.restart.FailureHandler; import org.springframework.boot.devtools.restart.MockRestartInitializer; import org.springframework.boot.devtools.restart.MockRestarter; import org.springframework.boot.devtools.restart.Restarter; import org.springframework.boot.web.embedded.tomcat.TomcatWebServer; import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; /** * Tests for {@link LocalDevToolsAutoConfiguration}. * * @author Phillip Webb * @author Andy Wilkinson * @author Vladimir Tsanev */ @ExtendWith(MockRestarter.class) class LocalDevToolsAutoConfigurationTests { private ConfigurableApplicationContext context; @AfterEach void cleanup() { if (this.context != null) { this.context.close(); } } @Test void thymeleafCacheIsFalse() throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); SpringResourceTemplateResolver resolver = this.context.getBean(SpringResourceTemplateResolver.class); assertThat(resolver.isCacheable()).isFalse(); } @Test void defaultPropertyCanBeOverriddenFromCommandLine() throws Exception { this.context = getContext(() -> initializeAndRun(Config.class, "--spring.thymeleaf.cache=true")); SpringResourceTemplateResolver resolver = this.context.getBean(SpringResourceTemplateResolver.class); assertThat(resolver.isCacheable()).isTrue(); } @Test void defaultPropertyCanBeOverriddenFromUserHomeProperties() throws Exception { String userHome = System.getProperty("user.home"); System.setProperty("user.home", new File("src/test/resources/user-home").getAbsolutePath()); try { this.context = getContext(() -> initializeAndRun(Config.class)); SpringResourceTemplateResolver resolver = this.context.getBean(SpringResourceTemplateResolver.class); assertThat(resolver.isCacheable()).isTrue(); } finally { System.setProperty("user.home", userHome); } } @Test void resourceCachePeriodIsZero() throws Exception { this.context = getContext(() -> initializeAndRun(WebResourcesConfig.class)); ResourceProperties properties = this.context.getBean(ResourceProperties.class); assertThat(properties.getCache().getPeriod()).isZero(); } @Test void liveReloadServer() throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); LiveReloadServer server = this.context.getBean(LiveReloadServer.class); assertThat(server.isStarted()).isTrue(); } @Test void liveReloadTriggeredOnContextRefresh() throws Exception { this.context = getContext(() -> initializeAndRun(ConfigWithMockLiveReload.class)); LiveReloadServer server = this.context.getBean(LiveReloadServer.class); reset(server); this.context.publishEvent(new ContextRefreshedEvent(this.context)); verify(server).triggerReload(); } @Test void liveReloadTriggeredOnClassPathChangeWithoutRestart() throws Exception { this.context = getContext(() -> initializeAndRun(ConfigWithMockLiveReload.class)); LiveReloadServer server = this.context.getBean(LiveReloadServer.class); reset(server); ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), false); this.context.publishEvent(event); verify(server).triggerReload(); } @Test void liveReloadNotTriggeredOnClassPathChangeWithRestart() throws Exception { this.context = getContext(() -> initializeAndRun(ConfigWithMockLiveReload.class)); LiveReloadServer server = this.context.getBean(LiveReloadServer.class); reset(server); ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), true); this.context.publishEvent(event); verify(server, never()).triggerReload(); } @Test void liveReloadDisabled() throws Exception { Map<String, Object> properties = new HashMap<>(); properties.put("spring.devtools.livereload.enabled", false); this.context = getContext(() -> initializeAndRun(Config.class, properties)); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.context.getBean(OptionalLiveReloadServer.class)); } @Test void restartTriggeredOnClassPathChangeWithRestart(Restarter restarter) throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), true); this.context.publishEvent(event); verify(restarter).restart(any(FailureHandler.class)); } @Test void restartNotTriggeredOnClassPathChangeWithRestart(Restarter restarter) throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), false); this.context.publishEvent(event); verify(restarter, never()).restart(); } @Test void restartWatchingClassPath() throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); ClassPathFileSystemWatcher watcher = this.context.getBean(ClassPathFileSystemWatcher.class); assertThat(watcher).isNotNull(); } @Test void restartDisabled() throws Exception { Map<String, Object> properties = new HashMap<>(); properties.put("spring.devtools.restart.enabled", false); this.context = getContext(() -> initializeAndRun(Config.class, properties)); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.context.getBean(ClassPathFileSystemWatcher.class)); } @Test void restartWithTriggerFile() throws Exception { Map<String, Object> properties = new HashMap<>(); properties.put("spring.devtools.restart.trigger-file", "somefile.txt"); this.context = getContext(() -> initializeAndRun(Config.class, properties)); ClassPathFileSystemWatcher classPathWatcher = this.context.getBean(ClassPathFileSystemWatcher.class); Object watcher = ReflectionTestUtils.getField(classPathWatcher, "fileSystemWatcher"); Object filter = ReflectionTestUtils.getField(watcher, "triggerFilter"); assertThat(filter).isInstanceOf(TriggerFileFilter.class); } @Test void watchingAdditionalPaths() throws Exception { Map<String, Object> properties = new HashMap<>(); properties.put("spring.devtools.restart.additional-paths", "src/main/java,src/test/java"); this.context = getContext(() -> initializeAndRun(Config.class, properties)); ClassPathFileSystemWatcher classPathWatcher = this.context.getBean(ClassPathFileSystemWatcher.class); Object watcher = ReflectionTestUtils.getField(classPathWatcher, "fileSystemWatcher"); @SuppressWarnings("unchecked") Map<File, Object> directories = (Map<File, Object>) ReflectionTestUtils.getField(watcher, "directories"); assertThat(directories).hasSize(2).containsKey(new File("src/main/java").getAbsoluteFile()) .containsKey(new File("src/test/java").getAbsoluteFile()); } @Test void devToolsSwitchesJspServletToDevelopmentMode() throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); TomcatWebServer tomcatContainer = (TomcatWebServer) ((ServletWebServerApplicationContext) this.context) .getWebServer(); Container context = tomcatContainer.getTomcat().getHost().findChildren()[0]; StandardWrapper jspServletWrapper = (StandardWrapper) context.findChild("jsp"); EmbeddedServletOptions options = (EmbeddedServletOptions) ReflectionTestUtils .getField(jspServletWrapper.getServlet(), "options"); assertThat(options.getDevelopment()).isTrue(); } private ConfigurableApplicationContext getContext(Supplier<ConfigurableApplicationContext> supplier) throws Exception { AtomicReference<ConfigurableApplicationContext> atomicReference = new AtomicReference<>(); Thread thread = new Thread(() -> { ConfigurableApplicationContext context = supplier.get(); atomicReference.getAndSet(context); }); thread.start(); thread.join(); return atomicReference.get(); } private ConfigurableApplicationContext initializeAndRun(Class<?> config, String... args) { return initializeAndRun(config, Collections.emptyMap(), args); } private ConfigurableApplicationContext initializeAndRun(Class<?> config, Map<String, Object> properties, String... args) { Restarter.initialize(new String[0], false, new MockRestartInitializer(), false); SpringApplication application = new SpringApplication(config); application.setDefaultProperties(getDefaultProperties(properties)); return application.run(args); } private Map<String, Object> getDefaultProperties(Map<String, Object> specifiedProperties) { Map<String, Object> properties = new HashMap<>(); properties.put("spring.thymeleaf.check-template-location", false); properties.put("spring.devtools.livereload.port", 0); properties.put("server.port", 0); properties.putAll(specifiedProperties); return properties; } @Configuration(proxyBeanMethods = false) @Import({ ServletWebServerFactoryAutoConfiguration.class, LocalDevToolsAutoConfiguration.class, ThymeleafAutoConfiguration.class }) static class Config { } @Configuration(proxyBeanMethods = false) @ImportAutoConfiguration({ ServletWebServerFactoryAutoConfiguration.class, LocalDevToolsAutoConfiguration.class, ThymeleafAutoConfiguration.class }) static class ConfigWithMockLiveReload { @Bean LiveReloadServer liveReloadServer() { return mock(LiveReloadServer.class); } } @Configuration(proxyBeanMethods = false) @Import({ ServletWebServerFactoryAutoConfiguration.class, LocalDevToolsAutoConfiguration.class, ResourceProperties.class }) static class WebResourcesConfig { } @Configuration(proxyBeanMethods = false) static class SessionRedisTemplateConfig { @Bean RedisTemplate<Object, Object> sessionRedisTemplate() { RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(mock(RedisConnectionFactory.class)); return redisTemplate; } } }
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.tasks.vcs; import com.intellij.dvcs.repo.Repository; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.vcs.VcsTaskHandler; import com.intellij.openapi.vcs.changes.ChangeListManagerImpl; import com.intellij.tasks.BranchInfo; import com.intellij.tasks.LocalTask; import com.intellij.tasks.TaskManager; import com.intellij.tasks.actions.OpenTaskDialog; import com.intellij.tasks.impl.LocalTaskImpl; import com.intellij.tasks.impl.TaskManagerImpl; import com.intellij.testFramework.HeavyPlatformTestCase; import com.intellij.testFramework.RunAll; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.List; /** * @author Dmitry Avdeev */ public abstract class TaskBranchesTest extends HeavyPlatformTestCase { private TaskManagerImpl myTaskManager; @Override protected void tearDown() throws Exception { new RunAll( () -> ChangeListManagerImpl.getInstanceImpl(myProject).forceStopInTestMode(), () -> ChangeListManagerImpl.getInstanceImpl(myProject).waitEverythingDoneInTestMode(), () -> myTaskManager = null, () -> super.tearDown() ).run(); } public void testVcsTaskHandler() { List<Repository> repositories = initRepositories("community", "idea"); Repository repository = repositories.get(0); String defaultBranchName = getDefaultBranchName(); assertEquals(defaultBranchName, repository.getCurrentBranchName()); VcsTaskHandler[] handlers = VcsTaskHandler.getAllHandlers(getProject()); assertEquals(1, handlers.length); VcsTaskHandler handler = handlers[0]; VcsTaskHandler.TaskInfo defaultInfo = handler.getAllExistingTasks()[0]; assertEquals(defaultBranchName, defaultInfo.getName()); assertEquals(2, defaultInfo.getRepositories().size()); final String first = "first"; VcsTaskHandler.TaskInfo firstInfo = handler.startNewTask(first); repository.update(); assertEquals(first, firstInfo.getName()); assertEquals(2, firstInfo.getRepositories().size()); assertEquals(2, getNumberOfBranches(repository)); assertEquals(first, repository.getCurrentBranchName()); handler.switchToTask(defaultInfo, null); repository.update(); assertEquals(defaultBranchName, repository.getCurrentBranchName()); final String second = "second"; VcsTaskHandler.TaskInfo secondInfo = handler.startNewTask(second); repository.update(); assertEquals(3, getNumberOfBranches(repository)); assertEquals(second, repository.getCurrentBranchName()); handler.switchToTask(firstInfo, null); createAndCommitChanges(repository); handler.closeTask(secondInfo, firstInfo); repository.update(); assertEquals(2, getNumberOfBranches(repository)); } public void testTaskManager() { List<Repository> repositories = initRepositories("community", "idea"); LocalTask defaultTask = myTaskManager.getActiveTask(); assertNotNull(defaultTask); LocalTaskImpl foo = myTaskManager.createLocalTask("foo"); LocalTask localTask = myTaskManager.activateTask(foo, false); myTaskManager.createBranch(localTask, defaultTask, myTaskManager.suggestBranchName(localTask), null); String defaultBranchName = getDefaultBranchName(); assertEquals(4, localTask.getBranches().size()); assertEquals(2, localTask.getBranches(true).size()); assertEquals(2, localTask.getBranches(false).size()); assertEquals(2, defaultTask.getBranches().size()); myTaskManager.activateTask(defaultTask, false); Repository repository = repositories.get(0); assertEquals(defaultBranchName, repository.getCurrentBranchName()); foo = myTaskManager.createLocalTask("foo"); localTask = myTaskManager.activateTask(foo, false); myTaskManager.createBranch(localTask, defaultTask, myTaskManager.suggestBranchName(localTask), null); assertEquals("foo", repository.getCurrentBranchName()); createAndCommitChanges(repository); myTaskManager.mergeBranch(localTask); repository.update(); assertEquals(defaultBranchName, repository.getCurrentBranchName()); assertEquals(1, getNumberOfBranches(repository)); myTaskManager.activateTask(defaultTask, false); myTaskManager.activateTask(foo, false); } public void testCommit() { Repository repository = initRepository("foo"); LocalTask defaultTask = myTaskManager.getActiveTask(); LocalTaskImpl foo = myTaskManager.createLocalTask("foo"); final LocalTask localTask = myTaskManager.activateTask(foo, false); myTaskManager.createBranch(localTask, defaultTask, myTaskManager.suggestBranchName(localTask), null); createAndCommitChanges(repository); myTaskManager.mergeBranch(localTask); repository.update(); assertEquals(getDefaultBranchName(), repository.getCurrentBranchName()); assertEquals(1, getNumberOfBranches(repository)); } public void testOpenTaskDialog() { initRepository("foo"); String defaultBranchName = getDefaultBranchName(); LocalTaskImpl task = myTaskManager.createLocalTask("foo"); OpenTaskDialog dialog = new OpenTaskDialog(getProject(), task); Disposer.register(getTestRootDisposable(), dialog.getDisposable()); try { dialog.createTask(); assertEquals("foo", myTaskManager.getActiveTask().getSummary()); List<BranchInfo> branches = task.getBranches(true); assertEquals(1, branches.size()); assertEquals(defaultBranchName, branches.get(0).name); branches = task.getBranches(false); assertEquals(1, branches.size()); assertEquals("foo", branches.get(0).name); } finally { dialog.close(DialogWrapper.OK_EXIT_CODE); } UIUtil.dispatchAllInvocationEvents(); } public void testBranchBloating() { Repository repository = initRepository("foo"); LocalTask defaultTask = myTaskManager.getActiveTask(); assertNotNull(defaultTask); assertEquals(0, defaultTask.getBranches().size()); LocalTaskImpl foo = myTaskManager.createLocalTask("foo"); LocalTask localTask = myTaskManager.activateTask(foo, false); myTaskManager.createBranch(localTask, defaultTask, myTaskManager.suggestBranchName(localTask), null); repository.update(); assertEquals(2, localTask.getBranches().size()); assertEquals(1, defaultTask.getBranches().size()); myTaskManager.activateTask(localTask, false); LocalTaskImpl bar = myTaskManager.createLocalTask("bar"); LocalTask barTask = myTaskManager.activateTask(bar, false); myTaskManager.createBranch(localTask, defaultTask, myTaskManager.suggestBranchName(barTask), null); repository.update(); assertEquals(1, defaultTask.getBranches().size()); } public void testCleanupRemovedBranch() { Repository repository = initRepository("foo"); LocalTask defaultTask = myTaskManager.getActiveTask(); assertNotNull(defaultTask); assertEquals(0, defaultTask.getBranches().size()); LocalTaskImpl foo = myTaskManager.createLocalTask("foo"); LocalTask localTask = myTaskManager.activateTask(foo, false); myTaskManager.createBranch(localTask, defaultTask, myTaskManager.suggestBranchName(localTask), null); assertEquals(2, localTask.getBranches().size()); assertEquals(1, defaultTask.getBranches().size()); // let's add non-existing branch BranchInfo info = new BranchInfo(); info.name = "non-existing"; info.repository = defaultTask.getBranches().get(0).repository; defaultTask.addBranch(info); repository.update(); assertEquals("foo", repository.getCurrentBranchName()); myTaskManager.activateTask(defaultTask, false); repository.update(); assertEquals(getDefaultBranchName(), repository.getCurrentBranchName()); // do not re-create "non-existing" assertEquals(2, getNumberOfBranches(repository)); } public void testSuggestBranchName() { initRepositories("community", "idea"); VcsTaskHandler[] handlers = VcsTaskHandler.getAllHandlers(getProject()); assertEquals(1, handlers.length); VcsTaskHandler handler = handlers[0]; String startName = "-Hello, this is long name with : and $"; assertFalse(handler.isBranchNameValid(startName)); String cleanUpBranchName = handler.cleanUpBranchName(startName); assertTrue(handler.isBranchNameValid(cleanUpBranchName)); } public void _testCurrentTasks() { initRepositories("foo", "bar"); VcsTaskHandler handler = VcsTaskHandler.getAllHandlers(getProject())[0]; VcsTaskHandler.TaskInfo[] tasks = handler.getAllExistingTasks(); assertEquals(1, tasks.length); VcsTaskHandler.TaskInfo defaultTask = tasks[0]; assertEquals(1, handler.getCurrentTasks().length); VcsTaskHandler.TaskInfo task = handler.startNewTask("new"); assertEquals(2, handler.getAllExistingTasks().length); assertEquals(1, handler.getCurrentTasks().length); handler.closeTask(task, defaultTask); VcsTaskHandler.TaskInfo[] existingTasks = handler.getAllExistingTasks(); assertEquals(Arrays.asList(existingTasks).toString(), 1, existingTasks.length); assertEquals(1, handler.getCurrentTasks().length); } private List<Repository> initRepositories(String... names) { return ContainerUtil.map(names, this::initRepository); } @Override protected void setUp() throws Exception { super.setUp(); myTaskManager = (TaskManagerImpl)TaskManager.getManager(getProject()); } @NotNull protected abstract Repository initRepository(@NotNull String name); @NotNull protected abstract String getDefaultBranchName(); protected abstract int getNumberOfBranches(@NotNull Repository repository); protected abstract void createAndCommitChanges(@NotNull Repository repository); }
/* * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved * * The original version of this source code and documentation * is copyrighted and owned by Taligent, Inc., a wholly-owned * subsidiary of IBM. These materials are provided under terms * of a License Agreement between Taligent and Sun. This technology * is protected by multiple US and International patents. * * This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ package sun.text.resources.no; import sun.util.resources.ParallelListResourceBundle; public class FormatData_no extends ParallelListResourceBundle { /** * Overrides ParallelListResourceBundle */ protected final Object[][] getContents() { return new Object[][] { { "MonthNames", new String[] { "januar", // january "februar", // february "mars", // march "april", // april "mai", // may "juni", // june "juli", // july "august", // august "september", // september "oktober", // october "november", // november "desember", // december "" // month 13 if applicable } }, { "standalone.MonthNames", new String[] { "januar", "februar", "mars", "april", "mai", "juni", "juli", "august", "september", "oktober", "november", "desember", "", } }, { "MonthAbbreviations", new String[] { "jan", // abb january "feb", // abb february "mar", // abb march "apr", // abb april "mai", // abb may "jun", // abb june "jul", // abb july "aug", // abb august "sep", // abb september "okt", // abb october "nov", // abb november "des", // abb december "" // abb month 13 if applicable } }, { "standalone.MonthAbbreviations", new String[] { "jan", "feb", "mar", "apr", "mai", "jun", "jul", "aug", "sep", "okt", "nov", "des", "", } }, { "MonthNarrows", new String[] { "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D", "", } }, { "standalone.MonthNarrows", new String[] { "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D", "", } }, { "DayNames", new String[] { "s\u00f8ndag", // Sunday "mandag", // Monday "tirsdag", // Tuesday "onsdag", // Wednesday "torsdag", // Thursday "fredag", // Friday "l\u00f8rdag" // Saturday } }, { "standalone.DayNames", new String[] { "s\u00f8ndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "l\u00f8rdag", } }, { "DayAbbreviations", new String[] { "s\u00f8", // abb Sunday "ma", // abb Monday "ti", // abb Tuesday "on", // abb Wednesday "to", // abb Thursday "fr", // abb Friday "l\u00f8" // abb Saturday } }, { "standalone.DayAbbreviations", new String[] { "s\u00f8.", "ma.", "ti.", "on.", "to.", "fr.", "l\u00f8.", } }, { "DayNarrows", new String[] { "S", "M", "T", "O", "T", "F", "L", } }, { "standalone.DayNarrows", new String[] { "S", "M", "T", "O", "T", "F", "L", } }, { "NumberElements", new String[] { ",", // decimal separator "\u00a0", // group (thousands) separator ";", // list separator "%", // percent sign "0", // native 0 digit "#", // pattern digit "-", // minus sign "E", // exponential "\u2030", // per mille "\u221e", // infinity "\ufffd" // NaN } }, { "TimePatterns", new String[] { "'kl 'HH.mm z", // full time pattern "HH:mm:ss z", // long time pattern "HH:mm:ss", // medium time pattern "HH:mm", // short time pattern } }, { "DatePatterns", new String[] { "d. MMMM yyyy", // full date pattern "d. MMMM yyyy", // long date pattern "dd.MMM.yyyy", // medium date pattern "dd.MM.yy", // short date pattern } }, { "DateTimePatterns", new String[] { "{1} {0}" // date-time pattern } }, { "DateTimePatternChars", "GyMdkHmsSEDFwWahKzZ" }, }; } }
// Copyright 2012 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.collide.client.code.autocomplete.codemirror; import static com.google.collide.client.code.autocomplete.TestUtils.CTRL_SPACE; import static com.google.gwt.event.dom.client.KeyCodes.KEY_BACKSPACE; import static org.waveprotocol.wave.client.common.util.SignalEvent.KeySignalType.DELETE; import com.google.collide.client.code.autocomplete.AutocompleteProposals; import com.google.collide.client.code.autocomplete.AutocompleteProposals.ProposalWithContext; import com.google.collide.client.code.autocomplete.AutocompleteResult; import com.google.collide.client.code.autocomplete.DefaultAutocompleteResult; import com.google.collide.client.code.autocomplete.LanguageSpecificAutocompleter; import com.google.collide.client.code.autocomplete.LanguageSpecificAutocompleter.ExplicitAction; import com.google.collide.client.code.autocomplete.LanguageSpecificAutocompleter.ExplicitActionType; import com.google.collide.client.code.autocomplete.MockAutocompleterEnvironment; import com.google.collide.client.code.autocomplete.MockAutocompleterEnvironment.MockAutocompleter; import com.google.collide.client.code.autocomplete.SignalEventEssence; import com.google.collide.client.code.autocomplete.TestUtils; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.input.TestSignalEvent; import com.google.collide.client.testutil.CodeMirrorTestCase; import com.google.collide.client.testutil.TestSchedulerImpl; import com.google.collide.client.util.PathUtil; import com.google.collide.client.util.input.ModifierKeys; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonStringSet; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.util.LineUtils; import com.google.collide.shared.util.JsonCollections; import com.google.gwt.core.client.Scheduler; import com.google.gwt.event.dom.client.KeyCodes; import org.waveprotocol.wave.client.common.util.SignalEvent.KeySignalType; import javax.annotation.Nullable; /** * Test for JS autocompletion cases, when CodeMirror parser is used. * */ public class JsCodemirrorTest extends CodeMirrorTestCase { static final SignalEventEssence DELETE_KEY = new SignalEventEssence( KEY_BACKSPACE, false, false, false, false, DELETE); private static final SignalEventEssence ENTER = new SignalEventEssence( KeyCodes.KEY_ENTER, false, false, false, false, KeySignalType.INPUT); @Override public String getModuleName() { return "com.google.collide.client.TestCode"; } public void testNoProposalsInCommentsAndStrings() { // 0 1 2 // 012345678901234567890123456789 String text1 = "var a = 'Hello Kitty'; // Funny?"; String text2 = "var b = /* Aha =) */ 0;"; checkHasProposals(text1, 0, true, "global"); checkHasProposals(text1, 8, true, "before string"); checkHasProposals(text1, 9, false, "string began"); checkHasProposals(text1, 10, false, "in string"); checkHasProposals(text1, 15, false, "in string after space"); checkHasProposals(text1, 21, true, "after string"); checkHasProposals(text1, 22, true, "after string"); checkHasProposals(text1, 23, true, "before comment"); checkHasProposals(text1, 26, false, "in comment after space"); checkHasProposals(text1, 30, false, "in comment"); checkHasProposals(text2, 0, true, "after comment"); checkHasProposals(text2, 8, true, "before multiline"); checkHasProposals(text2, 13, false, "in multiline"); checkHasProposals(text2, 15, false, "in multiline after space"); checkHasProposals(text2, 21, true, "after multiline"); } private void checkHasProposals(String text, int column, boolean expectHasProposals, String message) { MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment(); helper.setup(new PathUtil("foo.js"), text, 0, column, true); AutocompleteProposals proposals = helper.autocompleter.jsAutocompleter.findAutocompletions( helper.editor.getSelection(), CTRL_SPACE); assertEquals(message, expectHasProposals, !proposals.isEmpty()); } public void testNoTemplateProposalsAfterThis() { MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment(); helper.setup(new PathUtil("foo.js"), "this.", 0, 5, true); AutocompleteProposals proposals = helper.autocompleter.jsAutocompleter.findAutocompletions( helper.editor.getSelection(), CTRL_SPACE); assertTrue("has no proposals", proposals.isEmpty()); } public void testTemplateProposalsInGlobal() { MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment(); helper.setup(new PathUtil("foo.js"), "", 0, 0, true); AutocompleteProposals autocompletions = helper.autocompleter.jsAutocompleter.findAutocompletions( helper.editor.getSelection(), CTRL_SPACE); assertFalse("has proposals", autocompletions.isEmpty()); ProposalWithContext whileProposal = TestUtils.selectProposalByName(autocompletions, "while"); assertNotNull("has 'while'", whileProposal); helper.autocompleter.reallyFinishAutocompletion(whileProposal); assertEquals("while () {\n \n}", helper.editor.getDocument().asText()); } public void testAutocompletionAfterKeyword() { MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment(); helper.setup(new PathUtil("foo.js"), "for", 0, 3, true); AutocompleteProposals autocompletions = helper.autocompleter.jsAutocompleter.findAutocompletions( helper.editor.getSelection(), CTRL_SPACE); ProposalWithContext proposal = autocompletions.select(0); assertEquals("proposal name", "for", proposal.getItem().getName()); helper.autocompleter.reallyFinishAutocompletion(proposal); String text = helper.editor.getDocument().getFirstLine().getText(); assertEquals("resulting text", "for (;;) {\n", text); } public void testDoNotDieOnLongLines() { String longLine = " "; for (int i = 0; i < 12; i++) { longLine = longLine + longLine; } // longLine length is 4096 MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment(); String text = "function foo() {\n" + " var bar1;\n" + " var bar2 ='" + longLine + "';\n" + " var bar3;\n" + " " // Cursor here. + "}"; helper.setup(new PathUtil("foo.js"), text, 4, 2, true); helper.parser.begin(); helper.parseScheduler.requests.get(0).run(10); AutocompleteProposals autocompletions = helper.autocompleter.jsAutocompleter.findAutocompletions( helper.editor.getSelection(), CTRL_SPACE); JsonStringSet proposals = JsonCollections.createStringSet(); for (int i = 0, l = autocompletions.size(); i < l; i++) { proposals.add(autocompletions.get(i).getName()); } assertTrue("contains var defined before long line", proposals.contains("bar1")); assertTrue("contains var defined after long line", proposals.contains("bar3")); } public void testDoNotDieOnRegExp() { MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment(); String text = "function foo() {\n" + " var bar1 = /regexp/;\n" + " var bar2;\n" + " " // Cursor here. + "}"; helper.setup(new PathUtil("foo.js"), text, 3, 2, true); helper.parser.begin(); helper.parseScheduler.requests.get(0).run(10); AutocompleteProposals autocompletions = helper.autocompleter.jsAutocompleter.findAutocompletions( helper.editor.getSelection(), CTRL_SPACE); JsonStringSet proposals = JsonCollections.createStringSet(); for (int i = 0, l = autocompletions.size(); i < l; i++) { proposals.add(autocompletions.get(i).getName()); } assertTrue("contains var defined in line with regexp", proposals.contains("bar1")); assertTrue("contains var defined after line with regexp", proposals.contains("bar2")); } public void testDeleteAtBeginningOfDocument() { MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment(); String text = "<cursorAtTheBeginingOfFirstLine>"; helper.setup(new PathUtil("foo.js"), text, 0, 0, true); ExplicitAction action = helper.autocompleter.jsAutocompleter.getExplicitAction( helper.editor.getSelection(), DELETE_KEY, false); assertEquals(LanguageSpecificAutocompleter.ExplicitActionType.DEFAULT, action.getType()); } public void testClosePopupOnSpace() { MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment(); // TODO: vars in the global scope are not registered by CM. String text = "function a() { var abba, apple, arrow; a"; helper.setup(new PathUtil("foo.js"), text, 0, text.length(), true); final MockAutocompleter autocompleter = helper.autocompleter; assertFalse("initially popup is not shown", helper.popup.isShowing()); final JsonArray<Scheduler.ScheduledCommand> scheduled = JsonCollections.createArray(); // We want to click ctrl-space. Runnable ctrlSpaceClicker = new Runnable() { @Override public void run() { autocompleter.pressKey(CTRL_SPACE); } }; // Collect deferred tasks in array. TestSchedulerImpl.AngryScheduler scheduler = new TestSchedulerImpl.AngryScheduler() { @Override public void scheduleDeferred(ScheduledCommand scheduledCommand) { scheduled.add(scheduledCommand); } }; // Now, if we hit ctrl-space - popup will appear with 3 variables. TestSchedulerImpl.runWithSpecificScheduler(ctrlSpaceClicker, scheduler); assertEquals("actual autocompletion is deferred", 1, scheduled.size()); // Now autocompletion acts. scheduled.get(0).execute(); assertTrue("popup appeared", helper.popup.isShowing()); assertEquals("variables are proposed", 4, helper.popup.proposals.size()); // Now, if we type " " autocompletion popup should disappear. autocompleter.pressKey(new SignalEventEssence(' ')); assertFalse("popup disappeared", helper.popup.isShowing()); } public void testRawExplicitInContext() { SignalEventEssence quoteKey = new SignalEventEssence('"'); checkExplicit("line-comment", "// var a =", 0, quoteKey, null); checkExplicit("in-block-comment", "/* var a = */", 3, quoteKey, null); checkExplicit("block-comment-eol", "/* var a =\nsecond line*/", 0, quoteKey, null); checkExplicit("in-string", "var a =''", 1, quoteKey, null); checkExplicit("bs-in-string", "var a ='\"\"'", 2, DELETE_KEY, null); checkExplicit("bs-in-comment", "// var a =''", 1, DELETE_KEY, null); checkExplicit("bs-between-string", "var a ='''", 1, DELETE_KEY, null); } public void testBracesPairing() { checkExplicit("braces-pairing", "foo", 0, new SignalEventEssence('['), new DefaultAutocompleteResult("[]", "", 1)); } public void testBracesNotPairing() { checkExplicit("braces-not-pairing", "foo", 3, new SignalEventEssence('['), null); } public void testQuotesPairing() { checkExplicit("quotes-pairing", "", 0, new SignalEventEssence('"'), new DefaultAutocompleteResult("\"\"", "", 1)); } public void testQuotesNotPairing() { checkExplicit("quotes-not-pairing", "\"\"", 0, new SignalEventEssence('"'), null); } public void testBracesPassing() { checkExplicit( "braces-passing", "foo[]", 1, new SignalEventEssence(']'), DefaultAutocompleteResult.PASS_CHAR); } public void testBracesNotPassing() { checkExplicit("braces-not-passing", "[(()]", 2, new SignalEventEssence(')'), null); } public void testSymmetricDeletion() { DefaultAutocompleteResult bsDelete = new DefaultAutocompleteResult( "", 0, 1, 0, 1, null, ""); checkExplicit("bs-after-comment", "/* Q */ var a =''", 1, DELETE_KEY, bsDelete); checkExplicit("bs-braces", "foo[]", 1, DELETE_KEY, bsDelete); } public void testEnterBetweenCurlyBraces() { checkExplicit("enter-between-curly-braces", " {}", 1, ENTER, new DefaultAutocompleteResult("\n \n ", "", 5)); } private void checkExplicit(String message, String text, int tailOffset, SignalEventEssence trigger, @Nullable DefaultAutocompleteResult expected) { MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment(); Document document = Document.createFromString(text); int column = LineUtils.getLastCursorColumn(document.getFirstLine()) - tailOffset; helper.setup(new PathUtil("foo.js"), document, 0, column, true); ExplicitAction action = helper.autocompleter.jsAutocompleter.getExplicitAction( helper.editor.getSelection(), trigger, false); AutocompleteResult commonResult = action.getExplicitAutocompletion(); if (expected == null) { assertNull("result", commonResult); assertFalse("action", ExplicitActionType.EXPLICIT_COMPLETE == action.getType()); return; } else { assertTrue("action", ExplicitActionType.EXPLICIT_COMPLETE == action.getType()); } assertTrue("result type", commonResult instanceof DefaultAutocompleteResult); DefaultAutocompleteResult result = (DefaultAutocompleteResult) commonResult; assertNotNull(message + ":result", result); assertEquals(message + ":text", expected.getAutocompletionText(), result.getAutocompletionText()); assertEquals(message + ":delete", expected.getDeleteCount(), result.getDeleteCount()); assertEquals(message + ":bspace", expected.getBackspaceCount(), result.getBackspaceCount()); assertEquals(message + ":jump", expected.getJumpLength(), result.getJumpLength()); } /** * Integration test: check that * {@link com.google.collide.client.code.autocomplete.codegraph.CodeGraphAutocompleter} * allows * {@link com.google.collide.client.editor.input.DefaultScheme} to * perform specific textual changes. */ public void testDoNotPreventCtrlBs() { String text = "#!@abc "; MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment(); helper.setup(new PathUtil("test.js"), text, 0, text.length(), true); final Editor editor = helper.editor; final JsonArray<Scheduler.ScheduledCommand> scheduled = JsonCollections.createArray(); TestSchedulerImpl.AngryScheduler scheduler = new TestSchedulerImpl.AngryScheduler() { @Override public void scheduleDeferred(ScheduledCommand scheduledCommand) { scheduled.add(scheduledCommand); } }; Runnable ctrlBsClicker = new Runnable() { @Override public void run() { TestSignalEvent bsTrigger = new TestSignalEvent( KeyCodes.KEY_BACKSPACE, KeySignalType.DELETE, ModifierKeys.ACTION); editor.getInput().processSignalEvent(bsTrigger); } }; TestSchedulerImpl.runWithSpecificScheduler(ctrlBsClicker, scheduler); while (!scheduled.isEmpty()) { Scheduler.ScheduledCommand command = scheduled.remove(0); command.execute(); } String result2 = editor.getDocument().getFirstLine().getText(); assertEquals("after ctrl-BS", "#!@", result2); } }
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.deeplearning4j.arbiter.ui.listener; import it.unimi.dsi.fastutil.floats.FloatArrayList; import it.unimi.dsi.fastutil.ints.IntArrayList; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.deeplearning4j.core.storage.Persistable; import org.deeplearning4j.core.storage.StatsStorageRouter; import org.deeplearning4j.arbiter.optimize.api.OptimizationResult; import org.deeplearning4j.arbiter.optimize.runner.CandidateInfo; import org.deeplearning4j.arbiter.optimize.runner.IOptimizationRunner; import org.deeplearning4j.arbiter.optimize.runner.listener.StatusListener; import org.deeplearning4j.arbiter.optimize.serde.jackson.JsonMapper; import org.deeplearning4j.arbiter.ui.data.GlobalConfigPersistable; import org.deeplearning4j.arbiter.ui.data.ModelInfoPersistable; import org.deeplearning4j.nn.graph.ComputationGraph; import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; import org.nd4j.common.primitives.Pair; import java.io.IOException; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; /** * A {@link StatusListener} for reporting Arbiter/DL4J optimization results to a {@link StatsStorageRouter} * * @author Alex Black */ @Slf4j public class ArbiterStatusListener implements StatusListener { public static final int MAX_SCORE_VS_ITER_PTS = 1024; //Above this: subsample... every 2nd, 4th, 8th etc private final String sessionId; private final StatsStorageRouter statsStorage; private String ocJson; private long startTime = 0; private Map<Integer,Integer> candidateScoreVsIterSubsampleFreq = new ConcurrentHashMap<>(); private Map<Integer,Pair<IntArrayList,FloatArrayList>> candidateScoreVsIter = new ConcurrentHashMap<>(); private Map<Integer,ModelInfoPersistable> lastModelInfoPersistable = new ConcurrentHashMap<>(); public ArbiterStatusListener(@NonNull StatsStorageRouter statsStorage) { this(UUID.randomUUID().toString(), statsStorage); } public ArbiterStatusListener(@NonNull String sessionId, @NonNull StatsStorageRouter statsStorage){ this.sessionId = sessionId; this.statsStorage = statsStorage; } @Override public void onInitialization(IOptimizationRunner r) { Persistable p = getNewStatusPersistable(r); statsStorage.putStaticInfo(p); } @Override public void onShutdown(IOptimizationRunner runner) { //No op? } @Override public void onRunnerStatusChange(IOptimizationRunner r) { Persistable p = getNewStatusPersistable(r); statsStorage.putStaticInfo(p); } @Override public void onCandidateStatusChange(CandidateInfo candidateInfo, IOptimizationRunner runner, OptimizationResult result) { ModelInfoPersistable p = lastModelInfoPersistable.get(candidateInfo.getIndex()); if(p == null){ p = new ModelInfoPersistable.Builder() .timestamp(candidateInfo.getCreatedTime()) .sessionId(sessionId) .workerId(String.valueOf(candidateInfo.getIndex())) .modelIdx(candidateInfo.getIndex()) .score(candidateInfo.getScore()) .status(candidateInfo.getCandidateStatus()) .exceptionStackTrace(candidateInfo.getExceptionStackTrace()) .build(); lastModelInfoPersistable.put(candidateInfo.getIndex(), p); } if(p.getScore() == null){ p.setScore(candidateInfo.getScore()); } if(result != null && p.getExceptionStackTrace() == null && result.getCandidateInfo().getExceptionStackTrace() != null){ //Update exceptions that may have occurred since earlier model info instance p.setExceptionStackTrace(result.getCandidateInfo().getExceptionStackTrace()); } p.setStatus(candidateInfo.getCandidateStatus()); statsStorage.putUpdate(p); } @Override public void onCandidateIteration(CandidateInfo candidateInfo, Object candidate, int iteration) { double score; long numParams; int numLayers; String modelConfigJson; int totalNumUpdates; if(candidate instanceof MultiLayerNetwork){ MultiLayerNetwork m = (MultiLayerNetwork)candidate; score = m.score(); numParams = m.numParams(); numLayers = m.getnLayers(); modelConfigJson = m.getLayerWiseConfigurations().toJson(); totalNumUpdates = m.getLayerWiseConfigurations().getIterationCount(); } else if(candidate instanceof ComputationGraph) { ComputationGraph cg = (ComputationGraph)candidate; score = cg.score(); numParams = cg.numParams(); numLayers = cg.getNumLayers(); modelConfigJson = cg.getConfiguration().toJson(); totalNumUpdates = cg.getConfiguration().getIterationCount(); } else { score = 0; numParams = 0; numLayers = 0; totalNumUpdates = 0; modelConfigJson = ""; } int idx = candidateInfo.getIndex(); Pair<IntArrayList, FloatArrayList> pair = candidateScoreVsIter.computeIfAbsent(idx, k -> new Pair<>(new IntArrayList(), new FloatArrayList())); IntArrayList iter = pair.getFirst(); FloatArrayList scores = pair.getSecond(); //Do we need subsampling to avoid having too many data points? int subsamplingFreq = candidateScoreVsIterSubsampleFreq.computeIfAbsent(idx, k -> 1); if(iteration / subsamplingFreq > MAX_SCORE_VS_ITER_PTS){ //Double subsampling frequency and re-parse data subsamplingFreq *= 2; candidateScoreVsIterSubsampleFreq.put(idx, subsamplingFreq); IntArrayList newIter = new IntArrayList(); FloatArrayList newScores = new FloatArrayList(); for( int i=0; i<iter.size(); i++ ){ int it = iter.get(i); if(it % subsamplingFreq == 0){ newIter.add(it); newScores.add(scores.get(i)); } } iter = newIter; scores = newScores; candidateScoreVsIter.put(idx, new Pair<>(iter, scores)); } if(iteration % subsamplingFreq == 0) { iter.add(iteration); scores.add((float) score); } int[] iters = iter.toIntArray(); float[] fScores = new float[iters.length]; for( int i=0; i<iters.length; i++ ){ fScores[i] = scores.get(i); } ModelInfoPersistable p = new ModelInfoPersistable.Builder() .timestamp(candidateInfo.getCreatedTime()) .sessionId(sessionId) .workerId(String.valueOf(candidateInfo.getIndex())) .modelIdx(candidateInfo.getIndex()) .score(candidateInfo.getScore()) .status(candidateInfo.getCandidateStatus()) .scoreVsIter(iters, fScores) .lastUpdateTime(System.currentTimeMillis()) .numParameters(numParams) .numLayers(numLayers) .totalNumUpdates(totalNumUpdates) .paramSpaceValues(candidateInfo.getFlatParams()) .modelConfigJson(modelConfigJson) .exceptionStackTrace(candidateInfo.getExceptionStackTrace()) .build(); lastModelInfoPersistable.put(candidateInfo.getIndex(), p); statsStorage.putUpdate(p); } private GlobalConfigPersistable getNewStatusPersistable(IOptimizationRunner r){ // if(ocJson == null || this.startTime == 0L){ // //Want to update config once start time has been set // ocJson = JsonMapper.asJson(r.getConfiguration()); // this.startTime = r.getConfiguration().getExecutionStartTime(); // } //TODO: cache global config, but we don't want to have outdated info (like uninitialized termination conditions) try { ocJson = JsonMapper.getMapper().writeValueAsString(r.getConfiguration()); } catch (IOException e){ throw new RuntimeException(e); } GlobalConfigPersistable p = new GlobalConfigPersistable.Builder() .sessionId(sessionId) .timestamp(System.currentTimeMillis()) .optimizationConfigJson(ocJson) .candidateCounts(r.numCandidatesQueued(), r.numCandidatesCompleted(), r.numCandidatesFailed(), r.numCandidatesTotal()) .optimizationRunner(r.getClass().getSimpleName()) .build(); return p; } }
/* * Copyright (c) 2008-2020, Hazelcast, 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.hazelcast.jet.pipeline; import com.hazelcast.function.BiFunctionEx; import com.hazelcast.function.FunctionEx; import com.hazelcast.jet.accumulator.LongAccumulator; import com.hazelcast.jet.aggregate.AggregateOperation; import com.hazelcast.jet.aggregate.AggregateOperation1; import com.hazelcast.jet.aggregate.AggregateOperations; import com.hazelcast.jet.aggregate.CoAggregateOperationBuilder; import com.hazelcast.jet.datamodel.ItemsByTag; import com.hazelcast.jet.datamodel.Tag; import com.hazelcast.jet.datamodel.Tuple2; import com.hazelcast.jet.datamodel.Tuple3; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collector; import static com.hazelcast.function.ComparatorEx.comparingInt; import static com.hazelcast.jet.Util.entry; import static com.hazelcast.jet.aggregate.AggregateOperations.aggregateOperation2; import static com.hazelcast.jet.aggregate.AggregateOperations.aggregateOperation3; import static com.hazelcast.jet.aggregate.AggregateOperations.coAggregateOperationBuilder; import static com.hazelcast.jet.aggregate.AggregateOperations.maxBy; import static com.hazelcast.jet.datamodel.ItemsByTag.itemsByTag; import static com.hazelcast.jet.datamodel.Tuple2.tuple2; import static com.hazelcast.jet.datamodel.Tuple3.tuple3; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.summingLong; import static org.junit.Assert.assertEquals; public class BatchAggregateTest extends PipelineTestSupport { static final FunctionEx<Entry<Integer, Long>, String> FORMAT_FN = e -> String.format("(%04d: %04d)", e.getKey(), e.getValue()); static final BiFunctionEx<Integer, Tuple2<Long, Long>, String> FORMAT_FN_2 = (key, t2) -> String.format("(%04d: %04d, %04d)", key, t2.f0(), t2.f1()); static final BiFunctionEx<Integer, Tuple3<Long, Long, Long>, String> FORMAT_FN_3 = (key, t3) -> String.format("(%04d: %04d, %04d, %04d)", key, t3.f0(), t3.f1(), t3.f2()); private static final AggregateOperation1<Integer, LongAccumulator, Long> SUMMING = AggregateOperations.summingLong(i -> i); private static final int FACTOR_1 = 1_000; private static final int FACTOR_2 = 1_000_000; private List<Integer> input; @Before public void before() { input = sequence(itemCount); } @Test public void aggregate() { // When BatchStage<Long> aggregated = batchStageFromInput().aggregate(SUMMING); // Then aggregated.writeTo(sink); execute(); assertEquals( singletonList(input.stream().mapToLong(i -> i).sum()), new ArrayList<>(sinkList) ); } @Test public void when_aggregateZeroItems_then_producesOutput() { // When BatchStage<Long> aggregated = batchStageFromList(emptyList()).aggregate(SUMMING); // Then aggregated.writeTo(sink); execute(); assertEquals( singletonList(0L), new ArrayList<>(sinkList) ); } @Test public void when_maxOfZeroItems_then_producesNoOutput() { // When BatchStage<Integer> aggregated = batchStageFromList(emptyList()).aggregate(maxBy(comparingInt(i -> i))); // Then aggregated.writeTo(sink); execute(); assertEquals( emptyList(), new ArrayList<>(sinkList) ); } @Test public void aggregate2_withSeparateAggrOps() { // Given BatchStage<Integer> stage = batchStageFromInput(); // When BatchStage<Tuple2<Long, Long>> aggregated = batchStageFromInput() .aggregate2(SUMMING, stage, SUMMING); // Then aggregated.writeTo(sink); execute(); long expectedSum = input.stream().mapToLong(i -> i).sum(); assertEquals( singletonList(tuple2(expectedSum, expectedSum)), new ArrayList<>(sinkList) ); } @Test public void aggregate2_withAggrOp2() { // When BatchStage<Tuple2<Long, Long>> aggregated = batchStageFromInput() .aggregate2(batchStageFromInput(), aggregateOperation2(SUMMING, SUMMING)); // Then aggregated.writeTo(sink); execute(); long expectedSum = input.stream().mapToLong(i -> i).sum(); assertEquals( singletonList(tuple2(expectedSum, expectedSum)), new ArrayList<>(sinkList) ); } @Test public void aggregate2_withAggrOp2_with_finishFn() { // Given BiFunctionEx<Long, Long, Long> outputFn = (a, b) -> 10_000 * a + b; // When BatchStage<Long> aggregated = batchStageFromInput().aggregate2( batchStageFromInput(), aggregateOperation2(SUMMING, SUMMING, outputFn)); // Then aggregated.writeTo(sink); execute(); long expectedSum = input.stream().mapToLong(i -> i).sum(); assertEquals( singletonList(outputFn.apply(expectedSum, expectedSum)), new ArrayList<>(sinkList) ); } @Test public void aggregate3_withSeparateAggrOps() { // Given BatchStage<Integer> stage11 = batchStageFromInput(); // When BatchStage<Tuple2<Long, Long>> aggregated = batchStageFromInput() .aggregate2(SUMMING, stage11, SUMMING); // Then aggregated.writeTo(sink); execute(); long expectedSum = input.stream().mapToLong(i -> i).sum(); assertEquals( singletonList(tuple2(expectedSum, expectedSum)), new ArrayList<>(sinkList) ); } @Test public void aggregate3_withAggrOp3() { // Given BatchStage<Integer> stage1 = batchStageFromInput(); BatchStage<Integer> stage2 = batchStageFromInput(); // When BatchStage<Tuple3<Long, Long, Long>> aggregated = batchStageFromInput().aggregate3( stage1, stage2, aggregateOperation3(SUMMING, SUMMING, SUMMING)); // Then aggregated.writeTo(sink); execute(); long expectedSum = input.stream().mapToLong(i -> i).sum(); assertEquals( singletonList(tuple3(expectedSum, expectedSum, expectedSum)), new ArrayList<>(sinkList) ); } @Test public void aggregate3_withAggrOp3_withOutputFn() { // When BatchStage<Long> aggregated = batchStageFromInput().aggregate3( batchStageFromInput(), batchStageFromInput(), aggregateOperation3(SUMMING, SUMMING, SUMMING, (r0, r1, r2) -> r0 + r1 + r2)); // Then aggregated.writeTo(sink); execute(); assertEquals( singletonList(3 * input.stream().mapToLong(i -> i).sum()), new ArrayList<>(sinkList)); } private class AggregateBuilderFixture { FunctionEx<Integer, Integer> mapFn1 = i -> FACTOR_1 * i; FunctionEx<Integer, Integer> mapFn2 = i -> FACTOR_2 * i; BatchStage<Integer> stage1 = batchStageFromInput().map(mapFn1); BatchStage<Integer> stage2 = batchStageFromInput().map(mapFn2); } @Test public void aggregateBuilder_withSeparateAggrOps() { // Given AggregateBuilderFixture fx = new AggregateBuilderFixture(); // When AggregateBuilder<Long> b = batchStageFromInput().aggregateBuilder(SUMMING); Tag<Long> tag0 = b.tag0(); Tag<Long> tag1 = b.add(fx.stage1, SUMMING); Tag<Long> tag2 = b.add(fx.stage2, SUMMING); BatchStage<ItemsByTag> aggregated = b.build(); // Then aggregated.writeTo(sink); execute(); long sum0 = input.stream().mapToLong(i -> i).sum(); assertEquals( singletonList(itemsByTag(tag0, sum0, tag1, FACTOR_1 * sum0, tag2, FACTOR_2 * sum0)), new ArrayList<>(sinkList) ); } @Test public void aggregateBuilder_withComplexAggrOp() { // Given AggregateBuilderFixture fx = new AggregateBuilderFixture(); // When AggregateBuilder1<Integer> b = batchStageFromInput().aggregateBuilder(); Tag<Integer> tag0_in = b.tag0(); Tag<Integer> tag1_in = b.add(fx.stage1); Tag<Integer> tag2_in = b.add(fx.stage2); CoAggregateOperationBuilder agb = coAggregateOperationBuilder(); Tag<Long> tag0 = agb.add(tag0_in, SUMMING); Tag<Long> tag1 = agb.add(tag1_in, SUMMING); Tag<Long> tag2 = agb.add(tag2_in, SUMMING); AggregateOperation<Object[], ItemsByTag> aggrOp = agb.build(); BatchStage<ItemsByTag> aggregated = b.build(aggrOp); // Then aggregated.writeTo(sink); execute(); long sum0 = input.stream().mapToLong(i -> i).sum(); assertEquals( singletonList(itemsByTag(tag0, sum0, tag1, FACTOR_1 * sum0, tag2, FACTOR_2 * sum0)), new ArrayList<>(sinkList) ); } @Test @SuppressWarnings("ConstantConditions") public void aggregateBuilder_withSeparateAggrOps_withOutputFn() { // Given BatchStage<Integer> stage1 = batchStageFromInput(); BatchStage<Integer> stage2 = batchStageFromInput(); // When AggregateBuilder<Long> b = batchStageFromInput().aggregateBuilder(SUMMING); Tag<Long> tag0 = b.tag0(); Tag<Long> tag1 = b.add(stage1, SUMMING); Tag<Long> tag2 = b.add(stage2, SUMMING); BatchStage<Long> aggregated = b.build(ibt -> ibt.get(tag0) + ibt.get(tag1) + ibt.get(tag2)); // Then aggregated.writeTo(sink); execute(); assertEquals( singletonList(3 * input.stream().mapToLong(i -> i).sum()), new ArrayList<>(sinkList) ); } @Test @SuppressWarnings("ConstantConditions") public void aggregateBuilder_with_complexAggrOp_withOutputFn() { // Given BatchStage<Integer> stage1 = batchStageFromInput(); BatchStage<Integer> stage2 = batchStageFromInput(); // When AggregateBuilder1<Integer> b = batchStageFromInput().aggregateBuilder(); Tag<Integer> tag0_in = b.tag0(); Tag<Integer> tag1_in = b.add(stage1); Tag<Integer> tag2_in = b.add(stage2); CoAggregateOperationBuilder agb = coAggregateOperationBuilder(); Tag<Long> tag0 = agb.add(tag0_in, SUMMING); Tag<Long> tag1 = agb.add(tag1_in, SUMMING); Tag<Long> tag2 = agb.add(tag2_in, SUMMING); AggregateOperation<Object[], Long> aggrOp = agb.build(ibt -> ibt.get(tag0) + ibt.get(tag1) + ibt.get(tag2)); BatchStage<Long> aggregated = b.build(aggrOp); // Then aggregated.writeTo(sink); execute(); assertEquals( singletonList(3 * input.stream().mapToLong(i -> i).sum()), new ArrayList<>(sinkList) ); } @Test public void groupAggregate() { // Given FunctionEx<Integer, Integer> keyFn = i -> i % 5; // When BatchStage<Entry<Integer, Long>> aggregated = batchStageFromInput() .groupingKey(keyFn) .aggregate(SUMMING); // Then aggregated.writeTo(sink); execute(); Map<Integer, Long> expected = input.stream().collect(groupingBy(keyFn, summingLong(i -> i))); assertEquals( streamToString(expected.entrySet().stream(), FORMAT_FN), streamToString(sinkStreamOfEntry(), FORMAT_FN)); } private class GroupAggregateFixture { final FunctionEx<Integer, Integer> keyFn; final FunctionEx<Integer, Integer> mapFn1; final FunctionEx<Integer, Integer> mapFn2; final Collector<Integer, ?, Long> collectOp; final BatchStage<Integer> srcStage0; // Initialization in constructor to avoid lambda capture of `this` GroupAggregateFixture() { int offset = itemCount; keyFn = i -> i % 10; mapFn1 = i -> i + offset; mapFn2 = i -> i + 2 * offset; srcStage0 = batchStageFromInput(); collectOp = summingLong(i -> i); } BatchStage<Integer> srcStage1() { return batchStageFromInput().map(mapFn1); } BatchStage<Integer> srcStage2() { return batchStageFromInput().map(mapFn2); } } @Test public void groupAggregate2_withSeparateAggrOps() { // Given GroupAggregateFixture fx = new GroupAggregateFixture(); // When BatchStageWithKey<Integer, Integer> stage0 = fx.srcStage0.groupingKey(fx.keyFn); BatchStageWithKey<Integer, Integer> stage1 = fx.srcStage1().groupingKey(fx.keyFn); BatchStage<Entry<Integer, Tuple2<Long, Long>>> aggregated = stage0.aggregate2(SUMMING, stage1, SUMMING); // Then aggregated.writeTo(sink); execute(); Map<Integer, Long> expectedMap0 = input.stream().collect(groupingBy(fx.keyFn, fx.collectOp)); Map<Integer, Long> expectedMap1 = input.stream().map(fx.mapFn1).collect(groupingBy(fx.keyFn, fx.collectOp)); assertEquals( streamToString(expectedMap0.entrySet().stream(), e -> FORMAT_FN_2.apply(e.getKey(), tuple2(e.getValue(), expectedMap1.get(e.getKey())))), streamToString(this.<Integer, Tuple2<Long, Long>>sinkStreamOfEntry(), e -> FORMAT_FN_2.apply(e.getKey(), e.getValue())) ); } @Test public void groupAggregate2_withAggrOp2() { // Given GroupAggregateFixture fx = new GroupAggregateFixture(); // When BatchStageWithKey<Integer, Integer> stage0 = fx.srcStage0.groupingKey(fx.keyFn); BatchStageWithKey<Integer, Integer> stage1 = fx.srcStage1().groupingKey(fx.keyFn); BatchStage<Entry<Integer, Tuple2<Long, Long>>> aggregated = stage0.aggregate2(stage1, aggregateOperation2(SUMMING, SUMMING)); // Then aggregated.writeTo(sink); execute(); Map<Integer, Long> expectedMap0 = input.stream().collect(groupingBy(fx.keyFn, fx.collectOp)); Map<Integer, Long> expectedMap1 = input.stream().map(fx.mapFn1).collect(groupingBy(fx.keyFn, fx.collectOp)); assertEquals( streamToString(expectedMap0.entrySet().stream(), e -> FORMAT_FN_2.apply(e.getKey(), tuple2(e.getValue(), expectedMap1.get(e.getKey())))), streamToString(this.<Integer, Tuple2<Long, Long>>sinkStreamOfEntry(), e -> FORMAT_FN_2.apply(e.getKey(), e.getValue())) ); } @Test public void groupAggregate3_withSeparateAggrOps() { // Given GroupAggregateFixture fx = new GroupAggregateFixture(); // When BatchStageWithKey<Integer, Integer> stage0 = fx.srcStage0.groupingKey(fx.keyFn); BatchStageWithKey<Integer, Integer> stage1 = fx.srcStage1().groupingKey(fx.keyFn); BatchStageWithKey<Integer, Integer> stage2 = fx.srcStage2().groupingKey(fx.keyFn); BatchStage<Entry<Integer, Tuple3<Long, Long, Long>>> aggregated = stage0.aggregate3(SUMMING, stage1, SUMMING, stage2, SUMMING); // Then aggregated.writeTo(sink); execute(); Map<Integer, Long> expectedMap0 = input.stream().collect(groupingBy(fx.keyFn, fx.collectOp)); Map<Integer, Long> expectedMap1 = input.stream().map(fx.mapFn1).collect(groupingBy(fx.keyFn, fx.collectOp)); Map<Integer, Long> expectedMap2 = input.stream().map(fx.mapFn2).collect(groupingBy(fx.keyFn, fx.collectOp)); assertEquals( streamToString(expectedMap0.entrySet().stream(), e -> FORMAT_FN_3.apply( e.getKey(), tuple3(e.getValue(), expectedMap1.get(e.getKey()), expectedMap2.get(e.getKey())))), streamToString(this.<Integer, Tuple3<Long, Long, Long>>sinkStreamOfEntry(), e -> FORMAT_FN_3.apply( e.getKey(), e.getValue())) ); } @Test public void groupAggregate3_withAggrOp3() { // Given GroupAggregateFixture fx = new GroupAggregateFixture(); // When BatchStageWithKey<Integer, Integer> stage0 = fx.srcStage0.groupingKey(fx.keyFn); BatchStageWithKey<Integer, Integer> stage1 = fx.srcStage1().groupingKey(fx.keyFn); BatchStageWithKey<Integer, Integer> stage2 = fx.srcStage2().groupingKey(fx.keyFn); BatchStage<Entry<Integer, Tuple3<Long, Long, Long>>> aggregated = stage0.aggregate3(stage1, stage2, aggregateOperation3(SUMMING, SUMMING, SUMMING)); // Then aggregated.writeTo(sink); execute(); Map<Integer, Long> expectedMap0 = input.stream().collect(groupingBy(fx.keyFn, fx.collectOp)); Map<Integer, Long> expectedMap1 = input.stream().map(fx.mapFn1).collect(groupingBy(fx.keyFn, fx.collectOp)); Map<Integer, Long> expectedMap2 = input.stream().map(fx.mapFn2).collect(groupingBy(fx.keyFn, fx.collectOp)); assertEquals( streamToString(expectedMap0.entrySet().stream(), e -> FORMAT_FN_3.apply( e.getKey(), tuple3(e.getValue(), expectedMap1.get(e.getKey()), expectedMap2.get(e.getKey())))), streamToString(this.<Integer, Tuple3<Long, Long, Long>>sinkStreamOfEntry(), e -> FORMAT_FN_3.apply( e.getKey(), e.getValue())) ); } @Test public void groupAggregateBuilder_withSeparateAggrOps() { // Given GroupAggregateFixture fx = new GroupAggregateFixture(); BatchStageWithKey<Integer, Integer> stage0 = fx.srcStage0.groupingKey(fx.keyFn); BatchStageWithKey<Integer, Integer> stage1 = fx.srcStage1().groupingKey(fx.keyFn); BatchStageWithKey<Integer, Integer> stage2 = fx.srcStage2().groupingKey(fx.keyFn); // When GroupAggregateBuilder<Integer, Long> b = stage0.aggregateBuilder(SUMMING); Tag<Long> tag0 = b.tag0(); Tag<Long> tag1 = b.add(stage1, SUMMING); Tag<Long> tag2 = b.add(stage2, SUMMING); BatchStage<Entry<Integer, ItemsByTag>> aggregated = b.build(); // Then aggregated.writeTo(sink); execute(); Map<Integer, Long> expectedMap0 = input.stream().collect(groupingBy(fx.keyFn, fx.collectOp)); Map<Integer, Long> expectedMap1 = input.stream().map(fx.mapFn1).collect(groupingBy(fx.keyFn, fx.collectOp)); Map<Integer, Long> expectedMap2 = input.stream().map(fx.mapFn2).collect(groupingBy(fx.keyFn, fx.collectOp)); assertEquals( streamToString(expectedMap0.entrySet().stream(), e -> FORMAT_FN_3.apply( e.getKey(), tuple3(e.getValue(), expectedMap1.get(e.getKey()), expectedMap2.get(e.getKey())))), streamToString(this.<Integer, ItemsByTag>sinkStreamOfEntry(), e -> FORMAT_FN_3.apply( e.getKey(), tuple3(e.getValue().get(tag0), e.getValue().get(tag1), e.getValue().get(tag2)))) ); } @Test public void groupAggregateBuilder_withComplexAggrOp() { // Given GroupAggregateFixture fx = new GroupAggregateFixture(); BatchStageWithKey<Integer, Integer> stage0 = fx.srcStage0.groupingKey(fx.keyFn); BatchStageWithKey<Integer, Integer> stage1 = fx.srcStage1().groupingKey(fx.keyFn); BatchStageWithKey<Integer, Integer> stage2 = fx.srcStage2().groupingKey(fx.keyFn); // When GroupAggregateBuilder1<Integer, Integer> b = stage0.aggregateBuilder(); Tag<Integer> tag0_in = b.tag0(); Tag<Integer> tag1_in = b.add(stage1); Tag<Integer> tag2_in = b.add(stage2); CoAggregateOperationBuilder agb = coAggregateOperationBuilder(); Tag<Long> tag0 = agb.add(tag0_in, SUMMING); Tag<Long> tag1 = agb.add(tag1_in, SUMMING); Tag<Long> tag2 = agb.add(tag2_in, SUMMING); AggregateOperation<Object[], ItemsByTag> aggrOp = agb.build(); BatchStage<Entry<Integer, ItemsByTag>> aggregated = b.build(aggrOp); // Then aggregated.writeTo(sink); execute(); Map<Integer, Long> expectedMap0 = input.stream().collect(groupingBy(fx.keyFn, fx.collectOp)); Map<Integer, Long> expectedMap1 = input.stream().map(fx.mapFn1).collect(groupingBy(fx.keyFn, fx.collectOp)); Map<Integer, Long> expectedMap2 = input.stream().map(fx.mapFn2).collect(groupingBy(fx.keyFn, fx.collectOp)); assertEquals( streamToString(expectedMap0.entrySet().stream(), e -> FORMAT_FN_3.apply( e.getKey(), tuple3(e.getValue(), expectedMap1.get(e.getKey()), expectedMap2.get(e.getKey())))), streamToString(this.<Integer, ItemsByTag>sinkStreamOfEntry(), e -> FORMAT_FN_3.apply( e.getKey(), tuple3(e.getValue().get(tag0), e.getValue().get(tag1), e.getValue().get(tag2)))) ); } @Test @SuppressWarnings("ConstantConditions") public void groupAggregateBuilder_withComplexAggrOp_withOutputFn() { // Given GroupAggregateFixture fx = new GroupAggregateFixture(); BatchStageWithKey<Integer, Integer> stage0 = fx.srcStage0.groupingKey(fx.keyFn); BatchStageWithKey<Integer, Integer> stage1 = fx.srcStage1().groupingKey(fx.keyFn); BatchStageWithKey<Integer, Integer> stage2 = fx.srcStage2().groupingKey(fx.keyFn); // When GroupAggregateBuilder1<Integer, Integer> b = stage0.aggregateBuilder(); Tag<Integer> tag0_in = b.tag0(); Tag<Integer> tag1_in = b.add(stage1); Tag<Integer> tag2_in = b.add(stage2); CoAggregateOperationBuilder agb = coAggregateOperationBuilder(); Tag<Long> tag0 = agb.add(tag0_in, SUMMING); Tag<Long> tag1 = agb.add(tag1_in, SUMMING); Tag<Long> tag2 = agb.add(tag2_in, SUMMING); AggregateOperation<Object[], ItemsByTag> aggrOp = agb.build(); BatchStage<Entry<Integer, Long>> aggregated = b .build(aggrOp) .map(e -> { ItemsByTag ibt = e.getValue(); return entry(e.getKey(), ibt.get(tag0) + ibt.get(tag1) + ibt.get(tag2)); }); // Then aggregated.writeTo(sink); execute(); Map<Integer, Long> expectedMap0 = input.stream().collect(groupingBy(fx.keyFn, fx.collectOp)); Map<Integer, Long> expectedMap1 = input.stream().map(fx.mapFn1).collect(groupingBy(fx.keyFn, fx.collectOp)); Map<Integer, Long> expectedMap2 = input.stream().map(fx.mapFn2).collect(groupingBy(fx.keyFn, fx.collectOp)); assertEquals( streamToString(expectedMap0.entrySet().stream(), e -> FORMAT_FN.apply(entry(e.getKey(), e.getValue() + expectedMap1.get(e.getKey()) + expectedMap2.get(e.getKey())))), streamToString(sinkStreamOfEntry(), FORMAT_FN) ); } private BatchStage<Integer> batchStageFromInput() { return batchStageFromList(input); } }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2019 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.ui.trans.steps.stringoperations; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.core.util.Utils; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDialogInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.steps.stringoperations.StringOperationsMeta; import org.pentaho.di.ui.core.dialog.ErrorDialog; import org.pentaho.di.ui.core.gui.GUIResource; import org.pentaho.di.ui.core.widget.ColumnInfo; import org.pentaho.di.ui.core.widget.TableView; import org.pentaho.di.ui.trans.step.BaseStepDialog; import org.pentaho.di.ui.trans.step.TableItemInsertListener; /** * Dialog class for the StringOperations step. * * @author Samatar Hassan * @since 02 April 2009 */ public class StringOperationsDialog extends BaseStepDialog implements StepDialogInterface { private static Class<?> PKG = StringOperationsMeta.class; // for i18n purposes, needed by Translator2!! private Label wlKey; private TableView wFields; private FormData fdlKey, fdKey; private StringOperationsMeta input; // holds the names of the fields entering this step private Map<String, Integer> inputFields; private ColumnInfo[] ciKey; public StringOperationsDialog( Shell parent, Object in, TransMeta tr, String sname ) { super( parent, (BaseStepMeta) in, tr, sname ); input = (StringOperationsMeta) in; inputFields = new HashMap<String, Integer>(); } public String open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN ); props.setLook( shell ); setShellImage( shell, input ); ModifyListener lsMod = new ModifyListener() { public void modifyText( ModifyEvent e ) { input.setChanged(); } }; changed = input.hasChanged(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout( formLayout ); shell.setText( BaseMessages.getString( PKG, "StringOperationsDialog.Shell.Title" ) ); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Stepname line wlStepname = new Label( shell, SWT.RIGHT ); wlStepname.setText( BaseMessages.getString( PKG, "StringOperationsDialog.Stepname.Label" ) ); props.setLook( wlStepname ); fdlStepname = new FormData(); fdlStepname.left = new FormAttachment( 0, 0 ); fdlStepname.right = new FormAttachment( middle, -margin ); fdlStepname.top = new FormAttachment( 0, margin ); wlStepname.setLayoutData( fdlStepname ); wStepname = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wStepname.setText( stepname ); props.setLook( wStepname ); wStepname.addModifyListener( lsMod ); fdStepname = new FormData(); fdStepname.left = new FormAttachment( middle, 0 ); fdStepname.top = new FormAttachment( 0, margin ); fdStepname.right = new FormAttachment( 100, 0 ); wStepname.setLayoutData( fdStepname ); wlKey = new Label( shell, SWT.NONE ); wlKey.setText( BaseMessages.getString( PKG, "StringOperationsDialog.Fields.Label" ) ); props.setLook( wlKey ); fdlKey = new FormData(); fdlKey.left = new FormAttachment( 0, 0 ); fdlKey.top = new FormAttachment( wStepname, 2 * margin ); wlKey.setLayoutData( fdlKey ); int nrFieldCols = 11; int nrFieldRows = ( input.getFieldInStream() != null ? input.getFieldInStream().length : 1 ); ciKey = new ColumnInfo[nrFieldCols]; ciKey[0] = new ColumnInfo( BaseMessages.getString( PKG, "StringOperationsDialog.ColumnInfo.InStreamField" ), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { "" }, false ); ciKey[1] = new ColumnInfo( BaseMessages.getString( PKG, "StringOperationsDialog.ColumnInfo.OutStreamField" ), ColumnInfo.COLUMN_TYPE_TEXT, false ); ciKey[2] = new ColumnInfo( BaseMessages.getString( PKG, "StringOperationsDialog.ColumnInfo.Trim" ), ColumnInfo.COLUMN_TYPE_CCOMBO, StringOperationsMeta.trimTypeDesc, true ); ciKey[3] = new ColumnInfo( BaseMessages.getString( PKG, "StringOperationsDialog.ColumnInfo.LowerUpper" ), ColumnInfo.COLUMN_TYPE_CCOMBO, StringOperationsMeta.lowerUpperDesc, true ); ciKey[4] = new ColumnInfo( BaseMessages.getString( PKG, "StringOperationsDialog.ColumnInfo.Padding" ), ColumnInfo.COLUMN_TYPE_CCOMBO, StringOperationsMeta.paddingDesc, true ); ciKey[5] = new ColumnInfo( BaseMessages.getString( PKG, "StringOperationsDialog.ColumnInfo.CharPad" ), ColumnInfo.COLUMN_TYPE_TEXT, false ); ciKey[6] = new ColumnInfo( BaseMessages.getString( PKG, "StringOperationsDialog.ColumnInfo.LenPad" ), ColumnInfo.COLUMN_TYPE_TEXT, false ); ciKey[7] = new ColumnInfo( BaseMessages.getString( PKG, "StringOperationsDialog.ColumnInfo.InitCap" ), ColumnInfo.COLUMN_TYPE_CCOMBO, StringOperationsMeta.initCapDesc ); ciKey[8] = new ColumnInfo( BaseMessages.getString( PKG, "StringOperationsDialog.ColumnInfo.MaskXML" ), ColumnInfo.COLUMN_TYPE_CCOMBO, StringOperationsMeta.maskXMLDesc ); ciKey[9] = new ColumnInfo( BaseMessages.getString( PKG, "StringOperationsDialog.ColumnInfo.Digits" ), ColumnInfo.COLUMN_TYPE_CCOMBO, StringOperationsMeta.digitsDesc ); ciKey[10] = new ColumnInfo( BaseMessages.getString( PKG, "StringOperationsDialog.ColumnInfo.RemoveSpecialCharacters" ), ColumnInfo.COLUMN_TYPE_CCOMBO, StringOperationsMeta.removeSpecialCharactersDesc ); ciKey[1] .setToolTip( BaseMessages.getString( PKG, "StringOperationsDialog.ColumnInfo.OutStreamField.Tooltip" ) ); ciKey[1].setUsingVariables( true ); ciKey[4].setUsingVariables( true ); ciKey[5].setUsingVariables( true ); ciKey[6].setUsingVariables( true ); ciKey[7].setUsingVariables( true ); wFields = new TableView( transMeta, shell, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL, ciKey, nrFieldRows, lsMod, props ); fdKey = new FormData(); fdKey.left = new FormAttachment( 0, 0 ); fdKey.top = new FormAttachment( wlKey, margin ); fdKey.right = new FormAttachment( 100, -margin ); fdKey.bottom = new FormAttachment( 100, -30 ); wFields.setLayoutData( fdKey ); // THE BUTTONS wOK = new Button( shell, SWT.PUSH ); wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) ); wCancel = new Button( shell, SWT.PUSH ); wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) ); wGet = new Button( shell, SWT.PUSH ); wGet.setText( BaseMessages.getString( PKG, "StringOperationsDialog.GetFields.Button" ) ); fdGet = new FormData(); fdGet.right = new FormAttachment( 100, 0 ); fdGet.top = new FormAttachment( wStepname, 3 * middle ); wGet.setLayoutData( fdGet ); setButtonPositions( new Button[] { wOK, wGet, wCancel }, margin, null ); // Add listeners lsOK = new Listener() { public void handleEvent( Event e ) { ok(); } }; lsGet = new Listener() { public void handleEvent( Event e ) { get(); } }; lsCancel = new Listener() { public void handleEvent( Event e ) { cancel(); } }; wOK.addListener( SWT.Selection, lsOK ); wGet.addListener( SWT.Selection, lsGet ); wCancel.addListener( SWT.Selection, lsCancel ); lsDef = new SelectionAdapter() { public void widgetDefaultSelected( SelectionEvent e ) { ok(); } }; wStepname.addSelectionListener( lsDef ); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed( ShellEvent e ) { cancel(); } } ); // Set the shell size, based upon previous time... setSize(); getData(); // // Search the fields in the background // final Runnable runnable = new Runnable() { public void run() { StepMeta stepMeta = transMeta.findStep( stepname ); if ( stepMeta != null ) { try { RowMetaInterface row = transMeta.getPrevStepFields( stepMeta ); if ( row != null ) { // Remember these fields... for ( int i = 0; i < row.size(); i++ ) { inputFields.put( row.getValueMeta( i ).getName(), new Integer( i ) ); } setComboBoxes(); } // Dislay in red missing field names Display.getDefault().asyncExec( new Runnable() { public void run() { if ( !wFields.isDisposed() ) { for ( int i = 0; i < wFields.table.getItemCount(); i++ ) { TableItem it = wFields.table.getItem( i ); if ( !Utils.isEmpty( it.getText( 1 ) ) ) { if ( !inputFields.containsKey( it.getText( 1 ) ) ) { it.setBackground( GUIResource.getInstance().getColorRed() ); } } } } } } ); } catch ( KettleException e ) { logError( "Error getting fields from incoming stream!", e ); } } } }; new Thread( runnable ).start(); input.setChanged( changed ); shell.open(); while ( !shell.isDisposed() ) { if ( !display.readAndDispatch() ) { display.sleep(); } } return stepname; } protected void setComboBoxes() { Set<String> keySet = inputFields.keySet(); List<String> entries = new ArrayList<String>( keySet ); String[] fieldNames = entries.toArray( new String[entries.size()] ); Const.sortStrings( fieldNames ); ciKey[0].setComboValues( fieldNames ); } /** * Copy information from the meta-data input to the dialog fields. */ public void getData() { if ( input.getFieldInStream() != null ) { for ( int i = 0; i < input.getFieldInStream().length; i++ ) { TableItem item = wFields.table.getItem( i ); if ( input.getFieldInStream()[i] != null ) { item.setText( 1, input.getFieldInStream()[i] ); } if ( input.getFieldOutStream()[i] != null ) { item.setText( 2, input.getFieldOutStream()[i] ); } item.setText( 3, input.getTrimType()[i] ); item.setText( 4, input.getLowerUpper()[i] ); item.setText( 5, input.getPaddingType()[i] ); if ( input.getPadChar()[i] != null ) { item.setText( 6, input.getPadChar()[i] ); } if ( input.getPadLen()[i] != null ) { item.setText( 7, input.getPadLen()[i] ); } item.setText( 8, input.getInitCap()[i] ); item.setText( 9, input.getMaskXML()[i] ); item.setText( 10, input.getDigits()[i] ); item.setText( 11, input.getRemoveSpecialCharacters()[i] ); } } wFields.setRowNums(); wFields.optWidth( true ); wStepname.selectAll(); wStepname.setFocus(); } private void cancel() { stepname = null; input.setChanged( changed ); dispose(); } private void getInfo( StringOperationsMeta inf ) { int nrkeys = wFields.nrNonEmpty(); inf.allocate( nrkeys ); if ( isDebug() ) { logDebug( BaseMessages.getString( PKG, "StringOperationsDialog.Log.FoundFields", String.valueOf( nrkeys ) ) ); } //CHECKSTYLE:Indentation:OFF for ( int i = 0; i < nrkeys; i++ ) { TableItem item = wFields.getNonEmpty( i ); inf.getFieldInStream()[i] = item.getText( 1 ); inf.getFieldOutStream()[i] = item.getText( 2 ); inf.getTrimType()[i] = item.getText( 3 ); inf.getLowerUpper()[i] = item.getText( 4 ); inf.getPaddingType()[i] = item.getText( 5 ); inf.getPadChar()[i] = item.getText( 6 ); inf.getPadLen()[i] = item.getText( 7 ); inf.getInitCap()[i] = item.getText( 8 ); inf.getMaskXML()[i] = item.getText( 9 ); inf.getDigits()[i] = item.getText( 10 ); inf.getRemoveSpecialCharacters()[i] = item.getText( 11 ); } stepname = wStepname.getText(); // return value } private void ok() { if ( Utils.isEmpty( wStepname.getText() ) ) { return; } // Get the information for the dialog into the input structure. getInfo( input ); dispose(); } private void get() { try { RowMetaInterface r = transMeta.getPrevStepFields( stepname ); if ( r != null ) { TableItemInsertListener listener = new TableItemInsertListener() { public boolean tableItemInserted( TableItem tableItem, ValueMetaInterface v ) { if ( v.getType() == ValueMetaInterface.TYPE_STRING ) { // Only process strings tableItem.setText( 3, BaseMessages.getString( PKG, "StringOperationsMeta.TrimType.None" ) ); tableItem.setText( 4, BaseMessages.getString( PKG, "StringOperationsMeta.LowerUpper.None" ) ); tableItem.setText( 5, BaseMessages.getString( PKG, "StringOperationsMeta.Padding.None" ) ); tableItem.setText( 8, BaseMessages.getString( PKG, "System.Combo.No" ) ); tableItem.setText( 9, BaseMessages.getString( PKG, "StringOperationsMeta.MaskXML.None" ) ); tableItem.setText( 10, BaseMessages.getString( PKG, "StringOperationsMeta.Digits.None" ) ); tableItem.setText( 11, BaseMessages.getString( PKG, "StringOperationsMeta.RemoveSpecialCharacters.None" ) ); return true; } else { return false; } } }; BaseStepDialog.getFieldsFromPrevious( r, wFields, 1, new int[] { 1 }, new int[] {}, -1, -1, listener ); } } catch ( KettleException ke ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "StringOperationsDialog.FailedToGetFields.DialogTitle" ), BaseMessages.getString( PKG, "StringOperationsDialog.FailedToGetFields.DialogMessage" ), ke ); } } }
/** * */ package gov.va.med; import java.util.Date; import gov.va.med.GenericDataGenerator.Mode; import gov.va.med.NetworkSimulatingInputStream.DELAY_MODE; import gov.va.med.NetworkSimulatingInputStream.EXCEPTION_MODE; import gov.va.med.ReferenceMap.ReferenceKey; import gov.va.med.imaging.StudyURN; import gov.va.med.imaging.exceptions.URNFormatException; import gov.va.med.imaging.exchange.business.*; import gov.va.med.imaging.exchange.business.Patient.PatientSex; import gov.va.med.imaging.exchange.enums.ObjectOrigin; import gov.va.med.imaging.exchange.enums.PatientSensitivityLevel; import gov.va.med.imaging.exchange.enums.StudyDeletedImageState; import gov.va.med.imaging.exchange.enums.StudyLoadLevel; /** * @author vhaiswbeckec * */ public class ClinicalDisplayDataGenerator extends VistaDataGenerator { public static final PatientSensitivityLevel DEFAULT_PATIENT_SENSITIVITY = PatientSensitivityLevel.NO_ACTION_REQUIRED; /** * @param mode */ public ClinicalDisplayDataGenerator(DataGenerationConfiguration configuration) { super(configuration); } /** * @return */ public StudyFilter createStudyFilter( InstancePopulation instancePopulation, AggregationPopulation aggregation, CompositionPopulation composition, ReferenceMap references) { StudyFilter result = new StudyFilter(); references.putReference(ReferenceKey.STUDY_FILTER, result); if(instancePopulation == InstancePopulation.DEFAULT) { result.setFromDate(DEFAULT_START_DATE); result.setToDate(DEFAULT_END_DATE); result.setMaximumAllowedLevel(DEFAULT_PATIENT_SENSITIVITY); } return result; } /** * * @param instancePopulation * @param aggregation * @param composition * @return * @throws URNFormatException */ public Study createStudy( InstancePopulation instancePopulation, AggregationPopulation aggregation, CompositionPopulation composition, ReferenceMap references) throws URNFormatException { Study result = null; if(instancePopulation == InstancePopulation.NULL) { result = Study.create(null, null, StudyDeletedImageState.cannotIncludeDeletedImages); references.putReference(ReferenceKey.STUDY, result); } else { StudyURN studyUrn = (StudyURN)references.getReference(ReferenceMap.ReferenceKey.STUDY_URN); if(studyUrn == null) studyUrn = createStudyUrn(); references.putReference(ReferenceKey.STUDY_URN, studyUrn); if(instancePopulation == InstancePopulation.DEFAULT || instancePopulation == InstancePopulation.REQUIRED) { result = Study.create(studyUrn, StudyLoadLevel.STUDY_ONLY, StudyDeletedImageState.cannotIncludeDeletedImages); references.putReference(ReferenceKey.STUDY, result); } else if(instancePopulation == InstancePopulation.FULL) { result = Study.create(studyUrn, StudyLoadLevel.STUDY_AND_IMAGES, StudyDeletedImageState.cannotIncludeDeletedImages); references.putReference(ReferenceKey.STUDY, result); } } return result; } /** * * @param study */ public void postPopulateStudy(Study study) { if( study.getFirstImage() == null && study.getSeries() != null) { Image firstImage = null; for( Series series : study ) { for(Image image : series) { firstImage = image; break; } break; } if(firstImage != null) { study.setFirstImage(firstImage); study.setFirstImageIen(firstImage.getIen()); study.setPatientName(firstImage.getPatientName()); } } return; } /** * * @param instancePopulation * @param aggregation * @param composition * @param references * @return * @throws URNFormatException */ public Series createSeries( InstancePopulation instancePopulation, AggregationPopulation aggregation, CompositionPopulation composition, ReferenceMap references) throws URNFormatException { Series series = null; if(instancePopulation == InstancePopulation.NULL) { series = Series.create(null, null, null); references.putReference(ReferenceKey.SERIES, series); } ObjectOrigin objectOrigin = (ObjectOrigin)references.getReference(ReferenceKey.OBJECT_ORIGIN); if(instancePopulation == InstancePopulation.DEFAULT || instancePopulation == InstancePopulation.REQUIRED) { if(objectOrigin == null) objectOrigin = ObjectOrigin.VA; references.putReference(ReferenceKey.OBJECT_ORIGIN, objectOrigin); series = Series.create(objectOrigin, getOrCreateSeriesIen(references), getOrCreateSeriesNumber(references)); } else if(instancePopulation == InstancePopulation.FULL) { if(objectOrigin == null) objectOrigin = createObjectOrigin(); references.putReference(ReferenceKey.OBJECT_ORIGIN, objectOrigin); series = Series.create(objectOrigin, createSeriesIen(), Integer.toString(createRandomInt(1, 128)) ); } return series; } /** * * @param instancePopulation * @param aggregation * @param composition * @param references * @return * @throws URNFormatException */ public Image createImage( InstancePopulation instancePopulation, AggregationPopulation aggregation, CompositionPopulation composition, ReferenceMap references) throws URNFormatException { Image image = null; if(instancePopulation == InstancePopulation.NULL) { image = Image.create(null, null, null, null, null); references.putReference(ReferenceKey.IMAGE, image); } else { image = Image.create( getOrCreateSiteNumber(references), getOrCreateImageIen(references), getOrCreateStudyId(references), PatientIdentifier.icnPatientIdentifier(getOrCreatePatientICN(references)), getOrCreateModality(references) ); references.putReference(ReferenceKey.IMAGE, image); } return image; } /** * * @param instancePopulation * @param aggregation * @param composition * @param references * @return * @throws URNFormatException */ public Patient createPatient( InstancePopulation instancePopulation, AggregationPopulation aggregation, CompositionPopulation composition, ReferenceMap references) throws URNFormatException { Patient patient = null; if(instancePopulation == InstancePopulation.NULL) { patient = Patient.create(null, null, null, null, null, null, null, false); references.putReference(ReferenceKey.PATIENT, patient); } else { patient = Patient.create( getOrCreatePatientName(references), getOrCreatePatientICN(references), createVeteranStatus(), createPatientSex(), createDOB(), createRandomSSN(), null, false); references.putReference(ReferenceKey.PATIENT, patient); } return patient; } /** * * @param argv */ public static void main(String[] argv) { ClinicalDisplayDataGenerator generator = new ClinicalDisplayDataGenerator( new DataGenerationConfiguration(Mode.RANDOMIZE, EXCEPTION_MODE.RELIABLE, DELAY_MODE.NONE) ); try { Study study = generator.createStudy( InstancePopulation.FULL, AggregationPopulation.MANY, CompositionPopulation.MANY, ReferenceMap.createRoot() ); System.out.println("Study"); System.out.println(study.toString()); Series series = generator.createSeries( InstancePopulation.FULL, AggregationPopulation.MANY, CompositionPopulation.MANY, ReferenceMap.createRoot() ); System.out.println("Series"); System.out.println(series.toString()); Image image = generator.createImage( InstancePopulation.FULL, AggregationPopulation.MANY, CompositionPopulation.MANY, ReferenceMap.createRoot() ); System.out.println("Image"); System.out.println(image.toString()); } catch (URNFormatException x) { x.printStackTrace(); } } }
/** * <copyright> * </copyright> * * $Id$ */ package org.wso2.developerstudio.eclipse.gmf.esb.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.IEditingDomainItemProvider; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.IStructuredItemContentProvider; import org.eclipse.emf.edit.provider.ITreeItemContentProvider; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ViewerNotification; import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory; import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage; import org.wso2.developerstudio.eclipse.gmf.esb.KeyType; import org.wso2.developerstudio.eclipse.gmf.esb.Sequence; /** * This is the item provider adapter for a {@link org.wso2.developerstudio.eclipse.gmf.esb.Sequence} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class SequenceItemProvider extends MediatorItemProvider { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SequenceItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors != null) { itemPropertyDescriptors.clear(); } super.getPropertyDescriptors(object); addReferringSequenceTypePropertyDescriptor(object); if(((Sequence)object).getReferringSequenceType().equals(KeyType.DYNAMIC)){ addDynamicReferenceKeyPropertyDescriptor(object); }else { addStaticReferenceKeyPropertyDescriptor(object); } addDescriptionPropertyDescriptor(object); return itemPropertyDescriptors; } /** * This adds a property descriptor for the Name feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addNamePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Sequence_name_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Sequence_name_feature", "_UI_Sequence_type"), EsbPackage.Literals.SEQUENCE__NAME, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Key feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addKeyPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Sequence_key_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Sequence_key_feature", "_UI_Sequence_type"), EsbPackage.Literals.SEQUENCE__KEY, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Receive Sequence feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addReceiveSequencePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Sequence_receiveSequence_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Sequence_receiveSequence_feature", "_UI_Sequence_type"), EsbPackage.Literals.SEQUENCE__RECEIVE_SEQUENCE, true, false, false, ItemPropertyDescriptor.BOOLEAN_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Duplicate feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addDuplicatePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Sequence_duplicate_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Sequence_duplicate_feature", "_UI_Sequence_type"), EsbPackage.Literals.SEQUENCE__DUPLICATE, true, false, false, ItemPropertyDescriptor.BOOLEAN_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Referring Sequence Type feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addReferringSequenceTypePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Sequence_referringSequenceType_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Sequence_referringSequenceType_feature", "_UI_Sequence_type"), EsbPackage.Literals.SEQUENCE__REFERRING_SEQUENCE_TYPE, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Dynamic Reference Key feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addDynamicReferenceKeyPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Sequence_dynamicReferenceKey_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Sequence_dynamicReferenceKey_feature", "_UI_Sequence_type"), EsbPackage.Literals.SEQUENCE__DYNAMIC_REFERENCE_KEY, true, false, false, null, null, null)); } /** * This adds a property descriptor for the Static Reference Key feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addStaticReferenceKeyPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Sequence_staticReferenceKey_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Sequence_staticReferenceKey_feature", "_UI_Sequence_type"), EsbPackage.Literals.SEQUENCE__STATIC_REFERENCE_KEY, true, false, false, null, null, null)); } /** * This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an * {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or * {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) { if (childrenFeatures == null) { super.getChildrenFeatures(object); childrenFeatures.add(EsbPackage.Literals.SEQUENCE__INPUT_CONNECTOR); childrenFeatures.add(EsbPackage.Literals.SEQUENCE__OUTPUT_CONNECTOR); childrenFeatures.add(EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS); childrenFeatures.add(EsbPackage.Literals.SEQUENCE__DYNAMIC_REFERENCE_KEY); childrenFeatures.add(EsbPackage.Literals.SEQUENCE__STATIC_REFERENCE_KEY); } return childrenFeatures; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EStructuralFeature getChildFeature(Object object, Object child) { // Check the type of the specified child object and return the proper feature to use for // adding (see {@link AddCommand}) it as a child. return super.getChildFeature(object, child); } /** * This returns Sequence.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/Sequence")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { String label = ((Sequence)object).getName(); return label == null || label.length() == 0 ? getString("_UI_Sequence_type") : getString("_UI_Sequence_type") + " " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); switch (notification.getFeatureID(Sequence.class)) { case EsbPackage.SEQUENCE__NAME: case EsbPackage.SEQUENCE__KEY: case EsbPackage.SEQUENCE__RECEIVE_SEQUENCE: case EsbPackage.SEQUENCE__DUPLICATE: case EsbPackage.SEQUENCE__REFERRING_SEQUENCE_TYPE: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true)); return; case EsbPackage.SEQUENCE__INPUT_CONNECTOR: case EsbPackage.SEQUENCE__OUTPUT_CONNECTOR: case EsbPackage.SEQUENCE__INCLUDED_MEDIATORS: case EsbPackage.SEQUENCE__DYNAMIC_REFERENCE_KEY: case EsbPackage.SEQUENCE__STATIC_REFERENCE_KEY: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false)); return; } super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INPUT_CONNECTOR, EsbFactory.eINSTANCE.createSequenceInputConnector())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__OUTPUT_CONNECTOR, EsbFactory.eINSTANCE.createSequenceOutputConnector())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createCallMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createDropMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createFilterMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createMergeNode())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createLogMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createPublishEventMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createBAMMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createBeanMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createEJBMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createPropertyMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createEnrichMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createXSLTMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createSwitchMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createSequence())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createEventMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createEntitlementMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createEnqueueMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createClassMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createSpringMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createScriptMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createFaultMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createAggregateMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createRouterMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createCloneMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createForEachMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createIterateMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createCacheMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createXQueryMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createCalloutMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createRMSequenceMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createTransactionMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createOAuthMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createAutoscaleInMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createAutoscaleOutMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createHeaderMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createThrottleMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createCommandMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createDBLookupMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createDBReportMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createRuleMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createCallTemplateMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createLoopBackMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createRespondMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createSmooksMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createStoreMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createBuilderMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createPayloadFactoryMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createConditionalRouterMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createSendMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createURLRewriteMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createValidateMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createCloudConnectorOperation())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createDataMapperMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createFastXSLTMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__INCLUDED_MEDIATORS, EsbFactory.eINSTANCE.createCommentMediator())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__DYNAMIC_REFERENCE_KEY, EsbFactory.eINSTANCE.createNamespacedProperty())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.SEQUENCE__STATIC_REFERENCE_KEY, EsbFactory.eINSTANCE.createRegistryKeyProperty())); } }
/******************************************************************************* * 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.ofbiz.content.content; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.ofbiz.base.util.Debug; import org.apache.ofbiz.base.util.StringUtil; import org.apache.ofbiz.base.util.UtilGenerics; import org.apache.ofbiz.base.util.UtilMisc; import org.apache.ofbiz.base.util.UtilProperties; import org.apache.ofbiz.base.util.UtilValidate; import org.apache.ofbiz.entity.Delegator; import org.apache.ofbiz.entity.GenericEntityException; import org.apache.ofbiz.entity.GenericValue; import org.apache.ofbiz.entity.util.EntityQuery; import org.apache.ofbiz.entityext.permission.EntityPermissionChecker; import org.apache.ofbiz.security.Security; import org.apache.ofbiz.service.DispatchContext; import org.apache.ofbiz.service.GenericServiceException; import org.apache.ofbiz.service.LocalDispatcher; import org.apache.ofbiz.service.ModelService; import org.apache.ofbiz.service.ServiceUtil; /** * ContentPermissionServices Class * * Services for granting operation permissions on Content entities in a data-driven manner. */ public class ContentPermissionServices { public static final String module = ContentPermissionServices.class.getName(); public static final String resource = "ContentUiLabels"; public ContentPermissionServices() {} /** * checkContentPermission * *@param dctx The DispatchContext that this service is operating in *@param context Map containing the input parameters *@return Map with the result of the service, the output parameters * * This service goes thru a series of test to determine if the user has * authority to performed anyone of the passed in target operations. * * It expects a Content entity in "currentContent" * It expects a list of contentOperationIds in "targetOperationList" rather * than a scalar because it is thought that sometimes more than one operation * would fit the situation. * Similarly, it expects a list of contentPurposeTypeIds in "contentPurposeList". * Again, normally there will just be one, but it is possible that a Content * entity could have multiple purposes associated with it. * The userLogin GenericValue is also required. * A list of roleTypeIds is also possible. * * The basic sequence of testing events is: * First the ContentPurposeOperation table is checked to see if there are any * entries with matching purposes (and operations) with no roleTypeId (ie. _NA_). * This is done because it would be the most common scenario and is quick to check. * * Secondly, the CONTENTMGR permission is checked. * * Thirdly, the ContentPurposeOperation table is rechecked to see if there are * any conditions with roleTypeIds that match associated ContentRoles tied to the * user. * If a Party of "PARTY_GROUP" type is found, the PartyRelationship table is checked * to see if the current user is linked to that group. * * If no match is found to this point and the current Content entity has a value for * ownerContentId, then the last step is recusively applied, using the ContentRoles * associated with the ownerContent entity. */ public static Map<String, Object> checkContentPermission(DispatchContext dctx, Map<String, ? extends Object> context) { Debug.logWarning(new Exception(), "This service has been depricated in favor of [genericContentPermission]", module); Security security = dctx.getSecurity(); Delegator delegator = dctx.getDelegator(); //TODO this parameters is still not used but this service need to be replaced by genericContentPermission // String statusId = (String) context.get("statusId"); //TODO this parameters is still not used but this service need to be replaced by genericContentPermission // String privilegeEnumId = (String) context.get("privilegeEnumId"); GenericValue content = (GenericValue) context.get("currentContent"); Boolean bDisplayFailCond = (Boolean)context.get("displayFailCond"); boolean displayFailCond = false; if (bDisplayFailCond != null && bDisplayFailCond.booleanValue()) { displayFailCond = true; } Debug.logInfo("displayFailCond(0):" + displayFailCond, ""); Boolean bDisplayPassCond = (Boolean)context.get("displayPassCond"); boolean displayPassCond = false; if (bDisplayPassCond != null && bDisplayPassCond.booleanValue()) { displayPassCond = true; } Debug.logInfo("displayPassCond(0):" + displayPassCond, ""); Map<String, Object> results = new HashMap<String, Object>(); GenericValue userLogin = (GenericValue) context.get("userLogin"); String partyId = (String) context.get("partyId"); if (UtilValidate.isEmpty(partyId)) { String passedUserLoginId = (String)context.get("userLoginId"); if (UtilValidate.isNotEmpty(passedUserLoginId)) { try { userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", passedUserLoginId).cache().queryOne(); if (userLogin != null) { partyId = userLogin.getString("partyId"); } } catch (GenericEntityException e) { return ServiceUtil.returnError(e.getMessage()); } } } if (UtilValidate.isEmpty(partyId) && userLogin != null) { partyId = userLogin.getString("partyId"); } // Do entity permission check. This will pass users with administrative permissions. boolean passed = false; // I realized, belatedly, that I wanted to be able to pass parameters in as // strings so this service could be used in an action event directly, // so I had to write this code to handle both list and strings List<String> passedPurposes = UtilGenerics.checkList(context.get("contentPurposeList")); String contentPurposeString = (String) context.get("contentPurposeString"); if (UtilValidate.isNotEmpty(contentPurposeString)) { List<String> purposesFromString = StringUtil.split(contentPurposeString, "|"); if (passedPurposes == null) { passedPurposes = new LinkedList<String>(); } passedPurposes.addAll(purposesFromString); } EntityPermissionChecker.StdAuxiliaryValueGetter auxGetter = new EntityPermissionChecker.StdAuxiliaryValueGetter("ContentPurpose", "contentPurposeTypeId", "contentId"); // Sometimes permissions need to be checked before an entity is created, so // there needs to be a method for setting a purpose list auxGetter.setList(passedPurposes); List<String> targetOperations = UtilGenerics.checkList(context.get("targetOperationList")); String targetOperationString = (String) context.get("targetOperationString"); if (UtilValidate.isNotEmpty(targetOperationString)) { List<String> operationsFromString = StringUtil.split(targetOperationString, "|"); if (targetOperations == null) { targetOperations = new LinkedList<String>(); } targetOperations.addAll(operationsFromString); } EntityPermissionChecker.StdPermissionConditionGetter permCondGetter = new EntityPermissionChecker.StdPermissionConditionGetter("ContentPurposeOperation", "contentOperationId", "roleTypeId", "statusId", "contentPurposeTypeId", "privilegeEnumId"); permCondGetter.setOperationList(targetOperations); EntityPermissionChecker.StdRelatedRoleGetter roleGetter = new EntityPermissionChecker.StdRelatedRoleGetter("Content", "roleTypeId", "contentId", "partyId", "ownerContentId", "ContentRole"); List<String> passedRoles = UtilGenerics.checkList(context.get("roleTypeList")); if (passedRoles == null) passedRoles = new LinkedList<String>(); String roleTypeString = (String) context.get("roleTypeString"); if (UtilValidate.isNotEmpty(roleTypeString)) { List<String> rolesFromString = StringUtil.split(roleTypeString, "|"); passedRoles.addAll(rolesFromString); } roleGetter.setList(passedRoles); String entityAction = (String) context.get("entityOperation"); if (entityAction == null) entityAction = "_ADMIN"; if (userLogin != null && entityAction != null) { passed = security.hasEntityPermission("CONTENTMGR", entityAction, userLogin); } StringBuilder errBuf = new StringBuilder(); String permissionStatus = null; List<Object> entityIds = new LinkedList<Object>(); if (passed) { results.put("permissionStatus", "granted"); permissionStatus = "granted"; if (displayPassCond) { errBuf.append("\n hasEntityPermission(" + entityAction + "): PASSED"); } } else { if (displayFailCond) { errBuf.append("\n hasEntityPermission(" + entityAction + "): FAILED"); } if (content != null) entityIds.add(content); String quickCheckContentId = (String) context.get("quickCheckContentId"); if (UtilValidate.isNotEmpty(quickCheckContentId)) { List<String> quickList = StringUtil.split(quickCheckContentId, "|"); if (UtilValidate.isNotEmpty(quickList)) entityIds.addAll(quickList); } try { boolean check = EntityPermissionChecker.checkPermissionMethod(delegator, partyId, "Content", entityIds, auxGetter, roleGetter, permCondGetter); if (check) { results.put("permissionStatus", "granted"); } else { results.put("permissionStatus", "rejected"); } } catch (GenericEntityException e) { return ServiceUtil.returnError(e.getMessage()); } permissionStatus = (String)results.get("permissionStatus"); errBuf.append("\n permissionStatus:"); errBuf.append(permissionStatus); } if ((permissionStatus.equals("granted") && displayPassCond) || (permissionStatus.equals("rejected") && displayFailCond)) { // Don't show this if passed on 'hasEntityPermission' if (displayFailCond || displayPassCond) { if (!passed) { errBuf.append("\n targetOperations:"); errBuf.append(targetOperations); String errMsg = permCondGetter.dumpAsText(); errBuf.append("\n"); errBuf.append(errMsg); errBuf.append("\n partyId:"); errBuf.append(partyId); errBuf.append("\n entityIds:"); errBuf.append(entityIds); if (auxGetter != null) { errBuf.append("\n auxList:"); errBuf.append(auxGetter.getList()); } if (roleGetter != null) { errBuf.append("\n roleList:"); errBuf.append(roleGetter.getList()); } } } } Debug.logInfo("displayPass/FailCond(0), errBuf:" + errBuf.toString(), ""); results.put(ModelService.ERROR_MESSAGE, errBuf.toString()); return results; } public static Map<String, Object> checkAssocPermission(DispatchContext dctx, Map<String, ? extends Object> context) { Map<String, Object> results = new HashMap<String, Object>(); // Security security = dctx.getSecurity(); Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); Boolean bDisplayFailCond = (Boolean)context.get("displayFailCond"); String contentIdFrom = (String) context.get("contentIdFrom"); String contentIdTo = (String) context.get("contentIdTo"); GenericValue userLogin = (GenericValue) context.get("userLogin"); String entityAction = (String) context.get("entityOperation"); Locale locale = (Locale) context.get("locale"); if (entityAction == null) entityAction = "_ADMIN"; String permissionStatus = null; GenericValue contentTo = null; GenericValue contentFrom = null; try { contentTo = EntityQuery.use(delegator).from("Content").where("contentId", contentIdTo).cache().queryOne(); contentFrom = EntityQuery.use(delegator).from("Content").where("contentId", contentIdFrom).cache().queryOne(); } catch (GenericEntityException e) { return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentContentToOrFromErrorRetriving", locale)); } if (contentTo == null || contentFrom == null) { return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentContentToOrFromIsNull", UtilMisc.toMap("contentTo", contentTo, "contentFrom", contentFrom), locale)); } Map<String, Object> permResults = new HashMap<String, Object>(); // Use the purposes from the from entity for both cases. List<String> relatedPurposes = EntityPermissionChecker.getRelatedPurposes(contentFrom, null); List<String> relatedPurposesTo = EntityPermissionChecker.getRelatedPurposes(contentTo, relatedPurposes); Map<String, Object> serviceInMap = new HashMap<String, Object>(); serviceInMap.put("userLogin", userLogin); serviceInMap.put("targetOperationList", UtilMisc.toList("CONTENT_LINK_TO")); serviceInMap.put("contentPurposeList", relatedPurposesTo); serviceInMap.put("currentContent", contentTo); serviceInMap.put("displayFailCond", bDisplayFailCond); try { permResults = dispatcher.runSync("checkContentPermission", serviceInMap); } catch (GenericServiceException e) { Debug.logError(e, "Problem checking permissions", "ContentServices"); } permissionStatus = (String)permResults.get("permissionStatus"); if (permissionStatus == null || !permissionStatus.equals("granted")) { if (bDisplayFailCond != null && bDisplayFailCond.booleanValue()) { String errMsg = (String)permResults.get(ModelService.ERROR_MESSAGE); results.put(ModelService.ERROR_MESSAGE, errMsg); } return results; } serviceInMap.put("currentContent", contentFrom); serviceInMap.put("targetOperationList", UtilMisc.toList("CONTENT_LINK_FROM")); serviceInMap.put("contentPurposeList", relatedPurposes); try { permResults = dispatcher.runSync("checkContentPermission", serviceInMap); } catch (GenericServiceException e) { Debug.logError(e, "Problem checking permissions", "ContentServices"); } permissionStatus = (String)permResults.get("permissionStatus"); if (permissionStatus != null && permissionStatus.equals("granted")) { results.put("permissionStatus", "granted"); } else { if (bDisplayFailCond != null && bDisplayFailCond.booleanValue()) { String errMsg = (String)permResults.get(ModelService.ERROR_MESSAGE); results.put(ModelService.ERROR_MESSAGE, errMsg); } } return results; } }
/* * 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.samza.clustermanager; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import com.google.common.annotations.VisibleForTesting; import org.apache.samza.SamzaException; import org.apache.samza.clustermanager.container.placement.ContainerPlacementMetadataStore; import org.apache.samza.clustermanager.container.placement.ContainerPlacementRequestAllocator; import org.apache.samza.config.ApplicationConfig; import org.apache.samza.config.ClusterManagerConfig; import org.apache.samza.config.Config; import org.apache.samza.config.JobConfig; import org.apache.samza.config.StorageConfig; import org.apache.samza.container.ExecutionContainerIdManager; import org.apache.samza.container.LocalityManager; import org.apache.samza.container.TaskName; import org.apache.samza.coordinator.InputStreamsDiscoveredException; import org.apache.samza.job.metadata.JobCoordinatorMetadataManager; import org.apache.samza.coordinator.JobModelManager; import org.apache.samza.coordinator.MetadataResourceUtil; import org.apache.samza.coordinator.PartitionChangeException; import org.apache.samza.coordinator.StreamPartitionCountMonitor; import org.apache.samza.coordinator.StreamPartitionCountMonitorFactory; import org.apache.samza.coordinator.StreamRegexMonitor; import org.apache.samza.coordinator.StreamRegexMonitorFactory; import org.apache.samza.coordinator.metadatastore.NamespaceAwareCoordinatorStreamStore; import org.apache.samza.coordinator.stream.messages.SetChangelogMapping; import org.apache.samza.coordinator.stream.messages.SetContainerHostMapping; import org.apache.samza.coordinator.stream.messages.SetExecutionEnvContainerIdMapping; import org.apache.samza.coordinator.stream.messages.SetJobCoordinatorMetadataMessage; import org.apache.samza.job.JobCoordinatorMetadata; import org.apache.samza.job.model.ContainerModel; import org.apache.samza.job.model.JobModel; import org.apache.samza.job.model.JobModelUtil; import org.apache.samza.job.model.TaskModel; import org.apache.samza.metadatastore.MetadataStore; import org.apache.samza.metrics.JmxServer; import org.apache.samza.metrics.MetricsRegistryMap; import org.apache.samza.startpoint.StartpointManager; import org.apache.samza.storage.ChangelogStreamManager; import org.apache.samza.storage.StateBackendAdmin; import org.apache.samza.storage.StateBackendFactory; import org.apache.samza.system.StreamMetadataCache; import org.apache.samza.system.SystemAdmins; import org.apache.samza.util.DiagnosticsUtil; import org.apache.samza.util.ReflectionUtil; import org.apache.samza.util.SystemClock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implements a JobCoordinator that is completely independent of the underlying cluster * manager system. This {@link ClusterBasedJobCoordinator} handles functionality common * to both Yarn and Mesos. It takes care of * 1. Requesting resources from an underlying {@link ClusterResourceManager}. * 2. Ensuring that placement of processors to resources happens (as per whether host affinity * is configured or not). * * Any offer based cluster management system that must integrate with Samza will merely * implement a {@link ResourceManagerFactory} and a {@link ClusterResourceManager}. * * This class is not thread-safe. For safe access in multi-threaded context, invocations * should be synchronized by the callers. * * TODO: * 1. Refactor ClusterResourceManager to also handle process liveness, process start * callbacks * 2. Refactor the JobModelReader to be an interface. * 3. Make ClusterBasedJobCoordinator implement the JobCoordinator API as in SAMZA-881. * 4. Refactor UI state variables. * 5. Unit tests. * 6. Document newly added configs. */ public class ClusterBasedJobCoordinator { private static final Logger LOG = LoggerFactory.getLogger(ClusterBasedJobCoordinator.class); private final static String METRICS_SOURCE_NAME = "ApplicationMaster"; private final Config config; /** * State to track container failures, host-processor mappings */ private final SamzaApplicationState state; //even though some of these can be converted to local variables, it will not be the case //as we add more methods to the JobCoordinator and completely implement SAMZA-881. /** * Handles callback for allocated containers, failed containers. */ private final ContainerProcessManager containerProcessManager; /** * A JobModelManager to return and refresh the {@link org.apache.samza.job.model.JobModel} when required. */ private final JobModelManager jobModelManager; /** * A ChangelogStreamManager to handle creation of changelog stream and map changelog stream partitions */ private final ChangelogStreamManager changelogStreamManager; /* * The interval for polling the Task Manager for shutdown. */ private final long jobCoordinatorSleepInterval; /* * Config specifies if a Jmx server should be started on this Job Coordinator */ private final boolean isJmxEnabled; /** * Internal boolean to check if the job coordinator has already been started. */ private final AtomicBoolean isStarted = new AtomicBoolean(false); /** * A boolean variable indicating whether the job has durable state stores in the configuration */ private final boolean hasDurableStores; /** * The input topic partition count monitor */ private final StreamPartitionCountMonitor partitionMonitor; /** * The input stream regex monitor */ private final Optional<StreamRegexMonitor> inputStreamRegexMonitor; /** * Container placement request dispatcher and metastore reader/writer */ private final ContainerPlacementMetadataStore containerPlacementMetadataStore; private final ContainerPlacementRequestAllocator containerPlacementRequestAllocator; // Container Placement thread that reads requests from metastore private final Thread containerPlacementRequestAllocatorThread; /** * Metrics to track stats around container failures, needed containers etc. */ private final MetricsRegistryMap metrics; private final MetadataStore metadataStore; private final SystemAdmins systemAdmins; private final LocalityManager localityManager; /** * Internal variable for the instance of {@link JmxServer} */ private JmxServer jmxServer; /* * Denotes if the metadata changed across application attempts. Used only if job coordinator high availability is enabled */ private boolean metadataChangedAcrossAttempts = false; /** * Variable to keep the callback exception */ volatile private Exception coordinatorException = null; /** * Creates a new ClusterBasedJobCoordinator instance. * Invoke run() to actually run the job coordinator. * * @param metrics the registry for reporting metrics. * @param metadataStore metadata store to hold metadata. * @param fullJobConfig full job config. */ public ClusterBasedJobCoordinator(MetricsRegistryMap metrics, MetadataStore metadataStore, Config fullJobConfig) { this.metrics = metrics; this.metadataStore = metadataStore; this.config = fullJobConfig; // build a JobModelManager and ChangelogStreamManager and perform partition assignments. this.changelogStreamManager = new ChangelogStreamManager( new NamespaceAwareCoordinatorStreamStore(metadataStore, SetChangelogMapping.TYPE)); this.jobModelManager = JobModelManager.apply(config, changelogStreamManager.readPartitionMapping(), metadataStore, metrics); this.hasDurableStores = new StorageConfig(config).hasDurableStores(); this.state = new SamzaApplicationState(jobModelManager); // The systemAdmins should be started before partitionMonitor can be used. And it should be stopped when this coordinator is stopped. this.systemAdmins = new SystemAdmins(config, this.getClass().getSimpleName()); // SAMZA-2684: should these monitors be using the config from the job model calculation? this.partitionMonitor = getPartitionCountMonitor(config, systemAdmins); this.inputStreamRegexMonitor = getInputRegexMonitor(jobModelManager.jobModel(), config, systemAdmins); ClusterManagerConfig clusterManagerConfig = new ClusterManagerConfig(config); this.isJmxEnabled = clusterManagerConfig.getJmxEnabledOnJobCoordinator(); this.jobCoordinatorSleepInterval = clusterManagerConfig.getJobCoordinatorSleepInterval(); this.localityManager = new LocalityManager(new NamespaceAwareCoordinatorStreamStore(metadataStore, SetContainerHostMapping.TYPE)); if (isApplicationMasterHighAvailabilityEnabled()) { ExecutionContainerIdManager executionContainerIdManager = new ExecutionContainerIdManager( new NamespaceAwareCoordinatorStreamStore(metadataStore, SetExecutionEnvContainerIdMapping.TYPE)); state.processorToExecutionId.putAll(executionContainerIdManager.readExecutionEnvironmentContainerIdMapping()); generateAndUpdateJobCoordinatorMetadata(jobModelManager.jobModel()); } // build metastore for container placement messages containerPlacementMetadataStore = new ContainerPlacementMetadataStore(metadataStore); // build a container process Manager containerProcessManager = createContainerProcessManager(); // build utils related to container placements containerPlacementRequestAllocator = new ContainerPlacementRequestAllocator(containerPlacementMetadataStore, containerProcessManager, new ApplicationConfig(config)); this.containerPlacementRequestAllocatorThread = new Thread(containerPlacementRequestAllocator, "Samza-" + ContainerPlacementRequestAllocator.class.getSimpleName()); } /** * Starts the JobCoordinator. */ public void run() { if (!isStarted.compareAndSet(false, true)) { LOG.warn("Attempting to start an already started job coordinator. "); return; } // set up JmxServer (if jmx is enabled) if (isJmxEnabled) { jmxServer = new JmxServer(); state.jmxUrl = jmxServer.getJmxUrl(); state.jmxTunnelingUrl = jmxServer.getTunnelingJmxUrl(); } else { jmxServer = null; } try { // initialize JobCoordinator state LOG.info("Starting cluster based job coordinator"); // write the diagnostics metadata file String jobName = new JobConfig(config).getName().get(); String jobId = new JobConfig(config).getJobId(); Optional<String> execEnvContainerId = Optional.ofNullable(System.getenv("CONTAINER_ID")); DiagnosticsUtil.writeMetadataFile(jobName, jobId, METRICS_SOURCE_NAME, execEnvContainerId, config); //create necessary checkpoint and changelog streams, if not created JobModel jobModel = jobModelManager.jobModel(); MetadataResourceUtil metadataResourceUtil = new MetadataResourceUtil(jobModel, this.metrics, config); metadataResourceUtil.createResources(); // create all the resources required for state backend factories StorageConfig storageConfig = new StorageConfig(config); storageConfig.getBackupFactories().forEach(stateStorageBackendBackupFactory -> { StateBackendFactory stateBackendFactory = ReflectionUtil.getObj(stateStorageBackendBackupFactory, StateBackendFactory.class); StateBackendAdmin stateBackendAdmin = stateBackendFactory.getAdmin(jobModel, config); // Create resources required for state backend admin stateBackendAdmin.createResources(); // Validate resources required for state backend admin stateBackendAdmin.validateResources(); }); /* * We fanout startpoint if and only if * 1. Startpoint is enabled in configuration * 2. If AM HA is enabled, fanout only if startpoint enabled and job coordinator metadata changed */ if (shouldFanoutStartpoint()) { StartpointManager startpointManager = createStartpointManager(); startpointManager.start(); try { startpointManager.fanOut(JobModelUtil.getTaskToSystemStreamPartitions(jobModel)); } finally { startpointManager.stop(); } } // Remap changelog partitions to tasks Map<TaskName, Integer> prevPartitionMappings = changelogStreamManager.readPartitionMapping(); Map<TaskName, Integer> taskPartitionMappings = new HashMap<>(); Map<String, ContainerModel> containers = jobModel.getContainers(); for (ContainerModel containerModel : containers.values()) { for (TaskModel taskModel : containerModel.getTasks().values()) { taskPartitionMappings.put(taskModel.getTaskName(), taskModel.getChangelogPartition().getPartitionId()); } } changelogStreamManager.updatePartitionMapping(prevPartitionMappings, taskPartitionMappings); containerProcessManager.start(); systemAdmins.start(); partitionMonitor.start(); inputStreamRegexMonitor.ifPresent(StreamRegexMonitor::start); // containerPlacementRequestAllocator thread has to start after the cpm is started LOG.info("Starting the container placement handler thread"); containerPlacementMetadataStore.start(); containerPlacementRequestAllocatorThread.start(); boolean isInterrupted = false; while (!containerProcessManager.shouldShutdown() && !checkAndThrowException() && !isInterrupted && checkcontainerPlacementRequestAllocatorThreadIsAlive()) { try { Thread.sleep(jobCoordinatorSleepInterval); } catch (InterruptedException e) { isInterrupted = true; LOG.error("Interrupted in job coordinator loop", e); Thread.currentThread().interrupt(); } } } catch (Throwable e) { LOG.error("Exception thrown in the JobCoordinator loop", e); throw new SamzaException(e); } finally { onShutDown(); } } private boolean checkAndThrowException() throws Exception { if (coordinatorException != null) { throw coordinatorException; } return false; } private boolean checkcontainerPlacementRequestAllocatorThreadIsAlive() { if (containerPlacementRequestAllocatorThread.isAlive()) { return true; } LOG.info("{} thread is dead issuing a shutdown", containerPlacementRequestAllocatorThread.getName()); return false; } /** * Generate the job coordinator metadata for current application attempt and checks for changes in the * metadata from the previous attempt and writes the updates metadata to coordinator stream. * * @param jobModel job model used to generate the job coordinator metadata */ @VisibleForTesting void generateAndUpdateJobCoordinatorMetadata(JobModel jobModel) { JobCoordinatorMetadataManager jobCoordinatorMetadataManager = createJobCoordinatorMetadataManager(); JobCoordinatorMetadata previousMetadata = jobCoordinatorMetadataManager.readJobCoordinatorMetadata(); JobCoordinatorMetadata newMetadata = jobCoordinatorMetadataManager.generateJobCoordinatorMetadata(jobModel, config); if (!jobCoordinatorMetadataManager.checkForMetadataChanges(newMetadata, previousMetadata).isEmpty()) { jobCoordinatorMetadataManager.writeJobCoordinatorMetadata(newMetadata); metadataChangedAcrossAttempts = true; } } /** * Stops all components of the JobCoordinator. */ private void onShutDown() { try { partitionMonitor.stop(); inputStreamRegexMonitor.ifPresent(StreamRegexMonitor::stop); systemAdmins.stop(); shutDowncontainerPlacementRequestAllocatorAndUtils(); containerProcessManager.stop(); localityManager.close(); metadataStore.close(); } catch (Throwable e) { LOG.error("Exception while stopping cluster based job coordinator", e); } LOG.info("Stopped cluster based job coordinator"); if (jmxServer != null) { try { jmxServer.stop(); LOG.info("Stopped Jmx Server"); } catch (Throwable e) { LOG.error("Exception while stopping jmx server", e); } } } private void shutDowncontainerPlacementRequestAllocatorAndUtils() { // Shutdown container placement handler containerPlacementRequestAllocator.stop(); try { containerPlacementRequestAllocatorThread.join(); LOG.info("Stopped container placement handler thread"); containerPlacementMetadataStore.stop(); } catch (InterruptedException ie) { LOG.error("Container Placement handler thread join threw an interrupted exception", ie); Thread.currentThread().interrupt(); } } private StreamPartitionCountMonitor getPartitionCountMonitor(Config config, SystemAdmins systemAdmins) { StreamMetadataCache streamMetadataCache = new StreamMetadataCache(systemAdmins, 0, SystemClock.instance()); return new StreamPartitionCountMonitorFactory(streamMetadataCache, this.metrics).build(config, streamsChanged -> { // Fail the jobs with durable state store. Otherwise, application state.status remains UNDEFINED s.t. YARN job will be restarted if (hasDurableStores) { LOG.error( "Input topic partition count changed in a job with durable state. Failing the job. Changed topics: {}", streamsChanged.toString()); state.status = SamzaApplicationState.SamzaAppStatus.FAILED; } coordinatorException = new PartitionChangeException( "Input topic partition count changes detected for topics: " + streamsChanged.toString()); }); } private Optional<StreamRegexMonitor> getInputRegexMonitor(JobModel jobModel, Config config, SystemAdmins systemAdmins) { StreamMetadataCache streamMetadataCache = new StreamMetadataCache(systemAdmins, 0, SystemClock.instance()); return new StreamRegexMonitorFactory(streamMetadataCache, this.metrics).build(jobModel, config, (initialInputSet, newInputStreams, regexesMonitored) -> { if (hasDurableStores) { LOG.error("New input system-streams discovered. Failing the job. New input streams: {}" + " Existing input streams: {}", newInputStreams, initialInputSet); state.status = SamzaApplicationState.SamzaAppStatus.FAILED; } coordinatorException = new InputStreamsDiscoveredException("New input streams discovered: " + newInputStreams); }); } // The following two methods are package-private and for testing only @VisibleForTesting SamzaApplicationState.SamzaAppStatus getAppStatus() { // make sure to only return a unmodifiable copy of the status variable return state.status; } @VisibleForTesting StreamPartitionCountMonitor getPartitionMonitor() { return partitionMonitor; } @VisibleForTesting StartpointManager createStartpointManager() { return new StartpointManager(metadataStore); } @VisibleForTesting ContainerProcessManager createContainerProcessManager() { return new ContainerProcessManager(config, state, metrics, containerPlacementMetadataStore, localityManager, metadataChangedAcrossAttempts); } @VisibleForTesting JobCoordinatorMetadataManager createJobCoordinatorMetadataManager() { return new JobCoordinatorMetadataManager(new NamespaceAwareCoordinatorStreamStore(metadataStore, SetJobCoordinatorMetadataMessage.TYPE), JobCoordinatorMetadataManager.ClusterType.YARN, metrics); } @VisibleForTesting boolean isApplicationMasterHighAvailabilityEnabled() { return new JobConfig(config).getApplicationMasterHighAvailabilityEnabled(); } @VisibleForTesting boolean isMetadataChangedAcrossAttempts() { return metadataChangedAcrossAttempts; } /** * We only fanout startpoint if and only if * 1. Startpoint is enabled * 2. If AM HA is enabled, fanout only if startpoint enabled and job coordinator metadata changed * * @return true if it satisfies above conditions, false otherwise */ @VisibleForTesting boolean shouldFanoutStartpoint() { JobConfig jobConfig = new JobConfig(config); boolean startpointEnabled = jobConfig.getStartpointEnabled(); return isApplicationMasterHighAvailabilityEnabled() ? startpointEnabled && isMetadataChangedAcrossAttempts() : startpointEnabled; } }
package org.jivesoftware.openfire.keystore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.EOFException; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.*; import java.security.KeyStore; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Detects file-system based changes to (Java) keystores that back Openfire Certificate Stores, reloading them when * needed. * * @author Guus der Kinderen, guus.der.kinderen@gmail.com */ public class CertificateStoreWatcher { private static final Logger Log = LoggerFactory.getLogger( CertificateStoreWatcher.class ); private final Map<CertificateStore, Path> watchedStores = new HashMap<>(); private final Map<Path, WatchKey> watchedPaths = new HashMap<>(); private WatchService storeWatcher; private ExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); public CertificateStoreWatcher() { try { storeWatcher = FileSystems.getDefault().newWatchService(); executorService.submit( new Runnable() { @Override public void run() { while ( !executorService.isShutdown() ) { final WatchKey key; try { key = storeWatcher.poll( 5, TimeUnit.SECONDS ); } catch ( InterruptedException e ) { // Interrupted. Stop waiting continue; } if ( key == null ) { continue; } for ( final WatchEvent<?> event : key.pollEvents() ) { final WatchEvent.Kind<?> kind = event.kind(); // An OVERFLOW event can occur regardless of what kind of events the watcher was configured for. if ( kind == StandardWatchEventKinds.OVERFLOW ) { continue; } synchronized ( watchedStores ) { // The filename is the context of the event. final WatchEvent<Path> ev = (WatchEvent<Path>) event; final Path changedFile = ((Path) key.watchable()).resolve( ev.context() ); // Can't use the value from the 'watchedStores' map, as that's the parent dir, not the keystore file! for ( final CertificateStore store : watchedStores.keySet() ) { final Path storeFile = store.getConfiguration().getFile().toPath().normalize(); if ( storeFile.equals( changedFile ) ) { // Check if the modified file is usable. try ( final FileInputStream is = new FileInputStream( changedFile.toFile() ) ) { final KeyStore tmpStore = KeyStore.getInstance( store.getConfiguration().getType() ); tmpStore.load( is, store.getConfiguration().getPassword() ); } catch ( EOFException e ) { Log.debug( "The keystore is still being modified. Ignore for now. A new event should be thrown later.", e ); break; } catch ( Exception e ) { Log.debug( "Can't read the modified keystore with this config. Continue iterating over configs.", e ); continue; } Log.info( "A file system change was detected. A(nother) certificate store that is backed by file '{}' will be reloaded.", storeFile ); try { store.reload(); } catch ( CertificateStoreConfigException e ) { Log.warn( "An unexpected exception occurred while trying to reload a certificate store that is backed by file '{}'!", storeFile, e ); } } } } } // Reset the key to receive further events. key.reset(); } } }); } catch ( UnsupportedOperationException e ) { storeWatcher = null; Log.info( "This file system does not support watching file system objects for changes and events. Changes to Openfire certificate stores made outside of Openfire might not be detected. A restart of Openfire might be required for these to be applied." ); } catch ( IOException e ) { storeWatcher = null; Log.warn( "An exception occured while trying to create a service that monitors the Openfire certificate stores for changes. Changes to Openfire certificate stores made outside of Openfire might not be detected. A restart of Openfire might be required for these to be applied.", e ); } } /** * Shuts down this watcher, releasing all resources. */ public void destroy() { if ( executorService != null ) { executorService.shutdown(); } synchronized ( watchedStores ) { if ( storeWatcher != null ) { try { storeWatcher.close(); } catch ( IOException e ) { Log.warn( "Unable to close the watcherservice that is watching for file system changes to certificate stores.", e ); } } } } /** * Start watching the file that backs a Certificate Store for changes, reloading the Certificate Store when * appropriate. * * This method does nothing when the file watching functionality is not supported by the file system. * * @param store The certificate store (cannot be null). */ public void watch( CertificateStore store ) { if ( store == null ) { throw new IllegalArgumentException( "Argument 'store' cannot be null." ); } if ( storeWatcher == null ) { return; } final Path dir = store.getConfiguration().getFile().toPath().normalize().getParent(); synchronized ( watchedStores ) { watchedStores.put( store, dir ); // Watch the directory that contains the keystore, if we're not already watching it. if ( !watchedPaths.containsKey( dir ) ) { try { // Ignoring deletion events, as those changes should be applied via property value changes. final WatchKey watchKey = dir.register( storeWatcher, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE ); watchedPaths.put( dir, watchKey ); } catch ( Throwable t ) { Log.warn( "Unable to add a watcher for a path that contains files that provides the backend storage for certificate stores. Changes to those files are unlikely to be picked up automatically. Path: {}", dir, t ); watchedStores.remove( store ); } } } } /** * Stop watching the file that backs a Certificate Store for changes * * @param store The certificate store (cannot be null). */ public synchronized void unwatch( CertificateStore store ) { if ( store == null ) { throw new IllegalArgumentException( "Argument 'store' cannot be null." ); } synchronized ( watchedStores ) { watchedStores.remove( store ); final Path dir = store.getConfiguration().getFile().toPath().normalize().getParent(); // Check if there are any other stores being watched in the same directory. if ( watchedStores.containsValue( dir ) ) { return; } final WatchKey key = watchedPaths.remove( dir ); if ( key != null ) { key.cancel(); } } } }
/* * 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.tracing; import java.net.InetAddress; import java.nio.ByteBuffer; import java.util.List; import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.base.Stopwatch; import org.slf4j.helpers.MessageFormatter; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.progress.ProgressEvent; import org.apache.cassandra.utils.progress.ProgressEventNotifier; import org.apache.cassandra.utils.progress.ProgressListener; /** * ThreadLocal state for a tracing session. The presence of an instance of this class as a ThreadLocal denotes that an * operation is being traced. */ public abstract class TraceState implements ProgressEventNotifier { public final UUID sessionId; public final InetAddress coordinator; public final Stopwatch watch; public final ByteBuffer sessionIdBytes; public final Tracing.TraceType traceType; public final int ttl; private boolean notify; private final List<ProgressListener> listeners = new CopyOnWriteArrayList<>(); private String tag; public enum Status { IDLE, ACTIVE, STOPPED } private volatile Status status; // Multiple requests can use the same TraceState at a time, so we need to reference count. // See CASSANDRA-7626 for more details. private final AtomicInteger references = new AtomicInteger(1); protected TraceState(InetAddress coordinator, UUID sessionId, Tracing.TraceType traceType) { assert coordinator != null; assert sessionId != null; this.coordinator = coordinator; this.sessionId = sessionId; sessionIdBytes = ByteBufferUtil.bytes(sessionId); this.traceType = traceType; this.ttl = traceType.getTTL(); watch = Stopwatch.createStarted(); this.status = Status.IDLE; } /** * Activate notification with provided {@code tag} name. * * @param tag Tag name to add when emitting notification */ public void enableActivityNotification(String tag) { assert traceType == Tracing.TraceType.REPAIR; notify = true; this.tag = tag; } @Override public void addProgressListener(ProgressListener listener) { assert traceType == Tracing.TraceType.REPAIR; listeners.add(listener); } @Override public void removeProgressListener(ProgressListener listener) { assert traceType == Tracing.TraceType.REPAIR; listeners.remove(listener); } public int elapsed() { long elapsed = watch.elapsed(TimeUnit.MICROSECONDS); return elapsed < Integer.MAX_VALUE ? (int) elapsed : Integer.MAX_VALUE; } public synchronized void stop() { waitForPendingEvents(); status = Status.STOPPED; notifyAll(); } /* * Returns immediately if there has been trace activity since the last * call, otherwise waits until there is trace activity, or until the * timeout expires. * @param timeout timeout in milliseconds * @return activity status */ public synchronized Status waitActivity(long timeout) { if (status == Status.IDLE) { try { wait(timeout); } catch (InterruptedException e) { throw new RuntimeException(); } } if (status == Status.ACTIVE) { status = Status.IDLE; return Status.ACTIVE; } return status; } protected synchronized void notifyActivity() { status = Status.ACTIVE; notifyAll(); } public void trace(String format, Object arg) { trace(MessageFormatter.format(format, arg).getMessage()); } public void trace(String format, Object arg1, Object arg2) { trace(MessageFormatter.format(format, arg1, arg2).getMessage()); } public void trace(String format, Object[] args) { trace(MessageFormatter.arrayFormat(format, args).getMessage()); } public void trace(String message) { if (notify) notifyActivity(); traceImpl(message); for (ProgressListener listener : listeners) { listener.progress(tag, ProgressEvent.createNotification(message)); } } protected abstract void traceImpl(String message); protected void waitForPendingEvents() { // if tracing events are asynchronous, then you can use this method to wait for them to complete } public boolean acquireReference() { while (true) { int n = references.get(); if (n <= 0) return false; if (references.compareAndSet(n, n + 1)) return true; } } public int releaseReference() { waitForPendingEvents(); return references.decrementAndGet(); } }
/* * 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.commons.codec.language.bm; import java.util.Collections; import java.util.EnumMap; import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.Set; import org.apache.commons.codec.Resources; /** * Language codes. * <p> * Language codes are typically loaded from resource files. These are UTF-8 * encoded text files. They are systematically named following the pattern: * <blockquote>org/apache/commons/codec/language/bm/${{@link NameType#getName()} * languages.txt</blockquote> * <p> * The format of these resources is the following: * <ul> * <li><b>Language:</b> a single string containing no whitespace</li> * <li><b>End-of-line comments:</b> Any occurrence of '//' will cause all text * following on that line to be discarded as a comment.</li> * <li><b>Multi-line comments:</b> Any line starting with '/*' will start * multi-line commenting mode. This will skip all content until a line ending in * '*' and '/' is found.</li> * <li><b>Blank lines:</b> All blank lines will be skipped.</li> * </ul> * <p> * Ported from language.php * <p> * This class is immutable and thread-safe. * * @since 1.6 */ public class Languages { // Implementation note: This class is divided into two sections. The first part // is a static factory interface that // exposes org/apache/commons/codec/language/bm/%s_languages.txt for %s in // NameType.* as a list of supported // languages, and a second part that provides instance methods for accessing // this set for supported languages. /** * A set of languages. */ public static abstract class LanguageSet { public static LanguageSet from(final Set<String> langs) { return langs.isEmpty() ? NO_LANGUAGES : new SomeLanguages(langs); } public abstract boolean contains(String language); public abstract String getAny(); public abstract boolean isEmpty(); public abstract boolean isSingleton(); public abstract LanguageSet restrictTo(LanguageSet other); abstract LanguageSet merge(LanguageSet other); } /** * Some languages, explicitly enumerated. */ public static final class SomeLanguages extends LanguageSet { private final Set<String> languages; private SomeLanguages(final Set<String> languages) { this.languages = Collections.unmodifiableSet(languages); } @Override public boolean contains(final String language) { return this.languages.contains(language); } @Override public String getAny() { return this.languages.iterator().next(); } public Set<String> getLanguages() { return this.languages; } @Override public boolean isEmpty() { return this.languages.isEmpty(); } @Override public boolean isSingleton() { return this.languages.size() == 1; } @Override public LanguageSet restrictTo(final LanguageSet other) { if (other == NO_LANGUAGES) { return other; } if (other == ANY_LANGUAGE) { return this; } final SomeLanguages someLanguages = (SomeLanguages) other; final Set<String> set = new HashSet<>(Math.min(languages.size(), someLanguages.languages.size())); for (final String lang : languages) { if (someLanguages.languages.contains(lang)) { set.add(lang); } } return from(set); } @Override public LanguageSet merge(final LanguageSet other) { if (other == NO_LANGUAGES) { return this; } if (other == ANY_LANGUAGE) { return other; } final SomeLanguages someLanguages = (SomeLanguages) other; final Set<String> set = new HashSet<>(languages); set.addAll(someLanguages.languages); return from(set); } @Override public String toString() { return "Languages(" + languages.toString() + ")"; } } public static final String ANY = "any"; private static final Map<NameType, Languages> LANGUAGES = new EnumMap<>(NameType.class); static { for (final NameType s : NameType.values()) { LANGUAGES.put(s, getInstance(langResourceName(s))); } } public static Languages getInstance(final NameType nameType) { return LANGUAGES.get(nameType); } public static Languages getInstance(final String languagesResourceName) { // read languages list final Set<String> ls = new HashSet<>(); try (final Scanner lsScanner = new Scanner(Resources.getInputStream(languagesResourceName), ResourceConstants.ENCODING)) { boolean inExtendedComment = false; while (lsScanner.hasNextLine()) { final String line = lsScanner.nextLine().trim(); if (inExtendedComment) { if (line.endsWith(ResourceConstants.EXT_CMT_END)) { inExtendedComment = false; } } else if (line.startsWith(ResourceConstants.EXT_CMT_START)) { inExtendedComment = true; } else if (!line.isEmpty()) { ls.add(line); } } return new Languages(Collections.unmodifiableSet(ls)); } } private static String langResourceName(final NameType nameType) { return String.format("org/apache/commons/codec/language/bm/%s_languages.txt", nameType.getName()); } private final Set<String> languages; /** * No languages at all. */ public static final LanguageSet NO_LANGUAGES = new LanguageSet() { @Override public boolean contains(final String language) { return false; } @Override public String getAny() { throw new NoSuchElementException("Can't fetch any language from the empty language set."); } @Override public boolean isEmpty() { return true; } @Override public boolean isSingleton() { return false; } @Override public LanguageSet restrictTo(final LanguageSet other) { return this; } @Override public LanguageSet merge(final LanguageSet other) { return other; } @Override public String toString() { return "NO_LANGUAGES"; } }; /** * Any/all languages. */ public static final LanguageSet ANY_LANGUAGE = new LanguageSet() { @Override public boolean contains(final String language) { return true; } @Override public String getAny() { throw new NoSuchElementException("Can't fetch any language from the any language set."); } @Override public boolean isEmpty() { return false; } @Override public boolean isSingleton() { return false; } @Override public LanguageSet restrictTo(final LanguageSet other) { return other; } @Override public LanguageSet merge(final LanguageSet other) { return other; } @Override public String toString() { return "ANY_LANGUAGE"; } }; private Languages(final Set<String> languages) { this.languages = languages; } public Set<String> getLanguages() { return this.languages; } }
package jp.gr.java_conf.neko_daisuki.android.widget; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.ImageButton; import jp.gr.java_conf.neko_daisuki.android.view.MotionEventDispatcher; public class CircleImageButton extends ImageButton { private abstract class MotionEventProc implements MotionEventDispatcher.Proc { protected CircleImageButton mButton; public MotionEventProc(CircleImageButton button) { mButton = button; } public abstract boolean run(MotionEvent event); } private class ActionDownEventProc extends MotionEventProc { public ActionDownEventProc(CircleImageButton button) { super(button); } public boolean run(MotionEvent event) { /* * About ActionDownEventProc and ActionUpEventProc * =============================================== * * I expected that View.onTouchEvent() does everything needed * (changing button state to pressed, firing event listeners and * invalidating). But actual is not. So I implemented all manually. * * At first, what I did at here was calling * this.button.invalidte(). But background of the button did not * change. I do not know why exactly. Android source code (*1) * shows that the button state is changed to PREPRESSED at first. * Changing to PRESSED is happened later. This fact might relate. * * Android 4.0 (API level 14) has * ViewGroup.shouldDelayChildPressedState(). Overriding it to * return false in UzumakiSlider may be useful (*2. See definitions * of onTouchEvent() and isInScrollingContainer()). But I am using * Android 3.2, I did not try it. * * (*1) http://tools.oesf.biz/android-2.3.7_r1.0/xref/frameworks/base/core/java/android/view/View.java * (*2) http://tools.oesf.biz/android-4.0.1_r1.0/xref/frameworks/base/core/java/android/view/View.java */ mButton.setPressed(true); mButton.invalidate(); return true; } } private class ActionUpEventProc extends MotionEventProc { public ActionUpEventProc(CircleImageButton button) { super(button); } public boolean run(MotionEvent event) { mButton.setPressed(false); mButton.invalidate(); mButton.performClick(); return true; } } private abstract class Drawer { protected CircleImageButton mButton; protected int mEdgeWidth; public Drawer(CircleImageButton button) { mButton = button; mEdgeWidth = 2; } public abstract void draw(Canvas canvas, int centerX, int centerY, int outerRadius); protected int computeInnerRadius(int outerRadius) { return (int)(0.92 * outerRadius); } protected void drawButton(Canvas canvas, int centerX, int centerY, int outerRadius) { int innerRadius = computeInnerRadius(outerRadius); RectF outerRect = new RectF(centerX - outerRadius, centerY - outerRadius, centerX + outerRadius, centerY + outerRadius); RectF innerRect = new RectF(centerX - innerRadius, centerY - innerRadius, centerX + innerRadius, centerY + innerRadius); Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL); paint.setAntiAlias(true); Paint mainPaint = new Paint(paint); mainPaint.setColor(mButton.mBackgroundColor); canvas.drawCircle(centerX, centerY, outerRadius, mainPaint); Path topTie = new Path(); topTie.addArc(outerRect, 0, -180); topTie.lineTo(centerX - innerRadius, centerY); topTie.addArc(innerRect, -180, 180); topTie.lineTo(centerX + outerRadius, centerY); Paint topTiePaint = new Paint(paint); topTiePaint.setColor(mButton.mBrightColor); canvas.drawPath(topTie, topTiePaint); Path bottomTie = new Path(); bottomTie.addArc(outerRect, 0, 180); bottomTie.lineTo(centerX - innerRadius, centerY); bottomTie.addArc(innerRect, 180, -180); bottomTie.lineTo(centerX + outerRadius, centerY); Paint bottomTiePaint = new Paint(paint); bottomTiePaint.setColor(mButton.mShadowColor); canvas.drawPath(bottomTie, bottomTiePaint); float radius = 0.86f * outerRadius; RectF oval = new RectF(centerX - radius, centerY - radius, centerX + radius, centerY + radius); Path circle = new Path(); circle.addArc(oval, 0, -180); Paint circlePaint = new Paint(paint); circlePaint.setColor(mButton.mBrightColor); circlePaint.setStrokeWidth(1); circlePaint.setStyle(Paint.Style.STROKE); canvas.drawPath(circle, circlePaint); Path circle2 = new Path(); circle2.addArc(oval, 0, 180); Paint circlePaint2 = new Paint(paint); circlePaint2.setColor(mButton.mShadowColor); circlePaint2.setStrokeWidth(1); circlePaint2.setStyle(Paint.Style.STROKE); canvas.drawPath(circle2, circlePaint2); } protected void drawEdge(Canvas canvas, int centerX, int centerY, int radius) { Paint paint = new Paint(); paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(mEdgeWidth); RectF rect = new RectF(centerX - radius, centerY - radius, centerX + radius, centerY + radius); paint.setColor(mButton.mShadowColor); canvas.drawArc(rect, 0, -180, false, paint); //paint.setColor(this.button.brightColor); canvas.drawArc(rect, 0, 180, false, paint); } } private class NeutralDrawer extends Drawer { public NeutralDrawer(CircleImageButton button) { super(button); } public void draw(Canvas canvas, int centerX, int centerY, int outerRadius) { drawButton(canvas, centerX, centerY, outerRadius - mEdgeWidth); drawEdge(canvas, centerX, centerY, outerRadius); } } private class PressedDrawer extends Drawer { public PressedDrawer(CircleImageButton button) { super(button); } public void draw(Canvas canvas, int centerX, int centerY, int outerRadius) { int radius = (int)(0.99 * (outerRadius - mEdgeWidth)); drawButton(canvas, centerX, centerY, radius); drawShadow(canvas, centerX, centerY, outerRadius); drawEdge(canvas, centerX, centerY, outerRadius); } private void drawShadow(Canvas canvas, int centerX, int centerY, int radius) { Path path = new Path(); RectF rect = new RectF(centerX - radius, centerY - radius, centerX + radius, centerY + radius); path.addArc(rect, 0, -180); RectF rect2 = new RectF((float)(centerX - radius), (float)(centerY - 0.96 * radius), (float)(centerX + radius), (float)(centerY + 0.96 * radius)); path.arcTo(rect2, -180, 180); Paint paint = new Paint(); paint.setColor(0xff000000); paint.setAntiAlias(true); paint.setStyle(Paint.Style.FILL); canvas.drawPath(path, paint); } } private int mPadding; private int mBackgroundColor; private int mBrightColor; private int mShadowColor; private MotionEventDispatcher mMotionEventDispatcher; private Drawer mNeutralDrawer; private Drawer mPressedDrawer; public CircleImageButton(Context context) { super(context); initialize(); } public CircleImageButton(Context context, AttributeSet attrs) { super(context, attrs); initialize(); } public CircleImageButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initialize(); } @Override public boolean dispatchTouchEvent(MotionEvent event) { float deltaX = event.getX() - getCenterX(); float deltaY = event.getY() - getCenterY(); double distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY); boolean isInCircle = distance < getRadius(); return isInCircle ? super.dispatchTouchEvent(event) : false; } @Override public boolean onTouchEvent(MotionEvent event) { return mMotionEventDispatcher.dispatch(event); } @Override protected void onDraw(Canvas canvas) { int centerX = getCenterX(); int centerY = getCenterY(); Drawer drawer = isPressed() ? mPressedDrawer : mNeutralDrawer; drawer.draw(canvas, centerX, centerY, getRadius()); super.onDraw(canvas); } private int getRadius() { return Math.min(getWidth(), getHeight()) / 2 - mPadding; } private int getCenterX() { return getWidth() / 2; } private int getCenterY() { return getHeight() / 2; } private void initialize() { mPadding = 1; mBackgroundColor = Color.argb(255, 0xcc, 0xcc, 0xcc); mBrightColor = Color.argb(255, 255, 255, 255); mShadowColor = Color.argb(255, 138, 138, 138); mMotionEventDispatcher = new MotionEventDispatcher(); mMotionEventDispatcher.setDownProc(new ActionDownEventProc(this)); mMotionEventDispatcher.setUpProc(new ActionUpEventProc(this)); mNeutralDrawer = new NeutralDrawer(this); mPressedDrawer = new PressedDrawer(this); } } // vim: tabstop=4 shiftwidth=4 expandtab softtabstop=4
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/video/stitcher/v1/video_stitcher_service.proto package com.google.cloud.video.stitcher.v1; /** * * * <pre> * Request message for VideoStitcherService.deleteSlate. * </pre> * * Protobuf type {@code google.cloud.video.stitcher.v1.DeleteSlateRequest} */ public final class DeleteSlateRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.video.stitcher.v1.DeleteSlateRequest) DeleteSlateRequestOrBuilder { private static final long serialVersionUID = 0L; // Use DeleteSlateRequest.newBuilder() to construct. private DeleteSlateRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private DeleteSlateRequest() { name_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new DeleteSlateRequest(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private DeleteSlateRequest( 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; case 10: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.video.stitcher.v1.VideoStitcherServiceProto .internal_static_google_cloud_video_stitcher_v1_DeleteSlateRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.video.stitcher.v1.VideoStitcherServiceProto .internal_static_google_cloud_video_stitcher_v1_DeleteSlateRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.video.stitcher.v1.DeleteSlateRequest.class, com.google.cloud.video.stitcher.v1.DeleteSlateRequest.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; private volatile java.lang.Object name_; /** * * * <pre> * Required. The name of the slate to be deleted, in the form of * `projects/{project_number}/locations/{location}/slates/{id}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Required. The name of the slate to be deleted, in the form of * `projects/{project_number}/locations/{location}/slates/{id}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @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 (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } 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.video.stitcher.v1.DeleteSlateRequest)) { return super.equals(obj); } com.google.cloud.video.stitcher.v1.DeleteSlateRequest other = (com.google.cloud.video.stitcher.v1.DeleteSlateRequest) obj; if (!getName().equals(other.getName())) return false; 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 = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.video.stitcher.v1.DeleteSlateRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.video.stitcher.v1.DeleteSlateRequest 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.video.stitcher.v1.DeleteSlateRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.video.stitcher.v1.DeleteSlateRequest 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.video.stitcher.v1.DeleteSlateRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.video.stitcher.v1.DeleteSlateRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.video.stitcher.v1.DeleteSlateRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.video.stitcher.v1.DeleteSlateRequest 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.video.stitcher.v1.DeleteSlateRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.video.stitcher.v1.DeleteSlateRequest 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.video.stitcher.v1.DeleteSlateRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.video.stitcher.v1.DeleteSlateRequest 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.video.stitcher.v1.DeleteSlateRequest 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> * Request message for VideoStitcherService.deleteSlate. * </pre> * * Protobuf type {@code google.cloud.video.stitcher.v1.DeleteSlateRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.video.stitcher.v1.DeleteSlateRequest) com.google.cloud.video.stitcher.v1.DeleteSlateRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.video.stitcher.v1.VideoStitcherServiceProto .internal_static_google_cloud_video_stitcher_v1_DeleteSlateRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.video.stitcher.v1.VideoStitcherServiceProto .internal_static_google_cloud_video_stitcher_v1_DeleteSlateRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.video.stitcher.v1.DeleteSlateRequest.class, com.google.cloud.video.stitcher.v1.DeleteSlateRequest.Builder.class); } // Construct using com.google.cloud.video.stitcher.v1.DeleteSlateRequest.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(); name_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.video.stitcher.v1.VideoStitcherServiceProto .internal_static_google_cloud_video_stitcher_v1_DeleteSlateRequest_descriptor; } @java.lang.Override public com.google.cloud.video.stitcher.v1.DeleteSlateRequest getDefaultInstanceForType() { return com.google.cloud.video.stitcher.v1.DeleteSlateRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.video.stitcher.v1.DeleteSlateRequest build() { com.google.cloud.video.stitcher.v1.DeleteSlateRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.video.stitcher.v1.DeleteSlateRequest buildPartial() { com.google.cloud.video.stitcher.v1.DeleteSlateRequest result = new com.google.cloud.video.stitcher.v1.DeleteSlateRequest(this); result.name_ = name_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.video.stitcher.v1.DeleteSlateRequest) { return mergeFrom((com.google.cloud.video.stitcher.v1.DeleteSlateRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.video.stitcher.v1.DeleteSlateRequest other) { if (other == com.google.cloud.video.stitcher.v1.DeleteSlateRequest.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; onChanged(); } 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.video.stitcher.v1.DeleteSlateRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.video.stitcher.v1.DeleteSlateRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object name_ = ""; /** * * * <pre> * Required. The name of the slate to be deleted, in the form of * `projects/{project_number}/locations/{location}/slates/{id}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The name of the slate to be deleted, in the form of * `projects/{project_number}/locations/{location}/slates/{id}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The name of the slate to be deleted, in the form of * `projects/{project_number}/locations/{location}/slates/{id}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * * * <pre> * Required. The name of the slate to be deleted, in the form of * `projects/{project_number}/locations/{location}/slates/{id}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * * * <pre> * Required. The name of the slate to be deleted, in the form of * `projects/{project_number}/locations/{location}/slates/{id}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.video.stitcher.v1.DeleteSlateRequest) } // @@protoc_insertion_point(class_scope:google.cloud.video.stitcher.v1.DeleteSlateRequest) private static final com.google.cloud.video.stitcher.v1.DeleteSlateRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.video.stitcher.v1.DeleteSlateRequest(); } public static com.google.cloud.video.stitcher.v1.DeleteSlateRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DeleteSlateRequest> PARSER = new com.google.protobuf.AbstractParser<DeleteSlateRequest>() { @java.lang.Override public DeleteSlateRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new DeleteSlateRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<DeleteSlateRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DeleteSlateRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.video.stitcher.v1.DeleteSlateRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
/* * Copyright 2016 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.domain; import com.thoughtworks.go.config.*; import com.thoughtworks.go.util.GoConstants; import com.thoughtworks.go.util.command.EnvironmentVariableContext; import com.thoughtworks.go.work.DefaultGoPublisher; import java.io.File; import java.util.ArrayList; import java.util.List; public class DefaultJobPlan implements JobPlan { private long jobId; private long pipelineId; private JobIdentifier identifier; private Resources resources; private ArtifactPlans plans; private ArtifactPropertiesGenerators generators; private String agentUuid; private EnvironmentVariablesConfig variables; private EnvironmentVariablesConfig triggerVariables; private JobAgentConfig jobAgentConfig; private boolean fetchMaterials = StageConfig.DEFAULT_FETCH_MATERIALS; private boolean cleanWorkingDir = StageConfig.DEFAULT_CLEAN_WORKING_DIR; //FOR IBATIS protected DefaultJobPlan() { } public DefaultJobPlan(Resources resources, ArtifactPlans plans, ArtifactPropertiesGenerators generators, long jobId, JobIdentifier identifier, String agentUuid, EnvironmentVariablesConfig variables, EnvironmentVariablesConfig triggerTimeVariables, JobAgentConfig jobAgentConfig) { this.jobId = jobId; this.identifier = identifier; this.resources = resources; this.plans = plans; this.generators = generators; this.agentUuid = agentUuid; this.variables = variables; this.triggerVariables = triggerTimeVariables; this.jobAgentConfig = jobAgentConfig; } public String getPipelineName() { return identifier.getPipelineName(); } public String getStageName() { return identifier.getStageName(); } public String getName() { return identifier.getBuildName(); } public boolean match(List<Resource> resources) { return resources.containsAll(this.resources); } public long getJobId() { return jobId; } public JobIdentifier getIdentifier() { return identifier; } public void publishArtifacts(DefaultGoPublisher goPublisher, File workingDirectory) { ArtifactPlans mergedPlans = mergePlansForTest(); List<ArtifactPlan> failedArtifact = new ArrayList<>(); for (ArtifactPlan artifactPlan : mergedPlans) { try { artifactPlan.publish(goPublisher, workingDirectory); } catch (Exception e) { failedArtifact.add(artifactPlan); } } if (!failedArtifact.isEmpty()) { StringBuilder builder = new StringBuilder(); for (ArtifactPlan artifactPlan : failedArtifact) { artifactPlan.printSrc(builder); } throw new RuntimeException(String.format("[%s] Uploading finished. Failed to upload %s", GoConstants.PRODUCT_NAME, builder)); } } private ArtifactPlans mergePlansForTest() { TestArtifactPlan testArtifactPlan = null; final ArtifactPlans mergedPlans = new ArtifactPlans(); for (ArtifactPlan artifactPlan : plans) { if (artifactPlan.getArtifactType().isTest()) { if (testArtifactPlan == null) { testArtifactPlan = new TestArtifactPlan(artifactPlan); mergedPlans.add(testArtifactPlan); } else { testArtifactPlan.add(artifactPlan); } } else { mergedPlans.add(artifactPlan); } } return mergedPlans; } public List<ArtifactPropertiesGenerator> getPropertyGenerators() { return generators; } public List<ArtifactPlan> getArtifactPlans() { return plans; } //USED BY IBatis - do NOT add to the interface public List<ArtifactPropertiesGenerator> getGenerators() { return generators; } public List<ArtifactPlan> getPlans() { return plans; } public List<Resource> getResources() { return resources; } public void setGenerators(List<ArtifactPropertiesGenerator> generators) { this.generators = new ArtifactPropertiesGenerators(generators); } public void setJobId(long jobId) { this.jobId = jobId; } public void setIdentifier(JobIdentifier identifier) { this.identifier = identifier; } public void setPlans(List<ArtifactPlan> plans) { this.plans = new ArtifactPlans(plans); } public void setResources(List<Resource> resources) { this.resources = new Resources(resources); } public String toString() { return "[JobPlan " + "identifier=" + identifier + "resources=" + resources + " plans=" + plans + " generators=" + generators + "]"; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultJobPlan plan = (DefaultJobPlan) o; if (jobId != plan.jobId) { return false; } if (generators != null ? !generators.equals(plan.generators) : plan.generators != null) { return false; } if (identifier != null ? !identifier.equals(plan.identifier) : plan.identifier != null) { return false; } if (plans != null ? !plans.equals(plan.plans) : plan.plans != null) { return false; } if (resources != null ? !resources.equals(plan.resources) : plan.resources != null) { return false; } return true; } public int hashCode() { int result; result = (resources != null ? resources.hashCode() : 0); result = 31 * result + (plans != null ? plans.hashCode() : 0); result = 31 * result + (generators != null ? generators.hashCode() : 0); result = 31 * result + (int) (jobId ^ (jobId >>> 32)); result = 31 * result + (identifier != null ? identifier.hashCode() : 0); return result; } public String getAgentUuid() { return agentUuid; } public EnvironmentVariablesConfig getVariables() { return variables; } public void setVariables(EnvironmentVariablesConfig variables) { this.variables = variables; } public long getPipelineId() { return pipelineId; } public void setTriggerVariables(EnvironmentVariablesConfig environmentVariablesConfig) { triggerVariables = environmentVariablesConfig; } public boolean shouldFetchMaterials() { return fetchMaterials; } public void applyTo(EnvironmentVariableContext variableContext) { variables.addTo(variableContext); triggerVariables.addToIfExists(variableContext); } public void setAgentUuid(String agentUuid) { this.agentUuid = agentUuid; } public void setFetchMaterials(boolean fetchMaterials) { this.fetchMaterials = fetchMaterials; } public void setCleanWorkingDir(boolean cleanWorkingDir) { this.cleanWorkingDir = cleanWorkingDir; } public boolean shouldCleanWorkingDir() { return cleanWorkingDir; } public JobAgentConfig getJobAgentConfig() { return jobAgentConfig; } @Override public boolean requiresElasticAgent() { return jobAgentConfig != null; } public void setJobAgentConfig(JobAgentConfig jobAgentConfig) { this.jobAgentConfig = jobAgentConfig; } @Override public boolean assignedToAgent() { return agentUuid == null; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import javax.cache.CacheException; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteClientDisconnectedException; import org.apache.ignite.IgniteDataStreamer; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.processors.datastreamer.DataStreamerResponse; import org.apache.ignite.internal.util.lang.GridAbsPredicate; import org.apache.ignite.testframework.GridTestUtils; import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC; import static org.apache.ignite.cache.CacheMode.PARTITIONED; /** * */ public class IgniteClientReconnectStreamerTest extends IgniteClientReconnectAbstractTest { /** */ public static final String CACHE_NAME = "streamer"; /** {@inheritDoc} */ @Override protected int serverCount() { return 1; } /** {@inheritDoc} */ @Override protected int clientCount() { return 1; } /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); CacheConfiguration<Integer, Integer> ccfg = new CacheConfiguration<Integer, Integer>(CACHE_NAME) .setAtomicityMode(ATOMIC) .setCacheMode(PARTITIONED); cfg.setCacheConfiguration(ccfg); return cfg; } /** * @throws Exception If failed. */ public void testStreamerReconnect() throws Exception { final Ignite client = grid(serverCount()); assertTrue(client.cluster().localNode().isClient()); Ignite srv = clientRouter(client); final IgniteCache<Object, Object> srvCache = srv.cache(CACHE_NAME); IgniteDataStreamer<Integer, Integer> streamer = client.dataStreamer(CACHE_NAME); for (int i = 0; i < 50; i++) streamer.addData(i, i); streamer.flush(); GridTestUtils.waitForCondition(new GridAbsPredicate() { @Override public boolean apply() { return srvCache.localSize() == 50; } }, 2000L); assertEquals(50, srvCache.localSize()); reconnectClientNode(client, srv, new Runnable() { @Override public void run() { try { client.dataStreamer(CACHE_NAME); fail(); } catch (IgniteClientDisconnectedException e) { assertNotNull(e.reconnectFuture()); } } }); checkStreamerClosed(streamer); streamer = client.dataStreamer(CACHE_NAME); for (int i = 50; i < 100; i++) streamer.addData(i, i); streamer.flush(); GridTestUtils.waitForCondition(new GridAbsPredicate() { @Override public boolean apply() { return srvCache.localSize() == 100; } }, 2000L); assertEquals(100, srvCache.localSize()); streamer.close(); streamer.future().get(2, TimeUnit.SECONDS); srvCache.removeAll(); } /** * @throws Exception If failed. */ public void testStreamerReconnectInProgress() throws Exception { Ignite client = grid(serverCount()); assertTrue(client.cluster().localNode().isClient()); Ignite srv = clientRouter(client); final IgniteCache<Object, Object> srvCache = srv.cache(CACHE_NAME); final IgniteDataStreamer<Integer, Integer> streamer = client.dataStreamer(CACHE_NAME); BlockTcpCommunicationSpi commSpi = commSpi(srv); commSpi.blockMessage(DataStreamerResponse.class); final IgniteInternalFuture<Object> fut = GridTestUtils.runAsync(new Callable<Object>() { @Override public Object call() throws Exception { try { for (int i = 0; i < 50; i++) streamer.addData(i, i); streamer.flush(); } catch (CacheException e) { checkAndWait(e); return true; } finally { streamer.close(); } return false; } }); // Check that client waiting operation. GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { return fut.get(200); } }, IgniteFutureTimeoutCheckedException.class, null); assertNotDone(fut); commSpi.unblockMessage(); reconnectClientNode(client, srv, null); assertTrue((Boolean)fut.get(2, TimeUnit.SECONDS)); checkStreamerClosed(streamer); IgniteDataStreamer<Integer, Integer> streamer2 = client.dataStreamer(CACHE_NAME); for (int i = 0; i < 50; i++) streamer2.addData(i, i); streamer2.close(); GridTestUtils.waitForCondition(new GridAbsPredicate() { @Override public boolean apply() { return srvCache.localSize() == 50; } }, 2000L); assertEquals(50, srvCache.localSize()); } /** * @param streamer Streamer. */ private void checkStreamerClosed(IgniteDataStreamer<Integer, Integer> streamer) { try { streamer.addData(100, 100).get(); fail(); } catch (CacheException e) { checkAndWait(e); } try { streamer.flush(); fail(); } catch (CacheException e) { checkAndWait(e); } try { streamer.future().get(); fail(); } catch (CacheException e) { checkAndWait(e); } streamer.tryFlush(); streamer.close(); } }
/* * This file is part of "lunisolar-magma". * * (C) Copyright 2014-2022 Lunisolar (http://lunisolar.eu/). * * 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 eu.lunisolar.magma.func.predicate; import eu.lunisolar.magma.func.*; // NOSONAR import javax.annotation.Nonnull; // NOSONAR import javax.annotation.Nullable; // NOSONAR import java.util.Objects;// NOSONAR import eu.lunisolar.magma.basics.meta.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR import eu.lunisolar.magma.func.action.*; // NOSONAR import eu.lunisolar.magma.func.consumer.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR import eu.lunisolar.magma.func.function.*; // NOSONAR import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR import eu.lunisolar.magma.func.function.from.*; // NOSONAR import eu.lunisolar.magma.func.function.to.*; // NOSONAR import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR import eu.lunisolar.magma.func.predicate.*; // NOSONAR import eu.lunisolar.magma.func.supplier.*; // NOSONAR import org.testng.Assert; import org.testng.annotations.*; //NOSONAR import java.util.regex.Pattern; //NOSONAR import java.text.ParseException; //NOSONAR import eu.lunisolar.magma.basics.*; //NOSONAR import eu.lunisolar.magma.basics.exceptions.*; //NOSONAR import java.util.concurrent.atomic.AtomicInteger; //NOSONAR import eu.lunisolar.magma.func.tuple.*; // NOSONAR import java.util.function.*; // NOSONAR /** The test obviously concentrate on the interface methods the function it self is very simple. */ public class LBiObjLongPredicateTest<T1,T2> { private static final String ORIGINAL_MESSAGE = "Original message"; private static final String EXCEPTION_WAS_WRAPPED = "Exception was wrapped."; private static final String NO_EXCEPTION_WERE_THROWN = "No exception were thrown."; private boolean testValue = true; private LBiObjLongPredicate<Integer,Integer> sut = new LBiObjLongPredicate<Integer,Integer>(){ public boolean testX(Integer a1,Integer a2,long a3) { return testValue; } }; private LBiObjLongPredicate<Integer,Integer> sutAlwaysThrowing = LBiObjLongPredicate.biObjLongPred((a1,a2,a3) -> { throw new ParseException(ORIGINAL_MESSAGE, 0); }); private LBiObjLongPredicate<Integer,Integer> sutAlwaysThrowingUnchecked = LBiObjLongPredicate.biObjLongPred((a1,a2,a3) -> { throw new IndexOutOfBoundsException(ORIGINAL_MESSAGE); }); @Test public void testTheResult() throws Throwable { Assert.assertEquals(sut.test(100,100,100L), testValue); } @Test public void testTupleCall() throws Throwable { LBiObjLongTriple<Integer,Integer> domainObject = Tuple4U.biObjLongTriple(100,100,100L); Object result = sut.tupleTest(domainObject); Assert.assertEquals(result, testValue); } @Test public void testNonNullTest() throws Throwable { Assert.assertEquals(sut.nonNullTest(100,100,100L), testValue); } @Test public void testNestingTestUnchecked() throws Throwable { // then try { sutAlwaysThrowingUnchecked.nestingTest(100,100,100L); Assert.fail(NO_EXCEPTION_WERE_THROWN); } catch (Exception e) { Assert.assertEquals(e.getClass(), IndexOutOfBoundsException.class); Assert.assertNull(e.getCause()); Assert.assertEquals(e.getMessage(), ORIGINAL_MESSAGE); } } @Test public void testShovingTestUnchecked() throws Throwable { // then try { sutAlwaysThrowingUnchecked.shovingTest(100,100,100L); Assert.fail(NO_EXCEPTION_WERE_THROWN); } catch (Exception e) { Assert.assertEquals(e.getClass(), IndexOutOfBoundsException.class); Assert.assertNull(e.getCause()); Assert.assertEquals(e.getMessage(), ORIGINAL_MESSAGE); } } @Test public void testApplyAsBooleanShouldNotModifyValue() throws Throwable { Assert.assertEquals(sut.doApplyAsBoolean(100,100,100L), testValue); } @Test public void testFunctionalInterfaceDescription() throws Throwable { Assert.assertEquals(sut.functionalInterfaceDescription(), "LBiObjLongPredicate: boolean test(T1 a1,T2 a2,long a3)"); } @Test public void testBiObjLongPredMethod() throws Throwable { Assert.assertTrue(LBiObjLongPredicate.biObjLongPred((a1,a2,a3) -> testValue ) instanceof LBiObjLongPredicate); } @Test public void testnegate() throws Throwable { Assert.assertEquals(sut.negate().test(100,100,100L), !testValue); } @DataProvider(name="boolean permutations") public Object[][] permuations() { return new Object[][] { // b1 , b2 , AND , OR , XOR {false, false, false, false, false }, {true , false, false, true , true }, {false, true , false, true , true }, {true , true , true , true , false }, }; } @Test(dataProvider="boolean permutations") public void testAndOrXor(final boolean f1Result, final boolean f2Result, final boolean andResult, final boolean orResult, final boolean xorResult) throws Throwable { //given LBiObjLongPredicate<Integer,Integer> fun1 = LBiObjLongPredicate.biObjLongPred((a1,a2,a3) -> f1Result); LBiObjLongPredicate<Integer,Integer> fun2 = LBiObjLongPredicate.biObjLongPred((a1,a2,a3) -> f2Result); //when LBiObjLongPredicate<Integer,Integer> andFunction = fun1.and(fun2); LBiObjLongPredicate<Integer,Integer> orFunction = fun1.or(fun2); LBiObjLongPredicate<Integer,Integer> xorFunction = fun1.xor(fun2); //then Assert.assertEquals(andFunction.test(100,100,100L), andResult); Assert.assertEquals(orFunction.test(100,100,100L), orResult); Assert.assertEquals(xorFunction.test(100,100,100L), xorResult); } @Test public void testIsEqual() throws Throwable { //when LBiObjLongPredicate<Integer,Integer> equals = LBiObjLongPredicate.isEqual(1,1,1L); //then Assert.assertTrue(equals.test(1,1,1L)); Assert.assertFalse(equals.test(0,0,0L)); } // <editor-fold desc="compose (functional)"> @Test public void testCompose() throws Throwable { final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false); final AtomicInteger beforeCalls = new AtomicInteger(0); //given (+ some assertions) LBiObjLongPredicate<Integer,Integer> sutO = (a1,a2,a3) -> { mainFunctionCalled.set(true); Assert.assertEquals(a1, (Object) 90); Assert.assertEquals(a2, (Object) 91); Assert.assertEquals(a3, (Object) 92L); return true; }; LFunction<Integer,Integer> before1 = p0 -> { Assert.assertEquals(p0, (Object) 80); beforeCalls.incrementAndGet(); return 90; }; LFunction<Integer,Integer> before2 = p1 -> { Assert.assertEquals(p1, (Object) 81); beforeCalls.incrementAndGet(); return 91; }; LLongUnaryOperator before3 = p2 -> { Assert.assertEquals(p2, (Object) 82L); beforeCalls.incrementAndGet(); return 92L; }; //when LBiObjLongPredicate<Integer,Integer> function = sutO.compose(before1,before2,before3); function.test(80,81,82L); //then - finals Assert.assertTrue(mainFunctionCalled.get()); Assert.assertEquals(beforeCalls.get(), 3); } @Test public void testBiObjLongPredCompose() throws Throwable { final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false); final AtomicInteger beforeCalls = new AtomicInteger(0); //given (+ some assertions) LBiObjLongPredicate<Integer,Integer> sutO = (a1,a2,a3) -> { mainFunctionCalled.set(true); Assert.assertEquals(a1, (Object) 90); Assert.assertEquals(a2, (Object) 91); Assert.assertEquals(a3, (Object) 92L); return true; }; LFunction<Integer,Integer> before1 = p0 -> { Assert.assertEquals(p0, (Object) 80); beforeCalls.incrementAndGet(); return 90; }; LFunction<Integer,Integer> before2 = p1 -> { Assert.assertEquals(p1, (Object) 81); beforeCalls.incrementAndGet(); return 91; }; LToLongFunction<Integer> before3 = p2 -> { Assert.assertEquals(p2, (Object) 82); beforeCalls.incrementAndGet(); return 92L; }; //when LTriPredicate<Integer,Integer,Integer> function = sutO.biObjLongPredCompose(before1,before2,before3); function.test(80,81,82); //then - finals Assert.assertTrue(mainFunctionCalled.get()); Assert.assertEquals(beforeCalls.get(), 3); } // </editor-fold> // <editor-fold desc="then (functional)"> @Test public void testBoolToBiObjLongFunc0() throws Throwable { final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false); final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false); //given (+ some assertions) LBiObjLongPredicate<Integer,Integer> sutO = (a1,a2,a3) -> { mainFunctionCalled.set(true); Assert.assertEquals(a1, (Object) 80); Assert.assertEquals(a2, (Object) 81); Assert.assertEquals(a3, (Object) 82L); return true; }; LBoolFunction<Integer> thenFunction = p -> { thenFunctionCalled.set(true); // boolean Assert.assertEquals(p, (Object) true); // Integer return 100; }; //when LBiObjLongFunction<Integer,Integer,Integer> function = sutO.boolToBiObjLongFunc(thenFunction); Integer finalValue = function.apply(80,81,82L); //then - finals Assert.assertEquals(finalValue, (Object) 100); Assert.assertTrue(mainFunctionCalled.get()); Assert.assertTrue(thenFunctionCalled.get()); } @Test public void testBoolToBiObjLongPred1() throws Throwable { final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false); final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false); //given (+ some assertions) LBiObjLongPredicate<Integer,Integer> sutO = (a1,a2,a3) -> { mainFunctionCalled.set(true); Assert.assertEquals(a1, (Object) 80); Assert.assertEquals(a2, (Object) 81); Assert.assertEquals(a3, (Object) 82L); return true; }; LLogicalOperator thenFunction = p -> { thenFunctionCalled.set(true); // boolean Assert.assertEquals(p, (Object) true); // boolean return true; }; //when LBiObjLongPredicate<Integer,Integer> function = sutO.boolToBiObjLongPred(thenFunction); boolean finalValue = function.test(80,81,82L); //then - finals Assert.assertEquals(finalValue, (Object) true); Assert.assertTrue(mainFunctionCalled.get()); Assert.assertTrue(thenFunctionCalled.get()); } // </editor-fold> @Test(expectedExceptions = RuntimeException.class) public void testShove() { // given LBiObjLongPredicate<Integer,Integer> sutThrowing = LBiObjLongPredicate.biObjLongPred((a1,a2,a3) -> { throw new UnsupportedOperationException(); }); // when sutThrowing.shovingTest(100,100,100L); } @Test public void testToString() throws Throwable { Assert.assertTrue(sut.toString().startsWith(this.getClass().getName()+"$")); Assert.assertTrue(String.format("%s", sut).contains("LBiObjLongPredicate: boolean test(T1 a1,T2 a2,long a3)")); } @Test public void isThrowing() { Assert.assertFalse(sut.isThrowing()); } //<editor-fold desc="Variants"> private boolean variantLObj0Long2Obj1Pred(Integer a1,long a3,Integer a2) { return true; } @Test public void compilerSubstituteVariantLObj0Long2Obj1Pred() { LBiObjLongPredicate lambda = LBiObjLongPredicate./*<T1,T2>*/obj0Long2Obj1Pred(this::variantLObj0Long2Obj1Pred); Assert.assertTrue(lambda instanceof LBiObjLongPredicate.LObj0Long2Obj1Pred); } private boolean variantLObj1Obj0Long2Pred(Integer a2,Integer a1,long a3) { return true; } @Test public void compilerSubstituteVariantLObj1Obj0Long2Pred() { LBiObjLongPredicate lambda = LBiObjLongPredicate./*<T1,T2>*/obj1Obj0Long2Pred(this::variantLObj1Obj0Long2Pred); Assert.assertTrue(lambda instanceof LBiObjLongPredicate.LObj1Obj0Long2Pred); } private boolean variantLObj1Long2Obj0Pred(Integer a2,long a3,Integer a1) { return true; } @Test public void compilerSubstituteVariantLObj1Long2Obj0Pred() { LBiObjLongPredicate lambda = LBiObjLongPredicate./*<T1,T2>*/obj1Long2Obj0Pred(this::variantLObj1Long2Obj0Pred); Assert.assertTrue(lambda instanceof LBiObjLongPredicate.LObj1Long2Obj0Pred); } private boolean variantLLong2Obj0Obj1Pred(long a3,Integer a1,Integer a2) { return true; } @Test public void compilerSubstituteVariantLLong2Obj0Obj1Pred() { LBiObjLongPredicate lambda = LBiObjLongPredicate./*<T1,T2>*/long2Obj0Obj1Pred(this::variantLLong2Obj0Obj1Pred); Assert.assertTrue(lambda instanceof LBiObjLongPredicate.LLong2Obj0Obj1Pred); } private boolean variantLLong2Obj1Obj0Pred(long a3,Integer a2,Integer a1) { return true; } @Test public void compilerSubstituteVariantLLong2Obj1Obj0Pred() { LBiObjLongPredicate lambda = LBiObjLongPredicate./*<T1,T2>*/long2Obj1Obj0Pred(this::variantLLong2Obj1Obj0Pred); Assert.assertTrue(lambda instanceof LBiObjLongPredicate.LLong2Obj1Obj0Pred); } //</editor-fold> }
/* * Copyright 2015 The SageTV Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sage; public abstract class BasicVideoFrame extends java.awt.Panel { protected static final String VIDEOFRAME_KEY = "videoframe"; protected static final String VOLUME_STEP = "volume_step"; protected static final String MUTE_ON_ALT_SPEED_PLAY = "mute_on_alt_speed_play"; protected static final long HNAN2MIL = 10000L; // convert 100nano to milli protected static final String VIDEO_BG_COLOR = "video_bg_color"; protected static final String VIDEO_HORIZONTAL_SHIFT_FREQ = "video_horizontal_shift_freq"; private static final String ASPECT_RATIO_MODE = "aspect_ratio_mode"; private static final String VIDEO_TRANSLATE_X = "video_translate_x"; private static final String VIDEO_TRANSLATE_Y = "video_translate_y"; private static final String VIDEO_ZOOM_X = "video_zoom_x"; private static final String VIDEO_ZOOM_Y = "video_zoom_y"; private static final String DISPLAY_ASPECT_RATIO = "display_aspect_ratio"; public static final int ASPECT_FILL = 0; public static final int ASPECT_SOURCE = 1; public static final int ASPECT_4X3 = 2; public static final int ASPECT_16X9 = 3; public static final int NUM_ASPECT_RATIO_CODES = 4; public static final String[] ASPECT_RATIO_NAMES = {"Fill", "Source", "4x3", "16x9"}; public static String[] getAspectRatioModes() { String[] rv = new String[ASPECT_RATIO_NAMES.length]; rv[0] = Sage.rez(ASPECT_RATIO_NAMES[0]); rv[1] = Sage.rez(ASPECT_RATIO_NAMES[1]); rv[2] = ASPECT_RATIO_NAMES[2]; rv[3] = ASPECT_RATIO_NAMES[3]; return rv; } public static String getAspectRatioName(int x) { if (x == ASPECT_FILL) return Sage.rez("Fill"); else if (x == ASPECT_SOURCE) return Sage.rez("Source"); else if (x == ASPECT_4X3) return "4x3"; else if (x == ASPECT_16X9) return "16x9"; else return ""; } public static int getAspectRatioCode(String x) { if (Sage.rez("Fill").equals(x)) return ASPECT_FILL; else if (Sage.rez("Source").equals(x)) return ASPECT_SOURCE; else if ("4x3".equals(x)) return ASPECT_4X3; else if ("16x9".equals(x)) return ASPECT_16X9; else return 0; } public static String getCCStateName(int x) { switch (x) { case MediaPlayer.CC_DISABLED: return Sage.rez("Closed_Caption_Off"); case MediaPlayer.CC_ENABLED_CAPTION1: return "CC1"; case MediaPlayer.CC_ENABLED_CAPTION2: return "CC2"; case MediaPlayer.CC_ENABLED_TEXT1: return "CC3"; case MediaPlayer.CC_ENABLED_TEXT2: return "CC4"; } if (x >= MediaPlayer.CC_ENABLED_DTV_BASE && x < (MediaPlayer.CC_ENABLED_DTV_BASE + MediaPlayer.CC_DTV_COUNT)) return "DTVCC" + (x + 1 - MediaPlayer.CC_ENABLED_DTV_BASE); return Sage.rez("Closed_Caption_Off"); } public static int getCCStateCode(String x) { if ("CC1".equals(x)) return MediaPlayer.CC_ENABLED_CAPTION1; else if ("CC2".equals(x)) return MediaPlayer.CC_ENABLED_CAPTION2; else if ("Text1".equals(x) || "CC3".equals(x)) return MediaPlayer.CC_ENABLED_TEXT1; else if ("Text2".equals(x) || "CC4".equals(x)) return MediaPlayer.CC_ENABLED_TEXT2; else if (x != null && x.startsWith("DTVCC")) { try { int i = Integer.parseInt(x.substring(5)); if (i > 0 && i <= MediaPlayer.CC_DTV_COUNT) return MediaPlayer.CC_ENABLED_DTV_BASE + i - 1; } catch (NumberFormatException nfe) { if (Sage.DBG) System.out.println("ERROR parsing CC format name " + x + " of:" + nfe); } } return MediaPlayer.CC_DISABLED; } protected static final long TS_DELAY = 1500L; public BasicVideoFrame(UIManager inUIMgr) { super(); prefs = VIDEOFRAME_KEY + '/'; uiMgr = inUIMgr; volumeStep = uiMgr.getInt(prefs + VOLUME_STEP, 5)/100f; muteOnAlt = uiMgr.getBoolean(prefs + MUTE_ON_ALT_SPEED_PLAY, true); aspectRatioMode = uiMgr.getInt(prefs + ASPECT_RATIO_MODE, ASPECT_SOURCE); videoTranslateX = uiMgr.getInt(prefs + ASPECT_RATIO_MODE + '/' + aspectRatioMode + '/' + VIDEO_TRANSLATE_X, 0); videoTranslateY = uiMgr.getInt(prefs + ASPECT_RATIO_MODE + '/' + aspectRatioMode + '/' + VIDEO_TRANSLATE_Y, 0); videoZoomX = uiMgr.getFloat(prefs + ASPECT_RATIO_MODE + '/' + aspectRatioMode + '/' + VIDEO_ZOOM_X, 1.0f); videoZoomY = uiMgr.getFloat(prefs + ASPECT_RATIO_MODE + '/' + aspectRatioMode + '/' + VIDEO_ZOOM_Y, 1.0f); displayAspectRatio = uiMgr.getFloat(prefs + DISPLAY_ASPECT_RATIO, 16.0f/9.0f); String colorStr = uiMgr.get(prefs + VIDEO_BG_COLOR, "0,0,0"); java.util.StringTokenizer toker = new java.util.StringTokenizer(colorStr, ","); try { videoBGColor = new java.awt.Color(Integer.parseInt(toker.nextToken()), Integer.parseInt(toker.nextToken()), Integer.parseInt(toker.nextToken())); } catch (Exception e) { videoBGColor = new java.awt.Color(30, 30, 30); } videoHShiftFreq = uiMgr.getLong(prefs + VIDEO_HORIZONTAL_SHIFT_FREQ, 0); if (videoHShiftFreq != 0) { createVideoHShiftTimer(); } setLayout(new java.awt.LayoutManager() { public void addLayoutComponent(String name, java.awt.Component comp){} public java.awt.Dimension minimumLayoutSize(java.awt.Container parent) { return preferredLayoutSize(parent); } public java.awt.Dimension preferredLayoutSize(java.awt.Container parent) { return parent.getPreferredSize(); } public void removeLayoutComponent(java.awt.Component comp){} public void layoutContainer(java.awt.Container parent) { videoComp.setBounds(0, 0, parent.getWidth(), parent.getHeight()); refreshVideoSizing(); } }); setFocusTraversalKeysEnabled(false); setBackground(java.awt.Color.gray); videoComp = new VideoCanvas(); videoComp.setFocusTraversalKeysEnabled(false); add(videoComp); videoComp.setVisible(false); mmc = MMC.getInstance(); forcedPAR = uiMgr.getFloat("ui/forced_pixel_aspect_ratio", 0); } public void setVideoBounds(java.awt.geom.Rectangle2D.Float x) { videoBounds = x; } public abstract java.awt.Dimension getVideoSize(); private long cachedVideoHandle; public void resetVideoHandleCache() { cachedVideoHandle = 0; } public long getVideoHandle() { return getVideoHandle(false); } public long getVideoHandle(boolean noCache) { return (cachedVideoHandle == 0 || noCache) ? (cachedVideoHandle = UIUtils.getHWND(videoComp)) : cachedVideoHandle; } void addMouseListeners(java.awt.event.MouseListener listy) { addMouseListener(listy); videoComp.addMouseListener(listy); } void addMouseMotionListeners(java.awt.event.MouseMotionListener listy) { addMouseMotionListener(listy); videoComp.addMouseMotionListener(listy); } void removeMouseListeners(java.awt.event.MouseListener listy) { removeMouseListener(listy); videoComp.removeMouseListener(listy); } void removeMouseMotionListeners(java.awt.event.MouseMotionListener listy) { removeMouseMotionListener(listy); videoComp.removeMouseMotionListener(listy); } void addKeyListeners(java.awt.event.KeyListener listy) { addKeyListener(listy); videoComp.addKeyListener(listy); } public boolean getMuteOnAltSpeedPlay() { return muteOnAlt; } public void setMuteOnAltSpeedPlay(boolean x) { uiMgr.putBoolean(prefs + MUTE_ON_ALT_SPEED_PLAY, muteOnAlt = x); } private static final int VIDEO_TRANSLATE_X_PROP_INDEX = 0; private static final int VIDEO_TRANSLATE_Y_PROP_INDEX = 1; private static final int VIDEO_ZOOM_X_PROP_INDEX = 2; private static final int VIDEO_ZOOM_Y_PROP_INDEX = 3; protected static final String[][] AR_MODES_PROPS = { { VIDEOFRAME_KEY + '/' + ASPECT_RATIO_MODE + '/' + 0 + '/' + VIDEO_TRANSLATE_X, VIDEOFRAME_KEY + '/' + ASPECT_RATIO_MODE + '/' + 0 + '/' + VIDEO_TRANSLATE_Y, VIDEOFRAME_KEY + '/' + ASPECT_RATIO_MODE + '/' + 0 + '/' + VIDEO_ZOOM_X, VIDEOFRAME_KEY + '/' + ASPECT_RATIO_MODE + '/' + 0 + '/' + VIDEO_ZOOM_Y },{ VIDEOFRAME_KEY + '/' + ASPECT_RATIO_MODE + '/' + 1 + '/' + VIDEO_TRANSLATE_X, VIDEOFRAME_KEY + '/' + ASPECT_RATIO_MODE + '/' + 1 + '/' + VIDEO_TRANSLATE_Y, VIDEOFRAME_KEY + '/' + ASPECT_RATIO_MODE + '/' + 1 + '/' + VIDEO_ZOOM_X, VIDEOFRAME_KEY + '/' + ASPECT_RATIO_MODE + '/' + 1 + '/' + VIDEO_ZOOM_Y },{ VIDEOFRAME_KEY + '/' + ASPECT_RATIO_MODE + '/' + 2 + '/' + VIDEO_TRANSLATE_X, VIDEOFRAME_KEY + '/' + ASPECT_RATIO_MODE + '/' + 2 + '/' + VIDEO_TRANSLATE_Y, VIDEOFRAME_KEY + '/' + ASPECT_RATIO_MODE + '/' + 2 + '/' + VIDEO_ZOOM_X, VIDEOFRAME_KEY + '/' + ASPECT_RATIO_MODE + '/' + 2 + '/' + VIDEO_ZOOM_Y },{ VIDEOFRAME_KEY + '/' + ASPECT_RATIO_MODE + '/' + 3 + '/' + VIDEO_TRANSLATE_X, VIDEOFRAME_KEY + '/' + ASPECT_RATIO_MODE + '/' + 3 + '/' + VIDEO_TRANSLATE_Y, VIDEOFRAME_KEY + '/' + ASPECT_RATIO_MODE + '/' + 3 + '/' + VIDEO_ZOOM_X, VIDEOFRAME_KEY + '/' + ASPECT_RATIO_MODE + '/' + 3 + '/' + VIDEO_ZOOM_Y }}; public float getVideoZoomX(int assMode) { return uiMgr.getFloat(AR_MODES_PROPS[assMode][VIDEO_ZOOM_X_PROP_INDEX], 1.0f); } public float getVideoZoomY(int assMode) { return uiMgr.getFloat(AR_MODES_PROPS[assMode][VIDEO_ZOOM_Y_PROP_INDEX], 1.0f); } public int getVideoOffsetX(int assMode) { return uiMgr.getInt(AR_MODES_PROPS[assMode][VIDEO_TRANSLATE_X_PROP_INDEX], 0); } public int getVideoOffsetY(int assMode) { return uiMgr.getInt(AR_MODES_PROPS[assMode][VIDEO_TRANSLATE_Y_PROP_INDEX], 0); } public int getAspectRatioMode() { return aspectRatioMode; } public float getDisplayAspectRatio() { return displayAspectRatio; } public void setPixelAspectRatio(float f) { forcedPAR = f; } public float getPixelAspectRatio() { if (forcedPAR > 0) return forcedPAR; // We need to determine the full size of the UI display and then we can get the PAR from the DAR + DisplayResolution java.awt.Dimension displayRes = uiMgr.getUIDisplayResolution(); if (displayRes == null) return displayAspectRatio * (MMC.getInstance().isNTSCVideoFormat() ? 480 : 576) / (720.0f); return (displayAspectRatio * displayRes.height) / (displayRes.width); } public void setVideoSizingParams(int transX, int transY, float zoomX, float zoomY, int aspectMode) { if (aspectRatioMode != aspectMode || transX != videoTranslateX || transY != videoTranslateY || zoomX != videoZoomX || zoomY != videoZoomY) { uiMgr.putInt(prefs + ASPECT_RATIO_MODE, aspectRatioMode = aspectMode); uiMgr.putFloat(prefs + ASPECT_RATIO_MODE + '/' + aspectRatioMode + '/' + VIDEO_ZOOM_X, videoZoomX = zoomX); uiMgr.putFloat(prefs + ASPECT_RATIO_MODE + '/' + aspectRatioMode + '/' + VIDEO_ZOOM_Y, videoZoomY = zoomY); uiMgr.putInt(prefs + ASPECT_RATIO_MODE + '/' + aspectRatioMode + '/' + VIDEO_TRANSLATE_X, videoTranslateX = transX); uiMgr.putInt(prefs + ASPECT_RATIO_MODE + '/' + aspectRatioMode + '/' + VIDEO_TRANSLATE_Y, videoTranslateY = transY); refreshVideoSizing(); } } public void setVideoZoomX(float zoomX, int aspectMode) { uiMgr.putFloat(prefs + ASPECT_RATIO_MODE + '/' + aspectMode + '/' + VIDEO_ZOOM_X, zoomX); if (aspectRatioMode == aspectMode && zoomX != videoZoomX) { videoZoomX = zoomX; refreshVideoSizing(); } } public void setVideoZoomY(float zoomY, int aspectMode) { uiMgr.putFloat(prefs + ASPECT_RATIO_MODE + '/' + aspectMode + '/' + VIDEO_ZOOM_Y, zoomY); if (aspectRatioMode == aspectMode && zoomY != videoZoomY) { videoZoomY = zoomY; refreshVideoSizing(); } } public void setVideoOffsetX(int offX, int aspectMode) { uiMgr.putInt(prefs + ASPECT_RATIO_MODE + '/' + aspectMode + '/' + VIDEO_TRANSLATE_X, offX); if (aspectRatioMode == aspectMode && videoTranslateX != offX) { videoTranslateX = offX; refreshVideoSizing(); } } public void setVideoOffsetY(int offY, int aspectMode) { uiMgr.putInt(prefs + ASPECT_RATIO_MODE + '/' + aspectMode + '/' + VIDEO_TRANSLATE_Y, offY); if (aspectRatioMode == aspectMode && videoTranslateY != offY) { videoTranslateY = offY; refreshVideoSizing(); } } public void setAspectRatioMode(int aspectMode) { if (aspectRatioMode != aspectMode) { uiMgr.putInt(prefs + ASPECT_RATIO_MODE, aspectRatioMode = aspectMode); videoZoomX = uiMgr.getFloat(prefs + ASPECT_RATIO_MODE + '/' + aspectRatioMode + '/' + VIDEO_ZOOM_X, 1.0f); videoZoomY = uiMgr.getFloat(prefs + ASPECT_RATIO_MODE + '/' + aspectRatioMode + '/' + VIDEO_ZOOM_Y, 1.0f); videoTranslateX = uiMgr.getInt(prefs + ASPECT_RATIO_MODE + '/' + aspectRatioMode + '/' + VIDEO_TRANSLATE_X, 0); videoTranslateY = uiMgr.getInt(prefs + ASPECT_RATIO_MODE + '/' + aspectRatioMode + '/' + VIDEO_TRANSLATE_Y, 0); refreshVideoSizing(); // This will allow the UI to be refreshed by the user Catbert.processUISpecificHook("MediaPlayerPlayStateChanged", null, uiMgr, true); } } public void setDisplayAspectRatio(float f) { if (f != displayAspectRatio) { uiMgr.putFloat(prefs + DISPLAY_ASPECT_RATIO, displayAspectRatio = f); refreshVideoSizing(); } } public abstract float getCurrentAspectRatio(); public void refreshVideoSizing() { if (getParent() == null) return; refreshVideoSizing(getVideoSize()); } public void refreshVideoSizing(java.awt.Dimension vsize) { if (getParent() == null) return; sage.geom.Rectangle myBounds; if (videoBounds == null) { myBounds = new sage.geom.Rectangle(0, 0, getParent().getWidth(), getParent().getHeight()); } else myBounds = new sage.geom.Rectangle(videoBounds); int vw, vh; vw = vsize == null ? 0 : vsize.width; vh = vsize == null ? 0 : vsize.height; if (vw <= 0) vw = 720; if (vh <= 0) vh = MMC.getInstance().isNTSCVideoFormat() ? 480 : 576; sage.geom.Rectangle videoSrc = new sage.geom.Rectangle(0, 0, vw, vh); sage.geom.Rectangle videoDest = new sage.geom.Rectangle(myBounds.x, myBounds.y, myBounds.width, myBounds.height); int assMode = getAspectRatioMode(); float forcedRatio = getCurrentAspectRatio(); if (forcedRatio != 0) { if (videoDest.width/videoDest.height < forcedRatio) { float shrink = videoDest.height - videoDest.width/forcedRatio; videoDest.height -= shrink; videoDest.y += shrink/2; } else { float shrink = videoDest.width - videoDest.height*forcedRatio; videoDest.width -= shrink; videoDest.x += shrink/2; } } float zoomX = getVideoZoomX(assMode); float zoomY = getVideoZoomY(assMode); int transX = getVideoOffsetX(assMode); int transY = getVideoOffsetY(assMode); float widthAdjust = (zoomX - 1.0f)*videoDest.width; float heightAdjust = (zoomY - 1.0f)*videoDest.height; videoDest.x -= widthAdjust/2; videoDest.y -= heightAdjust/2; videoDest.width += widthAdjust; videoDest.height += heightAdjust; videoDest.x += transX; videoDest.y += transY; if (videoHShiftFreq != 0) { float maxHShift = (myBounds.width - videoDest.width)/2; long timeDiff = Sage.eventTime(); timeDiff %= videoHShiftFreq; if (timeDiff < videoHShiftFreq/2) { if (timeDiff < videoHShiftFreq/4) videoDest.x -= maxHShift*timeDiff*4/videoHShiftFreq; else videoDest.x -= maxHShift - (maxHShift*(timeDiff - videoHShiftFreq/4)*4/videoHShiftFreq); } else { timeDiff -= videoHShiftFreq/2; if (timeDiff < videoHShiftFreq/4) videoDest.x += maxHShift*timeDiff*4/videoHShiftFreq; else videoDest.x += maxHShift - (maxHShift*(timeDiff - videoHShiftFreq/4)*4/videoHShiftFreq); } } Sage.clipSrcDestRects(myBounds, videoSrc, videoDest); /*EMBEDDED_SWITCH*/ java.awt.Rectangle srcVideoRect = new java.awt.Rectangle(); java.awt.Rectangle usedVideoRect = new java.awt.Rectangle(); srcVideoRect.setRect(videoSrc.x, videoSrc.y, videoSrc.width, videoSrc.height); usedVideoRect.setRect(videoDest.x, videoDest.y, videoDest.width, videoDest.height); resizeVideo(srcVideoRect, usedVideoRect); /*/ resizeVideo(videoSrc, videoDest); /**/ /* // NOTE: If this is not run async on the UI thread it can deadlock because validate goes down into // the UI system and comes back up through the layout method above which locks things // that can conflict with the final renderer java.awt.EventQueue.invokeLater(new Runnable() { public void run() { videoComp.invalidate(); validate(); } }); */ } public java.awt.Color getVideoBGColor() { return videoBGColor; } public void setVideoBGColor(java.awt.Color x) { uiMgr.put(prefs + VIDEO_BG_COLOR, Integer.toString(x.getRed()) + "," + Integer.toString(x.getGreen()) + "," + Integer.toString(x.getBlue())); videoBGColor = x; } public long getVideoHShiftFreq() { return videoHShiftFreq; } public void setVideoHShiftFreq(long x) { if (x == videoHShiftFreq) return; uiMgr.putLong(prefs + VIDEO_HORIZONTAL_SHIFT_FREQ, (videoHShiftFreq = x)); if (videoHShiftTimer != null) { videoHShiftTimer.cancel(); videoHShiftTimer = null; } if (x != 0) { createVideoHShiftTimer(); } } protected abstract void createVideoHShiftTimer(); public abstract void inactiveFile(String inactiveFilename); public abstract boolean hasFile(); protected abstract void resizeVideo(final java.awt.Rectangle videoSrcRect, final java.awt.Rectangle videoDestRect); boolean setHideCursor(boolean x) { boolean rv = (x != hideCursor); hideCursor = x; return rv; } java.awt.Canvas getVideoComp() { return videoComp; } protected MMC mmc; protected UIManager uiMgr; protected String prefs; protected float volumeStep; protected final Object queueLock = new Object(); protected VideoCanvas videoComp; private int videoTranslateX; private int videoTranslateY; private float videoZoomX; private float videoZoomY; protected int aspectRatioMode; private float displayAspectRatio; protected boolean muteOnAlt; protected long videoHShiftFreq; protected java.awt.Color videoBGColor; protected java.util.TimerTask videoHShiftTimer; protected boolean hideCursor; protected java.awt.geom.Rectangle2D.Float videoBounds; protected float forcedPAR; static class VideoCanvas extends java.awt.Canvas { public void update(java.awt.Graphics g) { } public void paint(java.awt.Graphics g) { } } }
/** * 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.util; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.apache.camel.Channel; import org.apache.camel.Navigate; import org.apache.camel.Processor; import org.apache.camel.Service; import org.apache.camel.ShutdownableService; import org.apache.camel.StatefulService; import org.apache.camel.Suspendable; import org.apache.camel.SuspendableService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A collection of helper methods for working with {@link Service} objects. * * @version */ public final class ServiceHelper { private static final Logger LOG = LoggerFactory.getLogger(ServiceHelper.class); /** * Utility classes should not have a public constructor. */ private ServiceHelper() { } /** * Starts the given {@code value} if it's a {@link Service} or a collection of it. * <p/> * Calling this method has no effect if {@code value} is {@code null}. * * @see #startService(Service) * @see #startServices(Collection) */ public static void startService(Object value) throws Exception { if (value instanceof Service) { startService((Service)value); } else if (value instanceof Collection) { startServices((Collection<?>)value); } } /** * Starts the given {@code service}. * <p/> * Calling this method has no effect if {@code service} is {@code null}. * * @see Service#start() */ public static void startService(Service service) throws Exception { if (service != null) { service.start(); } } /** * Starts each element of the given {@code services} if {@code services} itself is * not {@code null}, otherwise this method would return immediately. * * @see #startServices(Collection) */ public static void startServices(Object... services) throws Exception { if (services == null) { return; } List<Object> list = Arrays.asList(services); startServices(list); } /** * Starts each element of the given {@code services} if {@code services} itself is * not {@code null}, otherwise this method would return immediately. * * @see #startService(Object) */ public static void startServices(Collection<?> services) throws Exception { if (services == null) { return; } for (Object value : services) { startService(value); } } /** * Stops each element of the given {@code services} if {@code services} itself is * not {@code null}, otherwise this method would return immediately. * <p/> * If there's any exception being thrown while stopping the elements one after the * other this method would rethrow the <b>first</b> such exception being thrown. * * @see #stopServices(Collection) */ public static void stopServices(Object... services) throws Exception { if (services == null) { return; } List<Object> list = Arrays.asList(services); stopServices(list); } /** * Stops the given {@code value}, rethrowing the first exception caught. * <p/> * Calling this method has no effect if {@code value} is {@code null}. * * @see Service#stop() * @see #stopServices(Collection) */ public static void stopService(Object value) throws Exception { if (isStopped(value)) { // only stop service if not already stopped LOG.trace("Service already stopped: {}", value); return; } if (value instanceof Service) { Service service = (Service)value; LOG.trace("Stopping service {}", value); service.stop(); } else if (value instanceof Collection) { stopServices((Collection<?>)value); } } /** * Stops each element of the given {@code services} if {@code services} itself is * not {@code null}, otherwise this method would return immediately. * <p/> * If there's any exception being thrown while stopping the elements one after the * other this method would rethrow the <b>first</b> such exception being thrown. * * @see #stopService(Object) */ public static void stopServices(Collection<?> services) throws Exception { if (services == null) { return; } Exception firstException = null; for (Object value : services) { try { stopService(value); } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Caught exception stopping service: " + value, e); } if (firstException == null) { firstException = e; } } } if (firstException != null) { throw firstException; } } /** * Stops and shutdowns each element of the given {@code services} if {@code services} itself is * not {@code null}, otherwise this method would return immediately. * <p/> * If there's any exception being thrown while stopping/shutting down the elements one after * the other this method would rethrow the <b>first</b> such exception being thrown. * * @see #stopAndShutdownServices(Collection) */ public static void stopAndShutdownServices(Object... services) throws Exception { if (services == null) { return; } List<Object> list = Arrays.asList(services); stopAndShutdownServices(list); } /** * Stops and shutdowns the given {@code service}, rethrowing the first exception caught. * <p/> * Calling this method has no effect if {@code value} is {@code null}. * * @see #stopService(Object) * @see ShutdownableService#shutdown() */ public static void stopAndShutdownService(Object value) throws Exception { stopService(value); // then try to shutdown if (value instanceof ShutdownableService) { ShutdownableService service = (ShutdownableService)value; LOG.trace("Shutting down service {}", value); service.shutdown(); } } /** * Stops and shutdowns each element of the given {@code services} if {@code services} * itself is not {@code null}, otherwise this method would return immediately. * <p/> * If there's any exception being thrown while stopping/shutting down the elements one after * the other this method would rethrow the <b>first</b> such exception being thrown. * * @see #stopService(Object) * @see ShutdownableService#shutdown() */ public static void stopAndShutdownServices(Collection<?> services) throws Exception { if (services == null) { return; } Exception firstException = null; for (Object value : services) { try { // must stop it first stopService(value); // then try to shutdown if (value instanceof ShutdownableService) { ShutdownableService service = (ShutdownableService)value; LOG.trace("Shutting down service: {}", service); service.shutdown(); } } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Caught exception shutting down service: " + value, e); } if (firstException == null) { firstException = e; } } } if (firstException != null) { throw firstException; } } /** * Resumes each element of the given {@code services} if {@code services} itself is * not {@code null}, otherwise this method would return immediately. * <p/> * If there's any exception being thrown while resuming the elements one after the * other this method would rethrow the <b>first</b> such exception being thrown. * * @see #resumeService(Object) */ public static void resumeServices(Collection<?> services) throws Exception { if (services == null) { return; } Exception firstException = null; for (Object value : services) { if (value instanceof Service) { Service service = (Service)value; try { resumeService(service); } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Caught exception resuming service: " + service, e); } if (firstException == null) { firstException = e; } } } } if (firstException != null) { throw firstException; } } /** * Resumes the given {@code service}. * <p/> * If {@code service} is both {@link org.apache.camel.Suspendable} and {@link org.apache.camel.SuspendableService} then * its {@link org.apache.camel.SuspendableService#resume()} is called but * <b>only</b> if {@code service} is already {@link #isSuspended(Object) * suspended}. * <p/> * If {@code service} is <b>not</b> a * {@link org.apache.camel.Suspendable} and {@link org.apache.camel.SuspendableService} then its * {@link org.apache.camel.Service#start()} is called. * <p/> * Calling this method has no effect if {@code service} is {@code null}. * * @param service the service * @return <tt>true</tt> if either <tt>resume</tt> method or * {@link #startService(Service)} was called, <tt>false</tt> * otherwise. * @throws Exception is thrown if error occurred * @see #startService(Service) */ public static boolean resumeService(Object service) throws Exception { if (service instanceof Suspendable && service instanceof SuspendableService) { SuspendableService ss = (SuspendableService) service; if (ss.isSuspended()) { LOG.debug("Resuming service {}", service); ss.resume(); return true; } else { return false; } } else { startService(service); return true; } } /** * Suspends each element of the given {@code services} if {@code services} itself is * not {@code null}, otherwise this method would return immediately. * <p/> * If there's any exception being thrown while suspending the elements one after the * other this method would rethrow the <b>first</b> such exception being thrown. * * @see #suspendService(Object) */ public static void suspendServices(Collection<?> services) throws Exception { if (services == null) { return; } Exception firstException = null; for (Object value : services) { if (value instanceof Service) { Service service = (Service)value; try { suspendService(service); } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Caught exception suspending service: " + service, e); } if (firstException == null) { firstException = e; } } } } if (firstException != null) { throw firstException; } } /** * Suspends the given {@code service}. * <p/> * If {@code service} is both {@link org.apache.camel.Suspendable} and {@link org.apache.camel.SuspendableService} then * its {@link org.apache.camel.SuspendableService#suspend()} is called but * <b>only</b> if {@code service} is <b>not</b> already * {@link #isSuspended(Object) suspended}. * <p/> * If {@code service} is <b>not</b> a * {@link org.apache.camel.Suspendable} and {@link org.apache.camel.SuspendableService} then its * {@link org.apache.camel.Service#stop()} is called. * <p/> * Calling this method has no effect if {@code service} is {@code null}. * * @param service the service * @return <tt>true</tt> if either the <tt>suspend</tt> method or * {@link #stopService(Object)} was called, <tt>false</tt> * otherwise. * @throws Exception is thrown if error occurred * @see #stopService(Object) */ public static boolean suspendService(Object service) throws Exception { if (service instanceof Suspendable && service instanceof SuspendableService) { SuspendableService ss = (SuspendableService) service; if (!ss.isSuspended()) { LOG.trace("Suspending service {}", service); ss.suspend(); return true; } else { return false; } } else { stopService(service); return true; } } /** * Is the given service stopping or already stopped? * * @return <tt>true</tt> if stopping or already stopped, <tt>false</tt> otherwise * @see StatefulService#isStopping() * @see StatefulService#isStopped() */ public static boolean isStopped(Object value) { if (value instanceof StatefulService) { StatefulService service = (StatefulService) value; if (service.isStopping() || service.isStopped()) { return true; } } return false; } /** * Is the given service starting or already started? * * @return <tt>true</tt> if starting or already started, <tt>false</tt> otherwise * @see StatefulService#isStarting() * @see StatefulService#isStarted() */ public static boolean isStarted(Object value) { if (value instanceof StatefulService) { StatefulService service = (StatefulService) value; if (service.isStarting() || service.isStarted()) { return true; } } return false; } /** * Is the given service suspending or already suspended? * * @return <tt>true</tt> if suspending or already suspended, <tt>false</tt> otherwise * @see StatefulService#isSuspending() * @see StatefulService#isSuspended() */ public static boolean isSuspended(Object value) { if (value instanceof StatefulService) { StatefulService service = (StatefulService) value; if (service.isSuspending() || service.isSuspended()) { return true; } } return false; } /** * Gathers all child services by navigating the service to recursively gather all child services. * <p/> * The returned set does <b>not</b> include the children being error handler. * * @param service the service * @return the services, including the parent service, and all its children */ public static Set<Service> getChildServices(Service service) { return getChildServices(service, false); } /** * Gathers all child services by navigating the service to recursively gather all child services. * * @param service the service * @param includeErrorHandler whether to include error handlers * @return the services, including the parent service, and all its children */ public static Set<Service> getChildServices(Service service, boolean includeErrorHandler) { Set<Service> answer = new LinkedHashSet<Service>(); doGetChildServices(answer, service, includeErrorHandler); return answer; } private static void doGetChildServices(Set<Service> services, Service service, boolean includeErrorHandler) { services.add(service); if (service instanceof Navigate) { Navigate<?> nav = (Navigate<?>) service; if (nav.hasNext()) { List<?> children = nav.next(); for (Object child : children) { if (child instanceof Channel) { if (includeErrorHandler) { // special for error handler as they are tied to the Channel Processor errorHandler = ((Channel) child).getErrorHandler(); if (errorHandler != null && errorHandler instanceof Service) { services.add((Service) errorHandler); } } Processor next = ((Channel) child).getNextProcessor(); if (next != null && next instanceof Service) { services.add((Service) next); } } if (child instanceof Service) { doGetChildServices(services, (Service) child, includeErrorHandler); } } } } } }
package pmm.pbm.data.base.entity; import java.util.ArrayList; import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import pmm.pbm.data.base.support.Example; @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class GenreExample extends Example { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table pbm_genre * * @mbg.generated */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table pbm_genre * * @mbg.generated */ public GenreExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table pbm_genre * * @mbg.generated */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table pbm_genre * * @mbg.generated */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table pbm_genre * * @mbg.generated */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table pbm_genre * * @mbg.generated */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table pbm_genre * * @mbg.generated */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table pbm_genre * * @mbg.generated */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table pbm_genre * * @mbg.generated */ public Criteria getCriteria() { if (oredCriteria.size() == 0) {createCriteria();} return oredCriteria.get(0); } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table pbm_genre * * @mbg.generated */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andIntroIsNull() { addCriterion("intro is null"); return (Criteria) this; } public Criteria andIntroIsNotNull() { addCriterion("intro is not null"); return (Criteria) this; } public Criteria andIntroEqualTo(String value) { addCriterion("intro =", value, "intro"); return (Criteria) this; } public Criteria andIntroNotEqualTo(String value) { addCriterion("intro <>", value, "intro"); return (Criteria) this; } public Criteria andIntroGreaterThan(String value) { addCriterion("intro >", value, "intro"); return (Criteria) this; } public Criteria andIntroGreaterThanOrEqualTo(String value) { addCriterion("intro >=", value, "intro"); return (Criteria) this; } public Criteria andIntroLessThan(String value) { addCriterion("intro <", value, "intro"); return (Criteria) this; } public Criteria andIntroLessThanOrEqualTo(String value) { addCriterion("intro <=", value, "intro"); return (Criteria) this; } public Criteria andIntroLike(String value) { addCriterion("intro like", value, "intro"); return (Criteria) this; } public Criteria andIntroNotLike(String value) { addCriterion("intro not like", value, "intro"); return (Criteria) this; } public Criteria andIntroIn(List<String> values) { addCriterion("intro in", values, "intro"); return (Criteria) this; } public Criteria andIntroNotIn(List<String> values) { addCriterion("intro not in", values, "intro"); return (Criteria) this; } public Criteria andIntroBetween(String value1, String value2) { addCriterion("intro between", value1, value2, "intro"); return (Criteria) this; } public Criteria andIntroNotBetween(String value1, String value2) { addCriterion("intro not between", value1, value2, "intro"); return (Criteria) this; } public Criteria andRankIsNull() { addCriterion("rank is null"); return (Criteria) this; } public Criteria andRankIsNotNull() { addCriterion("rank is not null"); return (Criteria) this; } public Criteria andRankEqualTo(Integer value) { addCriterion("rank =", value, "rank"); return (Criteria) this; } public Criteria andRankNotEqualTo(Integer value) { addCriterion("rank <>", value, "rank"); return (Criteria) this; } public Criteria andRankGreaterThan(Integer value) { addCriterion("rank >", value, "rank"); return (Criteria) this; } public Criteria andRankGreaterThanOrEqualTo(Integer value) { addCriterion("rank >=", value, "rank"); return (Criteria) this; } public Criteria andRankLessThan(Integer value) { addCriterion("rank <", value, "rank"); return (Criteria) this; } public Criteria andRankLessThanOrEqualTo(Integer value) { addCriterion("rank <=", value, "rank"); return (Criteria) this; } public Criteria andRankIn(List<Integer> values) { addCriterion("rank in", values, "rank"); return (Criteria) this; } public Criteria andRankNotIn(List<Integer> values) { addCriterion("rank not in", values, "rank"); return (Criteria) this; } public Criteria andRankBetween(Integer value1, Integer value2) { addCriterion("rank between", value1, value2, "rank"); return (Criteria) this; } public Criteria andRankNotBetween(Integer value1, Integer value2) { addCriterion("rank not between", value1, value2, "rank"); return (Criteria) this; } public Criteria andEnableIsNull() { addCriterion("enable is null"); return (Criteria) this; } public Criteria andEnableIsNotNull() { addCriterion("enable is not null"); return (Criteria) this; } public Criteria andEnableEqualTo(Boolean value) { addCriterion("enable =", value, "enable"); return (Criteria) this; } public Criteria andEnableNotEqualTo(Boolean value) { addCriterion("enable <>", value, "enable"); return (Criteria) this; } public Criteria andEnableGreaterThan(Boolean value) { addCriterion("enable >", value, "enable"); return (Criteria) this; } public Criteria andEnableGreaterThanOrEqualTo(Boolean value) { addCriterion("enable >=", value, "enable"); return (Criteria) this; } public Criteria andEnableLessThan(Boolean value) { addCriterion("enable <", value, "enable"); return (Criteria) this; } public Criteria andEnableLessThanOrEqualTo(Boolean value) { addCriterion("enable <=", value, "enable"); return (Criteria) this; } public Criteria andEnableIn(List<Boolean> values) { addCriterion("enable in", values, "enable"); return (Criteria) this; } public Criteria andEnableNotIn(List<Boolean> values) { addCriterion("enable not in", values, "enable"); return (Criteria) this; } public Criteria andEnableBetween(Boolean value1, Boolean value2) { addCriterion("enable between", value1, value2, "enable"); return (Criteria) this; } public Criteria andEnableNotBetween(Boolean value1, Boolean value2) { addCriterion("enable not between", value1, value2, "enable"); return (Criteria) this; } public Criteria andDeletedIsNull() { addCriterion("deleted is null"); return (Criteria) this; } public Criteria andDeletedIsNotNull() { addCriterion("deleted is not null"); return (Criteria) this; } public Criteria andDeletedEqualTo(Boolean value) { addCriterion("deleted =", value, "deleted"); return (Criteria) this; } public Criteria andDeletedNotEqualTo(Boolean value) { addCriterion("deleted <>", value, "deleted"); return (Criteria) this; } public Criteria andDeletedGreaterThan(Boolean value) { addCriterion("deleted >", value, "deleted"); return (Criteria) this; } public Criteria andDeletedGreaterThanOrEqualTo(Boolean value) { addCriterion("deleted >=", value, "deleted"); return (Criteria) this; } public Criteria andDeletedLessThan(Boolean value) { addCriterion("deleted <", value, "deleted"); return (Criteria) this; } public Criteria andDeletedLessThanOrEqualTo(Boolean value) { addCriterion("deleted <=", value, "deleted"); return (Criteria) this; } public Criteria andDeletedIn(List<Boolean> values) { addCriterion("deleted in", values, "deleted"); return (Criteria) this; } public Criteria andDeletedNotIn(List<Boolean> values) { addCriterion("deleted not in", values, "deleted"); return (Criteria) this; } public Criteria andDeletedBetween(Boolean value1, Boolean value2) { addCriterion("deleted between", value1, value2, "deleted"); return (Criteria) this; } public Criteria andDeletedNotBetween(Boolean value1, Boolean value2) { addCriterion("deleted not between", value1, value2, "deleted"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table pbm_genre * * @mbg.generated do_not_delete_during_merge */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } }
/*L * Copyright SAIC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cabio/LICENSE.txt for details. */ package gov.nih.nci.cabio; import gov.nih.nci.cabio.domain.Chromosome; import gov.nih.nci.cabio.domain.Gene; import gov.nih.nci.cabio.domain.GeneOntology; import gov.nih.nci.cabio.domain.GeneOntologyRelationship; import gov.nih.nci.cabio.domain.Taxon; import gov.nih.nci.search.SearchQuery; import gov.nih.nci.search.SearchResult; import javax.xml.namespace.QName; import javax.xml.rpc.ParameterMode; import junit.framework.TestCase; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Tests for the caBIO web services. This suite contains unit tests for each * method of the web services API. It also tests a few nested queries. * * @author <a href="mailto:rokickik@mail.nih.gov">Konrad Rokicki</a> */ public class WSTest extends TestCase { private static String WS_URL; private Call call; static { // attempt to get the right URL from the Java client configuration ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config-client.xml"); WS_URL = (String) ctx.getBean("RemoteServerURL") + "/services/caBIOService"; System.out.println("WS URL: "+WS_URL); } private void register(String urn, Class clazz) { QName qn = new QName(urn, clazz.getSimpleName()); call.registerTypeMapping(clazz, qn, new org.apache.axis.encoding.ser.BeanSerializerFactory(clazz, qn), new org.apache.axis.encoding.ser.BeanDeserializerFactory(clazz, qn)); } /** * Setup the Axis Call object and initialize the WS type mappings * used in the test cases. */ public void setUp() throws Exception { Service service = new Service(); this.call = (Call)service.createCall(); call.setTargetEndpointAddress(new java.net.URL(WS_URL)); register("urn:domain.cabio.nci.nih.gov", Gene.class); register("urn:domain.cabio.nci.nih.gov", Chromosome.class); register("urn:domain.cabio.nci.nih.gov", Taxon.class); register("urn:domain.cabio.nci.nih.gov", GeneOntology.class); register("urn:domain.cabio.nci.nih.gov", GeneOntologyRelationship.class); register("urn:search.nci.nih.gov", SearchQuery.class); register("urn:search.nci.nih.gov", SearchResult.class); } /** * Ensure getVersion returns the current version. */ public void testGetVersion() throws Exception { call.clearOperation(); call.setOperationName(new QName("caBIOService", "getVersion")); call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING); String version = (String)call.invoke(new Object[0]); assertNotNull(version); assertEquals("4.2",version); } /** * Ensure getRecordsPerQuery returns a positive number. */ public void testTotalNumberOfRecords() throws Exception { call.clearOperation(); call.setOperationName(new QName("caBIOService", "getRecordsPerQuery")); call.setReturnType(org.apache.axis.encoding.XMLType.XSD_INT); Integer count = (Integer)call.invoke(new Object[0]); assertNotNull(count); assertTrue(count>0); } /** * Ensure getTotalNumberOfRecords for the Gene is a positive number. */ public void testGetNumberOfGenes() throws Exception { call.clearOperation(); call.setOperationName(new QName("caBIOService", "getTotalNumberOfRecords")); call.addParameter("arg1",org.apache.axis.encoding.XMLType.XSD_STRING,ParameterMode.IN); call.addParameter("arg2", org.apache.axis.encoding.XMLType.XSD_ANYTYPE, ParameterMode.IN); call.setReturnType(org.apache.axis.encoding.XMLType.XSD_INT); Integer count = (Integer)call.invoke(new Object[] { "gov.nih.nci.cabio.domain.Gene", new Gene() }); assertNotNull(count); assertTrue((count>0)); } /** * Tests queryObject method. Query for Genes, where Gene symbol starts with * "br*", and taxon is Human. Ensure result list is not empty and all * result genes have ids and gene symbols. */ public void testQueryGeneTaxon() throws Exception { call.clearOperation(); call.setOperationName(new QName("caBIOService", "queryObject")); call.addParameter("arg1",org.apache.axis.encoding.XMLType.XSD_STRING,ParameterMode.IN); call.addParameter("arg2", org.apache.axis.encoding.XMLType.XSD_ANYTYPE, ParameterMode.IN); call.setReturnType(org.apache.axis.encoding.XMLType.SOAP_ARRAY); Gene gene = new Gene(); gene.setSymbol("br*"); Taxon tax = new Taxon(); tax.setId(new Long(5)); gene.setTaxon(tax); Object[] resultList = (Object[])call.invoke( new Object[] { "gov.nih.nci.cabio.domain.Gene", gene }); assertNotNull(resultList); assertTrue(resultList.length > 0); for(int i=0; i<resultList.length; i++) { Gene g = (Gene)resultList[i]; assertNotNull(g); assertNotNull(g.getId()); assertNotNull(g.getSymbol()); } } /** * Tests queryObject method. Query for parent GeneOntologyRelationship by * setting childGeneOntology. Ensure result list is not empty and that * all result GeneOntologyRelationship objects have ids and relationshipType. */ public void testQueryGeneOntology() throws Exception { call.clearOperation(); call.setOperationName(new QName("caBIOService", "queryObject")); call.addParameter("arg1",org.apache.axis.encoding.XMLType.XSD_STRING,ParameterMode.IN); call.addParameter("arg2", org.apache.axis.encoding.XMLType.XSD_ANYTYPE, ParameterMode.IN); call.setReturnType(org.apache.axis.encoding.XMLType.SOAP_ARRAY); GeneOntology geneOntology = new GeneOntology(); geneOntology.setId(new Long(5125)); GeneOntologyRelationship geneor = new GeneOntologyRelationship(); geneor.setChildGeneOntology(geneOntology); Object[] resultList = (Object[])call.invoke( new Object[] { "gov.nih.nci.cabio.domain.GeneOntologyRelationship", geneor }); assertNotNull(resultList); assertTrue(resultList.length > 0); for(int i=0; i<resultList.length; i++){ GeneOntologyRelationship gor = (GeneOntologyRelationship)resultList[i]; assertNotNull(gor); assertNotNull(gor.getId()); assertNotNull(gor.getRelationshipType()); } } /** * Test queryObject method. Query GeneOntology by Genes with symbol "brca". * Using the result Gene Ontologies get the child GeneOntologyRelationship. * Ensure all result GeneOntologyRelationship objects have ids and relationshipType. */ public void testGetAssociation() throws Exception { call.clearOperation(); call.setOperationName(new QName("caBIOService", "queryObject")); call.addParameter("arg1",org.apache.axis.encoding.XMLType.XSD_STRING,ParameterMode.IN); call.addParameter("arg2", org.apache.axis.encoding.XMLType.XSD_ANYTYPE, ParameterMode.IN); call.setReturnType(org.apache.axis.encoding.XMLType.SOAP_ARRAY); Gene g = new Gene(); g.setSymbol("nat*"); Object[] resultList = (Object[])call.invoke( new Object[] { "gov.nih.nci.cabio.domain.GeneOntology", g }); assertNotNull(resultList); assertTrue(resultList.length > 0); call.clearOperation(); call.setOperationName(new QName("caBIOService", "getAssociation")); call.addParameter("arg1", org.apache.axis.encoding.XMLType.XSD_ANYTYPE, ParameterMode.IN); call.addParameter("arg2",org.apache.axis.encoding.XMLType.XSD_STRING,ParameterMode.IN); call.addParameter("arg3",org.apache.axis.encoding.XMLType.XSD_INTEGER,ParameterMode.IN); call.setReturnType(org.apache.axis.encoding.XMLType.SOAP_ARRAY); for(int i=0; i<resultList.length; i++) { GeneOntology geneOnt = new GeneOntology(); geneOnt = (GeneOntology)resultList[i]; Object[] childGOCollection = (Object[])call.invoke(new Object[] { geneOnt, "childGeneOntologyRelationshipCollection", new Integer(0) }); for(int o=0; o<childGOCollection.length; o++){ GeneOntologyRelationship childGOR = (GeneOntologyRelationship)childGOCollection[o]; assertNotNull(childGOR); assertNotNull(childGOR.getId()); assertNotNull(childGOR.getRelationshipType()); } } } /** * Test exists method for Grid Ids by querying with BRCA1's bigid. */ public void testGridIdExists() throws Exception { String bigId = "hdl://2500.1.PMEUQUCCL5/DXZ7ZIOFOE"; call.clearOperation(); call.setOperationName(new QName("caBIOService", "exist")); call.addParameter("arg1",org.apache.axis.encoding.XMLType.XSD_STRING,ParameterMode.IN); call.setReturnType(org.apache.axis.encoding.XMLType.XSD_BOOLEAN); boolean found = ((Boolean)call.invoke(new Object[] {bigId})).booleanValue(); assertTrue(found); } /** * Test getDataObject method for Grid Ids by querying for the Gene BRCA1 * with its bigId. */ public void testGetDataObject() throws Exception { String bigId = "hdl://2500.1.PMEUQUCCL5/DXZ7ZIOFOE"; call.clearOperation(); call.setOperationName(new QName("caBIOService", "getDataObject")); call.addParameter("arg1",org.apache.axis.encoding.XMLType.XSD_STRING,ParameterMode.IN); call.setReturnType(org.apache.axis.encoding.XMLType.XSD_ANYTYPE); Gene dataObject = (Gene)call.invoke(new Object[] {bigId}); assertNotNull(dataObject); assertEquals(dataObject.getBigid(), bigId); } /** * Ensure Freestyle search with a SearchQuery works. */ public void testFreestyleSearch() throws Exception { SearchQuery query = new SearchQuery(); query.setKeyword("Tirapazamine"); call.clearOperation(); call.setOperationName(new QName("caBIOService", "search")); call.addParameter("arg1",org.apache.axis.encoding.XMLType.XSD_ANYTYPE,ParameterMode.IN); call.setReturnType(org.apache.axis.encoding.XMLType.SOAP_ARRAY); Object[] resultList = (Object[])call.invoke(new Object[] {query}); assertNotNull(resultList); assertTrue(resultList.length>0); boolean agentFound = false; for(Object o : resultList) { SearchResult sr = (SearchResult)o; assertNotNull(sr); if (sr.getClassName().endsWith(".Agent")) { agentFound = true; } } assertTrue("No agent found in results",agentFound); } }
/** * Copyright (c) 2010 Yahoo! 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. See accompanying LICENSE file. */ package org.apache.oozie.workflow.lite; import org.apache.oozie.service.Services; import org.apache.oozie.workflow.WorkflowException; import org.apache.oozie.workflow.WorkflowInstance; import org.apache.oozie.test.XTestCase; import org.apache.oozie.util.WritableUtils; import org.apache.oozie.util.XConfiguration; import org.apache.oozie.ErrorCode; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class TestLiteWorkflowLib extends XTestCase { static Map<String, Integer> enters = new HashMap<String, Integer>(); static Map<String, Integer> exits = new HashMap<String, Integer>(); static Map<String, Integer> kills = new HashMap<String, Integer>(); static Map<String, Integer> fails = new HashMap<String, Integer>(); static int enterCounter = 0; static int exitCounter = 0; static int killCounter = 0; static int failCounter = 0; private Services services; public static abstract class BaseNodeHandler extends NodeHandler { private boolean synch; protected BaseNodeHandler(Boolean synch) { this.synch = synch; } @Override public boolean enter(Context context) { enters.put(context.getNodeDef().getName(), enterCounter++); return synch; } @Override public String exit(Context context) { exits.put(context.getNodeDef().getName(), exitCounter++); return context.getNodeDef().getTransitions().get(0); } @Override public void kill(Context context) { kills.put(context.getNodeDef().getName(), killCounter++); } @Override public void fail(Context context) { fails.put(context.getNodeDef().getName(), failCounter++); } } public static class AsynchNodeHandler extends BaseNodeHandler { public AsynchNodeHandler() { super(false); } } public static class SynchNodeHandler extends BaseNodeHandler { public SynchNodeHandler() { super(true); } } public static class TestActionNodeHandler extends ActionNodeHandler { @Override public void start(Context context) { } @Override public void end(Context context) { } } public static class TestDecisionNodeHandler extends DecisionNodeHandler { @Override public void start(Context context) { enters.put(context.getNodeDef().getName(), enterCounter++); } @Override public void end(Context context) { exits.put(context.getNodeDef().getName(), exitCounter++); } } public static class TestRootContextHandler extends SynchNodeHandler { @Override public boolean enter(Context context) { assertNotNull(context.getNodeDef()); assertNotNull(context.getSignalValue()); assertNotNull(context.getProcessInstance()); assertEquals("/", context.getExecutionPath()); assertEquals(null, context.getParentExecutionPath("/")); assertEquals("A", context.getVar("a")); assertEquals("AA", context.getTransientVar("ta")); context.setVar("b", "B"); context.setTransientVar("tb", "BB"); return super.enter(context); } @Override public String exit(Context context) { assertEquals("A", context.getVar("a")); assertEquals("AA", context.getTransientVar("ta")); context.setVar("b", "B"); context.setTransientVar("tb", "BB"); return super.exit(context); } } public static class TestForkedContextHandler extends SynchNodeHandler { @Override public boolean enter(Context context) { assertNotNull(context.getNodeDef()); assertNotNull(context.getSignalValue()); assertNotNull(context.getProcessInstance()); assertEquals("/a/", context.getExecutionPath()); assertEquals("/", context.getParentExecutionPath("/a/")); return super.enter(context); } } @Override protected void setUp() throws Exception { super.setUp(); services = new Services(); services.init(); enters.clear(); exits.clear(); kills.clear(); fails.clear(); enterCounter = 0; exitCounter = 0; killCounter = 0; failCounter = 0; } @Override protected void tearDown() throws Exception { services.destroy(); super.tearDown(); } public void testEmptyWorkflow() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("end")) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); assertEquals(WorkflowInstance.Status.PREP, job.getStatus()); job.start(); assertEquals(WorkflowInstance.Status.SUCCEEDED, job.getStatus()); } public void testKillWorkflow() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("kill")) .addNode(new KillNodeDef("kill", "killed")) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); assertEquals(WorkflowInstance.Status.PREP, job.getStatus()); job.start(); assertEquals(WorkflowInstance.Status.KILLED, job.getStatus()); } public void testWorkflowStates() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("one")) .addNode(new NodeDef("one", null, AsynchNodeHandler.class, Arrays.asList(new String[]{"end"}))) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); assertEquals(WorkflowInstance.Status.PREP, job.getStatus()); job.kill(); assertEquals(WorkflowInstance.Status.KILLED, job.getStatus()); job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); job.fail("one"); assertEquals(WorkflowInstance.Status.FAILED, job.getStatus()); job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); try { job.suspend(); fail(); } catch (WorkflowException ex) { //nop } try { job.resume(); fail(); } catch (WorkflowException ex) { //nop } job.start(); assertEquals(WorkflowInstance.Status.RUNNING, job.getStatus()); try { job.resume(); fail(); } catch (WorkflowException ex) { //nop } try { job.start(); fail(); } catch (WorkflowException ex) { //nop } job.suspend(); assertEquals(WorkflowInstance.Status.SUSPENDED, job.getStatus()); try { job.suspend(); fail(); } catch (WorkflowException ex) { //nop } try { job.start(); fail(); } catch (WorkflowException ex) { //nop } job.resume(); assertEquals(WorkflowInstance.Status.RUNNING, job.getStatus()); try { job.resume(); fail(); } catch (WorkflowException ex) { //nop } try { job.start(); fail(); } catch (WorkflowException ex) { //nop } job.kill(); assertEquals(WorkflowInstance.Status.KILLED, job.getStatus()); try { job.kill(); fail(); } catch (WorkflowException ex) { //nop } try { job.suspend(); fail(); } catch (WorkflowException ex) { //nop } try { job.resume(); fail(); } catch (WorkflowException ex) { //nop } try { job.start(); fail(); } catch (WorkflowException ex) { //nop } } public void testSynchSimple() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("one")) .addNode(new NodeDef("one", null, SynchNodeHandler.class, Arrays.asList(new String[]{"end"}))) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); job.start(); assertEquals(WorkflowInstance.Status.SUCCEEDED, job.getStatus()); assertEquals(1, enters.size()); assertEquals(1, exits.size()); assertEquals(0, kills.size()); assertEquals(0, fails.size()); } public void testNodeContext() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("one")) .addNode(new NodeDef("one", null, TestRootContextHandler.class, Arrays.asList(new String[]{"end"}))) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); job.setVar("a", "A"); job.setTransientVar("ta", "AA"); job.start(); assertEquals(WorkflowInstance.Status.SUCCEEDED, job.getStatus()); assertEquals("B", job.getVar("b")); assertEquals("BB", job.getTransientVar("tb")); assertEquals(1, enters.size()); assertEquals(1, exits.size()); assertEquals(0, kills.size()); assertEquals(0, fails.size()); } public void testSynchDouble() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("one")) .addNode(new NodeDef("one", null, SynchNodeHandler.class, Arrays.asList(new String[]{"two"}))) .addNode(new NodeDef("two", null, SynchNodeHandler.class, Arrays.asList(new String[]{"end"}))) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); job.start(); assertEquals(WorkflowInstance.Status.SUCCEEDED, job.getStatus()); assertEquals(2, enters.size()); assertEquals(2, exits.size()); assertEquals(0, kills.size()); assertEquals(0, fails.size()); } public void testAsynchSimple() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("one")) .addNode(new NodeDef("one", null, AsynchNodeHandler.class, Arrays.asList(new String[]{"end"}))) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); job.start(); assertEquals(WorkflowInstance.Status.RUNNING, job.getStatus()); job.signal("/", ""); assertEquals(WorkflowInstance.Status.SUCCEEDED, job.getStatus()); assertEquals(1, enters.size()); assertEquals(1, exits.size()); assertEquals(0, kills.size()); assertEquals(0, fails.size()); } public void testInvalidExecutionPath() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("one")) .addNode(new NodeDef("one", null, AsynchNodeHandler.class, Arrays.asList(new String[]{"end"}))) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); job.start(); assertEquals(WorkflowInstance.Status.RUNNING, job.getStatus()); job.signal("/a/", ""); assertEquals(WorkflowInstance.Status.FAILED, job.getStatus()); } public void testSimpleFork() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("one")) .addNode(new NodeDef("one", null, SynchNodeHandler.class, Arrays.asList(new String[]{"f"}))) .addNode(new ForkNodeDef("f", Arrays.asList(new String[]{"two", "three"}))) .addNode(new NodeDef("two", null, SynchNodeHandler.class, Arrays.asList(new String[]{"j"}))) .addNode(new NodeDef("three", null, SynchNodeHandler.class, Arrays.asList(new String[]{"j"}))) .addNode(new JoinNodeDef("j", "four")) .addNode(new NodeDef("four", null, SynchNodeHandler.class, Arrays.asList(new String[]{"end"}))) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); job.start(); assertEquals(WorkflowInstance.Status.SUCCEEDED, job.getStatus()); assertEquals(4, enters.size()); assertEquals(4, exits.size()); assertEquals(0, kills.size()); assertEquals(0, fails.size()); assertTrue(enters.get("one") < enters.get("two")); assertTrue(enters.get("one") < enters.get("three")); assertTrue(enters.get("three") < enters.get("four")); assertTrue(enters.get("two") < enters.get("four")); } public void testForkedContext() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("f")) .addNode(new ForkNodeDef("f", Arrays.asList(new String[]{"a", "b"}))) .addNode(new NodeDef("a", null, TestForkedContextHandler.class, Arrays.asList(new String[]{"j"}))) .addNode(new NodeDef("b", null, SynchNodeHandler.class, Arrays.asList(new String[]{"j"}))) .addNode(new JoinNodeDef("j", "end")) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); job.start(); assertEquals(WorkflowInstance.Status.SUCCEEDED, job.getStatus()); } public void testNestedFork() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("testWf", "<worklfow-app/>", new StartNodeDef("one")) .addNode(new NodeDef("one", null, SynchNodeHandler.class, Arrays.asList(new String[]{"f"}))) .addNode(new ForkNodeDef("f", Arrays.asList(new String[]{"two", "three"}))) .addNode(new NodeDef("two", null, SynchNodeHandler.class, Arrays.asList(new String[]{"f2"}))) .addNode(new NodeDef("three", null, SynchNodeHandler.class, Arrays.asList(new String[]{"j"}))) .addNode(new ForkNodeDef("f2", Arrays.asList(new String[]{"four", "five", "six"}))) .addNode(new NodeDef("four", null, SynchNodeHandler.class, Arrays.asList(new String[]{"j2"}))) .addNode(new NodeDef("five", null, SynchNodeHandler.class, Arrays.asList(new String[]{"j2"}))) .addNode(new NodeDef("six", null, SynchNodeHandler.class, Arrays.asList(new String[]{"j2"}))) .addNode(new JoinNodeDef("j2", "seven")) .addNode(new NodeDef("seven", null, SynchNodeHandler.class, Arrays.asList(new String[]{"j"}))) .addNode(new JoinNodeDef("j", "end")) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "abcde"); job.start(); assertEquals(WorkflowInstance.Status.SUCCEEDED, job.getStatus()); assertEquals(7, enters.size()); assertEquals(7, exits.size()); assertEquals(0, kills.size()); assertEquals(0, fails.size()); assertTrue(enters.get("one") < enters.get("two")); assertTrue(enters.get("one") < enters.get("three")); assertTrue(enters.get("two") < enters.get("four")); assertTrue(enters.get("four") < enters.get("seven")); assertTrue(enters.get("five") < enters.get("seven")); assertTrue(enters.get("six") < enters.get("seven")); } public void testKillWithRunningNodes() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("f")) .addNode(new ForkNodeDef("f", Arrays.asList(new String[]{"a", "b"}))) .addNode(new NodeDef("a", null, SynchNodeHandler.class, Arrays.asList(new String[]{"j"}))) .addNode(new NodeDef("b", null, AsynchNodeHandler.class, Arrays.asList(new String[]{"j"}))) .addNode(new JoinNodeDef("j", "end")) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); job.start(); assertEquals(WorkflowInstance.Status.RUNNING, job.getStatus()); job.kill(); assertEquals(2, enters.size()); assertEquals(1, kills.size()); assertEquals(1, exits.size()); assertEquals(0, fails.size()); } public void testFailWithRunningNodes() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("f")) .addNode(new ForkNodeDef("f", Arrays.asList(new String[]{"a", "b"}))) .addNode(new NodeDef("a", null, SynchNodeHandler.class, Arrays.asList(new String[]{"j"}))) .addNode(new NodeDef("b", null, AsynchNodeHandler.class, Arrays.asList(new String[]{"j"}))) .addNode(new JoinNodeDef("j", "end")).addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); job.start(); assertEquals(WorkflowInstance.Status.RUNNING, job.getStatus()); job.fail("b"); assertEquals(2, enters.size()); assertEquals(0, kills.size()); assertEquals(1, exits.size()); assertEquals(1, fails.size()); } public void testDoneWithRunningNodes() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("f")) .addNode(new ForkNodeDef("f", Arrays.asList(new String[]{"a", "b"}))) .addNode(new NodeDef("a", null, AsynchNodeHandler.class, Arrays.asList(new String[]{"j"}))) .addNode(new NodeDef("b", null, AsynchNodeHandler.class, Arrays.asList(new String[]{"end"}))) .addNode(new JoinNodeDef("j", "end")) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); job.start(); assertEquals(WorkflowInstance.Status.RUNNING, job.getStatus()); job.signal("/b/", ""); assertEquals(2, enters.size()); assertEquals(1, kills.size()); assertEquals(1, exits.size()); assertEquals(0, fails.size()); } public void testWFKillWithRunningNodes() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("f")) .addNode(new ForkNodeDef("f", Arrays.asList(new String[]{"a", "b"}))) .addNode(new NodeDef("a", null, AsynchNodeHandler.class, Arrays.asList(new String[]{"j"}))) .addNode(new NodeDef("b", null, AsynchNodeHandler.class, Arrays.asList(new String[]{"kill"}))) .addNode(new JoinNodeDef("j", "end")) .addNode(new KillNodeDef("kill", "killed")) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); job.start(); assertEquals(WorkflowInstance.Status.RUNNING, job.getStatus()); job.signal("/b/", ""); assertEquals(2, enters.size()); assertEquals(1, kills.size()); assertEquals(1, exits.size()); assertEquals(0, fails.size()); } public void testWfFailWithRunningNodes() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("f")) .addNode(new ForkNodeDef("f", Arrays.asList(new String[]{"a", "b"}))) .addNode(new NodeDef("a", null, AsynchNodeHandler.class, Arrays.asList(new String[]{"j"}))) .addNode(new NodeDef("b", null, AsynchNodeHandler.class, Arrays.asList(new String[]{"x"}))) .addNode(new JoinNodeDef("j", "end")) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); try { job.start(); job.signal("/b/", ""); } catch (WorkflowException ex) { } assertEquals(WorkflowInstance.Status.FAILED, job.getStatus()); assertEquals(2, enters.size()); assertEquals(1, fails.size()); //assertEquals(1, kills.size()); assertEquals(1, exits.size()); assertEquals(1, fails.size()); } public void testDecision() throws WorkflowException { List<String> decTrans = new ArrayList<String>(); decTrans.add("one"); decTrans.add("two"); decTrans.add("three"); LiteWorkflowApp def = new LiteWorkflowApp("testWf", "<worklfow-app/>", new StartNodeDef("d")) .addNode(new DecisionNodeDef("d", "", TestDecisionNodeHandler.class, decTrans)) .addNode(new NodeDef("one", null, SynchNodeHandler.class, Arrays.asList(new String[]{"end"}))) .addNode(new NodeDef("two", null, SynchNodeHandler.class, Arrays.asList(new String[]{"end"}))) .addNode(new NodeDef("three", null, SynchNodeHandler.class, Arrays.asList(new String[]{"end"}))) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "abcde"); job.start(); assertEquals(WorkflowInstance.Status.RUNNING, job.getStatus()); job.signal("/", "one"); assertEquals(WorkflowInstance.Status.SUCCEEDED, job.getStatus()); assertEquals(2, enters.size()); assertEquals(2, exits.size()); assertTrue(enters.containsKey("one")); assertTrue(!enters.containsKey("two")); assertTrue(!enters.containsKey("three")); enters.clear(); job = new LiteWorkflowInstance(def, new XConfiguration(), "abcde"); job.start(); assertEquals(WorkflowInstance.Status.RUNNING, job.getStatus()); job.signal("/", "two"); assertEquals(WorkflowInstance.Status.SUCCEEDED, job.getStatus()); assertTrue(!enters.containsKey("one")); assertTrue(enters.containsKey("two")); assertTrue(!enters.containsKey("three")); enters.clear(); job = new LiteWorkflowInstance(def, new XConfiguration(), "abcde"); job.start(); assertEquals(WorkflowInstance.Status.RUNNING, job.getStatus()); job.signal("/", "three"); assertEquals(WorkflowInstance.Status.SUCCEEDED, job.getStatus()); assertTrue(!enters.containsKey("one")); assertTrue(!enters.containsKey("two")); assertTrue(enters.containsKey("three")); enters.clear(); job = new LiteWorkflowInstance(def, new XConfiguration(), "abcde"); job.start(); assertEquals(WorkflowInstance.Status.RUNNING, job.getStatus()); try { job.signal("/", "bla"); fail(); } catch (Exception e) { } assertEquals(WorkflowInstance.Status.FAILED, job.getStatus()); } public void testActionOKError() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("a")) .addNode(new ActionNodeDef("a", "", TestActionNodeHandler.class, "b", "c")) .addNode(new NodeDef("b", null, SynchNodeHandler.class, Arrays.asList(new String[]{"end"}))) .addNode(new NodeDef("c", null, SynchNodeHandler.class, Arrays.asList(new String[]{"end"}))) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); job.start(); assertEquals(WorkflowInstance.Status.RUNNING, job.getStatus()); job.signal("/", "OK"); assertEquals(WorkflowInstance.Status.SUCCEEDED, job.getStatus()); assertTrue(enters.containsKey("b")); assertTrue(!enters.containsKey("c")); enters.clear(); job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); job.start(); assertEquals(WorkflowInstance.Status.RUNNING, job.getStatus()); job.signal("/", "ERROR"); assertEquals(WorkflowInstance.Status.SUCCEEDED, job.getStatus()); assertTrue(!enters.containsKey("b")); assertTrue(enters.containsKey("c")); } public void testJobPersistance() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("one")) .addNode(new NodeDef("one", null, AsynchNodeHandler.class, Arrays.asList(new String[]{"end"}))) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); job.setVar("a", "A"); job.setTransientVar("b", "B"); assertEquals(WorkflowInstance.Status.PREP, job.getStatus()); assertEquals("A", job.getVar("a")); assertEquals("B", job.getTransientVar("b")); assertEquals("1", job.getId()); byte[] array = WritableUtils.toByteArray(job); job = WritableUtils.fromByteArray(array, LiteWorkflowInstance.class); assertEquals(WorkflowInstance.Status.PREP, job.getStatus()); assertEquals("A", job.getVar("a")); assertEquals(null, job.getTransientVar("b")); assertEquals("1", job.getId()); job.start(); assertEquals(WorkflowInstance.Status.RUNNING, job.getStatus()); array = WritableUtils.toByteArray(job); job = WritableUtils.fromByteArray(array, LiteWorkflowInstance.class); assertEquals(WorkflowInstance.Status.RUNNING, job.getStatus()); job.signal("/", ""); assertEquals(WorkflowInstance.Status.SUCCEEDED, job.getStatus()); } public void testImmediateError() throws WorkflowException { LiteWorkflowApp workflowDef = new LiteWorkflowApp("testWf", "<worklfow-app/>", new StartNodeDef("one")) .addNode(new NodeDef("one", null, SynchNodeHandler.class, Arrays.asList(new String[]{"two"}))) .addNode(new NodeDef("two", null, SynchNodeHandler.class, Arrays.asList(new String[]{"four"}))) .addNode(new NodeDef("three", null, SynchNodeHandler.class, Arrays.asList(new String[]{"end"}))) .addNode(new EndNodeDef("end")); LiteWorkflowInstance workflowJob = new LiteWorkflowInstance(workflowDef, new XConfiguration(), "abcde"); try { workflowJob.start(); } catch (WorkflowException e) { } assertEquals(WorkflowInstance.Status.FAILED, workflowJob.getStatus()); assertEquals(2, enters.size()); assertEquals(2, exits.size()); assertEquals(0, kills.size()); assertEquals(0, fails.size()); } public void testSelfTransition() throws WorkflowException { try { new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("one")) .addNode(new NodeDef("one", null, SynchNodeHandler.class, Arrays.asList(new String[]{"one"}))) .addNode(new EndNodeDef("end")); fail(); } catch (WorkflowException ex) { assertEquals(ErrorCode.E0706, ex.getErrorCode()); } } public void testLoopSimple() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("one")) .addNode(new NodeDef("one", null, SynchNodeHandler.class, Arrays.asList(new String[]{"two"}))) .addNode(new NodeDef("two", null, SynchNodeHandler.class, Arrays.asList(new String[]{"one"}))) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); try { job.start(); fail(); } catch (WorkflowException ex) { assertEquals(ErrorCode.E0709, ex.getErrorCode()); } assertEquals(WorkflowInstance.Status.FAILED, job.getStatus()); } public void testLoopFork() throws WorkflowException { LiteWorkflowApp def = new LiteWorkflowApp("wf", "<worklfow-app/>", new StartNodeDef("one")) .addNode(new NodeDef("one", null, SynchNodeHandler.class, Arrays.asList(new String[]{"f"}))) .addNode(new ForkNodeDef("f", Arrays.asList(new String[]{"two", "three"}))) .addNode(new NodeDef("two", null, SynchNodeHandler.class, Arrays.asList(new String[]{"j"}))) .addNode(new NodeDef("three", null, SynchNodeHandler.class, Arrays.asList(new String[]{"j"}))) .addNode(new JoinNodeDef("j", "four")) .addNode(new NodeDef("four", null, SynchNodeHandler.class, Arrays.asList(new String[]{"f"}))) .addNode(new EndNodeDef("end")); LiteWorkflowInstance job = new LiteWorkflowInstance(def, new XConfiguration(), "1"); try { job.start(); fail(); } catch (WorkflowException ex) { assertEquals(ErrorCode.E0709, ex.getErrorCode()); } assertEquals(WorkflowInstance.Status.FAILED, job.getStatus()); } }
/* * $Header: /var/chroot/cvs/cvs/factsheetDesigner/extern/jakarta-slide-server-src-2.1-iPlus Edit/src/stores/org/apache/slide/store/impl/rdbms/MySql41RDBMSAdapter.java,v 1.2 2006-01-22 22:49:05 peter-cvs Exp $ * $Revision: 1.2 $ * $Date: 2006-01-22 22:49:05 $ * * ==================================================================== * * Copyright 1999-2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.slide.store.impl.rdbms; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import org.apache.slide.common.Service; import org.apache.slide.common.ServiceAccessException; import org.apache.slide.common.Uri; import org.apache.slide.content.NodeRevisionDescriptor; import org.apache.slide.content.NodeRevisionNumber; import org.apache.slide.store.impl.rdbms.MySqlRDBMSAdapter; import org.apache.slide.structure.ObjectNode; import org.apache.slide.structure.ObjectNotFoundException; import org.apache.slide.util.logger.Logger; /** * Adapter for MySQL 4.1. DELETE semantics are somewhat deviant * from MySQL 4.0. Table names should be referred to by their alias. * */ public class MySql41RDBMSAdapter extends MySqlRDBMSAdapter { /** * @param service * @param logger */ public MySql41RDBMSAdapter(Service service, Logger logger) { super(service, logger); } /* * @see org.apache.slide.store.impl.rdbms.RDBMSAdapter#removeObject( * java.sql.Connection, org.apache.slide.common.Uri, * org.apache.slide.structure.ObjectNode) */ public void removeObject(Connection connection, Uri uri, ObjectNode object) throws ServiceAccessException, ObjectNotFoundException { PreparedStatement statement = null; try { clearBinding(connection, uri); // delete links try { statement = connection.prepareStatement( "delete l from LINKS l, URI u where l.URI_ID = u.URI_ID and u.URI_STRING = ?"); statement.setString(1, uri.toString()); statement.executeUpdate(); } finally { close(statement); } // delete version history // FIXME: Is this true??? Should the version history be removed if the object is removed??? try { statement = connection.prepareStatement( "delete vh from VERSION_HISTORY vh, URI u where vh.URI_ID = u.URI_ID and u.URI_STRING = ?"); statement.setString(1, uri.toString()); statement.executeUpdate(); } finally { close(statement); } // delete version try { statement = connection.prepareStatement( "delete v from VERSION v, URI u where v.URI_ID = u.URI_ID and u.URI_STRING = ?"); statement.setString(1, uri.toString()); statement.executeUpdate(); } finally { close(statement); } // delete the object itself try { statement = connection.prepareStatement( "delete o from OBJECT o, URI u where o.URI_ID = u.URI_ID and u.URI_STRING = ?"); statement.setString(1, uri.toString()); statement.executeUpdate(); } finally { close(statement); } // finally delete the uri try { statement = connection.prepareStatement("delete from URI where URI_STRING = ?"); statement.setString(1, uri.toString()); statement.executeUpdate(); } finally { close(statement); } } catch (SQLException e) { throw createException(e, uri.toString()); } } /* * @see org.apache.slide.store.impl.rdbms.RDBMSAdapter#removeRevisionContent( * java.sql.Connection, org.apache.slide.common.Uri, * org.apache.slide.content.NodeRevisionDescriptor) */ public void removeRevisionContent(Connection connection, Uri uri, NodeRevisionDescriptor revisionDescriptor) throws ServiceAccessException { try { PreparedStatement statement = null; try { statement = connection.prepareStatement( "delete vc from VERSION_CONTENT vc, VERSION_HISTORY vh, URI u where vc.VERSION_ID = vh.VERSION_ID and vh.REVISION_NO = ? and vh.URI_ID=u.URI_ID AND u.URI_STRING=?"); statement.setString(1, revisionDescriptor.getRevisionNumber().toString()); statement.setString(2, uri.toString()); statement.executeUpdate(); } finally { close(statement); } } catch (SQLException e) { throw createException(e, uri.toString()); } } /* * @see org.apache.slide.store.impl.rdbms.RDBMSAdapter#removeRevisionDescriptor( * java.sql.Connection, org.apache.slide.common.Uri, * org.apache.slide.content.NodeRevisionNumber) */ public void removeRevisionDescriptor(Connection connection, Uri uri, NodeRevisionNumber revisionNumber) throws ServiceAccessException { PreparedStatement statement = null; try { try { statement = connection.prepareStatement( "delete vl from VERSION_LABELS vl, VERSION_HISTORY vh, URI u where vl.VERSION_ID = vh.VERSION_ID and vh.REVISION_NO = ? and vh.URI_ID = u.URI_ID AND u.URI_STRING = ?"); statement.setString(1, revisionNumber.toString()); statement.setString(2, uri.toString()); statement.executeUpdate(); } finally { close(statement); } try { statement = connection.prepareStatement( "delete p from PROPERTIES p, VERSION_HISTORY vh, URI u where p.VERSION_ID = vh.VERSION_ID and vh.REVISION_NO = ? and vh.URI_ID = u.URI_ID AND u.URI_STRING = ?"); statement.setString(1, revisionNumber.toString()); statement.setString(2, uri.toString()); statement.executeUpdate(); } finally { close(statement); } } catch (SQLException e) { throw createException(e, uri.toString()); } } /* * @see org.apache.slide.store.impl.rdbms.RDBMSAdapter#removeRevisionDescriptors( * java.sql.Connection, org.apache.slide.common.Uri) */ public void removeRevisionDescriptors(Connection connection, Uri uri) throws ServiceAccessException { PreparedStatement statement = null; try { statement = connection.prepareStatement( "delete vp from VERSION_PREDS vp, VERSION_HISTORY vh, URI u where vp.VERSION_ID = vh.VERSION_ID and vh.URI_ID = u.URI_ID and u.URI_STRING = ?"); statement.setString(1, uri.toString()); statement.executeUpdate(); } catch (SQLException e) { throw createException(e, uri.toString()); } finally { close(statement); } } /* * @see org.apache.slide.store.impl.rdbms.StandardRDBMSAdapter#clearBinding(java.sql.Connection, org.apache.slide.common.Uri) */ protected void clearBinding(Connection connection, Uri uri) throws ServiceAccessException, ObjectNotFoundException, SQLException { PreparedStatement statement = null; // clear this uri from having bindings and being bound try { statement = connection.prepareStatement( "delete c from BINDING c, URI u where c.URI_ID = u.URI_ID and u.URI_STRING = ?"); statement.setString(1, uri.toString()); statement.executeUpdate(); } finally { close(statement); } try { statement = connection.prepareStatement( "delete c from PARENT_BINDING c, URI u where c.URI_ID = u.URI_ID and u.URI_STRING = ?"); statement.setString(1, uri.toString()); statement.executeUpdate(); } finally { close(statement); } } }